js_compile/compiler.rs
1//! The bytecode compiler.
2//!
3//! Compilation is a single walk over the AST that emits *symbolic* instructions
4//! (jump targets are label ids, variable references are names), followed by a
5//! resolution pass that turns them into final bytecode. Splitting it this way
6//! keeps the emitter readable: nothing has to know slot indices or byte offsets
7//! while it is still discovering them.
8//!
9//! Variable resolution follows the reference implementation's model:
10//!
11//! * every function has a flat table of arguments and locals;
12//! * block scopes form a chain through [`VarDef::scope_next`], which is what makes
13//! `let`/`const` bindings visible only inside their block and lets the runtime
14//! put them back into the temporal dead zone on entry;
15//! * a name that is not in the current function is looked up in the enclosing
16//! ones; if found, the variable is marked captured and reached through a
17//! closure reference;
18//! * a name found nowhere is a global, reached through a closure entry as well.
19//!
20//! Emission order and instruction choice deliberately mirror `quickjs.c`: the
21//! differential test compares disassembly with the reference opcode by opcode, so
22//! an unnecessary `dup` or a differently chosen short form shows up immediately.
23
24use crate::bytecode::LineCol;
25use crate::bytecode::{
26 ANONYMOUS_BINDING, Atom, ClosureType, ClosureVar, Constant, EvalPrivate, EvalPrivateKind,
27 EvalSite, EvalVisible, ExportEntry, Function as CompiledFunction, FunctionKind, ImportEntry,
28 ModuleMeta, ModuleRequest, VarDef, VarKind,
29};
30use crate::disasm;
31use crate::opcode::Opcode;
32use js_parse::Position;
33use js_parse::Span;
34use js_parse::SyntaxError;
35use js_parse::Wtf8;
36use js_parse::ast::{self, *};
37
38/// A label id, local to the function being compiled.
39#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
40pub struct Label(u32);
41
42/// The name of the hidden local that carries a function's `[[HomeObject]]` for `super`.
43///
44/// The reference calls the variable `home_object` and prints it as `"<home_object>"`, which
45/// is why the brackets are part of the name; nothing a program writes can collide with it.
46const HOME_OBJECT: &str = "<home_object>";
47
48/// The local holding the function `super()` constructs from.
49///
50/// The reference's `JS_ATOM_this_active_func`. Unlike `<home_object>` this one is printed
51/// with its dots, because that is the atom's text: its dump shows `1: var this.active_func`.
52const ACTIVE_FUNC: &str = "this.active_func";
53
54/// The local holding `new.target`, likewise spelled the way the reference's dump shows it.
55const NEW_TARGET: &str = "new.target";
56
57/// Stand-in for a constant-pool index that is only known later in the instruction stream.
58///
59/// One user: the class constructor's `fclosure`, whose slot the reference assigns after the
60/// members have taken theirs. `u32::MAX` is not a reachable pool index — a class with four
61/// billion members is not a thing — and the compiler patches it before resolution runs, so a
62/// missed patch is a panic-free compiler error rather than a wrong jump.
63const CTOR_INDEX_PLACEHOLDER: u32 = u32::MAX;
64
65/// One step of a class's initialisation, in source order.
66///
67/// A static block is not a member the class keeps — it is a run of statements that executes
68/// at the point the class definition reaches it — so it belongs *inside* the initialiser
69/// function rather than alongside the fields as a separate pass. Merging the two is what
70/// makes `static a = 1; static {}` and `static {}; static a = 1` order-sensitive in the
71/// same way the reference is.
72enum StaticInitItem<'a> {
73 /// `static x = value`, or `x = value` for the instance half.
74 Field(FieldKey<'a>, Option<&'a Expr>),
75 /// `static { … }`
76 Block {
77 body: &'a [Stmt],
78 /// Position of the `{`, which is where the reference puts the function.
79 body_start: Position,
80 },
81}
82
83/// The next template-site identity, process-wide.
84///
85/// A counter rather than something derived from the unit: two compilation units that both
86/// number their sites from zero would collide in the realm's registry, and a collision
87/// there is observable — it would hand the *same* template object to two unrelated sites.
88fn next_template_site() -> u32 {
89 static NEXT: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0);
90 NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed)
91}
92
93/// How one field names its property.
94///
95/// A computed key is *not* re-evaluated per instance: the reference evaluates it once at
96/// class definition and stores it in a `<computed_field>N` binding, because the key of a field
97/// is fixed when the class is created. Keeping the expression here instead made
98/// `class C { [k] = 1 }` re-read `k` on every `new`, which is a different program when `k`
99/// changes — and worse, the operand order was wrong, so `class C { ["a"] = 1 }` produced
100/// `{1: "a"}`.
101enum FieldKey<'a> {
102 /// `x`, `"x"`, `0` — the property name is static text.
103 Literal(&'a PropKey),
104 /// `#x`: the class-scope binding that holds the private symbol.
105 Private(String),
106 /// `[expr]`: the class-scope binding that holds the evaluated key.
107 Computed(String),
108}
109
110/// The `var_block` sentinel for a binding that lives at function scope.
111///
112/// It has to be a value a *real* block key can never take. Block keys are source
113/// offsets, so `0` is a perfectly ordinary key — the first block statement of a file
114/// gets it — and using `0` as the sentinel made `{ let y = 2 }` at offset zero look
115/// like a function-scoped `var`, which is how a top-level block's `let` leaked out of
116/// its block. The body block already uses `u64::MAX` to stay clear of offsets, so the
117/// sentinel takes the slot below it.
118const FUNCTION_SCOPE: u64 = u64::MAX - 3;
119
120/// The `var_block` sentinel for a binding of the parameter list.
121///
122/// A function whose parameter list contains a default expression gets *two* variable
123/// environments: one for the parameters and one for the body, so a `var` in the body
124/// that shares a name with a parameter is a different binding. The parameter bindings
125/// therefore need a scope key of their own: reachable while the defaults are
126/// evaluated, invisible to the body, and never merged with a body `var` of the same
127/// name.
128///
129/// Without this, `function f(a = 1, p = () => a) { var a = 2 }` made `p()` return 2:
130/// the closure and the body shared one slot, when only the parameters were in scope
131/// when it was created.
132const PARAM_SCOPE: u64 = u64::MAX - 4;
133
134/// The name of the hidden local a `using` declaration caches its dispose method in.
135///
136/// It has to be a name no source can produce, because a script may declare anything: the
137/// angle brackets keep it out of the identifier grammar, exactly like `<ret>`.
138fn using_method_name(name: &str) -> String {
139 format!("<using.method {name}>")
140}
141
142/// The `blocks` parent sentinel for "this block has no enclosing block".
143///
144/// Same reasoning as [`FUNCTION_SCOPE`]: `0` is a legal block key, and when it was
145/// also the terminator the chain walk from the script body reached the file's
146/// offset-zero block and treated it as an *enclosing* block — so that block's `let`
147/// leaked into the body scope.
148const NO_PARENT: u64 = u64::MAX - 2;
149
150/// The block key for a script body. Distinct from both sentinels and unreachable from
151/// any source offset.
152const SCRIPT_BODY: u64 = u64::MAX - 1;
153
154/// An operand of a symbolic instruction.
155#[derive(Debug, Clone, PartialEq)]
156enum Op {
157 /// An immediate integer.
158 Int(i32),
159 /// A jump target.
160 Label(Label),
161 /// A constant pool index.
162 Const(u32),
163 /// An atom, before interning.
164 Atom(Atom),
165 /// An interned atom, as an index into [`Function::atoms`].
166 AtomId(u32),
167 /// A resolved slot.
168 Slot(Slot),
169}
170
171/// Where a resolved variable lives.
172#[derive(Debug, Clone, Copy, PartialEq, Eq)]
173enum Slot {
174 Arg(u32),
175 Loc(u32),
176 VarRef(u32),
177 /// A global, by closure-var index.
178 Global(u32),
179 /// A global *declared* in this script. The reference keeps these bindings in
180 /// reference cells so that the script and any closure share one variable, so
181 /// a store goes through `put_var_ref` while a read uses `get_var`.
182 GlobalDecl(u32),
183}
184
185/// What a symbolic variable access does, which decides the final opcode.
186#[derive(Debug, Clone, Copy, PartialEq, Eq)]
187enum VarAction {
188 /// Read the value.
189 Get,
190 /// Read the value, yielding `undefined` for an undeclared global.
191 GetUndef,
192 /// Write, leaving nothing on the stack.
193 Put,
194 /// Write and initialise, leaving the value on the stack.
195 PutInit,
196 /// Write, leaving the value on the stack.
197 Set,
198 /// Initialise a binding that may only be initialised once, such as a derived
199 /// constructor's `this`.
200 PutInitChecked,
201 /// Initialise, leaving the value on the stack and without the `const` check.
202 ///
203 /// A class's own scope binding is a `const` that has to be initialised in the middle
204 /// of the definition — after the constructor exists but before the static fields run
205 /// — and the value has to survive for the outer store to use.
206 SetInit,
207 /// Write a binding that lives in a reference cell.
208 PutRef,
209 /// Read through a reference the caller already pushed: `[ref] -> [ref, value]`.
210 GetRef,
211 /// Push a **Reference** (§6.2.5) to the binding, so the same lvalue can be read and
212 /// written without resolving the name twice.
213 ///
214 /// Only emitted where a direct `eval` may run in between: `x *= (eval("var x = 2"), 4)`
215 /// must read the `x` of §13.15.3 step 2 and store to *that* one at step 7, and by then
216 /// the eval has declared a shadowing binding with the same name.
217 MakeRef,
218}
219
220#[derive(Debug, Clone)]
221enum Insn {
222 /// A fully determined instruction.
223 Fixed { op: Opcode, operands: Vec<Op> },
224 /// A variable access, resolved in the second pass.
225 ///
226 /// `block` is the lexical block the access appears in, which is what makes
227 /// shadowing work: two bindings can share a name, and the one that wins is
228 /// whichever scope encloses the access.
229 Var {
230 action: VarAction,
231 name: String,
232 block: u64,
233 /// Whether the access was written in the parameter list; see
234 /// [`FnState::in_params`].
235 in_params: bool,
236 },
237 /// Close a binding *if* it turned out to be captured.
238 ///
239 /// Whether a `for (let i ...)` loop variable needs a fresh per-iteration cell is
240 /// only known once the body has been compiled — a closure created there is the
241 /// thing that makes it necessary. The reference emits `close_loc` exactly in that
242 /// case and nothing otherwise, so the decision is deferred to [`resolve`] instead
243 /// of emitted blind.
244 CloseCaptured { name: String, block: u64 },
245 /// `delete name`, which can only answer `false` once the binding is known.
246 ///
247 /// It is not a `Var` action because `delete_var` carries an *atom*: the runtime
248 /// looks the name up on the global object, which is what distinguishes an implicit
249 /// global (configurable, deletable) from a declared one (a binding, always `false`).
250 DeleteVar { name: String },
251 /// An instruction that dead-code elimination removed. It keeps its slot so
252 /// that label indices stay valid, and resolves to no bytecode.
253 Dead,
254}
255
256/// Where `break` and `continue` jump to.
257///
258/// Targets are stacked as the compiler enters loops and labelled statements, so a
259/// bare `break` needs no analysis: it is simply the innermost target. A labelled
260/// one searches outward by name.
261#[derive(Debug, Clone)]
262struct JumpTarget {
263 /// The labels attached to this target. `l: for(;;)` gives one name; a bare
264 /// loop gives none; `a: b: for(;;)` gives two, because both labels name the
265 /// same statement and `break a` must reach the same place as `break b`.
266 names: Vec<String>,
267 /// Where `break` lands. `None` for a construct `break` may only leave, not
268 /// target — a `try`, whose entry exists purely to unwind.
269 break_label: Option<Label>,
270 /// Where `continue` lands. `None` for anything that is not a loop.
271 continue_label: Option<Label>,
272 /// Stack slots to discard when control leaves this construct by a jump.
273 ///
274 /// Both `switch` and `try` leave something on the value stack for the duration
275 /// of the construct — the discriminant, or the `catch` offset — and a jump out
276 /// has to take it with it. A loop leaves nothing.
277 drop_count: u32,
278 /// The finalizer to run when control leaves this construct.
279 ///
280 /// Set on a `try` even when it has no `finally`: the label is always emitted and
281 /// the empty-subroutine removal cleans up afterwards, so the code that unwinds
282 /// does not have to know whether a finalizer exists.
283 finally_label: Option<Label>,
284 /// Whether this is a labelled non-loop statement, which an unlabelled `break`
285 /// does not reach.
286 is_regular_stmt: bool,
287 /// Whether leaving this construct has to close an iterator.
288 ///
289 /// A `for`/`of` loop keeps an iterator on the value stack, and leaving early has
290 /// to run its `return` method. `for`/`in` keeps only an enumeration object, which
291 /// is dropped rather than closed.
292 has_iterator: bool,
293 /// Whether that iterator speaks the *async* protocol.
294 ///
295 /// An async close has to `await` the inner `return`, so it is an inline instruction
296 /// sequence rather than one opcode — the reference's `emit_iterator_close`.
297 is_async_iterator: bool,
298}
299
300/// Whether a named property read should be `get_field2` rather than `dup; get_field`.
301///
302/// Both leave `source value` on the stack, so this is purely which spelling the reference
303/// picked, and it picked it by whether it had to build a *reference* for the target:
304///
305/// * a target that is itself a pattern starts by boxing the value, so the copy is what it
306/// consumes — `get_field2` (and a default does not change that: `{a: {b} = {}}` still
307/// destructures);
308/// * a `let`/`const` binding needs no reference, so the reference takes the short form;
309/// * a `var`, and any assignment target, go through `dup; get_field`, because the
310/// reference builds a reference for them — which is what `with` needs.
311fn reads_with_get_field2(decl: Option<VarDeclKind>, value: &Pattern) -> bool {
312 nests_a_pattern(value) || matches!(decl, Some(VarDeclKind::Let) | Some(VarDeclKind::Const))
313}
314
315/// Whether binding this pattern starts by boxing the value it was handed.
316fn nests_a_pattern(pattern: &Pattern) -> bool {
317 match &pattern.kind {
318 PatternKind::Array { .. } | PatternKind::Object { .. } => true,
319 PatternKind::Assign { target, .. } => nests_a_pattern(target),
320 _ => false,
321 }
322}
323
324/// `copy_data_properties` flags for an object-literal spread.
325///
326/// The byte packs three fields: the low bits are the stack offset of the source,
327/// the next three the offset of the exclusion list, and bit 2 asks for symbol keys
328/// as well as string keys. A spread passes a literal `null` exclusion list right
329/// below the source, so that field stays zero and only the source offset and the
330/// symbol bit are set — hence `{...v}` copies symbols, which the flag name says.
331const COPY_ALL_PROPERTIES: i32 = 2 | (1 << 2);
332
333/// The expression a `...` introduces.
334///
335/// The parser marks the spread in two places — the element/property variant and an
336/// [`ExprKind::Spread`] wrapper around the argument — so the wrapper has to be
337/// stepped through before the argument can be compiled.
338fn spread_argument(spread: &Expr) -> &Expr {
339 match &spread.kind {
340 ExprKind::Spread(inner) => inner,
341 _ => spread,
342 }
343}
344
345/// The flag byte `define_method` takes.
346///
347/// The low two bits pick value/getter/setter; bit 2 marks the property
348/// enumerable, which every object-literal method is.
349/// What kind of class constructor a function is being compiled as.
350///
351/// A constructor is not an ordinary method: a base one materialises `this` and refuses
352/// to run without `new`, and a derived one starts with `this` in the dead zone until
353/// `super()` produces it.
354#[derive(Debug, Clone, Copy, PartialEq, Eq)]
355enum CtorKind {
356 /// Not a class constructor.
357 None,
358 /// A constructor of a class without `extends`.
359 Base,
360 /// A constructor of a class with `extends`.
361 Derived,
362}
363
364/// The flag byte `define_method` takes for a class member.
365///
366/// The low two bits pick value/getter/setter; bit 2 marks the property enumerable, which
367/// a class method is *not* — that is the whole difference from an object-literal method,
368/// and the reason `Object.keys(C.prototype)` stays empty.
369fn class_method_flags(kind: MethodKind) -> i32 {
370 match kind {
371 MethodKind::Constructor | MethodKind::Method => 0,
372 MethodKind::Get => 1,
373 MethodKind::Set => 2,
374 }
375}
376
377fn define_method_flags(kind: PropertyKind) -> i32 {
378 let base = match kind {
379 PropertyKind::Value | PropertyKind::Method => 0,
380 PropertyKind::Get => 1,
381 PropertyKind::Set => 2,
382 };
383 base | 4
384}
385
386/// Convert a numeric property key to the text an atom would be made from.
387///
388/// `PropertyKey` of a number is `ToString(number)`, the same conversion every other place
389/// uses — so this goes through [`crate::number::number_to_string`] rather than formatting
390/// the value here. It used to accept only `[1e-6, 1e21)` and reject the rest, on the
391/// theory that Rust's `{}` and JavaScript's spelling diverge at the extremes; they do, and
392/// that is exactly why the spec's own algorithm is the thing to call. `get 0.0000001() {}`
393/// binds the key `"1e-7"`, and the rejection made it a `SyntaxError` instead.
394///
395/// The `Result` is kept because the call sites are in a `?` chain, and a key conversion
396/// that could still fail (a non-finite value from a source literal, which the lexer does
397/// not produce) belongs on the same path as the rest of a property name's errors.
398fn numeric_key_text(value: f64, _span: Span) -> Result<String, SyntaxError> {
399 Ok(crate::number::number_to_string(value))
400}
401
402/// Collect the operands of a same-operator logical run, in source order.
403///
404/// Recurses down the left spine only: `((a || b) || c)` contributes `a`, `b`, then
405/// the caller appends `c`. A node with a different operator is one operand.
406fn collect_same_operator<'a>(op: LogicalOp, expr: &'a Expr, out: &mut Vec<&'a Expr>) {
407 if let ExprKind::Logical {
408 op: inner_op,
409 left,
410 right,
411 } = &expr.kind
412 && *inner_op == op
413 {
414 collect_same_operator(op, left, out);
415 out.push(right);
416 return;
417 }
418 out.push(expr);
419}
420
421/// The jump a logical assignment or `??` takes when the value is kept.
422///
423/// `||` and `&&` branch on truthiness, so the same opcode serves both the operator
424/// and `??` once [`Compiler::emit_logical_test`] has pushed a boolean. `??` keeps
425/// the value when it is *not* null-ish, so it is the `if_false` side.
426fn logical_jump(op: AssignOp) -> Opcode {
427 match op {
428 AssignOp::Or => Opcode::IfTrue,
429 AssignOp::And | AssignOp::Coalesce => Opcode::IfFalse,
430 _ => Opcode::IfFalse,
431 }
432}
433
434/// Whether a loop enumerates keys or values.
435#[derive(Debug, Clone, Copy, PartialEq, Eq)]
436enum ForLoopKind {
437 /// `for (x in o)` — the keys of an object.
438 In,
439 /// `for (x of o)` — the values of an iterable.
440 Of,
441 /// `for await (x of o)` — the values of an async iterable, or of a sync one.
442 AwaitOf,
443}
444
445/// Which part of a `try` statement a block key refers to.
446#[derive(Debug, Clone, Copy)]
447enum TryPart {
448 /// The guarded block.
449 Block = 0,
450 /// The handler body, excluding the catch parameter.
451 Catch = 1,
452 /// The finalizer block.
453 Finally = 2,
454 /// The catch parameter's own scope.
455 Param = 3,
456}
457
458/// A lexical scope, identified while hoisting and numbered at the end.
459///
460/// Scope identity is needed in two passes that must agree: declarations are
461/// hoisted in source order (so slots come out in source order, as in the
462/// reference), but a binding belongs to the block it was written in, which is only
463/// entered later. Blocks are therefore keyed by the source position of their
464/// opening brace, which is stable across both walks.
465#[derive(Debug, Clone, Copy)]
466struct Block {
467 /// Source position of the block.
468 key: u64,
469 /// The block this one is nested in; `0` for the function scope.
470 parent: u64,
471}
472
473/// One function under construction.
474struct FnState {
475 /// The function's own source range, used to record its text for
476 /// `Function.prototype.toString`.
477 span: Option<(usize, usize)>,
478 name: String,
479 kind: FunctionKind,
480 strict: bool,
481 args: Vec<VarDef>,
482 vars: Vec<VarDef>,
483 closure_vars: Vec<ClosureVar>,
484 cpool: Vec<Constant>,
485 atoms: Vec<Atom>,
486 /// Every lexical scope, in creation order.
487 blocks: Vec<Block>,
488 /// The block currently being parsed or compiled.
489 current_block: u64,
490 /// The block a *nested* function was created in, so a capture made from here can be
491 /// resolved against the enclosing function's lexical scopes rather than against a
492 /// flat name table. Without it, `function f(){ class S{} }` capturing `S` found the
493 /// function's own `let S` instead of the class body's `const S`.
494 created_in_block: u64,
495 /// The block each local was declared in, parallel to `vars`. `0` means the
496 /// function scope, where `var` bindings live.
497 var_block: Vec<u64>,
498 /// Set when the expression just compiled left no value on the stack.
499 ///
500 /// Only a store can do that: `put_field` consumes the object and the value, so
501 /// an assignment whose result is unused emits nothing extra. The expression
502 /// statement then has nothing to drop.
503 no_value: bool,
504 /// Whether a label was placed since the last instruction was emitted.
505 ///
506 /// The `put`/`get` fold is only valid when the two are adjacent in the final
507 /// stream; a label in between means a jump can land on the read, so the store has
508 /// to keep consuming its value. A flag is enough and avoids having to reason about
509 /// which index a label recorded.
510 label_since_insn: bool,
511 /// Whether the value of the expression being compiled is thrown away.
512 ///
513 /// Only an expression *statement* discards its value, and only the outermost
514 /// assignment in it may act on that: in `x = (o.a = 1)` the inner assignment
515 /// still has to produce a value. Consumed by [`Compiler::assign`], which is
516 /// the one construct whose bytecode depends on it.
517 discard_value: bool,
518 /// The block that holds the function body.
519 body_block: u64,
520 /// Head of each scope's binding chain, indexed by level. Filled in by
521 /// [`rebuild_scope_chain`]; the scope chain is only needed at run time.
522 block_heads: Vec<i32>,
523 /// Enclosing `break`/`continue` targets, innermost last.
524 jump_targets: Vec<JumpTarget>,
525 insns: Vec<Insn>,
526 labels: Vec<Option<usize>>,
527 /// Captured locals, which need a reference cell.
528 var_ref_count: u32,
529 line: u32,
530 column: u32,
531 /// Whether this is a script body. A script's top-level declarations create
532 /// global properties rather than locals, which is why they show up as
533 /// closure variables with `[global_decl]`.
534 is_script: bool,
535 /// Whether this is a module body.
536 ///
537 /// A module body is a script in every respect that matters here — no `arguments`,
538 /// no `this` of its own — but its top-level declarations are *module*-scoped
539 /// instead of global, which is what this flag changes.
540 is_module: bool,
541 /// Whether this frame is an `eval` body; see [`Compiler::eval_body`].
542 is_eval_body: bool,
543 /// Whether the function is an arrow, which never gets its own `arguments`.
544 is_arrow: bool,
545 /// The name a *named function expression* binds inside its own body.
546 /// How many parameters count towards `.length`.
547 defined_args: u32,
548 /// Parameters that are not a plain name, with the argument slot each came from.
549 param_prologue: Vec<(usize, Pattern)>,
550 /// What kind of class constructor this function is, if any.
551 ctor_kind: CtorKind,
552 /// Whether the class has instance fields, so the constructor has to run their
553 /// initialiser before it returns.
554 /// What the nested function about to be compiled should be told about its class.
555 class_ctor_pending: Option<CtorKind>,
556 /// Whether this function needs the hidden `this` local, because an arrow inside it
557 /// refers to `this`.
558 ///
559 /// An arrow has no `this` of its own, so the reference materialises the enclosing
560 /// function's receiver into a local and lets the arrow capture it as an ordinary
561 /// closure variable. Declaring the local is not enough on its own: the store that
562 /// fills it has to be prepended to the body, which is what this flag arranges.
563 needs_this_local: bool,
564 /// The same, for `arguments`.
565 needs_arguments_local: bool,
566 /// The same, for `new.target`.
567 needs_new_target_local: bool,
568 /// Whether the body already opens by filling a `this` local, which
569 /// [`Compiler::begin_this_local`] does for a constructor and a field initialiser.
570 has_this_prologue: bool,
571 /// The same, for `<home_object>`: the object `super` resolves against.
572 ///
573 /// An arrow and a static block have no home object of their own — only the method or
574 /// initialiser they were written in does — so `super.x` inside one is a read of the
575 /// enclosing function's `[[HomeObject]]`. The value is materialised into a local there
576 /// by `special_object 4`, the same way `this` is.
577 needs_home_object_local: bool,
578 /// Whether this function has an `arguments` binding of its own.
579 ///
580 /// False for a class field initialiser and a static block: §15.7 puts them outside any
581 /// function, so `arguments` does not exist there and `eval('arguments')` inside one is a
582 /// `SyntaxError` rather than the caller's arguments object. The parser already enforces
583 /// that for written code; this carries the same fact to the `eval` call site, which has
584 /// to compile the eval'd source under the caller's restriction.
585 no_arguments_binding: bool,
586 /// The same, for `this.active_func`: the function `super()` constructs from.
587 ///
588 /// An arrow has no `super` of its own, so it reads the enclosing function's — and that
589 /// is a *lexical* relationship, not a stack one. The reference keeps `this_active_func`
590 /// as a local of the enclosing function; an arrow that escaped the constructor
591 /// (`iter.return = () => super()`) then finds it in its closure even with the
592 /// constructor nowhere on the call stack.
593 needs_active_func_local: bool,
594 /// Hidden locals of the `with` blocks currently open, innermost last.
595 with_names: Vec<String>,
596 /// How many of [`FnState::with_names`] were already open when this function was
597 /// created, i.e. belong to an *enclosing* function.
598 ///
599 /// The distinction decides shadowing, and it is positional rather than lexical. A
600 /// `with` opened **inside** this function's body sits nearer than the function's own
601 /// environment, so it shadows even a `var` of this function:
602 /// `function f(){ with(o){ var v = 1 } }` writes `o.v`. A `with` opened **outside**
603 /// does not: `with(o){ function f(){ var v = 1 } }` writes `f`'s local `v`, because
604 /// `f`'s environment is the inner one. Treating both alike broke one family or the
605 /// other — `S12.10_A1.2` and `S12.10_A1.7` are these two cases.
606 inherited_with_names: usize,
607 /// Set while a with-guard is being emitted, so the guard's own accesses are not
608 /// wrapped in another guard.
609 emitting_with_guard: bool,
610 self_name: Option<String>,
611 /// Where the function body starts, in source order; see [`Function::body_start`].
612 body_start: (u32, u32),
613 /// Whether the body contains a *direct* `eval(...)` call.
614 ///
615 /// A direct eval sees every binding of the function that called it, including ones
616 /// no other code mentions. It also hands those bindings to any closure it creates,
617 /// which can outlive the function. Both need the bindings to live in cells, so this
618 /// flag makes the function treat all of them as captured.
619 has_direct_eval: bool,
620 /// Whether this function's body contains a direct `eval` **anywhere**, known before any
621 /// of it is compiled.
622 ///
623 /// [`Self::has_direct_eval`] is learned as the eval call is compiled, which is too late
624 /// for an lvalue that must be resolved *before* the right-hand side that contains the
625 /// eval. This one is seeded from the AST, so `x *= (eval("var x = 2"), 4)` knows to pin
626 /// the reference before it emits the read.
627 eval_can_declare: bool,
628 /// Whether the parameter list contains a default expression, which is what gives
629 /// the function a second variable environment (see [`PARAM_SCOPE`]).
630 has_parameter_expressions: bool,
631 /// `IsSimpleParameterList`: every parameter is a plain binding identifier.
632 simple_parameter_list: bool,
633 /// Whether the instructions being emitted belong to the parameter list.
634 ///
635 /// References made here must not see the body's `var`s: the body has not run yet,
636 /// and the reference's own model keeps the two scopes apart.
637 in_params: bool,
638 /// Whether an arrow created in this function's parameter list needs the parameter
639 /// scope's `arguments` binding.
640 needs_param_arguments: bool,
641 /// Whether this function was *created* inside a parameter list.
642 ///
643 /// Inherited, so `f(a = () => () => c)` hides `f`'s body bindings from the inner
644 /// arrow too. The name reference is the arrow's, but the scope it must not see
645 /// belongs to the function the arrow was born in.
646 created_in_params: bool,
647 /// What each direct `eval(...)` in this function can see; see [`EvalSite`].
648 ///
649 /// Only filled in by [`Compiler::materialize_eval_sites`], because the answer is not
650 /// final while the body is still being compiled: a named function expression declares
651 /// its own name binding *after* the body, and that binding is exactly what
652 /// `eval("myfunc = 1")` has to find.
653 eval_sites: Vec<EvalSite>,
654 /// Direct `eval` call sites seen so far: where, and the block that was current.
655 pending_eval_sites: Vec<(Span, u64, bool, Vec<EvalPrivate>, bool)>,
656 /// Whether this body contains `await`.
657 ///
658 /// For a *module* this decides whether its body is an async function: top-level
659 /// `await` makes the whole graph's evaluation asynchronous, which is why the flag has
660 /// to survive to the compiled function rather than being a local of the compiler.
661 has_await: bool,
662 /// The module tables, when this body is a module.
663 ///
664 /// Only the top-level state ever has one: `export` and `import` are top-level
665 /// statements, so nothing nested can add to these tables.
666 module: Option<ModuleMeta>,
667 /// Whether the self-name prologue (`special_object 2` then the store) has been
668 /// emitted for this function.
669 ///
670 /// A *nested* function's lookup declares the binding early (see
671 /// [`resolve_slot`]), so `provide_self_name` cannot decide on its own whether the
672 /// prologue is still needed — the binding existing is not the same as it being
673 /// initialised.
674 self_name_initialized: bool,
675 /// Whether the code emitted so far leaves the program's result on the stack.
676 /// The reference tracks this for the hidden `<ret>` local of an eval script.
677 leaves_value: bool,
678 /// Statement nesting depth, used to tell top-level statements apart.
679 stmt_depth: u32,
680 /// Function declarations waiting to be instantiated at scope entry, as
681 /// (target slot, constant pool index). The reference emits these from
682 /// `instantiate_hoisted_definitions` rather than at the statement, because a
683 /// declaration is visible before it is reached.
684 hoisted: Vec<(u64, HoistTarget, u32)>,
685 /// Function declarations whose bodies are compiled only once the enclosing scope
686 /// has finished hoisting, as (owning block, declaration).
687 ///
688 /// Compiling a body at the declaration makes the result depend on source order: in
689 /// `function f(){ return t } var t`, `t` is not declared yet when `f` is compiled,
690 /// so the read resolved to a *global* instead of the enclosing `var`. Hoisting the
691 /// names first and the bodies second is what removes that dependence.
692 deferred_funcs: Vec<(u64, Box<ast::Function>)>,
693 /// The source position of the node being compiled. Every instruction emitted
694 /// takes it, which is how the position table that feeds stack traces is built.
695 cur_pos: Option<Position>,
696 /// One position per entry in `insns`, index-aligned.
697 insn_pos: Vec<Option<Position>>,
698}
699
700/// Where a hoisted function declaration is stored.
701#[derive(Debug, Clone)]
702enum HoistTarget {
703 Arg(u32),
704 Loc(u32),
705 /// A global, which the resolver looks up by name.
706 Global(String),
707}
708
709impl FnState {
710 /// Whether this function suspends: a generator or an async function.
711 ///
712 /// A suspending function's `return` is a `return_async` and its body starts with an
713 /// `initial_yield`, so almost every statement that touches control flow asks this.
714 fn is_suspending(&self) -> bool {
715 self.kind.is_generator() || self.kind.is_async()
716 }
717
718 fn new(name: impl Into<String>, kind: FunctionKind) -> FnState {
719 FnState {
720 span: None,
721 name: name.into(),
722 kind,
723 strict: false,
724 args: Vec::new(),
725 vars: Vec::new(),
726 closure_vars: Vec::new(),
727 cpool: Vec::new(),
728 atoms: Vec::new(),
729 blocks: Vec::new(),
730 current_block: 0,
731 created_in_block: NO_PARENT,
732 var_block: Vec::new(),
733 no_value: false,
734 label_since_insn: false,
735 discard_value: false,
736 body_block: 0,
737 block_heads: Vec::new(),
738 jump_targets: Vec::new(),
739 insns: Vec::new(),
740 labels: Vec::new(),
741 var_ref_count: 0,
742 line: 1,
743 column: 1,
744 is_script: false,
745 is_eval_body: false,
746 is_module: false,
747 is_arrow: false,
748 defined_args: 0,
749 param_prologue: Vec::new(),
750 ctor_kind: CtorKind::None,
751 class_ctor_pending: None,
752 needs_this_local: false,
753 needs_arguments_local: false,
754 needs_new_target_local: false,
755 has_this_prologue: false,
756 needs_home_object_local: false,
757 no_arguments_binding: false,
758 needs_active_func_local: false,
759 with_names: Vec::new(),
760 inherited_with_names: 0,
761 emitting_with_guard: false,
762 self_name: None,
763 has_direct_eval: false,
764 eval_can_declare: false,
765 body_start: (0, 0),
766 has_parameter_expressions: false,
767 simple_parameter_list: true,
768 in_params: false,
769 needs_param_arguments: false,
770 created_in_params: false,
771 eval_sites: Vec::new(),
772 pending_eval_sites: Vec::new(),
773 has_await: false,
774 module: None,
775 self_name_initialized: false,
776 leaves_value: false,
777 stmt_depth: 0,
778 hoisted: Vec::new(),
779 deferred_funcs: Vec::new(),
780 cur_pos: None,
781 insn_pos: Vec::new(),
782 }
783 }
784
785 /// The scope a declaration lands in: a script's top-level declarations are
786 /// globals, everything else gets a slot.
787 /// Whether a binding declared *now* becomes a property of the global object.
788 ///
789 /// For a script, a top-level `var` and the top-level `let`/`const` are globals.
790 /// The `var` case is decided by the keyword rather than by the cursor position:
791 /// `var` is function-scoped, so a `var i` in a `for` head is still the same
792 /// binding as a `var i` in the body, even though the head has its own block.
793 fn declares_globally(&self, def: &VarDef) -> bool {
794 // A module's top-level declarations are *module*-scoped: they live in the module
795 // record, never on the global object. Two modules can both declare `var x`
796 // without seeing each other, which is the whole point.
797 if self.is_module {
798 return false;
799 }
800 // An `eval` body's lexical declarations belong to the environment §19.2.1.3 creates
801 // for that one evaluation, so they stay locals of the eval's own frame. Its `var`s
802 // do declare globally here — the runtime moves them into the caller's variable
803 // environment — because the compiler cannot tell whether the caller has a function.
804 if self.is_eval_body && def.is_lexical {
805 return false;
806 }
807 self.is_script && (!def.is_lexical || self.current_block == self.body_block)
808 }
809}
810
811/// The compiler's entry point.
812pub struct Compiler {
813 /// The text being compiled, kept so each function can record its own slice for
814 /// `Function.prototype.toString`.
815 source: Option<String>,
816 module: bool,
817 /// Whether the program is an **`eval` body** rather than a script.
818 ///
819 /// §19.2.1.3 declares an eval's `let`/`const`/`class` in a fresh declarative environment
820 /// created for that one evaluation, so they must not reach the realm's global lexical
821 /// table: `eval("let x = 3")` leaves `x` unbound afterwards, and judging by
822 /// `typeof xNonStrict` is exactly what `eval-code/direct/lex-env-distinct-let` does.
823 /// The `var`s are a separate matter — those belong to the caller's variable environment,
824 /// which the *runtime* resolves.
825 eval_body: bool,
826 /// Whether the program itself is the body of an `async` function.
827 ///
828 /// This is the reference's `JS_EVAL_FLAG_ASYNC`: the body may `await`, and its
829 /// completion value is wrapped so a returned promise is not adopted.
830 async_body: bool,
831 /// Enclosing functions, outermost first. The last entry is the current one.
832 stack: Vec<FnState>,
833 /// The private names visible at this point, innermost class body last.
834 ///
835 /// A stack rather than a field of `FnState` because a private name is *lexically* scoped
836 /// to the class body: a method, an arrow inside it and a class nested inside that arrow
837 /// all resolve against the same entries, and the parser accepts exactly that set
838 /// (`self.private` in `parser.rs`). `FnState` is per-function, so it would lose the outer
839 /// class's names the moment a method started.
840 private_scopes: Vec<std::collections::HashMap<String, PrivateUse>>,
841 /// Whether the expression [`Compiler::expr`] is about to compile is the one its
842 /// statement asked to discard.
843 ///
844 /// `FnState::discard_value` says "the statement's value is thrown away", which is only
845 /// ever true of the statement's own expression — an assignment nested inside it, as in
846 /// `f(x = 1)`, has a value that is very much used. Clearing the flag on the way in and
847 /// keeping the answer here is what tells the two apart; without it the nested store
848 /// consumed its value, `call` took the callee as its argument, and `f(x = 1)` inside a
849 /// function threw `undefined is not a function`.
850 discard_root: bool,
851}
852
853/// How a use site of a private name compiles.
854///
855/// The four cases come straight from the reference's `JSVarKindEnum`: the binding holds a
856/// symbol for a field, a function for a method or getter, and nothing at all for the `#a` half
857/// of a setter-only accessor pair.
858#[derive(Clone, Copy, PartialEq, Eq)]
859enum PrivateKind {
860 /// `#x = 1`: an own property keyed by the symbol in the binding.
861 Field,
862 /// `#m() {}`: the binding holds the function; a use site brand-checks the receiver.
863 Method,
864 /// `get #a() {}`: the binding holds the getter, and a read calls it.
865 Getter,
866 /// `set #a(v) {}` with no getter: `#a` is declared but never filled, and reading it is
867 /// the same `TypeError` as reading an uninitialised `const`.
868 Setter,
869}
870
871/// What the compiler knows about one `#name` where it is used.
872#[derive(Clone)]
873struct PrivateUse {
874 kind: PrivateKind,
875 /// `#a<set>` when the class defines a setter for this name.
876 ///
877 /// A second binding, not a second field of the first: the reference stores the setter
878 /// closure under `#a<set>` (`get_private_setter_name`) and reads it back by that name.
879 setter: Option<String>,
880}
881
882/// The class-scope bindings one class body needs, in declaration order.
883#[derive(Default)]
884struct ClassPlan {
885 /// `#x`, `#m`, `#a`, `#a<set>`, `<computed_field>0`, … — everything declared in a `const`
886 /// at class entry, in member order.
887 bindings: Vec<String>,
888 /// The private names, for the use sites inside the body.
889 uses: std::collections::HashMap<String, PrivateUse>,
890 /// Computed field keys, by element index, so the emission pass does not have to redo the
891 /// per-half counter that names them.
892 computed: std::collections::HashMap<usize, String>,
893 /// Whether the instance initialiser has to add the brand to `this`.
894 instance_brand: bool,
895 /// Whether the constructor itself has to carry the brand.
896 static_brand: bool,
897}
898
899impl ClassPlan {
900 /// Walk a class body once and decide every class-scope binding it needs.
901 ///
902 /// Order is the reference's: a member's binding is created when the member is parsed, so
903 /// `class C { #m(){} #x = 1 }` declares `#m` before `#x`, and a setter adds `#a<set>`
904 /// immediately after `#a`. Getting this order wrong renumbers every slot in the class and
905 /// the disassembly stops matching even when every instruction is right.
906 fn build(class: &Class) -> ClassPlan {
907 let mut plan = ClassPlan::default();
908 let mut instance_keys = 0usize;
909 let mut static_keys = 0usize;
910 for (index, element) in class.elements.iter().enumerate() {
911 match element {
912 ClassElement::Method {
913 key: PropName::Private(ident),
914 kind,
915 is_static,
916 ..
917 } => {
918 let name = format!("#{}", ident.name);
919 let first = !plan.uses.contains_key(&name);
920 if first {
921 plan.bindings.push(name.clone());
922 plan.uses.insert(
923 name.clone(),
924 PrivateUse {
925 kind: match kind {
926 MethodKind::Get => PrivateKind::Getter,
927 MethodKind::Set => PrivateKind::Setter,
928 _ => PrivateKind::Method,
929 },
930 setter: None,
931 },
932 );
933 }
934 match kind {
935 MethodKind::Set => {
936 let binding = format!("{name}<set>");
937 plan.bindings.push(binding.clone());
938 if let Some(use_) = plan.uses.get_mut(&name) {
939 use_.setter = Some(binding);
940 }
941 }
942 // A getter is what makes the name readable, so a pair that started
943 // as a setter becomes readable once the getter arrives.
944 MethodKind::Get => {
945 if let Some(use_) = plan.uses.get_mut(&name) {
946 use_.kind = PrivateKind::Getter;
947 }
948 }
949 _ => {}
950 }
951 if *is_static {
952 plan.static_brand = true;
953 } else {
954 plan.instance_brand = true;
955 }
956 }
957 ClassElement::Method {
958 key: PropName::Computed(_),
959 ..
960 } => {}
961 ClassElement::Method { .. } => {}
962 ClassElement::Field {
963 key: PropName::Private(ident),
964 ..
965 } => {
966 let name = format!("#{}", ident.name);
967 if !plan.uses.contains_key(&name) {
968 plan.bindings.push(name.clone());
969 plan.uses.insert(
970 name,
971 PrivateUse {
972 kind: PrivateKind::Field,
973 setter: None,
974 },
975 );
976 }
977 }
978 ClassElement::Field {
979 key: PropName::Computed(_),
980 is_static,
981 ..
982 } => {
983 let index_in_half = if *is_static {
984 static_keys += 1;
985 static_keys - 1
986 } else {
987 instance_keys += 1;
988 instance_keys - 1
989 };
990 let binding = computed_field_binding(index_in_half, *is_static);
991 plan.bindings.push(binding.clone());
992 plan.computed.insert(index, binding);
993 }
994 ClassElement::Field { .. } | ClassElement::StaticBlock { .. } => {}
995 }
996 }
997 plan
998 }
999
1000 /// How a private name used inside the body compiles, or `None` if no enclosing class
1001 /// declares it.
1002 fn find<'a>(compiler: &'a Compiler, name: &str) -> Option<&'a PrivateUse> {
1003 compiler
1004 .private_scopes
1005 .iter()
1006 .rev()
1007 .find_map(|scope| scope.get(name))
1008 }
1009}
1010
1011impl Compiler {
1012 /// The exact source text of a function, for `Function.prototype.toString`.
1013 ///
1014 /// §20.2.3.5 requires the *original* text: a function must stringify back to what
1015 /// was written, comments and odd spacing included. Slicing the recorded span out of
1016 /// the whole source is the only way to get that — rebuilding it from the AST would
1017 /// normalise the text, and answering `[native code]` for a script function (which is
1018 /// what this engine used to do) makes the result useless for feature detection and
1019 /// for libraries that read their own source.
1020 ///
1021 /// Top-level bodies have no single expression span, so their `source` stays `None`
1022 /// and `toString` falls back to the calling convention the spec allows.
1023 fn function_source(
1024 &self,
1025 span: Option<(usize, usize)>,
1026 line: u32,
1027 column: u32,
1028 ) -> Option<String> {
1029 let source = self.source.as_ref()?;
1030 let span = span?;
1031 let bytes = source.as_bytes();
1032 let start = span.0;
1033 let end = span.1;
1034 if start >= bytes.len() || end > bytes.len() || start >= end {
1035 let _ = (line, column);
1036 return None;
1037 }
1038 Some(source.get(start..end)?.to_string())
1039 }
1040}
1041
1042/// Compile a script.
1043pub fn compile_script(program: &Program) -> Result<CompiledFunction, SyntaxError> {
1044 Compiler::new(false).compile(program)
1045}
1046
1047/// Compile a script, keeping its text so `Function.prototype.toString` can answer with
1048/// the original source.
1049///
1050/// The separate entry point rather than a parameter on [`compile_script`] because the
1051/// tests and the disassembler compile from an AST they built themselves and have no
1052/// source to give; they keep the `None` behaviour they already relied on.
1053pub fn compile_script_with_source(
1054 program: &Program,
1055 source: &str,
1056) -> Result<CompiledFunction, SyntaxError> {
1057 let mut compiler = Compiler::new(false);
1058 compiler.source = Some(source.to_string());
1059 compiler.compile(program)
1060}
1061
1062/// [`compile_script_with_source`] for a module.
1063pub fn compile_module_with_source(
1064 program: &Program,
1065 source: &str,
1066) -> Result<CompiledFunction, SyntaxError> {
1067 let mut compiler = Compiler::new(true);
1068 compiler.source = Some(source.to_string());
1069 compiler.compile(program)
1070}
1071
1072/// Compile a script whose top level is the body of an `async` function.
1073/// The body is an ordinary script in every other way — it still reports a completion value
1074/// — but the value is wrapped in `{value}` and the function's kind is `Async`, so running
1075/// it answers a promise instead of a value. The wrapper is what keeps that promise from
1076/// being *adopted*: `await 1` completes with `1`, and the reference resolves to
1077/// `{value: 1}` rather than to `1` — the same shape `std.evalScript(…, {async: true})`
1078/// documents.
1079pub fn compile_script_suspensible(program: &Program) -> Result<CompiledFunction, SyntaxError> {
1080 Compiler::for_suspensible_script().compile(program)
1081}
1082
1083/// Compile a module.
1084pub fn compile_module(program: &Program) -> Result<CompiledFunction, SyntaxError> {
1085 Compiler::new(true).compile(program)
1086}
1087
1088/// Compile a direct `eval` body that inherits private names from its caller.
1089///
1090/// `class C { #m = 44; f() { return eval("this.#m") } }` is legal — private names are
1091/// lexically scoped and the eval runs inside the caller's scope — but the names live in the
1092/// *call site's* compilation unit, so they have to be handed over. Seeding them as the
1093/// outermost private scope is what lets the eval resolve `#m` to the caller's binding: the
1094/// read compiles as an ordinary name lookup of `#m`, which at run time finds the caller's
1095/// slot through the same `eval`-scope machinery every other inherited name uses.
1096///
1097/// `suspensible` selects the `{async: true}` form (`std.evalScript(s, {async: true})`), whose
1098/// body may `await`.
1099pub fn compile_eval_with_private(
1100 program: &Program,
1101 private: &[EvalPrivate],
1102 suspensible: bool,
1103 eval_body: bool,
1104) -> Result<CompiledFunction, SyntaxError> {
1105 let mut compiler = if suspensible {
1106 let mut compiler = Compiler::new(false);
1107 compiler.async_body = true;
1108 compiler
1109 } else {
1110 Compiler::new(false)
1111 };
1112 // `evalScript` reaches this same function but evaluates a *global script*, whose
1113 // top-level `let` is a global lexical binding; only a real `eval` gets the
1114 // per-evaluation environment §19.2.1.3 creates.
1115 compiler.eval_body = eval_body;
1116 if !private.is_empty() {
1117 let scope: std::collections::HashMap<String, PrivateUse> = private
1118 .iter()
1119 .map(|entry| {
1120 (
1121 entry.name.clone(),
1122 PrivateUse {
1123 kind: match entry.kind {
1124 EvalPrivateKind::Field => PrivateKind::Field,
1125 EvalPrivateKind::Method => PrivateKind::Method,
1126 EvalPrivateKind::Getter => PrivateKind::Getter,
1127 EvalPrivateKind::Setter => PrivateKind::Setter,
1128 },
1129 setter: entry.setter.clone(),
1130 },
1131 )
1132 })
1133 .collect();
1134 compiler.private_scopes.push(scope);
1135 }
1136 compiler.compile(program)
1137}
1138
1139impl Compiler {
1140 /// Create a compiler.
1141 pub fn new(module: bool) -> Compiler {
1142 Compiler {
1143 source: None,
1144 module,
1145 eval_body: false,
1146 async_body: false,
1147 stack: Vec::new(),
1148 private_scopes: Vec::new(),
1149 discard_root: false,
1150 }
1151 }
1152
1153 /// Create a compiler for an `eval` body.
1154 /// Create a compiler for a script whose top level is an `async` function body.
1155 fn for_suspensible_script() -> Compiler {
1156 Compiler {
1157 source: None,
1158 module: false,
1159 eval_body: false,
1160 async_body: true,
1161 stack: Vec::new(),
1162 private_scopes: Vec::new(),
1163 discard_root: false,
1164 }
1165 }
1166
1167 /// Compile a whole program into its top-level function.
1168 pub fn compile(mut self, program: &Program) -> Result<CompiledFunction, SyntaxError> {
1169 let mut state = FnState::new("<eval>", FunctionKind::Normal);
1170 // A module body is *not* a script: it has no completion value, so no hidden
1171 // `<ret>` local and no `put_loc0` before each statement. What it shares with one
1172 // is having no `arguments` of its own and no receiver — see `is_module`.
1173 state.is_script = !self.module;
1174 state.is_module = self.module;
1175 state.is_eval_body = self.eval_body;
1176 if self.module {
1177 state.module = Some(ModuleMeta::default());
1178 }
1179 state.strict = program.strict || self.module;
1180 state.line = program.span.start.line;
1181 state.column = program.span.start.column;
1182 // Locals are numbered in declaration order; `<ret>` is always slot 0.
1183 //
1184 // `var_block` has to grow in step with `vars`: it is indexed by slot, so a
1185 // slot that only appears in one of the two arrays shifts every later
1186 // binding's block and silently loses the temporal-dead-zone marking for
1187 // the script's own blocks. A function frame has no `<ret>`, which is why
1188 // the misalignment only showed up at the top level.
1189 if !self.module {
1190 state.vars.push(VarDef::var("<ret>"));
1191 state.var_block.push(FUNCTION_SCOPE);
1192 }
1193 self.stack.push(state);
1194 // The body is its own scope, keyed by the position of the program.
1195 // The script body needs a key no statement can produce. Statement keys are
1196 // source offsets, and the program's own start offset is `0` — which is also
1197 // the offset of the first statement, so a top-level `{ let x }` or
1198 // `for (let i …)` used to share the body's block and lose its scope.
1199 let body_key = SCRIPT_BODY;
1200 self.push_block(body_key, NO_PARENT);
1201 self.state().body_block = body_key;
1202 // A module body opens with a re-entry guard. The host evaluates a module exactly
1203 // once, so the guard never fires in practice — but the reference emits it, and a
1204 // module function called a second time (through `eval` of its own source, say)
1205 // must not run its body again.
1206 let module_guard = self.module.then(|| self.new_label());
1207 if let Some(body) = module_guard {
1208 // The guard wraps the *hoisting* too: a second evaluation of the same module
1209 // body must not even re-create its function declarations.
1210 self.emit(Opcode::PushThis, &[]);
1211 self.emit_jump(Opcode::IfFalse, body, &[]);
1212 }
1213 self.hoist(&program.body, body_key)?;
1214 // The scope entry is what emits the hoisted `fclosure`/store pairs, so it has to
1215 // come before the guard's `return_undef`: the reference's jump target sits past
1216 // both, and a second evaluation therefore re-creates nothing.
1217 self.emit_scope_enter(body_key);
1218 if let Some(body) = module_guard {
1219 self.emit(Opcode::ReturnUndef, &[]);
1220 self.place_label(body);
1221 }
1222 // Through `stmts` rather than the loop, so a `using` region at the top level of an
1223 // eval'd body or a module gets its disposal epilogue like any other block.
1224 self.stmts(&program.body)?;
1225 if self.module {
1226 // A module has no completion value; its body simply ends.
1227 self.emit(Opcode::Undefined, &[]);
1228 self.emit(Opcode::ReturnAsync, &[]);
1229 // Top-level `await` makes the body an async function, so the host runs it as
1230 // a coroutine and waits. Without this the `await` opcode would suspend in a
1231 // body that nothing knows how to resume — which is what "a generator body ran
1232 // as an ordinary call" was reporting.
1233 if self.cur().has_await {
1234 self.state().kind = FunctionKind::Async;
1235 }
1236 } else if self.async_body {
1237 // An async body reports its completion value the same way, but through an
1238 // object: the function answers a promise, and resolving that promise *with*
1239 // the completion value would adopt a promise completion instead of reporting
1240 // it. `{value}` is what makes `evalScript("Promise.resolve(7)", {async:true})`
1241 // resolve to `{value: <promise>}` rather than to `7`.
1242 //
1243 // The shape is the reference's, byte for byte (`quickjs.c`: "wrap the return
1244 // value in an object so that promises can be safely returned").
1245 self.emit(Opcode::Object, &[]);
1246 self.emit(Opcode::Dup, &[]);
1247 self.emit(Opcode::GetLoc, &[Op::Slot(Slot::Loc(0))]);
1248 self.emit(Opcode::PutField, &[Op::Atom(Atom::from_text("value"))]);
1249 self.emit(Opcode::Return, &[]);
1250 self.state().kind = FunctionKind::Async;
1251 } else {
1252 // The program's value is whatever the last expression statement stored in
1253 // the hidden `<ret>` local; `put_loc0`/`get_loc0` folding turns the common
1254 // case into a single `set_loc0`.
1255 self.emit(Opcode::GetLoc, &[Op::Slot(Slot::Loc(0))]);
1256 self.emit(Opcode::Return, &[]);
1257 }
1258 Ok(self.finish_current())
1259 }
1260
1261 // -- emitting ----------------------------------------------------------
1262
1263 fn state(&mut self) -> &mut FnState {
1264 self.stack.last_mut().expect("a function is being compiled")
1265 }
1266
1267 fn cur(&self) -> &FnState {
1268 self.stack.last().expect("a function is being compiled")
1269 }
1270
1271 fn emit(&mut self, op: Opcode, operands: &[Op]) {
1272 self.state().label_since_insn = false;
1273 let pos = self.cur().cur_pos;
1274 self.state().insns.push(Insn::Fixed {
1275 op,
1276 operands: operands.to_vec(),
1277 });
1278 self.state().insn_pos.push(pos);
1279 }
1280
1281 /// Reset the script's hidden return value to `undefined`.
1282 ///
1283 /// Called at the start of every statement that does not itself produce the
1284 /// program's value, which is how the reference keeps `if`/loop results from
1285 /// leaking into an eval result.
1286 fn reset_value(&mut self) {
1287 if !self.cur().is_script {
1288 return;
1289 }
1290 self.emit(Opcode::Undefined, &[]);
1291 self.emit(Opcode::PutLoc, &[Op::Slot(Slot::Loc(0))]);
1292 self.state().leaves_value = false;
1293 }
1294
1295 /// Whether `name` is a local or argument slot rather than a global.
1296 fn is_slot(&self, name: &str) -> bool {
1297 self.cur().vars.iter().any(|v| v.name == name)
1298 || self.cur().args.iter().any(|a| a.name == name)
1299 }
1300
1301 /// `with (object) body`
1302 ///
1303 /// The boxed object lives in a hidden local marked [`VarKind::With`]. A local is
1304 /// what makes the object reachable from a closure created inside the block, and it
1305 /// is also what lets an `eval` find it: the runtime collects the active `With`
1306 /// locals of every frame and resolves names against them before the realm.
1307 ///
1308 /// Inside the block every name reference is spelled as "look in the with objects
1309 /// first", innermost outwards, and falls through to the ordinary access. The test is
1310 /// `in`, which is `HasProperty` — the same question the spec's Object Environment
1311 /// Record asks.
1312 fn with_stmt(&mut self, object: &Expr, body: &Stmt) -> Result<(), SyntaxError> {
1313 // `with (e) s` completes with `UpdateEmpty(s, undefined)` — an *empty* body still
1314 // produces `undefined`, it does not inherit the previous statement's value. So
1315 // `eval("1; with({}){}")` is `undefined` while `eval("1; with({}){2;}")` is `2`.
1316 // Without this the sticky `<ret>` local leaked the `1` through, the same way it
1317 // would for an `if` or a loop.
1318 self.reset_value();
1319 let name = self.next_with_name();
1320 // The object expression is evaluated *outside* the scope it introduces, so no
1321 // wrapper may be emitted for the names it mentions.
1322 let saved = std::mem::take(&mut self.state().with_names);
1323 self.expr(object)?;
1324 self.state().with_names = saved;
1325 self.emit(Opcode::ToObject, &[]);
1326 self.declare_hidden_local(&name, VarKind::With);
1327 // Pushed before the store so the store itself is not guarded by an *outer*
1328 // `with` — the object being stored is the new one, not something to look up.
1329 self.state().with_names.push(name.clone());
1330 self.emit_var(VarAction::Put, &name);
1331 let result = self.stmt(body);
1332 self.state().with_names.pop();
1333 result
1334 }
1335
1336 /// A hidden-local name for one `with` block, distinct from every enclosing one.
1337 fn next_with_name(&self) -> String {
1338 let depth = self.cur().with_names.len();
1339 if depth == 0 {
1340 "<with>".to_string()
1341 } else {
1342 format!("<with{depth}>")
1343 }
1344 }
1345
1346 /// Declare a hidden local that must stay a *local* even in a script.
1347 ///
1348 /// A script's `var` is a property of the global object, but the `with` object is not
1349 /// part of the source program's name space at all — it only exists for the compiler
1350 /// and the runtime — so it goes straight into the frame's slot list.
1351 fn declare_hidden_local(&mut self, name: &str, kind: VarKind) {
1352 let state = self.state();
1353 if state.vars.iter().any(|v| v.name == name) {
1354 return;
1355 }
1356 state.var_block.push(FUNCTION_SCOPE);
1357 state.vars.push(VarDef {
1358 kind,
1359 ..VarDef::var(name)
1360 });
1361 }
1362
1363 /// Emit a name access, guarded by every active `with` object.
1364 ///
1365 /// Each guard is `get_loc <with>; push_atom_value name; in; if_false <next>` and then
1366 /// the read itself; the outer guards and the plain access are what the `if_false`
1367 /// jumps to, so the innermost object wins.
1368 fn emit_with_guarded(&mut self, action: VarAction, name: &str) {
1369 let names = self.visible_with_names(name);
1370 let done = self.new_label();
1371 let mut starts = Vec::new();
1372 // Innermost object first: the last `with` opened is the one that shadows the
1373 // others, so its guard has to be the first chance to satisfy the name.
1374 for with_name in names.iter().rev() {
1375 let next = self.new_label();
1376 // `with_has_var` takes the object and carries the name as an atom. It is not
1377 // `in`: an Object Environment Record also consults `Symbol.unscopables`, so
1378 // `globalThis[Symbol.unscopables] = {v: true}` leaves `v` to the outer scope.
1379 self.emit_var(VarAction::Get, with_name);
1380 self.emit(Opcode::WithHasVar, &[Op::Atom(Atom::from_text(name))]);
1381 self.emit_jump(Opcode::IfFalse, next, &[]);
1382 starts.push(next);
1383 // The operation is `with_get_var`/`with_put_var`, not a plain property access:
1384 // `GetBindingValue`/`SetMutableBinding` ask `HasProperty` **again** before
1385 // getting or setting. That second question is observable — a proxy's `has`
1386 // trap runs one more time (`get-binding-value-call-with-proxy-env` logs
1387 // `has, get unscopables, has, get`) and an `unscopables` getter that deletes
1388 // the property leaves a binding that has gone, which strict code must report
1389 // as a `ReferenceError` rather than write to.
1390 match action {
1391 // A store already has its value on the stack, and `with_put_var` takes the
1392 // pair in `put_field`'s order: object first, then the value.
1393 VarAction::Put | VarAction::PutInit => {
1394 self.emit_var(VarAction::Get, with_name);
1395 self.emit(Opcode::Swap, &[]);
1396 self.emit(Opcode::WithPutVar, &[Op::Atom(Atom::from_text(name))]);
1397 }
1398 _ => {
1399 self.emit_var(VarAction::Get, with_name);
1400 self.emit(Opcode::WithGetVar, &[Op::Atom(Atom::from_text(name))]);
1401 }
1402 }
1403 self.emit_jump(Opcode::Goto, done, &[]);
1404 self.place_label(next);
1405 }
1406 self.emit_var(action, name);
1407 self.place_label(done);
1408 }
1409
1410 /// The `with` blocks that can shadow `name`, innermost last.
1411 ///
1412 /// A parameter or a local of this function is *inside* every `with` this function
1413 /// opened, so those shadow it; a `with` that was already open when this function was
1414 /// created is outside the function's own environment, so the local wins and that
1415 /// block is skipped. See [`FnState::inherited_with_names`].
1416 fn visible_with_names(&self, name: &str) -> Vec<String> {
1417 let state = self.cur();
1418 // The hidden `<with…>` locals are how the guard reaches its own objects, so they
1419 // must never be guarded themselves — not by their own block (which would recurse)
1420 // and not by an enclosing one (which would ask a `with` object whether it has a
1421 // property called `<with>`, always answer no, and waste the chain). Source can
1422 // never spell these names, so exempting all of them changes nothing else.
1423 if state.with_names.iter().any(|hidden| hidden == name) {
1424 return Vec::new();
1425 }
1426 let start = if self.is_slot(name) {
1427 state.inherited_with_names
1428 } else {
1429 0
1430 };
1431 state.with_names[start..]
1432 .iter()
1433 .filter(|hidden| hidden.as_str() != name)
1434 .cloned()
1435 .collect()
1436 }
1437
1438 /// Compile `x` as a **reference** to the with object's property, resolving the object
1439 /// once for the whole read-modify-write.
1440 ///
1441 /// `x += 1`, `x++` and `x ||= v` read and then write the same name. Two independent
1442 /// guards get that wrong the moment the read changes the answer: with
1443 /// `{ get x(){ delete this.x; return 2 } }`, `with (o) { x++ }` reads through the
1444 /// getter — which removes the property — and then the write's own guard no longer
1445 /// finds it, so the store landed on the *global* `x` and `o.x` stayed `undefined`. The
1446 /// reference resolves the base once (`with_make_ref`) and reuses it for both halves.
1447 ///
1448 /// The same shape comes out of compiling the name as a **member** of the with object:
1449 /// `get_field2`/`put_field` already evaluate their receiver once, and the hidden
1450 /// `<with>` local holds exactly the object the guard just tested. So each candidate
1451 /// object gets `if the name is bound here, compile as `this.name`; otherwise fall
1452 /// through to the next object`, and the last fallback is the ordinary name.
1453 fn with_reference(
1454 &mut self,
1455 name: &str,
1456 guarded: &mut dyn FnMut(&mut Self, &str) -> Result<(), SyntaxError>,
1457 plain: &mut dyn FnMut(&mut Self) -> Result<(), SyntaxError>,
1458 ) -> Result<(), SyntaxError> {
1459 let targets = self.visible_with_names(name);
1460 if targets.is_empty() {
1461 return plain(self);
1462 }
1463 let done = self.new_label();
1464 let result = self.with_reference_inner(name, &targets, guarded, plain, done);
1465 self.place_label(done);
1466 result
1467 }
1468
1469 fn with_reference_inner(
1470 &mut self,
1471 name: &str,
1472 targets: &[String],
1473 guarded: &mut dyn FnMut(&mut Self, &str) -> Result<(), SyntaxError>,
1474 plain: &mut dyn FnMut(&mut Self) -> Result<(), SyntaxError>,
1475 done: Label,
1476 ) -> Result<(), SyntaxError> {
1477 let Some((innermost, outer)) = targets.split_last() else {
1478 return plain(self);
1479 };
1480 let next = self.new_label();
1481 self.emit_var(VarAction::Get, innermost);
1482 self.emit(Opcode::WithHasVar, &[Op::Atom(Atom::from_text(name))]);
1483 self.emit_jump(Opcode::IfFalse, next, &[]);
1484 guarded(self, innermost)?;
1485 self.emit_jump(Opcode::Goto, done, &[]);
1486 self.place_label(next);
1487 self.with_reference_inner(name, outer, guarded, plain, done)
1488 }
1489
1490 /// `delete name`, honouring any enclosing `with`.
1491 ///
1492 /// Inside a `with` the name may be a property of the with object, and then `delete`
1493 /// removes *that* property instead of touching the outer binding —
1494 /// `with (o) { delete p }` answers `true` and leaves `o` without `p` even when a
1495 /// global `p` exists. Left to the resolver it deleted the global instead, so the
1496 /// `statements/with/S12.10_A1.*` family then saw a `ReferenceError` on every later
1497 /// `p`.
1498 ///
1499 /// Emitted as a sequence here rather than during resolution because a resolution slot
1500 /// holds one instruction, and this is a loop over the with objects plus a fallback.
1501 fn delete_ident(&mut self, name: &str) {
1502 let names = self.cur().with_names.clone();
1503 let done = self.new_label();
1504 let mut starts = Vec::new();
1505 if !names.is_empty() {
1506 self.state().emitting_with_guard = true;
1507 // Innermost object first, like the read/write guard: the last `with` opened is
1508 // the one that shadows the others.
1509 for with_name in names.iter().rev() {
1510 let next = self.new_label();
1511 self.emit_var(VarAction::Get, with_name);
1512 self.emit(Opcode::WithHasVar, &[Op::Atom(Atom::from_text(name))]);
1513 self.emit_jump(Opcode::IfFalse, next, &[]);
1514 // `delete` takes the receiver then the key.
1515 self.emit_var(VarAction::Get, with_name);
1516 self.emit(Opcode::PushAtomValue, &[Op::Atom(Atom::from_text(name))]);
1517 self.emit(Opcode::Delete, &[]);
1518 self.emit_jump(Opcode::Goto, done, &[]);
1519 self.place_label(next);
1520 starts.push(next);
1521 }
1522 self.state().emitting_with_guard = false;
1523 }
1524 // The fallback: not a property of any with object, so the ordinary rule applies.
1525 let pos = self.cur().cur_pos;
1526 self.state().insns.push(Insn::DeleteVar {
1527 name: name.to_string(),
1528 });
1529 self.state().insn_pos.push(pos);
1530 if !names.is_empty() {
1531 self.place_label(done);
1532 }
1533 }
1534
1535 fn emit_var(&mut self, action: VarAction, name: &str) {
1536 // Peephole: `put_x v` followed by `get_x v` becomes `set_x v`, which
1537 // stores and keeps the value in one instruction. The reference does this
1538 // in a post-pass; folding it at emit time keeps instruction indices
1539 // stable, which matters because labels are recorded as indices.
1540 //
1541 // Only slots have a `set_` form: a global is stored with `put_var` and
1542 // read with `get_var`, and the reference does not fold those.
1543 //
1544 // A label between the two cancels the fold. `set_x v` leaves the value on
1545 // the stack, which is only equivalent when the read immediately follows the
1546 // store; when a jump target sits in between, the store must *consume* the
1547 // value and the read must fetch it afresh. A loop head is exactly that
1548 // case — `for (var i = 0; i < 3; i++)` stores the initialiser, then the
1549 // condition re-reads it — and folding across the label would make the
1550 // condition compare whatever the previous iteration left on the stack.
1551 if action == VarAction::Get {
1552 let is_slot = self.is_slot(name);
1553 let at_label = std::mem::take(&mut self.state().label_since_insn);
1554 //
1555 // `arguments` is excluded because the reference treats it as a special
1556 // binding: it is initialised once and read many times, and folding its
1557 // initialisation into a `set_` would leave the object on the stack where
1558 // the reference leaves nothing.
1559 if is_slot
1560 && name != "arguments"
1561 && !at_label
1562 && let Some(Insn::Var {
1563 action: previous,
1564 name: previous_name,
1565 ..
1566 }) = self.state().insns.last_mut()
1567 && *previous == VarAction::Put
1568 && previous_name == name
1569 {
1570 *previous = VarAction::Set;
1571 return;
1572 }
1573 }
1574 // Inside a `with`, every name lookup consults the with objects first. Two names
1575 // are exempt:
1576 //
1577 // * the hidden `<with…>` locals themselves, or the guard would recurse;
1578 // * a name this function **declares** — a parameter, a `var`, or a `let` of the
1579 // current body. `with` sits *outside* the function's own environment, so a
1580 // function declared inside a `with` still resolves its own bindings first:
1581 // `with (o) { function f(){ var value = "x" } }` writes `f`'s local `value`, not
1582 // `o.value`. Guarding it anyway wrote through to the with object whenever it
1583 // happened to have the name, which is why
1584 // `statements/with/S12.10_A1.7` saw `myObj.value` change. The runtime's
1585 // `eval_binding_value` already models the same order.
1586 let guarded = !self.visible_with_names(name).is_empty()
1587 && matches!(action, VarAction::Get | VarAction::Put | VarAction::PutInit)
1588 && !self.state().emitting_with_guard;
1589 if guarded {
1590 self.state().emitting_with_guard = true;
1591 self.emit_with_guarded(action, name);
1592 self.state().emitting_with_guard = false;
1593 return;
1594 }
1595 let block = self.cur().current_block;
1596 self.state().label_since_insn = false;
1597 let pos = self.cur().cur_pos;
1598 let in_params = self.cur().in_params;
1599 self.state().insns.push(Insn::Var {
1600 action,
1601 name: name.to_string(),
1602 block,
1603 in_params,
1604 });
1605 self.state().insn_pos.push(pos);
1606 }
1607
1608 fn new_label(&mut self) -> Label {
1609 let state = self.state();
1610 state.labels.push(None);
1611 Label(state.labels.len() as u32 - 1)
1612 }
1613
1614 fn place_label(&mut self, label: Label) {
1615 let index = self.cur().insns.len();
1616 self.state().label_since_insn = true;
1617 self.state().labels[label.0 as usize] = Some(index);
1618 }
1619
1620 fn emit_jump(&mut self, op: Opcode, label: Label, extra: &[Op]) {
1621 let mut operands = vec![Op::Label(label)];
1622 operands.extend_from_slice(extra);
1623 self.emit(op, &operands);
1624 }
1625
1626 // -- scopes ------------------------------------------------------------
1627
1628 /// Start a new lexical scope inside `parent`.
1629 fn push_block(&mut self, key: u64, parent: u64) {
1630 let state = self.state();
1631 if !state.blocks.iter().any(|b| b.key == key) {
1632 state.blocks.push(Block { key, parent });
1633 }
1634 state.current_block = key;
1635 }
1636
1637 /// Emit the code that runs when a lexical scope is entered.
1638 ///
1639 /// Every `let`/`const`/`class` binding starts out in the temporal dead zone,
1640 /// so entering its block marks it uninitialised. Hoisted function
1641 /// declarations are created here instead, which is why a call before the
1642 /// declaration still works.
1643 ///
1644 /// The order is not obvious: bindings are emitted in *reverse* declaration
1645 /// order, because the reference walks its scope chain, which is built by
1646 /// prepending.
1647 fn emit_scope_enter(&mut self, block: u64) {
1648 // Only *this* scope's hoisted declarations are consumed here; the rest stay in the
1649 // list for the scope that owns them. `std::mem::take` used to empty the whole list,
1650 // so entering an outer scope threw away every nested block's function
1651 // declarations: `function h(){ { function k(){} } return k; }` answered
1652 // `undefined`, and `{ function g(){} }` was `undefined` even *inside* the block.
1653 // That is one Annex B rule the engine otherwise implements (a sloppy-mode function
1654 // in a block is also a `var` of the enclosing function), and it is what makes the
1655 // `for (const ctor of ctors) { function f(){} … }` shape in test262 work.
1656 let mut hoisted = std::mem::take(&mut self.state().hoisted);
1657 let mut rest = Vec::with_capacity(hoisted.len());
1658 let mut mine: Vec<(HoistTarget, u32)> = Vec::new();
1659 for (owner, target, pool_index) in hoisted.drain(..) {
1660 if owner == block {
1661 mine.push((target, pool_index));
1662 } else {
1663 rest.push((owner, target, pool_index));
1664 }
1665 }
1666 self.state().hoisted = rest;
1667 mine.sort_by_key(|(target, _)| match target {
1668 HoistTarget::Arg(index) | HoistTarget::Loc(index) => *index,
1669 HoistTarget::Global(_) => u32::MAX,
1670 });
1671 for (target, pool_index) in mine {
1672 self.emit(Opcode::Fclosure, &[Op::Const(pool_index)]);
1673 match target {
1674 HoistTarget::Arg(index) => self.emit(Opcode::PutArg, &[Op::Slot(Slot::Arg(index))]),
1675 HoistTarget::Loc(index) => self.emit(Opcode::PutLoc, &[Op::Slot(Slot::Loc(index))]),
1676 HoistTarget::Global(name) => {
1677 // A global binding lives in a reference cell, so the store
1678 // goes through `put_var_ref` while reads use `get_var`.
1679 let block = self.cur().current_block;
1680 let pos = self.cur().cur_pos;
1681 let in_params = self.cur().in_params;
1682 self.state().insns.push(Insn::Var {
1683 action: VarAction::PutRef,
1684 name,
1685 block,
1686 in_params,
1687 });
1688 self.state().insn_pos.push(pos);
1689 }
1690 }
1691 }
1692 for index in self.block_vars_reversed(block) {
1693 self.emit(
1694 Opcode::SetLocUninitialized,
1695 &[Op::Slot(Slot::Loc(index as u32))],
1696 );
1697 }
1698 }
1699
1700 /// Emit the code that runs when a lexical scope is exited.
1701 ///
1702 /// A captured binding has to be closed: detaching its reference cell freezes
1703 /// the value the binding had when the block ended, which is what a closure
1704 /// created inside the block must keep seeing.
1705 fn emit_scope_leave(&mut self, block: u64) {
1706 for index in self.block_vars_reversed(block) {
1707 if self.cur().vars[index].is_captured {
1708 self.emit(Opcode::CloseLoc, &[Op::Slot(Slot::Loc(index as u32))]);
1709 }
1710 }
1711 }
1712
1713 /// Locals declared in `block`, in reverse declaration order.
1714 fn block_vars_reversed(&self, block: u64) -> Vec<usize> {
1715 let state = self.cur();
1716 let mut out: Vec<usize> = (0..state.vars.len())
1717 .filter(|index| {
1718 state.var_block.get(*index).copied() == Some(block)
1719 && state.vars[*index].is_lexical
1720 // A derived constructor's `this` is lexical but is not initialised by
1721 // entering the scope: `check_ctor` proves it, so its dead-zone marker
1722 // was emitted with the constructor's own prologue.
1723 && state.vars[*index].name != "this"
1724 })
1725 .collect();
1726 out.reverse();
1727 out
1728 }
1729
1730 /// Declare a local, even at the top level of a script.
1731 ///
1732 /// A `catch` parameter is always a local: the reference puts it in the
1733 /// function's own variable list (`1: catch e`), never in the global object,
1734 /// because it only exists while the handler runs.
1735 fn declare_local(&mut self, _name: &str, def: VarDef) -> u32 {
1736 let state = self.state();
1737 let index = state.vars.len() as u32;
1738 // A `catch` parameter belongs to a scope even though it is not lexical: the
1739 // runtime instantiates it per handler entry, but it never sits in the
1740 // temporal dead zone.
1741 let block = if def.is_lexical || def.kind == crate::bytecode::VarKind::Catch {
1742 state.current_block
1743 } else {
1744 0
1745 };
1746 state.var_block.push(block);
1747 state.vars.push(def);
1748 index
1749 }
1750
1751 fn declare(&mut self, name: &str, def: VarDef) -> u32 {
1752 if self.cur().is_module
1753 && self.cur().current_block == self.cur().body_block
1754 && !matches!(def.kind, VarKind::Using | VarKind::UsingMethod)
1755 {
1756 // Only the body's own block: a `let` inside a module-level `{}` is still an
1757 // ordinary local of that block, not a module variable.
1758 //
1759 // A `using` binding is excluded on purpose, and the reference excludes it in
1760 // the same place (`var_def_type != JS_VAR_DEF_USING`, with the comment
1761 // "'using' variables are currently not exported in modules"): a module-level
1762 // `using` is an ordinary *local* of the module body function, not a module
1763 // cell. Two things follow, and both are what the reference does — `export {a}`
1764 // of a `using` binding is "exported variable 'a' does not exist", and
1765 // disposal works, because the disposal epilogue addresses locals by slot.
1766 //
1767 // The hidden dispose-method variable is excluded for a stronger reason: it is
1768 // *always* a local (`add_scope_var` in the reference), and it must sit
1769 // immediately after its value so `using_dispose` can find it at `slot + 1`.
1770 return self.declare_module(name, &def);
1771 }
1772 if self.cur().declares_globally(&def) {
1773 self.declare_global(name, &def);
1774 return 0;
1775 }
1776 let state = self.state();
1777 let index = state.vars.len() as u32;
1778 let block = if def.is_lexical {
1779 state.current_block
1780 } else {
1781 0
1782 };
1783 state.var_block.push(block);
1784 state.vars.push(def);
1785 index
1786 }
1787
1788 /// Declare a `using` binding and its cached dispose method, returning both slots.
1789 ///
1790 /// The two are adjacent by construction, because `using_dispose` addresses the pair as
1791 /// `(value, value + 1)` — the reference does the same and documents the constraint.
1792 fn declare_using(&mut self, name: &str) -> (u32, u32) {
1793 let mut def = VarDef::lexical(name);
1794 def.kind = VarKind::Using;
1795 // A `using` binding is immutable, exactly like a `const`: assigning to one is a
1796 // `TypeError` at run time, which is what `using-invalid-assignment-*-for` assert.
1797 // `VarDef::lexical` leaves `is_const` false, so the store would have landed.
1798 def.is_const = true;
1799 let value = self.declare(name, def);
1800 let mut method = VarDef::lexical(using_method_name(name));
1801 method.kind = VarKind::UsingMethod;
1802 let method_slot = self.declare(&using_method_name(name), method);
1803 (value, method_slot)
1804 }
1805
1806 /// The slot a `using` binding's dispose method lives in.
1807 fn using_method_slot(&self, name: &str) -> Option<u32> {
1808 let hidden = using_method_name(name);
1809 self.cur()
1810 .vars
1811 .iter()
1812 .position(|var| var.name == hidden)
1813 .map(|index| index as u32)
1814 }
1815
1816 // -- statements --------------------------------------------------------
1817
1818 fn stmt(&mut self, stmt: &Stmt) -> Result<(), SyntaxError> {
1819 self.stmt_labelled(stmt, &[])
1820 }
1821
1822 /// Compile a statement that a chain of labels names.
1823 ///
1824 /// Only a loop consumes `labels`; every other statement ignores them (the
1825 /// parser has already rejected a label on a statement that cannot use it).
1826 fn stmt_labelled(&mut self, stmt: &Stmt, labels: &[String]) -> Result<(), SyntaxError> {
1827 // Only a *top-level* expression statement supplies the program's value.
1828 let saved = self.cur().leaves_value;
1829 self.state().leaves_value =
1830 matches!(stmt.kind, StmtKind::Expr(_)) && self.cur().stmt_depth == 0;
1831 self.state().stmt_depth += 1;
1832 let result = self.stmt_inner(stmt, labels);
1833 self.state().stmt_depth -= 1;
1834 // A nested statement never contributes the program's value, so the flag
1835 // the wrapper set above is what survives.
1836 let produced = self.cur().leaves_value && self.cur().stmt_depth == 0;
1837 self.state().leaves_value = produced;
1838 let _ = saved;
1839 result
1840 }
1841
1842 fn stmt_inner(&mut self, stmt: &Stmt, labels: &[String]) -> Result<(), SyntaxError> {
1843 match &stmt.kind {
1844 StmtKind::Empty | StmtKind::Debugger => {}
1845 StmtKind::Expr(expr) => {
1846 // The statement's first token is a position the reference records: an
1847 // expression statement is the `hasexpr:` arm of `js_parse_statement`,
1848 // which calls `emit_source_pos(s, s->token.ptr)` before parsing it. That
1849 // is why an error from a construct with no position of its own (`[...it]`
1850 // with a throwing iterator, `` `${x}` ``) reports the statement's start.
1851 let saved = self.cur().cur_pos;
1852 self.state().cur_pos = Some(expr.span.start);
1853 // An expression statement's value is thrown away — except in a
1854 // script, where it becomes the program's result. `assign` reads this
1855 // and clears it, so a nested assignment still produces a value.
1856 self.state().discard_value = !self.cur().is_script;
1857 let result = self.expr(expr);
1858 self.state().discard_value = false;
1859 result?;
1860 if std::mem::take(&mut self.state().no_value) {
1861 // A store whose value was discarded left nothing to drop.
1862 } else if self.cur().is_script {
1863 // The program's value lands in the hidden `<ret>` local.
1864 self.emit(Opcode::PutLoc, &[Op::Slot(Slot::Loc(0))]);
1865 } else {
1866 self.emit(Opcode::Drop, &[]);
1867 }
1868 // Restored last: the trailing `drop` is part of the statement, and in the
1869 // reference it simply inherits whatever the expression last recorded.
1870 self.state().cur_pos = saved;
1871 }
1872 StmtKind::Block(body) => {
1873 // The block's declarations were hoisted with its enclosing
1874 // statement list, so there is nothing left to declare here.
1875 let key = stmt.span.start.offset as u64;
1876 let parent = self.cur().current_block;
1877 self.push_block(key, parent);
1878 self.emit_scope_enter(key);
1879 // A block is where a `using` region lives, so its statements have to go
1880 // through `stmts`: that is what emits the disposal epilogue.
1881 self.stmts(body)?;
1882 self.emit_scope_leave(key);
1883 self.state().current_block = parent;
1884 }
1885 StmtKind::VarDecl(decl) => self.var_decl(decl)?,
1886 // A function declaration was already instantiated when its scope was
1887 // entered, so the statement itself emits nothing.
1888 StmtKind::FuncDecl(_) => {}
1889 StmtKind::If { test, cons, alt } => {
1890 self.reset_value();
1891 let else_label = self.new_label();
1892 let end_label = self.new_label();
1893 self.expr(test)?;
1894 self.emit_jump(Opcode::IfFalse, else_label, &[]);
1895 self.stmt(cons)?;
1896 if alt.is_some() {
1897 self.emit_jump(Opcode::Goto, end_label, &[]);
1898 }
1899 self.place_label(else_label);
1900 if let Some(alt) = alt {
1901 self.stmt(alt)?;
1902 self.place_label(end_label);
1903 }
1904 }
1905 StmtKind::While { test, body } => {
1906 self.reset_value();
1907 let top = self.new_label();
1908 let end = self.new_label();
1909 self.place_label(top);
1910 self.expr(test)?;
1911 // The condition's false branch and `break` share one target,
1912 // which is why a `while` loop needs only one end label.
1913 self.emit_jump(Opcode::IfFalse, end, &[]);
1914 self.loop_body(body, labels, top, end)?;
1915 self.emit_jump(Opcode::Goto, top, &[]);
1916 self.place_label(end);
1917 }
1918 StmtKind::DoWhile { body, test } => {
1919 self.reset_value();
1920 let top = self.new_label();
1921 let cont = self.new_label();
1922 let end = self.new_label();
1923 self.place_label(top);
1924 // `continue` in a `do…while` runs the test, so it lands on `cont`
1925 // rather than on the loop head.
1926 self.loop_body(body, labels, cont, end)?;
1927 self.place_label(cont);
1928 self.expr(test)?;
1929 self.emit_jump(Opcode::IfTrue, top, &[]);
1930 self.place_label(end);
1931 }
1932 StmtKind::For {
1933 init,
1934 test,
1935 update,
1936 body,
1937 } => {
1938 self.reset_value();
1939 let for_key = stmt.span.start.offset as u64;
1940 let for_parent = self.cur().current_block;
1941 self.push_block(for_key, for_parent);
1942 self.emit_scope_enter(for_key);
1943 let mut using_head = None;
1944 if let Some(init) = init {
1945 match init {
1946 ForInit::VarDecl(decl) if decl.kind.is_using() => {
1947 // A `using` resource declared in the head lives until the whole
1948 // statement ends, not one iteration, so the disposal region has
1949 // to wrap the loop — and there may be several of them, each
1950 // needing its own region so that a later initialiser that
1951 // throws still disposes the earlier resources
1952 // (`initializer-disposed-if-subsequent-initializer-throws-in-forstatement-head`).
1953 using_head = Some(decl);
1954 }
1955 ForInit::VarDecl(decl) => {
1956 self.var_decl(decl)?;
1957 }
1958 ForInit::Expr(expr) => {
1959 // The head's value is discarded. Saying so lets an
1960 // assignment store with `put` instead of `dup`+`put`, which
1961 // is what the reference emits — and the difference matters:
1962 // a `dup`/`drop` pair around the store gives the peephole a
1963 // chance to fold the store into the *condition's* read.
1964 self.state().discard_value = true;
1965 let result = self.expr(expr);
1966 self.state().discard_value = false;
1967 result?;
1968 if !std::mem::take(&mut self.state().no_value) {
1969 self.emit(Opcode::Drop, &[]);
1970 }
1971 }
1972 }
1973 }
1974 // A `using` head's resource is disposed when the statement ends, on every
1975 // way out: `break`, `return`, an exception, and reaching the end.
1976 let flow = match using_head {
1977 Some(decl) => self.for_using_head(
1978 decl, 0, init, test, update, body, labels, for_key, for_parent,
1979 ),
1980 None => {
1981 self.for_loop_tail(init, test, update, body, labels, for_key, for_parent)
1982 }
1983 };
1984 flow?;
1985 }
1986 StmtKind::Return(value) => self.return_stmt(value.as_deref())?,
1987 StmtKind::Throw(expr) => {
1988 self.expr(expr)?;
1989 self.emit(Opcode::Throw, &[]);
1990 }
1991 StmtKind::Break(_) | StmtKind::Continue(_) => {
1992 // Labels and loops are wired up in a later milestone; a bare
1993 // break/continue jumps to the innermost enclosing target, which
1994 // the loop helpers register.
1995 self.control_transfer(stmt)?;
1996 }
1997 StmtKind::Labeled { label, body } => {
1998 self.labeled(label, body, stmt)?;
1999 }
2000 StmtKind::Switch {
2001 discriminant,
2002 cases,
2003 } => {
2004 self.switch(discriminant, cases, stmt)?;
2005 }
2006 StmtKind::Try {
2007 block,
2008 handler,
2009 finalizer,
2010 } => {
2011 self.try_stmt(stmt, block, handler, finalizer.as_deref())?;
2012 }
2013 StmtKind::ForIn { left, right, body } => {
2014 self.for_in_of(stmt, left, right, body, ForLoopKind::In, labels)?;
2015 }
2016 StmtKind::ForOf {
2017 left,
2018 right,
2019 body,
2020 is_await,
2021 } => {
2022 let kind = if *is_await {
2023 ForLoopKind::AwaitOf
2024 } else {
2025 ForLoopKind::Of
2026 };
2027 self.for_in_of(stmt, left, right, body, kind, labels)?;
2028 }
2029 StmtKind::With { object, body } => self.with_stmt(object, body)?,
2030 StmtKind::ClassDecl(class) => self.class_definition(class, false)?,
2031 // `import` emits nothing: hoisting already bound its names, and the host
2032 // fills their cells before the body runs.
2033 StmtKind::Import(_) => {}
2034 StmtKind::Export(decl) => self.export_stmt(decl)?,
2035 }
2036 Ok(())
2037 }
2038
2039 /// Compile `return`, running every enclosing finalizer on the way out.
2040 ///
2041 /// `nip_catch` is what makes this possible: it discards everything on the stack
2042 /// down to and including the `catch` offset while keeping the return value on
2043 /// top, so the frame the finalizer sees has the same shape as on the normal
2044 /// path.
2045 fn return_stmt(&mut self, value: Option<&Expr>) -> Result<(), SyntaxError> {
2046 let mut has_value = value.is_some();
2047 if let Some(expr) = value {
2048 // `return f(x)` is a tail call *only* when nothing has to happen to the
2049 // value afterwards. A `finally` or an open iterator in scope forces the
2050 // normal path, because the cleanup has to run after the call returns —
2051 // which is exactly what a tail call refuses to do.
2052 //
2053 // A **generator or async function** never tail-calls either: its `return` is
2054 // not a return to the caller but `return_async`, which reads the value off the
2055 // stack and finishes the coroutine. A tail call replaces the frame and hands
2056 // the callee's result straight to whoever resumed us, so the value vanished and
2057 // `it.next(42)` answered `{done: true, value: undefined}` for
2058 // `function* g(){ return f(yield) }`. The reference emits `call1` plus
2059 // `return_async` there and has no tail form for a suspending body at all.
2060 let plain = !self.cur().is_suspending()
2061 // A derived constructor's return is not just the value: a non-object answer
2062 // becomes `this`, so the frame has to survive to run that.
2063 && self.cur().ctor_kind != CtorKind::Derived
2064 && self
2065 .cur()
2066 .jump_targets
2067 .iter()
2068 .all(|target| target.finally_label.is_none() && !target.has_iterator);
2069 if plain && self.expr_if_tail_call(expr)? {
2070 // A tail call never reaches `expr`, so the direct-eval bookkeeping has to
2071 // happen here as well.
2072 self.note_direct_eval(expr);
2073 return Ok(());
2074 }
2075 self.expr(expr)?;
2076 }
2077 // `return v` in an *async generator* awaits `v` before anything else happens —
2078 // `AsyncGeneratorYield`/`AsyncGeneratorReturn` settle the value first, and the
2079 // reference's `emit_return` puts the `await` ahead of the `finally` unwinding for
2080 // exactly that reason ("the await must be done before handling the finally in case
2081 // it raises an exception").
2082 if has_value && self.cur().kind == FunctionKind::AsyncGenerator {
2083 self.emit(Opcode::Await, &[]);
2084 self.state().has_await = true;
2085 }
2086 has_value = self.emit_unwind_for_return(has_value);
2087 // A generator or async function does not return to its caller: it either
2088 // finishes, and the value becomes `{value, done: true}`, or it suspends.
2089 // `return_async` is the "finished" half, and it reads the value off the stack
2090 // rather than carrying it, which is what the resume machinery expects.
2091 if self.cur().is_suspending() {
2092 if !has_value {
2093 self.emit(Opcode::Undefined, &[]);
2094 }
2095 self.emit(Opcode::ReturnAsync, &[]);
2096 return Ok(());
2097 }
2098 // A derived constructor's result is `this` whenever the body does not answer an
2099 // object, and `this` is a local in the dead zone until `super()` returns — which is
2100 // why reading it here is also what turns `constructor(){ return; }` into the
2101 // ReferenceError the reference reports. The interpreter could not do this on its
2102 // own: by the time it sees `undefined` come back, the frame that held `this` is
2103 // gone, and `construct`'s own idea of `this` is the placeholder it made before the
2104 // body ran (`derived-class-return-override-with-{undefined,empty}`).
2105 if self.cur().ctor_kind == CtorKind::Derived {
2106 if !has_value {
2107 self.emit_var(VarAction::Get, "this");
2108 self.emit(Opcode::Return, &[]);
2109 return Ok(());
2110 }
2111 // `return <expr>` is only *sometimes* `this`: `undefined` is, any other
2112 // primitive is a `TypeError` (raised by `construct`), and an object replaces
2113 // `this` outright. Which one it is can only be known at run time.
2114 let keep = self.new_label();
2115 self.emit(Opcode::Dup, &[]);
2116 self.emit(Opcode::IsUndefined, &[]);
2117 self.emit_jump(Opcode::IfFalse, keep, &[]);
2118 self.emit(Opcode::Drop, &[]);
2119 self.emit_var(VarAction::Get, "this");
2120 self.place_label(keep);
2121 self.emit(Opcode::Return, &[]);
2122 return Ok(());
2123 }
2124 if has_value {
2125 self.emit(Opcode::Return, &[]);
2126 } else {
2127 self.emit(Opcode::ReturnUndef, &[]);
2128 }
2129 Ok(())
2130 }
2131
2132 /// Close an iterator: the reference's `emit_iterator_close`.
2133 ///
2134 /// The synchronous form is one opcode. The asynchronous one has to *await* the inner
2135 /// `return` — §7.4.6 calls the method and then `Await`s its result — so it is an inline
2136 /// sequence, and three details in it are load-bearing:
2137 ///
2138 /// * the iterator object is compared against `undefined` first, because a loop that
2139 /// ran to completion clears that slot rather than closing an exhausted iterator;
2140 /// * a missing `return` method is not an error, so it is tested for `undefined`/`null`;
2141 /// * `preserve_completion` keeps whatever was underneath (the return value of the
2142 /// function being left), which is why one branch ends on `nip` and the other on `drop`.
2143 fn emit_iterator_close(&mut self, is_async: bool, preserve_completion: bool) {
2144 if !is_async {
2145 if preserve_completion {
2146 self.emit(Opcode::Rot3r, &[]);
2147 self.emit(Opcode::Undefined, &[]);
2148 }
2149 self.emit(Opcode::IteratorClose, &[]);
2150 return;
2151 }
2152 if preserve_completion {
2153 // `iter next completion -> completion iter`
2154 self.emit(Opcode::Nip, &[]);
2155 self.emit(Opcode::Swap, &[]);
2156 } else {
2157 // `iter next catch_offset -> iter`
2158 self.emit(Opcode::Drop, &[]);
2159 self.emit(Opcode::Drop, &[]);
2160 }
2161 let done = self.new_label();
2162 let no_return = self.new_label();
2163 self.emit(Opcode::Dup, &[]);
2164 self.emit(Opcode::IsUndefined, &[]);
2165 self.emit_jump(Opcode::IfTrue, done, &[]);
2166 self.emit(Opcode::GetField2, &[Op::Atom(Atom::from_text("return"))]);
2167 self.emit(Opcode::Dup, &[]);
2168 self.emit(Opcode::IsUndefinedOrNull, &[]);
2169 self.emit_jump(Opcode::IfTrue, no_return, &[]);
2170 self.emit(Opcode::CallMethod, &[Op::Int(0)]);
2171 self.emit(Opcode::Await, &[]);
2172 self.state().has_await = true;
2173 self.emit_jump(Opcode::Goto, done, &[]);
2174 self.place_label(no_return);
2175 self.emit(Opcode::Drop, &[]);
2176 self.place_label(done);
2177 self.emit(Opcode::Drop, &[]);
2178 }
2179
2180 /// Emit the finalizer/iterator cleanup for leaving the current position with a
2181 /// return, and report whether a value is now on the stack for it to carry.
2182 ///
2183 /// Shared by `return` and by the `return(v)` half of a `yield`: both abandon every
2184 /// enclosing `finally` at once, and the two used to be separate — the `yield` path
2185 /// simply emitted `return_async`, so `it.return()` ended the generator without ever
2186 /// running `finally` blocks the body was sitting inside.
2187 fn emit_unwind_for_return(&mut self, mut has_value: bool) -> bool {
2188 let targets = self.cur().jump_targets.clone();
2189 for target in targets.iter().rev() {
2190 if target.finally_label.is_none() && !target.has_iterator {
2191 continue;
2192 }
2193 if !has_value {
2194 // The cleanup expects a value to pass through; with nothing to
2195 // return, `undefined` stands in.
2196 self.emit(Opcode::Undefined, &[]);
2197 has_value = true;
2198 }
2199 self.emit(Opcode::NipCatch, &[]);
2200 if target.has_iterator {
2201 // Rewind to the loop's own slots and hand the close a dummy catch offset:
2202 // the loop is being abandoned, so there is nothing left to catch.
2203 self.emit_iterator_close(target.is_async_iterator, true);
2204 } else if let Some(finally) = target.finally_label {
2205 self.emit_jump(Opcode::Gosub, finally, &[]);
2206 }
2207 }
2208 has_value
2209 }
2210
2211 /// Compile a statement list, stopping at the first statement that cannot
2212 /// fall through.
2213 fn stmts(&mut self, body: &[Stmt]) -> Result<(), SyntaxError> {
2214 for (index, stmt) in body.iter().enumerate() {
2215 // A `using` declaration is not just a binding: everything after it, to the end
2216 // of the list, runs inside its disposal region. Compiling the rest of the list
2217 // recursively is what gives nested regions their innermost-first order.
2218 if Self::using_declaration(stmt).is_some() {
2219 return self.using_region(stmt, &body[index + 1..]);
2220 }
2221 self.stmt(stmt)?;
2222 if Self::terminates(stmt) {
2223 break;
2224 }
2225 }
2226 Ok(())
2227 }
2228
2229 /// The declaration a `using` statement carries, if it is one.
2230 fn using_declaration(stmt: &Stmt) -> Option<&VarDecl> {
2231 match &stmt.kind {
2232 StmtKind::VarDecl(decl) if decl.kind.is_using() => Some(decl),
2233 _ => None,
2234 }
2235 }
2236
2237 /// Compile `decl` and then the rest of its block, disposing when the block ends.
2238 ///
2239 /// The shape mirrors a `try`/`finally`, and deliberately so: the disposal has to run on
2240 /// every way out of the block — reaching its end, `return`, `break`, `continue`, and an
2241 /// exception — and this engine already funnels all of those through `catch` plus
2242 /// `gosub`. Registering the region as a jump target with a `finally_label` is what makes
2243 /// `return` and `break` dispose without knowing anything about `using`.
2244 ///
2245 /// ```text
2246 /// <declaration> value -> x, method -> x+1
2247 /// catch CATCH <- an exception in the rest lands here
2248 /// REST:
2249 /// <the rest of the block>
2250 /// drop <- the catch offset, on the fall-through path
2251 /// undefined; gosub DISPOSE; drop
2252 /// goto END
2253 /// CATCH:
2254 /// using_dispose x <- merges the failure into the pending exception
2255 /// throw
2256 /// DISPOSE:
2257 /// using_dispose_init
2258 /// using_dispose x
2259 /// using_dispose_end <- rethrows if a dispose failed
2260 /// ret
2261 /// END:
2262 /// ```
2263 fn using_region(&mut self, stmt: &Stmt, rest: &[Stmt]) -> Result<(), SyntaxError> {
2264 let Some(decl) = Self::using_declaration(stmt) else {
2265 unreachable!("using_region is only called for a using declaration");
2266 };
2267 self.using_declarator(stmt, decl, 0, rest)
2268 }
2269
2270 /// One declarator of a `using` declaration, plus the region around everything after it.
2271 ///
2272 /// A `using` may list several resources — `using a = x, b = y;` — and each one is
2273 /// disposed when the block ends, in **reverse** order: §14.3.1.4 pushes them onto
2274 /// `DisposableResourceStack` in source order and §9.5.5 disposes from the top. Nesting
2275 /// one region per declarator gives exactly that, because the inner region ends first
2276 /// (`multiple-resources-disposed-in-reverse-order`). Compiling only the first left the
2277 /// rest undisposed.
2278 fn using_declarator(
2279 &mut self,
2280 stmt: &Stmt,
2281 decl: &VarDecl,
2282 index: usize,
2283 rest: &[Stmt],
2284 ) -> Result<(), SyntaxError> {
2285 let Some(declarator) = decl.declarators.get(index) else {
2286 return self.stmts(rest);
2287 };
2288 // `using` binds a plain identifier and has no pattern form, which the parser
2289 // enforces; the region still has to know *which* slot to dispose.
2290 let name = match &declarator.target.kind {
2291 PatternKind::Ident(ident) => Some(ident.name.clone()),
2292 _ => None,
2293 };
2294 let single = Stmt {
2295 kind: StmtKind::VarDecl(VarDecl {
2296 kind: decl.kind,
2297 declarators: vec![declarator.clone()],
2298 span: declarator.span,
2299 }),
2300 span: declarator.span,
2301 };
2302 self.stmt(&single)?;
2303 let Some(name) = name else {
2304 // Unreachable for a well-formed `using`, but a bare `using` with no declarator
2305 // must not make the compiler panic.
2306 return self.using_declarator(stmt, decl, index + 1, rest);
2307 };
2308 let Some(value_slot) = self.using_value_slot(&name) else {
2309 // Declared globally, which the parser rules out for a script; a module's
2310 // top level is a scope, and there the disposal stays a known gap.
2311 return self.using_declarator(stmt, decl, index + 1, rest);
2312 };
2313 // A block that ends in a `return` or a `throw` never reaches its own epilogue; the
2314 // exit path already disposed.
2315 let live = !rest.last().is_some_and(Self::terminates);
2316 let _ = stmt;
2317 self.using_region_around(
2318 value_slot,
2319 live,
2320 decl.kind == VarDeclKind::AwaitUsing,
2321 |compiler| compiler.using_declarator(stmt, decl, index + 1, rest),
2322 )
2323 }
2324
2325 /// One `using` declarator of a `for` head, wrapped in its disposal region, and then the
2326 /// next — so the resources nest inside-out and dispose in reverse order.
2327 #[allow(clippy::too_many_arguments)]
2328 fn for_using_head(
2329 &mut self,
2330 decl: &VarDecl,
2331 index: usize,
2332 init: &Option<ForInit>,
2333 test: &Option<Box<Expr>>,
2334 update: &Option<Box<Expr>>,
2335 body: &Stmt,
2336 labels: &[String],
2337 for_key: u64,
2338 for_parent: u64,
2339 ) -> Result<(), SyntaxError> {
2340 let Some(declarator) = decl.declarators.get(index) else {
2341 return self.for_loop_tail(init, test, update, body, labels, for_key, for_parent);
2342 };
2343 let name = match &declarator.target.kind {
2344 PatternKind::Ident(ident) => Some(ident.name.clone()),
2345 _ => None,
2346 };
2347 self.var_decl(&VarDecl {
2348 kind: decl.kind,
2349 declarators: vec![declarator.clone()],
2350 span: declarator.span,
2351 })?;
2352 let Some(slot) = name.and_then(|name| self.using_value_slot(&name)) else {
2353 return self.for_using_head(
2354 decl,
2355 index + 1,
2356 init,
2357 test,
2358 update,
2359 body,
2360 labels,
2361 for_key,
2362 for_parent,
2363 );
2364 };
2365 self.using_region_around(
2366 slot,
2367 true,
2368 decl.kind == VarDeclKind::AwaitUsing,
2369 |compiler| {
2370 compiler.for_using_head(
2371 decl,
2372 index + 1,
2373 init,
2374 test,
2375 update,
2376 body,
2377 labels,
2378 for_key,
2379 for_parent,
2380 )
2381 },
2382 )
2383 }
2384
2385 /// The half of a `for` statement that runs inside its head's disposal region: the
2386 /// per-iteration bindings, the test, the body and the update.
2387 ///
2388 /// Split out so that a `using` head can wrap exactly this much — see the
2389 /// `StmtKind::For` arm — because the resource lives as long as the statement.
2390 #[allow(clippy::too_many_arguments)]
2391 fn for_loop_tail(
2392 &mut self,
2393 init: &Option<ForInit>,
2394 test: &Option<Box<Expr>>,
2395 update: &Option<Box<Expr>>,
2396 body: &Stmt,
2397 labels: &[String],
2398 for_key: u64,
2399 for_parent: u64,
2400 ) -> Result<(), SyntaxError> {
2401 // A `let`/`const` in the head gets a *fresh binding per iteration*,
2402 // so a closure made in the body captures that iteration's value
2403 // instead of sharing one. The reference expresses this with
2404 // `close_loc`, which swaps in a new reference cell holding the
2405 // current value; the three points below are the ones it uses — after
2406 // the initialiser, before the update, and after the loop.
2407 let loop_bindings = match init {
2408 Some(ForInit::VarDecl(decl)) if decl.kind != VarDeclKind::Var => {
2409 let mut names: Vec<String> = Vec::new();
2410 for declarator in &decl.declarators {
2411 let mut idents = Vec::new();
2412 declarator.target.bound_names(&mut idents);
2413 names.extend(idents.into_iter().map(|ident| ident.name));
2414 }
2415 names
2416 }
2417 _ => Vec::new(),
2418 };
2419 // The reference also closes right after the initialiser, so the first
2420 // iteration's closures get their own cell rather than sharing the one
2421 // the initialiser wrote into.
2422 for name in &loop_bindings {
2423 let pos = self.cur().cur_pos;
2424 self.state().insns.push(Insn::CloseCaptured {
2425 name: name.clone(),
2426 block: for_key,
2427 });
2428 self.state().insn_pos.push(pos);
2429 }
2430 let top = self.new_label();
2431 let cont = self.new_label();
2432 let end = self.new_label();
2433 self.place_label(top);
2434 if let Some(test) = test {
2435 self.expr(test)?;
2436 self.emit_jump(Opcode::IfFalse, end, &[]);
2437 }
2438 // `continue` runs the update expression first, so it lands on
2439 // `cont`, which sits just before the update.
2440 self.loop_body(body, labels, cont, end)?;
2441 self.place_label(cont);
2442 // Each iteration ends with a fresh cell, so the closures the body just
2443 // created keep the cell they captured and the update writes to a new
2444 // one. Without this every closure in the loop shares one binding.
2445 let binding_block = for_key;
2446 for name in &loop_bindings {
2447 let pos = self.cur().cur_pos;
2448 self.state().insns.push(Insn::CloseCaptured {
2449 name: name.clone(),
2450 block: binding_block,
2451 });
2452 self.state().insn_pos.push(pos);
2453 }
2454 if let Some(update) = update {
2455 self.state().discard_value = true;
2456 let result = self.expr(update);
2457 self.state().discard_value = false;
2458 result?;
2459 if !std::mem::take(&mut self.state().no_value) {
2460 self.emit(Opcode::Drop, &[]);
2461 }
2462 }
2463 self.emit_jump(Opcode::Goto, top, &[]);
2464 self.place_label(end);
2465 self.emit_scope_leave(for_key);
2466 self.state().current_block = for_parent;
2467 Ok(())
2468 }
2469
2470 /// The slot a `using` binding's value lives in.
2471 fn using_value_slot(&self, name: &str) -> Option<u32> {
2472 self.cur()
2473 .vars
2474 .iter()
2475 .position(|var| var.name == name && var.kind == VarKind::Using)
2476 .map(|index| index as u32)
2477 }
2478
2479 /// Wrap `inside` in a disposal region for the resource in `value_slot`.
2480 ///
2481 /// Shared between a `using` statement — which owns the rest of its block — and a
2482 /// `for (using x of …)` body, which owns only one iteration. The shape mirrors a
2483 /// `try`/`finally`, deliberately: the disposal has to run on every way out — reaching
2484 /// the end, `return`, `break`, `continue`, and an exception — and this engine already
2485 /// funnels all of those through `catch` plus `gosub`. Registering the region as a jump
2486 /// target with a `finally_label` is what makes `return` and `break` dispose without
2487 /// knowing anything about `using`.
2488 ///
2489 /// ```text
2490 /// catch CATCH <- an exception inside lands here
2491 /// <inside>
2492 /// drop <- the catch offset, on the fall-through path
2493 /// undefined; gosub DISPOSE; drop
2494 /// goto END
2495 /// CATCH:
2496 /// using_dispose slot <- merges the failure into the pending exception
2497 /// throw
2498 /// DISPOSE:
2499 /// using_dispose_init
2500 /// using_dispose slot
2501 /// using_dispose_end <- rethrows if a dispose failed
2502 /// ret
2503 /// END:
2504 /// ```
2505 fn using_region_around(
2506 &mut self,
2507 value_slot: u32,
2508 live: bool,
2509 is_await_using: bool,
2510 inside: impl FnOnce(&mut Self) -> Result<(), SyntaxError>,
2511 ) -> Result<(), SyntaxError> {
2512 let catch_label = self.new_label();
2513 let end_label = self.new_label();
2514 let dispose_label = self.new_label();
2515
2516 self.emit_jump(Opcode::Catch, catch_label, &[]);
2517 self.push_jump_target(JumpTarget {
2518 names: Vec::new(),
2519 break_label: None,
2520 continue_label: None,
2521 // The catch offset is the one thing on the stack that leaving has to remove.
2522 drop_count: 1,
2523 finally_label: Some(dispose_label),
2524 is_regular_stmt: false,
2525 has_iterator: false,
2526 is_async_iterator: false,
2527 });
2528 inside(self)?;
2529 self.pop_jump_target();
2530
2531 if live {
2532 self.emit(Opcode::Drop, &[]);
2533 self.emit(Opcode::Undefined, &[]);
2534 self.emit_jump(Opcode::Gosub, dispose_label, &[]);
2535 self.emit(Opcode::Drop, &[]);
2536 self.emit_jump(Opcode::Goto, end_label, &[]);
2537 }
2538
2539 // An exception unwinds to here with the thrown value on the stack, which is exactly
2540 // the shape `using_dispose` expects as its error state.
2541 self.place_label(catch_label);
2542 self.emit(Opcode::UsingDispose, &[Op::Slot(Slot::Loc(value_slot))]);
2543 self.emit(Opcode::Throw, &[]);
2544
2545 self.place_label(dispose_label);
2546 // Inside the subroutine the return value and the `gosub` return address are both
2547 // live, and neither an outer finalizer nor another region may run before this one
2548 // has finished.
2549 self.push_jump_target(JumpTarget {
2550 names: Vec::new(),
2551 break_label: None,
2552 continue_label: None,
2553 drop_count: 2,
2554 finally_label: None,
2555 is_regular_stmt: false,
2556 has_iterator: false,
2557 is_async_iterator: false,
2558 });
2559 self.emit(Opcode::UsingDisposeInit, &[]);
2560 if is_await_using {
2561 // `AsyncDisposableStack`'s order: call the method, **await** its result, and
2562 // fold a rejection into the error state. The catch is what turns that
2563 // rejection — which arrives as an exception from `await` — into the merged
2564 // error, so one failure is rethrown as itself and two become a
2565 // `SuppressedError` (§27.1.3.3's `DisposeResources` steps 5–6).
2566 //
2567 // The shape is the reference's `js_emit_dispose_scope`, adapted to this
2568 // engine's error-state protocol: `using_dispose_init` pushed the state and
2569 // `using_dispose_end` will consume it, so both arms have to leave it in place.
2570 let catch_label = self.new_label();
2571 let merged_label = self.new_label();
2572 self.emit_jump(Opcode::Catch, catch_label, &[]);
2573 self.emit(
2574 Opcode::UsingDisposeAsync,
2575 &[Op::Slot(Slot::Loc(value_slot))],
2576 );
2577 self.emit(Opcode::Await, &[]);
2578 // The awaited value, and the catch offset the successful path still holds.
2579 self.emit(Opcode::Drop, &[]);
2580 self.emit(Opcode::Drop, &[]);
2581 self.emit_jump(Opcode::Goto, merged_label, &[]);
2582 self.place_label(catch_label);
2583 self.emit(Opcode::UsingDisposeMerge, &[]);
2584 self.place_label(merged_label);
2585 self.state().has_await = true;
2586 } else {
2587 self.emit(Opcode::UsingDispose, &[Op::Slot(Slot::Loc(value_slot))]);
2588 }
2589 self.emit(Opcode::UsingDisposeEnd, &[]);
2590 self.pop_jump_target();
2591 self.emit(Opcode::Ret, &[]);
2592 self.place_label(end_label);
2593 Ok(())
2594 }
2595
2596 /// Declare every name a statement list introduces, before compiling any of
2597 /// it, so a reference that appears textually before a declaration still
2598 /// resolves.
2599 ///
2600 /// Declarations are walked in source order because that is the order the
2601 /// reference numbers its slots in: `let a; var b;` gives `a` slot 0 and `b`
2602 /// slot 1, while `var b; let a;` gives the opposite. `var` and function
2603 /// declarations hoist out to the function scope; lexical names belong to the
2604 /// block they were written in, which `block` records.
2605 fn hoist(&mut self, body: &[Stmt], block: u64) -> Result<(), SyntaxError> {
2606 let saved = self.cur().current_block;
2607 self.state().current_block = block;
2608 let result = self.hoist_list(body);
2609 // Only now is every binding of this scope known, so the deferred function
2610 // bodies can be compiled against the finished list. Compiled at its own
2611 // declaration instead, a body that names a `var` written further down would
2612 // have resolved that name as a global.
2613 if result.is_ok() {
2614 let deferred = std::mem::take(&mut self.state().deferred_funcs);
2615 let mut outcome = Ok(());
2616 for (owner, func) in deferred {
2617 let previous = self.cur().current_block;
2618 self.state().current_block = owner;
2619 outcome = self.func_decl(&func);
2620 self.state().current_block = previous;
2621 if outcome.is_err() {
2622 break;
2623 }
2624 }
2625 self.state().current_block = saved;
2626 return outcome;
2627 }
2628 // `current_block` is restored by the caller for a block statement, since
2629 // it needs it set while compiling; only clean up on the hoist path.
2630 self.state().current_block = saved;
2631 result
2632 }
2633
2634 fn hoist_list(&mut self, body: &[Stmt]) -> Result<(), SyntaxError> {
2635 for stmt in body {
2636 self.hoist_stmt(stmt)?;
2637 }
2638 Ok(())
2639 }
2640
2641 /// Whether a statement always transfers control away, making everything after
2642 /// it in the same list unreachable.
2643 ///
2644 /// The reference drops such statements in `skip_dead_code`, so `return 1;
2645 /// let x = 2;` compiles to the same bytecode as `return 1;`.
2646 fn terminates(stmt: &Stmt) -> bool {
2647 matches!(
2648 stmt.kind,
2649 StmtKind::Return(_) | StmtKind::Throw(_) | StmtKind::Break(_) | StmtKind::Continue(_)
2650 )
2651 }
2652
2653 fn hoist_stmt(&mut self, stmt: &Stmt) -> Result<(), SyntaxError> {
2654 match &stmt.kind {
2655 StmtKind::VarDecl(decl) => {
2656 for declarator in &decl.declarators {
2657 let mut names = Vec::new();
2658 declarator.target.bound_names(&mut names);
2659 for name in names {
2660 let text = name.name.clone();
2661 if decl.kind == VarDeclKind::Var {
2662 let def = VarDef::var(text.clone());
2663 self.declare_var(&text, def);
2664 } else if decl.kind.is_using() {
2665 // Two adjacent slots: the resource, then the dispose method
2666 // snapshotted at declaration. `using_dispose` reads them as a
2667 // pair `(slot, slot + 1)`, so nothing may be declared between
2668 // them — which is why both are declared here, in one step,
2669 // rather than the method being added at emission time.
2670 self.declare_using(&text);
2671 } else {
2672 let def = if decl.kind == VarDeclKind::Const {
2673 VarDef::constant(text.clone())
2674 } else {
2675 VarDef::lexical(text.clone())
2676 };
2677 self.declare(&text, def);
2678 }
2679 }
2680 }
2681 }
2682 StmtKind::FuncDecl(func) => {
2683 if let Some(name) = &func.name {
2684 // A function declaration is a `var` binding that happens to
2685 // hold a function, not a lexical one.
2686 let mut def = VarDef::var(name.name.clone());
2687 // Marked so that an `eval` establishing it can apply
2688 // `CanDeclareGlobalFunction` rather than the laxer `var` rule. Only
2689 // the *global* form is marked: the kind is printed by the
2690 // disassembler, and a local function declaration is `var g` there,
2691 // exactly like the reference.
2692 if self.cur().declares_globally(&def) {
2693 def.kind = crate::bytecode::VarKind::GlobalFunctionDecl;
2694 }
2695 self.declare_var(&name.name.clone(), def);
2696 }
2697 // The function object is created when the scope is entered, so it
2698 // exists before the declaration is reached. Its body is compiled
2699 // *after* this scope's hoisting finishes, so a name it uses resolves
2700 // even when the `var` that declares it comes later in the source.
2701 let owner = self.cur().current_block;
2702 self.state().deferred_funcs.push((owner, func.clone()));
2703 }
2704 StmtKind::ClassDecl(class) => {
2705 if let Some(name) = &class.name {
2706 self.declare(&name.name.clone(), VarDef::lexical(name.name.clone()));
2707 }
2708 }
2709 // A module's imports are bound before any of its code runs, and its exports
2710 // declare the very bindings they export — so both hoist the declarations
2711 // their `StmtKind` arm will later emit code for.
2712 StmtKind::Import(decl) => self.hoist_import(decl)?,
2713 StmtKind::Export(decl) => self.hoist_export(decl)?,
2714 StmtKind::Block(inner) => self.hoist_block(stmt.span.start.offset as u64, inner)?,
2715 StmtKind::If { cons, alt, .. } => {
2716 self.hoist_stmt(cons)?;
2717 if let Some(alt) = alt {
2718 self.hoist_stmt(alt)?;
2719 }
2720 }
2721 StmtKind::While { body, .. }
2722 | StmtKind::DoWhile { body, .. }
2723 | StmtKind::Labeled { body, .. }
2724 | StmtKind::With { body, .. } => self.hoist_stmt(body)?,
2725 StmtKind::For { init, body, .. } => {
2726 // A `for` head gets its own scope even when it declares nothing,
2727 // because `let` in the head is scoped to the loop.
2728 let key = stmt.span.start.offset as u64;
2729 let parent = self.cur().current_block;
2730 self.push_block(key, parent);
2731 if let Some(init) = init
2732 && let ForInit::VarDecl(decl) = init
2733 {
2734 self.hoist_stmt(&Stmt::new(StmtKind::VarDecl(decl.clone()), stmt.span))?;
2735 }
2736 self.hoist_stmt(body)?;
2737 self.state().current_block = parent;
2738 }
2739 StmtKind::ForIn { left, body, .. } | StmtKind::ForOf { left, body, .. } => {
2740 let key = stmt.span.start.offset as u64;
2741 let parent = self.cur().current_block;
2742 self.push_block(key, parent);
2743 if let ForHead::VarDecl(decl) = left {
2744 self.hoist_stmt(&Stmt::new(StmtKind::VarDecl(decl.clone()), stmt.span))?;
2745 }
2746 self.hoist_stmt(body)?;
2747 self.state().current_block = parent;
2748 }
2749 StmtKind::Try {
2750 block,
2751 handler,
2752 finalizer,
2753 } => {
2754 self.hoist_block(Self::try_block_key(stmt, TryPart::Block), block)?;
2755 let try_parent = self.cur().current_block;
2756 if let Some(handler) = handler {
2757 // The catch parameter belongs to the function scope, not to a
2758 // block: it is a `catch` binding rather than a `let`, so it is
2759 // never in the temporal dead zone and `emit_scope_enter` must
2760 // not mark it uninitialised. It still has to be declared before
2761 // the handler body is hoisted, so it takes the slot the
2762 // reference gives it (bindings are numbered in source order).
2763 if let Some(pattern) = &handler.param {
2764 // The parameter gets its own scope, so entering the handler
2765 // does not have to re-declare it. It is not lexical, so it
2766 // is never marked uninitialised.
2767 let key = Self::try_block_key(stmt, TryPart::Param);
2768 let parent = self.cur().current_block;
2769 self.push_block(key, parent);
2770 // A destructuring parameter binds several names, one slot each,
2771 // in the order they are written. The reference declares those as
2772 // `let`s rather than as one `catch` binding — its dump prints
2773 // `0: let e` for `catch ({e})` but `0: catch e` for `catch (e)` —
2774 // so the kind follows the shape of the parameter.
2775 //
2776 // Neither form is in the dead zone: the stores run as the handler
2777 // is entered, so both use the unchecked `put_loc`.
2778 let destructures = !matches!(pattern.kind, PatternKind::Ident(_));
2779 let mut names = Vec::new();
2780 pattern.bound_names(&mut names);
2781 for name in names {
2782 let def = VarDef {
2783 name: name.name.clone(),
2784 is_const: false,
2785 is_lexical: destructures,
2786 kind: if destructures {
2787 crate::bytecode::VarKind::LexicalCatch
2788 } else {
2789 crate::bytecode::VarKind::Catch
2790 },
2791 is_captured: false,
2792 scope_level: 0,
2793 scope_next: None,
2794 };
2795 self.declare_local(&name.name.clone(), def);
2796 }
2797 // The handler body nests inside the parameter's scope, so the
2798 // body's bindings chain on to the parameter (the reference
2799 // prints `let y [next:1]`, pointing at `e`).
2800 self.state().current_block = key;
2801 }
2802 self.hoist_block(Self::try_block_key(stmt, TryPart::Catch), &handler.body)?;
2803 // Back to the block the `try` itself lives in, so the finalizer
2804 // is a sibling of the handler rather than nested in it.
2805 self.state().current_block = try_parent;
2806 }
2807 if let Some(finalizer) = finalizer {
2808 self.hoist_block(Self::try_block_key(stmt, TryPart::Finally), finalizer)?;
2809 }
2810 }
2811 StmtKind::Switch { cases, .. } => {
2812 let key = stmt.span.start.offset as u64;
2813 let parent = self.cur().current_block;
2814 self.push_block(key, parent);
2815 for case in cases {
2816 self.hoist_list(&case.body)?;
2817 }
2818 self.state().current_block = parent;
2819 }
2820 _ => {}
2821 }
2822 Ok(())
2823 }
2824
2825 /// Hoist a nested statement list, which is its own lexical scope.
2826 fn hoist_block(&mut self, key: u64, body: &[Stmt]) -> Result<(), SyntaxError> {
2827 let parent = self.cur().current_block;
2828 self.push_block(key, parent);
2829 self.hoist_list(body)?;
2830 self.state().current_block = parent;
2831 Ok(())
2832 }
2833
2834 /// A block key for one part of a `try` statement.
2835 ///
2836 /// The three parts are three separate scopes, so they cannot share the key a
2837 /// statement's own offset would give them: the try block, the handler body and
2838 /// the finalizer would then look like one scope, and their `let` bindings would
2839 /// be marked uninitialised only on entering the first of them.
2840 fn try_block_key(stmt: &Stmt, part: TryPart) -> u64 {
2841 (stmt.span.start.offset as u64) * 4 + part as u64
2842 }
2843
2844 /// Declare a `var`: it lives in the function's own scope, not the block's.
2845 fn declare_var(&mut self, name: &str, def: VarDef) {
2846 if self.cur().is_module {
2847 self.declare_module(name, &def);
2848 return;
2849 }
2850 if self.cur().declares_globally(&def) {
2851 self.declare_global(name, &def);
2852 return;
2853 }
2854 let state = self.state();
2855 // Only a binding of *this* function scope counts as "already declared". A
2856 // parameter or a block-scoped `let` of the same name is a different binding that
2857 // the new `var` shadows, and needs a slot of its own.
2858 //
2859 // Counting them made a named function expression's own name vanish:
2860 // `function n() { let n = 1 }` found the `let` and returned early, so no
2861 // function-scope slot was ever pushed. The prologue that initialises the name then
2862 // resolved `n` at block 0, skipped the block-scoped binding (a different block) and
2863 // walked out through the closure table — writing the function into the *global*
2864 // `n`. That is `scope-lex-open` under `expressions/call` and three siblings.
2865 if state.vars.iter().enumerate().any(|(index, v)| {
2866 v.name == name
2867 && state.var_block.get(index).copied() == Some(FUNCTION_SCOPE)
2868 && !v.is_lexical
2869 }) {
2870 return;
2871 }
2872 // A `var` belongs to the function scope, never to the enclosing block.
2873 state.var_block.push(FUNCTION_SCOPE);
2874 state.vars.push(def);
2875 }
2876
2877 /// Declare `name` as a binding of the parameter scope, returning its slot.
2878 fn declare_param_var(&mut self, name: &str) -> u32 {
2879 declare_param_var_at(self.state(), name)
2880 }
2881
2882 /// Declare one of the parameter list's own bindings: a `let` of the parameter scope.
2883 ///
2884 /// The `scope_next` chain is the reference's. Bindings are prepended to their scope,
2885 /// so each points at the one declared before it and the oldest ends the chain with
2886 /// `-2` (`ARG_SCOPE_END`); the dump prints exactly that, and the chain is what the
2887 /// runtime walks when it instantiates them.
2888 fn declare_param_binding(&mut self, name: &str) -> u32 {
2889 let state = self.state();
2890 let previous = state
2891 .vars
2892 .iter()
2893 .enumerate()
2894 .rev()
2895 .find(|(index, var)| {
2896 state.var_block.get(*index).copied() == Some(PARAM_SCOPE) && var.is_lexical
2897 })
2898 .map(|(index, _)| index as i32);
2899 let index = state.vars.len() as u32;
2900 state.var_block.push(PARAM_SCOPE);
2901 let mut def = VarDef::lexical(name);
2902 // A scope of its own, so the dump prints `[next:…]`. The parameter scope is not
2903 // the function's, and its bindings are initialised one by one rather than all at
2904 // once — which is exactly what the dead zone needs.
2905 def.scope_level = 1;
2906 def.scope_next = Some(previous.unwrap_or(-2));
2907 state.vars.push(def);
2908 index
2909 }
2910
2911 /// The slot of a parameter-list binding, if the list has one by that name.
2912 fn param_binding_slot(&self, name: &str) -> Option<u32> {
2913 let state = self.cur();
2914 state
2915 .vars
2916 .iter()
2917 .enumerate()
2918 .position(|(index, var)| {
2919 var.name == name
2920 && var.is_lexical
2921 && state.var_block.get(index).copied() == Some(PARAM_SCOPE)
2922 })
2923 .map(|index| index as u32)
2924 }
2925
2926 /// Every parameter-list binding, in declaration order.
2927 fn param_binding_names(&self) -> Vec<String> {
2928 let state = self.cur();
2929 state
2930 .vars
2931 .iter()
2932 .enumerate()
2933 .filter(|(index, var)| {
2934 var.is_lexical && state.var_block.get(*index).copied() == Some(PARAM_SCOPE)
2935 })
2936 .map(|(_, var)| var.name.clone())
2937 .collect()
2938 }
2939
2940 /// The body's own binding for `name`, as opposed to the parameter's copy of it.
2941 fn body_var_slot(&self, name: &str) -> Option<u32> {
2942 let state = self.cur();
2943 state
2944 .vars
2945 .iter()
2946 .enumerate()
2947 .find(|(index, var)| {
2948 var.name == name && state.var_block.get(*index).copied() == Some(FUNCTION_SCOPE)
2949 })
2950 .map(|(index, _)| index as u32)
2951 }
2952
2953 /// Give the *parameter* scope an `arguments` binding if the parameter list mentions
2954 /// one.
2955 ///
2956 /// With parameter expressions the reference creates two: an unmapped one in the
2957 /// argument scope, for the defaults and anything they close over, and the body's own.
2958 /// They are separate bindings, which is what makes
2959 /// `(a = eval("var arguments = 1"), p = () => arguments) => { var arguments = 2 }`
2960 /// report 1 from `p` and 2 from the body.
2961 fn provide_param_arguments(&mut self) {
2962 if !self.cur().has_parameter_expressions {
2963 return;
2964 }
2965 let mentioned = self.cur().needs_param_arguments
2966 || self
2967 .cur()
2968 .insns
2969 .iter()
2970 .any(|insn| matches!(insn, Insn::Var { name, in_params: true, .. } if name == "arguments"));
2971 if !mentioned {
2972 return;
2973 }
2974 let slot = self.declare_param_var("arguments");
2975 let magic = if self.cur().strict || !self.cur().simple_parameter_list {
2976 0
2977 } else {
2978 1
2979 };
2980 self.prepend_initialiser_to(
2981 slot,
2982 Insn::Fixed {
2983 op: Opcode::SpecialObject,
2984 operands: vec![Op::Int(magic)],
2985 },
2986 );
2987 }
2988
2989 /// [`Compiler::prepend_initialiser`] for a slot rather than a name.
2990 fn prepend_initialiser_to(&mut self, slot: u32, producer: Insn) {
2991 let current = self.stack.len() - 1;
2992 let init = [
2993 producer,
2994 Insn::Fixed {
2995 op: Opcode::PutLoc,
2996 operands: vec![Op::Slot(Slot::Loc(slot))],
2997 },
2998 ];
2999 let inserted = init.len();
3000 for (index, instruction) in init.into_iter().enumerate() {
3001 self.stack[current].insns.insert(index, instruction);
3002 }
3003 for placed in self.stack[current].labels.iter_mut().flatten() {
3004 *placed += inserted;
3005 }
3006 self.state().label_since_insn = false;
3007 }
3008
3009 /// Give the function an `arguments` binding if its body mentions one.
3010 ///
3011 /// The check runs on the *instruction* stream rather than the AST: by this point
3012 /// every reference has become an `Insn::Var`, so scanning is exact and needs no
3013 /// AST walker. Declaring lazily matters for more than tidiness — always declaring
3014 /// would renumber every later local slot and stop the bytecode matching the
3015 /// reference, which only adds the binding when the body uses it.
3016 ///
3017 /// `arguments` is a local, initialised at the top of the body by
3018 /// `special_object`; that is the reference's shape, so the disassembly agrees.
3019 fn provide_arguments(&mut self) {
3020 let current = self.stack.len() - 1;
3021 if self.stack[current].is_script || self.stack[current].is_module {
3022 // A module has no `arguments` binding; referring to it is a ReferenceError,
3023 // which is exactly what an unbound name produces.
3024 return;
3025 }
3026 // An arrow has no `arguments` of its own: the binding belongs to the enclosing
3027 // function, which is why `() => arguments` sees the caller's arguments.
3028 if self.stack[current].is_arrow {
3029 if self.mentions("arguments") {
3030 self.ensure_enclosing_arguments();
3031 }
3032 return;
3033 }
3034 // Only a *body* mention needs the body's binding: the parameter list has one of
3035 // its own (see [`Compiler::provide_param_arguments`]).
3036 //
3037 // `delete arguments` counts too: it compiles to `DeleteVar`, which is not a
3038 // `Var`, so without this the body got no binding at all — the name resolved to
3039 // the global object and `delete` answered `true` for a binding that cannot be
3040 // deleted. The reference answers `false`.
3041 let mentioned = self.cur().insns.iter().any(|insn| match insn {
3042 Insn::Var {
3043 name, in_params, ..
3044 } => name == "arguments" && !*in_params,
3045 Insn::DeleteVar { name } => name == "arguments",
3046 _ => false,
3047 });
3048 // A mention that resolves to the body's *own* lexical `arguments` is not a request
3049 // for the implicit one — `function f(p = 1) { let arguments; }` shadows it, and the
3050 // implicit binding is not created at all. Providing it anyway was worse than useless:
3051 // its prologue store resolved past the shadowing `let` and landed on the **global**,
3052 // so `function f(p = eval("var arguments")) { let arguments; }` defined
3053 // `globalThis.arguments` as a side effect (`globalThis.arguments unchanged` in
3054 // test262's `fn-body-cntns-arguments-lex-bind` family).
3055 //
3056 // Lexical only. `var arguments = 1` in the body is a different thing entirely: the
3057 // var *is* the binding, and the implicit arguments object is initialised into it at
3058 // entry, which is why `function f(){ return typeof arguments; var arguments = 1 }`
3059 // answers `"object"` (`S13_A15_T4`). Suppressing the prologue for those two made
3060 // `typeof arguments` `"undefined"`.
3061 if self
3062 .cur()
3063 .vars
3064 .iter()
3065 .any(|var| var.name == "arguments" && var.needs_check())
3066 {
3067 return;
3068 }
3069 if !mentioned && !self.cur().needs_arguments_local {
3070 return;
3071 }
3072 // The request may have come only from a parameter-list arrow, in which case the
3073 // parameter scope's binding already answers for it and the body needs none.
3074 if !mentioned && self.cur().has_parameter_expressions && !self.body_mentions_arguments() {
3075 return;
3076 }
3077 // 0 is strict `arguments`, 1 is sloppy (mapped) `arguments`.
3078 //
3079 // With parameter expressions the list and the body are separate environments, so
3080 // an assignment to a parameter cannot be reflected into `arguments` at all — the
3081 // arguments object is unmapped whatever the mode, which is why the reference emits
3082 // `special_object 0` here even in sloppy code.
3083 // A non-simple parameter list (`[a]`, `...rest`, `a = 1`) makes the arguments
3084 // object unmapped whatever the mode — §10.4.4 keys the decision on
3085 // `IsSimpleParameterList`, not on strictness alone.
3086 let magic = if self.stack[current].strict || !self.stack[current].simple_parameter_list {
3087 0
3088 } else {
3089 1
3090 };
3091 // A mapped `arguments` shares storage with the parameters: `arguments[0] = 2`
3092 // has to be visible as `a`, and assigning `a` has to be visible as `arguments[0]`.
3093 // The only storage both sides can see is a reference cell, so every parameter the
3094 // object maps gets one — even a parameter no closure captured. Without this the
3095 // slot holds a plain copy and the mapping has nothing to write through.
3096 if magic == 1 {
3097 for arg in &mut self.stack[current].args {
3098 arg.is_captured = true;
3099 }
3100 }
3101 self.prepend_binding("arguments", magic);
3102 }
3103
3104 /// Whether a *body* instruction refers to `arguments`.
3105 fn body_mentions_arguments(&self) -> bool {
3106 self.cur()
3107 .insns
3108 .iter()
3109 .any(|insn| matches!(insn, Insn::Var { name, in_params, .. } if name == "arguments" && !*in_params))
3110 }
3111
3112 /// Whether the function body's instruction stream refers to `name`.
3113 fn mentions(&self, name: &str) -> bool {
3114 let current = self.stack.len() - 1;
3115 // A binding of the parameter scope does not answer for the body: the body's own
3116 // `arguments` (or self-name) still has to be provided for it.
3117 if self.stack[current]
3118 .vars
3119 .iter()
3120 .enumerate()
3121 .any(|(index, v)| {
3122 v.name == name
3123 && self.stack[current].var_block.get(index).copied() != Some(PARAM_SCOPE)
3124 })
3125 {
3126 return false;
3127 }
3128 self.stack[current]
3129 .insns
3130 .iter()
3131 .any(|insn| matches!(insn, Insn::Var { name: used, .. } if used == name))
3132 }
3133
3134 /// Bind the name a named function expression uses to refer to itself.
3135 ///
3136 /// The value is `special_object 2`, the function currently running, so the binding
3137 /// is the closure itself and not a copy. It is a local of this function, which is
3138 /// what keeps `g` out of the enclosing scope.
3139 /// Give the function a local `this`, for an arrow inside it to capture.
3140 fn provide_this_local(&mut self) {
3141 let current = self.stack.len() - 1;
3142 if !self.stack[current].needs_this_local || self.stack[current].has_this_prologue {
3143 return;
3144 }
3145 if !self.stack[current]
3146 .vars
3147 .iter()
3148 .any(|var| var.name == "this")
3149 {
3150 self.declare_hidden_local("this", VarKind::Normal);
3151 }
3152 self.prepend_initialiser(
3153 "this",
3154 Insn::Fixed {
3155 op: Opcode::PushThis,
3156 operands: vec![],
3157 },
3158 );
3159 }
3160
3161 /// Give the function a local `<home_object>`, for an arrow or a static block inside it
3162 /// to read through `super`.
3163 fn provide_home_object_local(&mut self) {
3164 let current = self.stack.len() - 1;
3165 if !self.stack[current].needs_home_object_local {
3166 return;
3167 }
3168 if !self.stack[current]
3169 .vars
3170 .iter()
3171 .any(|var| var.name == HOME_OBJECT)
3172 {
3173 self.declare_hidden_local(HOME_OBJECT, VarKind::Normal);
3174 }
3175 self.prepend_initialiser(
3176 HOME_OBJECT,
3177 Insn::Fixed {
3178 op: Opcode::SpecialObject,
3179 operands: vec![Op::Int(4)],
3180 },
3181 );
3182 }
3183
3184 fn provide_self_name(&mut self) {
3185 let current = self.stack.len() - 1;
3186 let Some(name) = self.stack[current].self_name.clone() else {
3187 return;
3188 };
3189 if self.stack[current].self_name_initialized {
3190 return;
3191 }
3192 // Either the body refers to the name, or a nested function already forced the
3193 // binding into existence while being resolved. A direct `eval` can name it
3194 // without mentioning it, so its presence is a third reason: in strict mode
3195 // `eval("f = 1")` has to raise a `TypeError` rather than a `ReferenceError`, and
3196 // that only happens if the binding exists.
3197 // Only a *function-scope* declaration can already hold the name. A block-scoped
3198 // `let` of the same name shadows it without replacing it, so the binding still has
3199 // to be created — see `declare_var`.
3200 let declared = self.stack[current]
3201 .vars
3202 .iter()
3203 .any(|v| v.name == name && !v.is_lexical);
3204 if !declared && !self.mentions(&name) && !self.stack[current].has_direct_eval {
3205 return;
3206 }
3207 self.stack[current].self_name_initialized = true;
3208 self.prepend_binding_with(&name, 2, VarKind::FunctionName);
3209 }
3210
3211 /// Insert `special_object magic` plus the store to `name` at the top of the body.
3212 ///
3213 /// Prepending shifts every label that has been placed, so they are all moved by
3214 /// the number of instructions inserted.
3215 fn prepend_binding(&mut self, name: &str, magic: i32) {
3216 self.prepend_binding_with(name, magic, VarKind::Normal);
3217 }
3218
3219 /// [`Compiler::prepend_binding`] for a binding that is more than a plain local.
3220 fn prepend_binding_with(&mut self, name: &str, magic: i32, kind: VarKind) {
3221 let current = self.stack.len() - 1;
3222 // A function-expression's own name is immutable in strict mode, which is what
3223 // makes `f = 1` inside a strict body throw instead of being dropped.
3224 let is_const = kind == VarKind::FunctionName && self.stack[current].strict;
3225 self.declare_var(
3226 name,
3227 VarDef {
3228 kind,
3229 is_const,
3230 ..VarDef::var(name)
3231 },
3232 );
3233 let init = [
3234 Insn::Fixed {
3235 op: Opcode::SpecialObject,
3236 operands: vec![Op::Int(magic)],
3237 },
3238 Insn::Var {
3239 // An initialisation, not an assignment: sloppy mode drops stores to a
3240 // function-expression's own name, and the prologue is what puts the
3241 // value there in the first place.
3242 action: if kind == VarKind::FunctionName {
3243 VarAction::PutInit
3244 } else {
3245 VarAction::Put
3246 },
3247 name: name.to_string(),
3248 block: 0,
3249 in_params: false,
3250 },
3251 ];
3252 let inserted = init.len();
3253 for (index, instruction) in init.into_iter().enumerate() {
3254 self.stack[current].insns.insert(index, instruction);
3255 }
3256 for placed in self.stack[current].labels.iter_mut().flatten() {
3257 *placed += inserted;
3258 }
3259 // A store sits at the insertion point now, so the `put`/`get` fold must not
3260 // reach across it.
3261 self.stack[current].label_since_insn = true;
3262 }
3263
3264 /// Record a top-level script declaration as a global.
3265 ///
3266 /// A script's top-level `var`/`let`/`function` create properties of the
3267 /// global object, not slots in the script's frame, so they show up as closure
3268 /// variables instead.
3269 fn declare_global(&mut self, name: &str, def: &VarDef) {
3270 let state = self.state();
3271 if let Some(existing) = state.closure_vars.iter_mut().find(|c| c.name == name) {
3272 // The name was already referenced, from a function compiled before this
3273 // declaration was reached — `function a(){ b() } function b(){}` resolves
3274 // `b` while `b` is still unknown, and that guess has to be corrected here.
3275 // Leaving it as a plain global meant the declaration was never registered,
3276 // so the binding did not exist at run time and `a()` threw
3277 // `b is not defined`.
3278 if matches!(existing.closure_type, ClosureType::Global) {
3279 existing.closure_type = ClosureType::GlobalDecl;
3280 existing.is_const = def.is_const;
3281 existing.is_lexical = def.is_lexical;
3282 existing.is_function_decl =
3283 def.kind == crate::bytecode::VarKind::GlobalFunctionDecl;
3284 }
3285 return;
3286 }
3287 state.closure_vars.push(ClosureVar {
3288 name: name.to_string(),
3289 is_const: def.is_const,
3290 is_lexical: def.is_lexical,
3291 is_function_decl: def.kind == crate::bytecode::VarKind::GlobalFunctionDecl,
3292 closure_type: ClosureType::GlobalDecl,
3293 var_idx: 0,
3294 });
3295 }
3296
3297 /// Record a module-level declaration as a module variable.
3298 ///
3299 /// The binding is a closure variable of the module body, so reads and writes are
3300 /// ordinary `var_ref` opcodes — the same shape a captured local has. What differs is
3301 /// *who fills the cell*: the module record does, before the body runs, and an import
3302 /// points its cell at the exporting module's, which is what makes bindings live and
3303 /// cycles work.
3304 fn declare_module(&mut self, name: &str, def: &VarDef) -> u32 {
3305 let state = self.state();
3306 if let Some(existing) = state.closure_vars.iter_mut().find(|c| c.name == name) {
3307 // The name may have been referenced before this declaration was hoisted,
3308 // which resolved it as a plain global. Correct that here, the way
3309 // `declare_global` does.
3310 if matches!(existing.closure_type, ClosureType::Global) {
3311 existing.closure_type = ClosureType::ModuleDecl;
3312 existing.is_const = def.is_const;
3313 existing.is_lexical = def.is_lexical;
3314 }
3315 return 0;
3316 }
3317 state.closure_vars.push(ClosureVar {
3318 name: name.to_string(),
3319 is_const: def.is_const,
3320 is_lexical: def.is_lexical,
3321 is_function_decl: false,
3322 closure_type: ClosureType::ModuleDecl,
3323 var_idx: 0,
3324 });
3325 0
3326 }
3327
3328 /// Declare a module variable and answer its closure-variable index.
3329 ///
3330 /// [`Compiler::declare_module`] answers `0` because its callers want a *slot*, and a
3331 /// module variable is not one. The import table needs the real index instead, because
3332 /// that is the position the host writes the cell into.
3333 fn declare_module_var(&mut self, name: &str, def: &VarDef) -> u32 {
3334 self.declare_module(name, def);
3335 self.cur()
3336 .closure_vars
3337 .iter()
3338 .position(|c| c.name == name)
3339 .map(|index| index as u32)
3340 .unwrap_or(0)
3341 }
3342
3343 /// Declare one imported binding as a module variable.
3344 ///
3345 /// Returns the closure-variable index, which is what the import table records: the
3346 /// host writes the exporter's cell into that slot before the body runs.
3347 fn declare_import(&mut self, name: &str, is_const: bool) -> u32 {
3348 let state = self.state();
3349 if let Some(index) = state.closure_vars.iter().position(|c| c.name == name) {
3350 // Keep the slot, fix the kind: the name may already have been referenced.
3351 state.closure_vars[index].closure_type = ClosureType::ModuleImport;
3352 state.closure_vars[index].is_const = is_const;
3353 return index as u32;
3354 }
3355 state.closure_vars.push(ClosureVar {
3356 name: name.to_string(),
3357 // An imported binding cannot be assigned: `x = 1` on an import is a
3358 // `TypeError` at run time, which the const flag is what produces.
3359 is_const: true,
3360 // Lexical, so reads go through `get_var_ref_check`: before linking has filled
3361 // the cell an import is in its dead zone, and reading it there must say so
3362 // rather than answer `undefined`.
3363 is_lexical: true,
3364 is_function_decl: false,
3365 closure_type: ClosureType::ModuleImport,
3366 var_idx: 0,
3367 });
3368 state.closure_vars.len() as u32 - 1
3369 }
3370
3371 /// Emit the code an `export` needs.
3372 ///
3373 /// Only `export default <expr>` has any: everything else is a table entry whose
3374 /// binding is declared elsewhere. The expression is stored into the hidden
3375 /// `*default*` variable rather than returned, because the module body has no value
3376 /// to speak of.
3377 fn export_stmt(&mut self, decl: &ExportDecl) -> Result<(), SyntaxError> {
3378 match &decl.kind {
3379 ExportKind::Declaration(stmt) => self.stmt(stmt),
3380 ExportKind::Default(expr) => {
3381 // `export default class Foo {}`: evaluate the declaration (which binds
3382 // `Foo`), then copy its value into the hidden `*default*` binding, because a
3383 // class declaration is a *statement* and `expr` cannot be compiled as one.
3384 if let ExprKind::Class(class) = &expr.kind
3385 && class.name.is_some()
3386 {
3387 self.stmt(&Stmt {
3388 kind: StmtKind::ClassDecl(class.clone()),
3389 span: expr.span,
3390 })?;
3391 let Some(name) = &class.name else {
3392 return Ok(());
3393 };
3394 self.emit_var(VarAction::Get, &name.name);
3395 let index = self.declare_export_default();
3396 self.emit(Opcode::PutVarRef, &[Op::Slot(Slot::VarRef(index))]);
3397 return Ok(());
3398 }
3399 // A named default function/class is already a module binding; the export
3400 // points at it and there is nothing to evaluate.
3401 if matches!(&expr.kind, ExprKind::Function(func) if func.name.is_some()) {
3402 return Ok(());
3403 }
3404 self.expr(expr)?;
3405 // §16.2.1.10 step 1.b: an *anonymous* default export is named `"default"`
3406 // by `SetFunctionName`, exactly as `var f = function(){}` is named `f`. The
3407 // name is observable — `imported.default.name` — and without this an
3408 // anonymous `export default class {}` arrived with the empty name.
3409 self.set_name_if_anonymous(expr, &Wtf8::new("default"));
3410 let index = self.declare_export_default();
3411 self.emit(Opcode::PutVarRef, &[Op::Slot(Slot::VarRef(index))]);
3412 Ok(())
3413 }
3414 ExportKind::Named { .. } | ExportKind::All { .. } => Ok(()),
3415 }
3416 }
3417
3418 /// A module name as the string it denotes.
3419 fn module_name_text(name: &ModuleName) -> &str {
3420 match name {
3421 ModuleName::Ident(ident) => &ident.name,
3422 ModuleName::Str(text) => text,
3423 }
3424 }
3425
3426 /// Bind `import`'s local names and record where each one comes from.
3427 ///
3428 /// Nothing is emitted: an import is not an instruction, it is a promise that the
3429 /// binding's cell will be filled before the body runs. The cell lands in the module's
3430 /// environment at a fixed index, and the host fills it from the exporter's cell —
3431 /// which is why a cyclic import can bind before the other module has evaluated.
3432 fn hoist_import(&mut self, decl: &ImportDecl) -> Result<(), SyntaxError> {
3433 let request = self.module_request(&decl.source, &decl.attributes, decl.phase);
3434 for specifier in &decl.specifiers {
3435 let (local, name, is_star) = match specifier {
3436 ImportSpecifier::Default(ident) => {
3437 (ident.name.clone(), "default".to_string(), false)
3438 }
3439 ImportSpecifier::Namespace(ident) => (ident.name.clone(), String::new(), true),
3440 ImportSpecifier::Named { imported, local } => (
3441 local.name.clone(),
3442 Self::module_name_text(imported).to_string(),
3443 false,
3444 ),
3445 };
3446 // `import * as ns` is *not* a live binding of another module's variable —
3447 // it is a value of its own, which is why the reference declares it like a
3448 // module variable and the host stores the namespace object in that cell.
3449 let var_idx = if is_star {
3450 // `const`: a namespace object is a value, and the binding is immutable.
3451 self.declare_module_var(&local, &VarDef::constant(local.clone()))
3452 } else {
3453 self.declare_import(&local, true)
3454 };
3455 self.module_meta().imports.push(ImportEntry {
3456 module: request,
3457 name,
3458 var_idx,
3459 is_star,
3460 phase: decl.phase,
3461 });
3462 }
3463 Ok(())
3464 }
3465
3466 /// Record what an `export` offers, declaring the binding it exports.
3467 ///
3468 /// `export var x = 1` is a declaration like any other; only the table entry is extra.
3469 fn hoist_export(&mut self, decl: &ExportDecl) -> Result<(), SyntaxError> {
3470 match &decl.kind {
3471 ExportKind::Declaration(stmt) => {
3472 // The inner declaration keeps its own hoisting, then every name it binds
3473 // becomes an export of the same name.
3474 self.hoist_stmt(stmt)?;
3475 let mut names = Vec::new();
3476 Self::declared_names(stmt, &mut names);
3477 for name in names {
3478 let var_idx = self.module_binding_index(&name);
3479 self.exports_local(&name, var_idx);
3480 }
3481 }
3482 ExportKind::Default(expr) => {
3483 // The reference puts a default export in a hidden `*default*` variable,
3484 // so `export default function f(){}` can export a *value* while `f` stays
3485 // a binding of the module.
3486 if let ExprKind::Function(func) = &expr.kind
3487 && let Some(name) = &func.name
3488 {
3489 let text = name.name.clone();
3490 self.hoist_stmt(&Stmt {
3491 kind: StmtKind::FuncDecl(func.clone()),
3492 span: expr.span,
3493 })?;
3494 let var_idx = self.module_binding_index(&text);
3495 self.module_meta().exports.push(ExportEntry::Local {
3496 export_name: "default".to_string(),
3497 var_idx,
3498 });
3499 return Ok(());
3500 }
3501 if let ExprKind::Class(class) = &expr.kind
3502 && class.name.is_some()
3503 {
3504 // `export default class Foo {}` binds `Foo` in the module scope **and**
3505 // stores the class into the hidden `*default*` binding — it is a
3506 // declaration *and* a value, unlike `export default class {}` which is
3507 // only a value.
3508 //
3509 // Pointing the `default` export straight at `Foo` looked simpler and was
3510 // wrong twice over: `module_binding_index` did not find the lexical
3511 // binding the hoist had just made, so it declared a second one that
3512 // nothing ever wrote, and `export_stmt` then had no code to emit for the
3513 // declaration either. `imported.default` came out `undefined` and `Foo`
3514 // was not in scope inside its own module.
3515 self.hoist_stmt(&Stmt {
3516 kind: StmtKind::ClassDecl(class.clone()),
3517 span: expr.span,
3518 })?;
3519 let var_idx = self.declare_export_default();
3520 self.exports_local("default", var_idx);
3521 return Ok(());
3522 }
3523 let var_idx = self.declare_export_default();
3524 self.module_meta().exports.push(ExportEntry::Local {
3525 export_name: "default".to_string(),
3526 var_idx,
3527 });
3528 }
3529 ExportKind::Named {
3530 specifiers,
3531 source,
3532 attributes,
3533 } => match source {
3534 Some(source) => {
3535 let request = self.module_request(source, attributes, ImportPhase::Evaluation);
3536 for specifier in specifiers {
3537 self.module_meta().exports.push(ExportEntry::Indirect {
3538 export_name: Self::module_name_text(&specifier.exported).to_string(),
3539 module: request,
3540 import_name: Self::module_name_text(&specifier.local).to_string(),
3541 });
3542 }
3543 }
3544 None => {
3545 for specifier in specifiers {
3546 let local = Self::module_name_text(&specifier.local).to_string();
3547 let export_name = Self::module_name_text(&specifier.exported).to_string();
3548 // `export { x }` where `x` is itself an **import** re-exports the
3549 // binding the import names, not a binding of this module
3550 // (§16.2.1.6.3: a local export whose local name is imported resolves
3551 // through the imported module). Recording it as a local made two
3552 // modules that both forward one import look like two different
3553 // bindings, and the name was reported ambiguous
3554 // (`import-and-export-propagates-binding`;
3555 // `namespace-unambiguous-if-import-star-as-and-export`).
3556 let closure_names: Vec<String> = self
3557 .cur()
3558 .closure_vars
3559 .iter()
3560 .map(|var| var.name.clone())
3561 .collect();
3562 let forwarded = self
3563 .module_meta()
3564 .imports
3565 .iter()
3566 .filter(|entry| {
3567 closure_names
3568 .get(entry.var_idx as usize)
3569 .is_some_and(|name| *name == local)
3570 })
3571 .map(|entry| (entry.module, entry.name.clone(), entry.is_star))
3572 .find(|(_, name, is_star)| !is_star || name.is_empty());
3573 if let Some((request, name, is_star)) = forwarded {
3574 // A namespace import has no export *name* of its own; the
3575 // resolution is `{ [[Module]]: m, [[BindingName]]: namespace }`,
3576 // which is what the marker below records.
3577 let import_name = if is_star {
3578 "*namespace*".to_string()
3579 } else {
3580 name
3581 };
3582 self.module_meta().exports.push(ExportEntry::Indirect {
3583 export_name,
3584 module: request,
3585 import_name,
3586 });
3587 continue;
3588 }
3589 let var_idx = self.module_binding_index(&local);
3590 self.module_meta().exports.push(ExportEntry::Local {
3591 export_name,
3592 var_idx,
3593 });
3594 }
3595 }
3596 },
3597 ExportKind::All {
3598 source,
3599 exported,
3600 attributes,
3601 } => {
3602 let request = self.module_request(source, attributes, ImportPhase::Evaluation);
3603 match exported {
3604 Some(name) => {
3605 self.module_meta().exports.push(ExportEntry::StarAs {
3606 export_name: Self::module_name_text(name).to_string(),
3607 module: request,
3608 });
3609 }
3610 None => {
3611 self.module_meta()
3612 .exports
3613 .push(ExportEntry::Star { module: request });
3614 }
3615 }
3616 }
3617 }
3618 Ok(())
3619 }
3620
3621 /// The names a declaration binds, which is what `export <decl>` exports.
3622 fn declared_names(stmt: &Stmt, out: &mut Vec<String>) {
3623 match &stmt.kind {
3624 StmtKind::VarDecl(decl) => {
3625 for declarator in &decl.declarators {
3626 let mut names = Vec::new();
3627 declarator.target.bound_names(&mut names);
3628 out.extend(names.into_iter().map(|name| name.name));
3629 }
3630 }
3631 StmtKind::FuncDecl(func) => {
3632 if let Some(name) = &func.name {
3633 out.push(name.name.clone());
3634 }
3635 }
3636 StmtKind::ClassDecl(class) => {
3637 if let Some(name) = &class.name {
3638 out.push(name.name.clone());
3639 }
3640 }
3641 _ => {}
3642 }
3643 }
3644
3645 /// The closure-variable index of a module binding, declaring it if the name was
3646 /// exported without being declared here.
3647 ///
3648 /// `export { x }` where `x` is not declared in the module is a link-time
3649 /// `SyntaxError`, not a compile-time one, so the slot still has to exist.
3650 fn module_binding_index(&mut self, name: &str) -> u32 {
3651 if let Some(index) = self.cur().closure_vars.iter().position(|c| c.name == name) {
3652 return index as u32;
3653 }
3654 self.declare_module_var(name, &VarDef::lexical(name.to_string()))
3655 }
3656
3657 fn exports_local(&mut self, export_name: &str, var_idx: u32) {
3658 self.module_meta().exports.push(ExportEntry::Local {
3659 export_name: export_name.to_string(),
3660 var_idx,
3661 });
3662 }
3663
3664 /// The hidden `*default*` binding `export default <expr>` stores into.
3665 fn declare_export_default(&mut self) -> u32 {
3666 const DEFAULT: &str = "*default*";
3667 if let Some(index) = self
3668 .cur()
3669 .closure_vars
3670 .iter()
3671 .position(|c| c.name == DEFAULT)
3672 {
3673 return index as u32;
3674 }
3675 self.declare_module_var(DEFAULT, &VarDef::lexical(DEFAULT.to_string()))
3676 }
3677
3678 /// The module tables, which only the top-level state has.
3679 fn module_meta(&mut self) -> &mut ModuleMeta {
3680 self.state()
3681 .module
3682 .as_mut()
3683 .expect("module tables are only touched while compiling a module")
3684 }
3685
3686 /// The index of `specifier`'s request, adding it if it is new.
3687 ///
3688 /// Deduplicated on the specifier *and* its attributes: the same file imported once as
3689 /// JSON and once as text is two modules with two different contents, which is exactly
3690 /// what `hello_module.js` does.
3691 fn module_request(
3692 &mut self,
3693 specifier: &str,
3694 attributes: &[ImportAttribute],
3695 phase: ImportPhase,
3696 ) -> u32 {
3697 let attributes: Vec<(String, String)> = attributes
3698 .iter()
3699 .map(|attribute| (attribute.key.clone(), attribute.value.clone()))
3700 .collect();
3701 let meta = self.module_meta();
3702 // De-duplicated on the specifier *and* the phase: one module can be asked for twice,
3703 // once eagerly and once deferred, and the two answers are different objects.
3704 if let Some(index) = meta.requests.iter().position(|request| {
3705 request.specifier == specifier
3706 && request.attributes == attributes
3707 && request.phase == phase
3708 }) {
3709 return index as u32;
3710 }
3711 meta.requests.push(ModuleRequest {
3712 specifier: specifier.to_string(),
3713 attributes,
3714 phase,
3715 });
3716 meta.requests.len() as u32 - 1
3717 }
3718
3719 /// Compile a loop body with a `break`/`continue` target pushed for it.
3720 fn loop_body(
3721 &mut self,
3722 body: &Stmt,
3723 labels: &[String],
3724 continue_label: Label,
3725 break_label: Label,
3726 ) -> Result<(), SyntaxError> {
3727 self.push_jump_target(JumpTarget {
3728 names: labels.to_vec(),
3729 break_label: Some(break_label),
3730 continue_label: Some(continue_label),
3731 // A loop leaves nothing of its own on the value stack.
3732 drop_count: 0,
3733 finally_label: None,
3734 is_regular_stmt: false,
3735 has_iterator: false,
3736 is_async_iterator: false,
3737 });
3738 let result = self.stmt(body);
3739 self.pop_jump_target();
3740 result
3741 }
3742
3743 fn push_jump_target(&mut self, target: JumpTarget) {
3744 self.state().jump_targets.push(target);
3745 }
3746
3747 fn pop_jump_target(&mut self) {
3748 self.state().jump_targets.pop();
3749 }
3750
3751 fn control_transfer(&mut self, stmt: &Stmt) -> Result<(), SyntaxError> {
3752 let (label, is_break) = match &stmt.kind {
3753 StmtKind::Break(label) => (label.as_ref(), true),
3754 StmtKind::Continue(label) => (label.as_ref(), false),
3755 _ => unreachable!("control_transfer is only called for break and continue"),
3756 };
3757
3758 // Walk outward from the innermost construct. Everything considered before
3759 // the match is a construct control is leaving, and leaving it has a cost:
3760 // its stack slots go, and its finalizer runs.
3761 let targets = self.cur().jump_targets.clone();
3762 for target in targets.iter().rev() {
3763 let destination = match (label, is_break) {
3764 // An unlabelled `break` skips a labelled non-loop statement: `break`
3765 // may name one, but the bare form only means "leave the loop".
3766 (None, true) => target.break_label.filter(|_| !target.is_regular_stmt),
3767 (None, false) => target.continue_label,
3768 (Some(name), true) => target
3769 .break_label
3770 .filter(|_| target.names.contains(&name.name)),
3771 (Some(name), false) => target
3772 .continue_label
3773 .filter(|_| target.names.contains(&name.name)),
3774 };
3775
3776 if let Some(destination) = destination {
3777 self.emit_jump(Opcode::Goto, destination, &[]);
3778 return Ok(());
3779 }
3780
3781 // Closing the iterator consumes the three slots the loop keeps on the
3782 // stack (iterator, next method, catch offset), so those are not dropped
3783 // again below.
3784 let mut remaining = target.drop_count;
3785 if target.has_iterator {
3786 self.emit_iterator_close(target.is_async_iterator, false);
3787 remaining = remaining.saturating_sub(3);
3788 }
3789 for _ in 0..remaining {
3790 self.emit(Opcode::Drop, &[]);
3791 }
3792 if let Some(finally) = target.finally_label {
3793 // The finalizer runs as a subroutine and is handed a dummy return
3794 // value, which is dropped afterwards to keep the stack the depth it
3795 // had before.
3796 self.emit(Opcode::Undefined, &[]);
3797 self.emit_jump(Opcode::Gosub, finally, &[]);
3798 self.emit(Opcode::Drop, &[]);
3799 }
3800 }
3801
3802 // The parser rejects a break/continue with no target, so reaching here
3803 // means the compiler's own bookkeeping is wrong.
3804 Err(SyntaxError::new(
3805 if is_break {
3806 "break has no enclosing loop or switch"
3807 } else {
3808 "continue has no enclosing loop"
3809 },
3810 stmt.span,
3811 ))
3812 }
3813
3814 /// Compile a labelled statement.
3815 ///
3816 /// `a: b: for(…)` is a chain of labels on one loop; every name has to reach
3817 /// that loop's targets, so the chain is collected and handed to the loop. A
3818 /// label on a non-loop statement only provides a `break` target, because
3819 /// `continue` may not target it.
3820 fn labeled(&mut self, label: &Ident, body: &Stmt, stmt: &Stmt) -> Result<(), SyntaxError> {
3821 let mut names = vec![label.name.clone()];
3822 let mut inner = body;
3823 while let StmtKind::Labeled {
3824 label: next,
3825 body: deeper,
3826 } = &inner.kind
3827 {
3828 names.push(next.name.clone());
3829 inner = deeper;
3830 }
3831 if Self::is_loop(inner) {
3832 return self.stmt_labelled(inner, &names);
3833 }
3834 let end = self.new_label();
3835 self.push_jump_target(JumpTarget {
3836 names,
3837 break_label: Some(end),
3838 continue_label: None,
3839 drop_count: 0,
3840 finally_label: None,
3841 is_regular_stmt: true,
3842 has_iterator: false,
3843 is_async_iterator: false,
3844 });
3845 let result = self.stmt(inner);
3846 self.pop_jump_target();
3847 result?;
3848 self.place_label(end);
3849 let _ = stmt;
3850 Ok(())
3851 }
3852
3853 /// Whether a statement is a loop, i.e. a valid target for `continue`.
3854 fn is_loop(stmt: &Stmt) -> bool {
3855 matches!(
3856 stmt.kind,
3857 StmtKind::While { .. }
3858 | StmtKind::DoWhile { .. }
3859 | StmtKind::For { .. }
3860 | StmtKind::ForIn { .. }
3861 | StmtKind::ForOf { .. }
3862 )
3863 }
3864
3865 /// Compile `switch`.
3866 ///
3867 /// The discriminant is evaluated once and stays on the value stack while the
3868 /// clauses compare against copies of it, so it is dropped at the end — which is
3869 /// why `switch (x) { }` still leaves `x` behind. Fallthrough is real: a
3870 /// clause's body jumps over the *next* clause's tests straight into its body.
3871 ///
3872 /// The tests form a chain: each `case` run compares and, on a miss, hands over to
3873 /// the next run's tests. Only the last run's miss reaches the `default` body, or
3874 /// the end of the switch when there is no `default`. That failure path can point
3875 /// backwards (`default` written first), so the runs and their labels are worked
3876 /// out before any code is emitted.
3877 fn switch(
3878 &mut self,
3879 discriminant: &Expr,
3880 cases: &[SwitchCase],
3881 stmt: &Stmt,
3882 ) -> Result<(), SyntaxError> {
3883 self.reset_value();
3884 // The discriminant is evaluated outside the switch's block scope, before
3885 // any `case` clause exists.
3886 self.expr(discriminant)?;
3887
3888 let switch_key = stmt.span.start.offset as u64;
3889 let switch_parent = self.cur().current_block;
3890 self.push_block(switch_key, switch_parent);
3891 self.emit_scope_enter(switch_key);
3892
3893 let break_label = self.new_label();
3894 self.push_jump_target(JumpTarget {
3895 names: Vec::new(),
3896 break_label: Some(break_label),
3897 // `switch` is a valid `break` target but not a `continue` target.
3898 continue_label: None,
3899 // The discriminant stays on the value stack for the whole statement, so
3900 // a `break` aimed further out has to discard it.
3901 drop_count: 1,
3902 finally_label: None,
3903 is_regular_stmt: false,
3904 has_iterator: false,
3905 is_async_iterator: false,
3906 });
3907
3908 // Runs of tests. `case 1: case 2: body` is one run: the empty clause hands
3909 // its label to the clause after it, so both tests reach the same body.
3910 let mut runs: Vec<(usize, usize)> = Vec::new();
3911 let mut scan = 0;
3912 while scan < cases.len() {
3913 if cases[scan].test.is_some() {
3914 let mut last = scan;
3915 while last + 1 < cases.len()
3916 && cases[last].test.is_some()
3917 && cases[last].body.is_empty()
3918 && cases[last + 1].test.is_some()
3919 {
3920 last += 1;
3921 }
3922 runs.push((scan, last));
3923 scan = last + 1;
3924 } else {
3925 scan += 1;
3926 }
3927 }
3928
3929 let body_labels: Vec<Label> = cases.iter().map(|_| self.new_label()).collect();
3930 let run_labels: Vec<Label> = runs.iter().map(|_| self.new_label()).collect();
3931 let default_at = cases.iter().position(|case| case.test.is_none());
3932 // Where the last run sends control when nothing matched.
3933 let miss_target = match default_at {
3934 Some(index) => body_labels[index],
3935 None => break_label,
3936 };
3937
3938 // When `default` comes first, control has to jump over it to reach the
3939 // tests. It only needs to when some clause actually has a test; otherwise
3940 // the default body is the entry point.
3941 let mut entry = None;
3942 if default_at == Some(0) && !runs.is_empty() {
3943 self.emit_jump(Opcode::Goto, run_labels[0], &[]);
3944 entry = Some(run_labels[0]);
3945 }
3946
3947 let mut index = 0;
3948 let mut run = 0;
3949 let result = (|| -> Result<(), SyntaxError> {
3950 while index < cases.len() {
3951 if cases[index].test.is_some() {
3952 let (first, last) = runs[run];
3953 // Reaching these tests from the preceding body is a
3954 // fallthrough, which continues inside the body and skips them.
3955 if index > 0 {
3956 self.emit_jump(Opcode::Goto, body_labels[index], &[]);
3957 }
3958 if let Some(label) = entry.take() {
3959 self.place_label(label);
3960 }
3961 self.place_label(run_labels[run]);
3962
3963 for (offset, case) in cases[first..=last].iter().enumerate() {
3964 let test = case.test.as_ref().unwrap();
3965 self.emit(Opcode::Dup, &[]);
3966 self.expr(test)?;
3967 self.emit(Opcode::StrictEq, &[]);
3968 if first + offset < last {
3969 self.emit_jump(Opcode::IfTrue, body_labels[index], &[]);
3970 } else {
3971 // Hand over to the next run's tests, or give up.
3972 let next = match runs.get(run + 1) {
3973 Some(_) => run_labels[run + 1],
3974 None => miss_target,
3975 };
3976 self.emit_jump(Opcode::IfFalse, next, &[]);
3977 }
3978 }
3979
3980 self.place_label(body_labels[index]);
3981 for case in &cases[first..=last] {
3982 self.stmts(&case.body)?;
3983 }
3984 index = last + 1;
3985 run += 1;
3986 } else {
3987 // `default`: control arrives here either by falling through or
3988 // because every test missed.
3989 self.place_label(body_labels[index]);
3990 self.stmts(&cases[index].body)?;
3991 index += 1;
3992 }
3993 }
3994 Ok(())
3995 })();
3996
3997 if result.is_ok() {
3998 self.place_label(break_label);
3999 // Discard the discriminant now that no test needs it.
4000 self.emit(Opcode::Drop, &[]);
4001 }
4002
4003 self.pop_jump_target();
4004 self.emit_scope_leave(switch_key);
4005 self.state().current_block = switch_parent;
4006 result
4007 }
4008
4009 /// Compile `try`/`catch`/`finally`.
4010 ///
4011 /// The shape is an exception table built out of `catch` instructions, each of
4012 /// which records where control goes if the instructions that follow raise:
4013 ///
4014 /// ```text
4015 /// catch HANDLER <- if the guarded block throws, jump to HANDLER
4016 /// <guarded block>
4017 /// drop <- discard the catch offset
4018 /// undefined; gosub FINALLY; drop
4019 /// goto END
4020 /// HANDLER:
4021 /// <bind the catch parameter>
4022 /// catch CATCH2 <- if the handler itself throws, go to CATCH2
4023 /// <handler body>
4024 /// drop; undefined; gosub FINALLY; drop; goto END
4025 /// CATCH2:
4026 /// gosub FINALLY; throw <- run the finalizer, then let the error out
4027 /// FINALLY:
4028 /// <finalizer>
4029 /// ret <- return to the `gosub`
4030 /// END:
4031 /// ```
4032 ///
4033 /// `gosub` is a subroutine call and `ret` returns to it, which is how one copy
4034 /// of the finalizer serves the normal path, the handler path and the
4035 /// propagating-exception path.
4036 ///
4037 /// The `undefined` before each `gosub` is a dummy return value: the finalizer
4038 /// runs with `ret_value` on the stack, and the normal path has no value to
4039 /// keep, so it pushes one to keep the stack depth identical on every path.
4040 fn try_stmt(
4041 &mut self,
4042 stmt: &Stmt,
4043 block: &[Stmt],
4044 handler: &Option<CatchClause>,
4045 finalizer: Option<&[Stmt]>,
4046 ) -> Result<(), SyntaxError> {
4047 self.reset_value();
4048
4049 let catch_label = self.new_label();
4050 let catch2_label = self.new_label();
4051 let finally_label = self.new_label();
4052 let end_label = self.new_label();
4053
4054 self.emit_jump(Opcode::Catch, catch_label, &[]);
4055
4056 // The guarded block. `break` may not target it, so its entry exists purely
4057 // to unwind: a jump out has to discard the catch offset and run the
4058 // finalizer.
4059 self.push_jump_target(JumpTarget {
4060 names: Vec::new(),
4061 break_label: None,
4062 continue_label: None,
4063 drop_count: 1,
4064 finally_label: Some(finally_label),
4065 is_regular_stmt: false,
4066 has_iterator: false,
4067 is_async_iterator: false,
4068 });
4069
4070 let block_key = Self::try_block_key(stmt, TryPart::Block);
4071 let block_parent = self.cur().current_block;
4072 self.push_block(block_key, block_parent);
4073 self.emit_scope_enter(block_key);
4074 self.stmts(block)?;
4075 self.emit_scope_leave(block_key);
4076 self.state().current_block = block_parent;
4077 // A guarded block that ends in a `return`/`throw` never reaches the
4078 // epilogue, so the reference does not emit one.
4079 self.pop_jump_target();
4080 let block_live = !block.last().is_some_and(Self::terminates);
4081
4082 if block_live {
4083 self.emit(Opcode::Drop, &[]);
4084 self.emit(Opcode::Undefined, &[]);
4085 self.emit_jump(Opcode::Gosub, finally_label, &[]);
4086 self.emit(Opcode::Drop, &[]);
4087 self.emit_jump(Opcode::Goto, end_label, &[]);
4088 }
4089
4090 if let Some(handler) = handler {
4091 self.place_label(catch_label);
4092 // The thrown value is on top of the stack: bind it, or discard it for
4093 // `catch { }`.
4094 match &handler.param {
4095 Some(pattern) => {
4096 // The stores resolve the names, so they have to run inside the
4097 // parameter's own scope; otherwise a same-named `catch` further out
4098 // could win. A `catch` binding is never in the dead zone, so the store
4099 // is the unchecked `put_loc` — the same one a plain `catch (e)` uses.
4100 let param_key = Self::try_block_key(stmt, TryPart::Param);
4101 let param_parent = self.cur().current_block;
4102 self.push_block(param_key, param_parent);
4103 self.destructure(pattern, Some(VarDeclKind::Var))?;
4104 self.state().current_block = param_parent;
4105 }
4106 None => self.emit(Opcode::Drop, &[]),
4107 }
4108 self.emit_jump(Opcode::Catch, catch2_label, &[]);
4109
4110 self.push_jump_target(JumpTarget {
4111 names: Vec::new(),
4112 break_label: None,
4113 continue_label: None,
4114 drop_count: 1,
4115 finally_label: Some(finally_label),
4116 is_regular_stmt: false,
4117 has_iterator: false,
4118 is_async_iterator: false,
4119 });
4120 let catch_key = Self::try_block_key(stmt, TryPart::Catch);
4121 let catch_parent = self.cur().current_block;
4122 self.push_block(catch_key, catch_parent);
4123 self.emit_scope_enter(catch_key);
4124 self.stmts(&handler.body)?;
4125 self.emit_scope_leave(catch_key);
4126 self.state().current_block = catch_parent;
4127 self.pop_jump_target();
4128 let handler_live = !handler.body.last().is_some_and(Self::terminates);
4129
4130 if handler_live {
4131 self.emit(Opcode::Drop, &[]);
4132 self.emit(Opcode::Undefined, &[]);
4133 self.emit_jump(Opcode::Gosub, finally_label, &[]);
4134 self.emit(Opcode::Drop, &[]);
4135 self.emit_jump(Opcode::Goto, end_label, &[]);
4136 }
4137
4138 // An error raised inside the handler still has to run the finalizer.
4139 self.place_label(catch2_label);
4140 self.emit_jump(Opcode::Gosub, finally_label, &[]);
4141 self.emit(Opcode::Throw, &[]);
4142 } else {
4143 // `try`/`finally` with no handler: the finalizer runs, then the error
4144 // keeps propagating.
4145 self.place_label(catch_label);
4146 self.emit_jump(Opcode::Gosub, finally_label, &[]);
4147 self.emit(Opcode::Throw, &[]);
4148 }
4149
4150 self.place_label(finally_label);
4151 // Inside the finalizer, leaving has a different cost: the return value and
4152 // the `gosub` return address are both on the stack, and neither finalizer nor
4153 // any outer one may run before the block has finished.
4154 self.push_jump_target(JumpTarget {
4155 names: Vec::new(),
4156 break_label: None,
4157 continue_label: None,
4158 drop_count: 2,
4159 finally_label: None,
4160 is_regular_stmt: false,
4161 has_iterator: false,
4162 is_async_iterator: false,
4163 });
4164 // §14.15.3 step 7: a finalizer that completes **normally** is discarded — the
4165 // `try` block's completion is what the statement answers. Only an abrupt exit from
4166 // the finalizer (`break`, `return`, a throw) replaces it, and that path jumps out
4167 // before the restore below.
4168 //
4169 // Without this the finalizer's last expression statement won: `eval('4; try { }
4170 // catch { } finally { 5; }')` answered `5` where the spec says `undefined`
4171 // (`cptn-finally-skip-catch`, `completion-values`).
4172 let saved_completion = if finalizer.is_some() && self.completion_slot().is_some() {
4173 self.declare_hidden_local("<finally.ret>", VarKind::Normal);
4174 self.emit_var(VarAction::Get, "<ret>");
4175 self.emit_var(VarAction::Put, "<finally.ret>");
4176 // And the body starts from *empty*, because an abrupt exit from the finalizer
4177 // keeps whatever the finalizer itself produced: `finally { break; }` answers
4178 // `undefined`, not the `try` block's value, while `finally { 42; break; }`
4179 // answers `42`. §14.15.3's `UpdateEmpty(F, undefined)` is what fills the empty
4180 // one in.
4181 self.emit(Opcode::Undefined, &[]);
4182 self.emit_var(VarAction::Put, "<ret>");
4183 true
4184 } else {
4185 false
4186 };
4187 if let Some(finalizer) = finalizer {
4188 let finally_key = Self::try_block_key(stmt, TryPart::Finally);
4189 let finally_parent = self.cur().current_block;
4190 self.push_block(finally_key, finally_parent);
4191 self.emit_scope_enter(finally_key);
4192 self.stmts(finalizer)?;
4193 self.emit_scope_leave(finally_key);
4194 self.state().current_block = finally_parent;
4195 }
4196 if saved_completion {
4197 // The finalizer's own statements have already run, so restoring now is what
4198 // discards a normal completion.
4199 self.emit_var(VarAction::Get, "<finally.ret>");
4200 self.emit_var(VarAction::Put, "<ret>");
4201 }
4202 self.pop_jump_target();
4203 self.emit(Opcode::Ret, &[]);
4204 self.place_label(end_label);
4205 Ok(())
4206 }
4207
4208 /// The slot of the completion-value local, when this body has one.
4209 ///
4210 /// Only a script or `eval` body has `<ret>`: a function's completion value is not
4211 /// observable, so there is nothing to keep.
4212 fn completion_slot(&self) -> Option<u32> {
4213 self.cur()
4214 .vars
4215 .iter()
4216 .position(|var| var.name == "<ret>")
4217 .map(|index| index as u32)
4218 }
4219
4220 /// Compile `for`/`in` and `for`/`of`.
4221 ///
4222 /// Both keep an enumeration record on the value stack for the whole loop, which
4223 /// is what makes leaving early expensive: the record has to be dropped, or the
4224 /// iterator closed. The layout is
4225 ///
4226 /// ```text
4227 /// <iterated expression>
4228 /// for_in_start | for_of_start <- pushes the record
4229 /// goto TEST
4230 /// NEXT:
4231 /// <bind the loop variable>
4232 /// <body>
4233 /// TEST:
4234 /// for_in_next | for_of_next 0
4235 /// if_false NEXT <- not finished: next iteration
4236 /// drop <- finished: discard the leftover value
4237 /// BREAK:
4238 /// drop | iterator_close <- the one cleanup `break` also uses
4239 /// ```
4240 ///
4241 /// `BREAK` sits *on* the cleanup rather than after it, so an early exit and the
4242 /// normal exit share one copy — which is why `break` inside the loop emits nothing
4243 /// of its own, and only a jump that passes *through* the loop pays for its record.
4244 fn for_in_of(
4245 &mut self,
4246 stmt: &Stmt,
4247 left: &ForHead,
4248 right: &Expr,
4249 body: &Stmt,
4250 kind: ForLoopKind,
4251 labels: &[String],
4252 ) -> Result<(), SyntaxError> {
4253 self.reset_value();
4254
4255 let loop_key = stmt.span.start.offset as u64;
4256 let loop_parent = self.cur().current_block;
4257 self.push_block(loop_key, loop_parent);
4258 self.emit_scope_enter(loop_key);
4259
4260 // The iterated expression is evaluated inside the loop's scope, after the
4261 // bindings exist in the temporal dead zone.
4262 self.expr(right)?;
4263
4264 let next = self.new_label();
4265 let test = self.new_label();
4266 let break_target = self.new_label();
4267
4268 let has_iterator = matches!(kind, ForLoopKind::Of | ForLoopKind::AwaitOf);
4269 match kind {
4270 ForLoopKind::In => self.emit(Opcode::ForInStart, &[]),
4271 ForLoopKind::Of => self.emit(Opcode::ForOfStart, &[]),
4272 ForLoopKind::AwaitOf => self.emit(Opcode::ForAwaitOfStart, &[]),
4273 }
4274 self.emit_jump(Opcode::Goto, test, &[]);
4275
4276 self.push_jump_target(JumpTarget {
4277 // `outer: for (x of xs) … break outer` needs the name here. Without it the
4278 // loop had no label to break to, and the compiler reported "break has no
4279 // enclosing loop" for a loop that was plainly enclosing it.
4280 names: labels.to_vec(),
4281 break_label: Some(break_target),
4282 continue_label: Some(test),
4283 // Passing through the loop has to dispose of its record. A `for`/`of`
4284 // record is three slots, and closing the iterator consumes all of them.
4285 drop_count: if has_iterator { 3 } else { 1 },
4286 finally_label: None,
4287 is_regular_stmt: false,
4288 has_iterator,
4289 is_async_iterator: matches!(kind, ForLoopKind::AwaitOf),
4290 });
4291
4292 self.place_label(next);
4293 self.bind_loop_variable(left)?;
4294
4295 // The reference marks the body with its own label here. Nothing jumps to it
4296 // once the loop is laid out, but it is not decoration: a label between the
4297 // store and the body is why `put_loc v; get_loc v` does *not* fold into
4298 // `set_loc v` when the body starts by reading the loop variable.
4299 let body_label = self.new_label();
4300 self.place_label(body_label);
4301 // `for (using x of …)` disposes once per iteration, so the body is a disposal
4302 // region rather than the whole loop: the resource is the element that this
4303 // iteration produced.
4304 let using_head = match left {
4305 ForHead::VarDecl(decl) if decl.kind.is_using() => {
4306 let slot =
4307 decl.declarators
4308 .first()
4309 .and_then(|declarator| match &declarator.target.kind {
4310 PatternKind::Ident(ident) => self.using_value_slot(&ident.name),
4311 _ => None,
4312 });
4313 slot.map(|slot| (slot, decl.kind == VarDeclKind::AwaitUsing))
4314 }
4315 _ => None,
4316 };
4317 match using_head {
4318 Some((slot, awaited)) => {
4319 let live = !Self::terminates(body);
4320 self.using_region_around(slot, live, awaited, |compiler| compiler.stmt(body))?;
4321 }
4322 None => self.stmt(body)?,
4323 }
4324
4325 // §14.7.5.6 `ForIn/OfBodyEvaluation` step 6: a `let`/`const` head gets a **fresh
4326 // binding each iteration**, so a closure the body creates keeps that iteration's
4327 // value. `CloseCaptured` is the same instruction the C-style `for` uses: it swaps in
4328 // a new reference cell holding the current value.
4329 //
4330 // The position is the *end* of the body, not the start: closing before the body
4331 // would leave the closures pointing at the cell the next `put_loc` overwrites, and
4332 // `for (const x of [1,2,3]) fs.push(() => x)` answered `2,3,3` instead of `1,2,3`.
4333 for name in Self::loop_binding_names(left) {
4334 let pos = self.cur().cur_pos;
4335 self.state().insns.push(Insn::CloseCaptured {
4336 name,
4337 block: loop_key,
4338 });
4339 self.state().insn_pos.push(pos);
4340 }
4341 self.place_label(test);
4342 match kind {
4343 ForLoopKind::In => self.emit(Opcode::ForInNext, &[]),
4344 ForLoopKind::Of => self.emit(Opcode::ForOfNext, &[Op::Int(0)]),
4345 ForLoopKind::AwaitOf => {
4346 // The reference's shape: step, `await` the result, then unpack it.
4347 self.emit(Opcode::ForAwaitOfNext, &[Op::Int(0)]);
4348 self.emit(Opcode::Await, &[]);
4349 self.state().has_await = true;
4350 self.emit(Opcode::IteratorGetValueDone, &[]);
4351 }
4352 }
4353 self.emit_jump(Opcode::IfFalse, next, &[]);
4354 // The loop is finished; `for_xx_next` left an `undefined` behind.
4355 self.emit(Opcode::Drop, &[]);
4356
4357 self.pop_jump_target();
4358 self.place_label(break_target);
4359 if has_iterator {
4360 // A loop that ran to completion finds its iterator slot already cleared (see
4361 // `iterator_get_value_done`), so this closes only an iterator abandoned by a
4362 // `break` that jumped here.
4363 self.emit_iterator_close(matches!(kind, ForLoopKind::AwaitOf), false);
4364 } else {
4365 self.emit(Opcode::Drop, &[]);
4366 }
4367
4368 self.emit_scope_leave(loop_key);
4369 self.state().current_block = loop_parent;
4370 Ok(())
4371 }
4372
4373 /// The names a `for (let … of/in …)` head declares, which need a fresh cell per
4374 /// iteration. An assignment head (`for (x of …)`) declares nothing, so it is empty.
4375 fn loop_binding_names(left: &ForHead) -> Vec<String> {
4376 let ForHead::VarDecl(decl) = left else {
4377 return Vec::new();
4378 };
4379 if decl.kind == VarDeclKind::Var {
4380 return Vec::new();
4381 }
4382 let mut names = Vec::new();
4383 for declarator in &decl.declarators {
4384 let mut idents = Vec::new();
4385 declarator.target.bound_names(&mut idents);
4386 names.extend(idents.into_iter().map(|ident| ident.name));
4387 }
4388 names
4389 }
4390
4391 /// Store the value `for_xx_next` left on the stack into the loop variable.
4392 fn bind_loop_variable(&mut self, left: &ForHead) -> Result<(), SyntaxError> {
4393 // A declaration *initialises* the binding, which is what takes a `let` out of
4394 // the temporal dead zone, so the store is the unchecked form. Assigning to a
4395 // binding declared elsewhere is an ordinary write and keeps its check.
4396 let (pattern, action) = match left {
4397 ForHead::VarDecl(decl) => (&decl.declarators[0].target, VarAction::PutInit),
4398 ForHead::Assign(pattern) => (pattern.as_ref(), VarAction::Put),
4399 };
4400 match &pattern.kind {
4401 PatternKind::Ident(name) => {
4402 // `for (using x of …)` validates and snapshots each iteration's value
4403 // before the body runs, which is what makes a non-disposable element fail
4404 // on the iteration that produced it rather than at the end of the loop.
4405 if let ForHead::VarDecl(decl) = left
4406 && decl.kind.is_using()
4407 {
4408 let method_slot = self
4409 .using_method_slot(&name.name)
4410 .expect("a using binding was declared during hoisting");
4411 self.emit(
4412 Opcode::UsingCheck,
4413 &[Op::Int(if decl.kind.is_await_using() { 1 } else { 0 })],
4414 );
4415 self.emit(Opcode::PutLoc, &[Op::Slot(Slot::Loc(method_slot))]);
4416 }
4417 self.emit_var(action, &name.name);
4418 Ok(())
4419 }
4420 // Every other target stores through the same path an assignment pattern
4421 // uses, which is what makes `for (a[0] in obj)` write each key into the
4422 // property instead of refusing the loop outright.
4423 _ => self.destructure(
4424 pattern,
4425 match left {
4426 ForHead::VarDecl(decl) => Some(decl.kind),
4427 ForHead::Assign(_) => None,
4428 },
4429 ),
4430 }
4431 }
4432
4433 fn var_decl(&mut self, decl: &VarDecl) -> Result<(), SyntaxError> {
4434 for declarator in &decl.declarators {
4435 let Some(init) = &declarator.init else {
4436 // `var x;` stays `undefined`. A lexical binding is different: it
4437 // has to be *initialised* to leave the temporal dead zone, so the
4438 // compiler supplies an explicit `undefined`.
4439 if decl.kind.is_lexical() {
4440 // A lexical binding has to be *initialised* to leave the temporal
4441 // dead zone, and a destructuring one is no different — `let {a}`
4442 // with no initialiser is a syntax error, but `let [a] = []` still
4443 // needs `a` to be initialised from an empty source, which the
4444 // pattern does on its own.
4445 self.emit(Opcode::Undefined, &[]);
4446 self.destructure(&declarator.target, Some(decl.kind))?;
4447 }
4448 continue;
4449 };
4450 match &declarator.target.kind {
4451 PatternKind::Ident(name) => {
4452 self.expr(init)?;
4453 self.set_name_if_anonymous(init, &Wtf8::new(&name.name));
4454 if decl.kind.is_using() {
4455 // `using_check` validates the value and snapshots its dispose
4456 // method: `value -> value, method`. The snapshot is what makes a
4457 // later change to `Symbol.dispose` irrelevant, and validating here
4458 // is what keeps the body from running at all when the value is not
4459 // disposable.
4460 let method_slot = self
4461 .using_method_slot(&name.name)
4462 .expect("a using binding was declared during hoisting");
4463 self.emit(
4464 Opcode::UsingCheck,
4465 &[Op::Int(if decl.kind.is_await_using() { 1 } else { 0 })],
4466 );
4467 self.emit(Opcode::PutLoc, &[Op::Slot(Slot::Loc(method_slot))]);
4468 self.emit_var(VarAction::PutInit, &name.name);
4469 continue;
4470 }
4471 // A declaration statement produces no value, so nothing is
4472 // duplicated onto the stack.
4473 match decl.kind {
4474 VarDeclKind::Var => self.emit_var(VarAction::Put, &name.name),
4475 _ => self.emit_var(VarAction::PutInit, &name.name),
4476 }
4477 }
4478 _ => {
4479 // A destructuring declaration keeps nothing on the stack: the
4480 // pattern consumes the initialiser.
4481 self.expr(init)?;
4482 self.destructure(&declarator.target, Some(decl.kind))?;
4483 }
4484 }
4485 }
4486 Ok(())
4487 }
4488
4489 /// Bind a destructuring pattern from the value on top of the stack.
4490 ///
4491 /// `decl` picks the mode. `Some(kind)` is a *declaration*: every target is an
4492 /// identifier and the store is a binding write, `put_*` for `var` and `put_*_init`
4493 /// for `let`/`const` so the binding leaves its dead zone. `None` is a destructuring
4494 /// *assignment*, where a member expression is a legal target and the store is an
4495 /// ordinary property write.
4496 ///
4497 /// The value is consumed. An assignment expression's own result is the right-hand
4498 /// side, which the caller keeps separately — the spec does not make the pattern's
4499 /// last store produce it.
4500 fn destructure(
4501 &mut self,
4502 pattern: &Pattern,
4503 decl: Option<VarDeclKind>,
4504 ) -> Result<(), SyntaxError> {
4505 match &pattern.kind {
4506 PatternKind::Ident(name) => {
4507 match decl {
4508 Some(VarDeclKind::Var) | None => {
4509 self.emit_var(VarAction::Put, &name.name);
4510 }
4511 Some(_) => self.emit_var(VarAction::PutInit, &name.name),
4512 }
4513 Ok(())
4514 }
4515 PatternKind::Assign { target, default } => {
4516 // A default only applies to `undefined`, not to `null`: `[a = 1] = [null]`
4517 // keeps `null`.
4518 //
4519 // The shape is the reference's: test for `undefined`, and when the value is
4520 // present fall **through** to a single store both paths share. The
4521 // alternatives — branching to the store on each side — need a second store
4522 // and a jump between them, which is what the dump used to show.
4523 let has_value = self.new_label();
4524 self.emit(Opcode::Dup, &[]);
4525 self.emit(Opcode::IsUndefined, &[]);
4526 self.emit_jump(Opcode::IfFalse, has_value, &[]);
4527 self.emit(Opcode::Drop, &[]);
4528 self.expr(default)?;
4529 // `var {f = function(){}} = {}` names the function `f`, like a plain
4530 // `var f = function(){}` does. Both pattern forms do it:
4531 // `BindingInitialization` names the value for a *binding* target, and since
4532 // ES2018 `DestructuringAssignmentEvaluation` does the same, so
4533 // `[f = () => {}] = []` also leaves `f.name === "f"`. A member target has
4534 // no name to give, which is why only an identifier qualifies.
4535 if let PatternKind::Ident(name) = &target.kind {
4536 self.set_name_if_anonymous(default, &Wtf8::new(&name.name));
4537 }
4538 self.place_label(has_value);
4539 self.destructure(target, decl)
4540 }
4541 PatternKind::Array { elements, rest } => self.destructure_array(elements, rest, decl),
4542 PatternKind::Object { properties, rest } => {
4543 self.destructure_object(properties, rest, decl, pattern)
4544 }
4545 PatternKind::Member(member) if decl.is_none() => {
4546 // An assignment pattern may store into a property. The value is on the
4547 // stack, so the receiver and the key go above it and `rot3l`/`swap2`
4548 // put the three in the order `put_array_el`/`put_field` expect.
4549 self.expr(&member.object)?;
4550 match &member.property {
4551 MemberProp::Ident(name) => {
4552 // `value obj` -> `obj value`, the order `put_field` takes.
4553 // Nothing needs to be left behind: a pattern element's value is
4554 // consumed by its own store.
4555 self.emit(Opcode::Swap, &[]);
4556 self.emit(Opcode::PutField, &[Op::Atom(Atom::from_text(&name.name))]);
4557 }
4558 MemberProp::Computed(index) => {
4559 self.expr(index)?;
4560 // `value obj key` -> `obj key value`.
4561 self.emit(Opcode::Rot3l, &[]);
4562 self.emit(Opcode::PutArrayEl, &[]);
4563 }
4564 MemberProp::Private(name) => {
4565 // `value obj` -> `obj value`, and the store half of the assignment is
4566 // the same one `obj.#x = value` uses — only without `insert2`,
4567 // because a pattern element's value is not wanted back.
4568 let binding = format!("#{}", name.name);
4569 let (kind, setter) = self.private_use(&binding, member.span)?;
4570 self.emit(Opcode::Swap, &[]);
4571 self.private_store(&binding, kind, setter.as_deref())?;
4572 }
4573 }
4574 Ok(())
4575 }
4576 PatternKind::Rest(inner) => self.destructure(inner, decl),
4577 PatternKind::Invalid(expr) => {
4578 Err(SyntaxError::new("invalid assignment target", expr.span))
4579 }
4580 _ => Err(SyntaxError::new(
4581 "this destructuring target is not supported by the compiler yet",
4582 pattern.span,
4583 )),
4584 }
4585 }
4586
4587 /// `[…]` on the left: drain an iterator, binding one target per element.
4588 ///
4589 /// A target that stores into a **property** — `[o.p] = it` — has its reference worked
4590 /// out *before* the value is pulled. That ordering is observable twice over
4591 /// (`array-elem-iter-thrw-close`):
4592 ///
4593 /// * `next` must not have been called yet when the reference throws, so
4594 /// `[ {}[thrower()] ] = iterable` reports `nextCount === 0`;
4595 /// * the iterator must still be closed, because the throw happens while the record is
4596 /// live — which is `catch_here`'s `catch_offset 0` doing its work.
4597 ///
4598 /// Doing it the other way round — pull the value, then evaluate the reference — got
4599 /// both wrong: an extra `next` call, and, when the reference threw, an iterator that had
4600 /// already been drained past.
4601 fn destructure_array(
4602 &mut self,
4603 elements: &[Option<PatternElement>],
4604 rest: &Option<Box<RestElement>>,
4605 decl: Option<VarDeclKind>,
4606 ) -> Result<(), SyntaxError> {
4607 // The iterator protocol is the same one `for (… of …)` uses, so a destructuring
4608 // pattern accepts any iterable and closes the iterator when the pattern ends
4609 // early. `for_of_next` pushes the value and a `done` flag; the flag comes off
4610 // first because it is on top.
4611 //
4612 // It also counts as an open iterator for `return` and `break`: a pattern is not a
4613 // loop, but the record is live across everything the pattern evaluates, so
4614 // `function* g(){ [ {} = yield ] = it }` resumed with `return()` has to close it
4615 // (`array-elem-iter-rtrn-close`). `emit_unwind_for_return` finds it by this entry
4616 // and `nip_catch` uncovers exactly the `iter next` pairs it left behind.
4617 //
4618 // A `break`/`continue` cannot occur inside a pattern, so `names` and both labels
4619 // are empty and `drop_count` — read only by that unreachable path — keeps the
4620 // reference's 2.
4621 self.push_jump_target(JumpTarget {
4622 names: Vec::new(),
4623 break_label: None,
4624 continue_label: None,
4625 drop_count: 2,
4626 finally_label: None,
4627 is_regular_stmt: false,
4628 has_iterator: true,
4629 is_async_iterator: false,
4630 });
4631 self.emit(Opcode::ForOfStart, &[]);
4632 for element in elements {
4633 match element {
4634 Some(PatternElement::Pattern(pattern)) => {
4635 match Self::member_element_target(pattern, decl) {
4636 // A prepared reference sits above the record, so `for_of_next` is
4637 // told how many values are in the way.
4638 Some(member) => {
4639 let extra = self.prepare_member_target(member)?;
4640 self.emit(Opcode::ForOfNext, &[Op::Int(extra)]);
4641 self.emit(Opcode::Drop, &[]);
4642 self.destructure_prepared(pattern, member)?;
4643 }
4644 None => {
4645 self.emit(Opcode::ForOfNext, &[Op::Int(0)]);
4646 self.emit(Opcode::Drop, &[]);
4647 self.destructure(pattern, decl)?;
4648 }
4649 }
4650 }
4651 Some(PatternElement::Property { span, .. }) => {
4652 return Err(SyntaxError::new(
4653 "a property pattern is not a valid array element",
4654 *span,
4655 ));
4656 }
4657 // An elision skips the value, which is already on the stack.
4658 None => {
4659 self.emit(Opcode::ForOfNext, &[Op::Int(0)]);
4660 self.emit(Opcode::Drop, &[]);
4661 self.emit(Opcode::Drop, &[]);
4662 }
4663 }
4664 }
4665 if let Some(rest) = rest {
4666 // The remaining values go into a fresh array. The target and its running
4667 // index stay on the stack above the iterator, which is what the operand of
4668 // `for_of_next` accounts for: two values sit above the iterator triple.
4669 let prepared = match decl {
4670 None => Self::member_rest_target(rest),
4671 // A binding pattern cannot store into a property.
4672 Some(_) => None,
4673 };
4674 let extra = match prepared {
4675 Some(member) => 2 + self.prepare_member_target(member)?,
4676 None => 2,
4677 };
4678 self.emit(Opcode::ArrayFrom, &[Op::Int(0)]);
4679 self.emit(Opcode::Push0, &[]);
4680 let top = self.new_label();
4681 self.place_label(top);
4682 self.emit(Opcode::ForOfNext, &[Op::Int(extra)]);
4683 let done = self.new_label();
4684 self.emit_jump(Opcode::IfTrue, done, &[]);
4685 self.emit(Opcode::DefineArrayEl, &[]);
4686 self.emit(Opcode::Inc, &[]);
4687 self.emit_jump(Opcode::Goto, top, &[]);
4688 self.place_label(done);
4689 self.emit(Opcode::Drop, &[]);
4690 self.emit(Opcode::Drop, &[]);
4691 match prepared {
4692 Some(member) => self.store_member_value(member)?,
4693 None => self.destructure_rest(rest, decl)?,
4694 }
4695 }
4696 self.emit(Opcode::IteratorClose, &[]);
4697 self.pop_jump_target();
4698 Ok(())
4699 }
4700
4701 /// The property an array element stores into, when it stores into one at all.
4702 ///
4703 /// `Assign` is peeled because `[o.p = d] = it` evaluates `o.p`'s reference at the same
4704 /// point `[o.p] = it` does; the default value is applied afterwards, on the pulled
4705 /// value. Nothing deeper is: a nested pattern's own targets are reached by recursing
4706 /// into `destructure`, and those never straddle a `for_of_next`.
4707 fn member_element_target(
4708 pattern: &Pattern,
4709 decl: Option<VarDeclKind>,
4710 ) -> Option<&ast::MemberPattern> {
4711 if decl.is_some() {
4712 return None;
4713 }
4714 match &pattern.kind {
4715 PatternKind::Member(member) => Some(member),
4716 PatternKind::Assign { target, .. } => Self::member_element_target(target, decl),
4717 _ => None,
4718 }
4719 }
4720
4721 /// The same, for a rest element.
4722 fn member_rest_target(rest: &RestElement) -> Option<&ast::MemberPattern> {
4723 match rest {
4724 RestElement::Member(member) => Some(member),
4725 RestElement::Pattern(pattern) => match &pattern.kind {
4726 PatternKind::Member(member) => Some(member),
4727 _ => None,
4728 },
4729 }
4730 }
4731
4732 /// Push a member target's reference — the object, and the key when the property is
4733 /// computed — and answer how many values that put above the iterator record.
4734 fn prepare_member_target(&mut self, member: &ast::MemberPattern) -> Result<i32, SyntaxError> {
4735 self.expr(&member.object)?;
4736 match &member.property {
4737 MemberProp::Ident(_) | MemberProp::Private(_) => Ok(1),
4738 MemberProp::Computed(index) => {
4739 self.expr(index)?;
4740 Ok(2)
4741 }
4742 }
4743 }
4744
4745 /// Store the value on top of the stack through a prepared member reference.
4746 ///
4747 /// `obj value` for a named property, `obj key value` for a computed one — the orders
4748 /// `put_field` and `put_array_el` take, so no reordering is needed here. The `swap` and
4749 /// `rot3l` in [`Compiler::destructure`]'s member case exist only because *it* starts
4750 /// with the value already on the stack.
4751 fn store_member_value(&mut self, member: &ast::MemberPattern) -> Result<(), SyntaxError> {
4752 match &member.property {
4753 MemberProp::Ident(name) => {
4754 self.emit(Opcode::PutField, &[Op::Atom(Atom::from_text(&name.name))]);
4755 }
4756 MemberProp::Computed(_) => self.emit(Opcode::PutArrayEl, &[]),
4757 MemberProp::Private(name) => {
4758 let binding = format!("#{}", name.name);
4759 let (kind, setter) = self.private_use(&binding, member.span)?;
4760 self.private_store(&binding, kind, setter.as_deref())?;
4761 }
4762 }
4763 Ok(())
4764 }
4765
4766 /// The value of an array element whose member reference is already prepared.
4767 ///
4768 /// Only the default-value test differs from [`Compiler::destructure`]: the reference
4769 /// and the value are both on the stack while the test runs, which is why the object is
4770 /// evaluated before the default rather than after it.
4771 fn destructure_prepared(
4772 &mut self,
4773 pattern: &Pattern,
4774 member: &ast::MemberPattern,
4775 ) -> Result<(), SyntaxError> {
4776 if let PatternKind::Assign { default, .. } = &pattern.kind {
4777 let has_value = self.new_label();
4778 self.emit(Opcode::Dup, &[]);
4779 self.emit(Opcode::IsUndefined, &[]);
4780 self.emit_jump(Opcode::IfFalse, has_value, &[]);
4781 self.emit(Opcode::Drop, &[]);
4782 self.expr(default)?;
4783 self.place_label(has_value);
4784 }
4785 self.store_member_value(member)
4786 }
4787
4788 /// `{…}` on the left: read properties off one boxed source object.
4789 fn destructure_object(
4790 &mut self,
4791 properties: &[Option<PatternElement>],
4792 rest: &Option<Box<RestElement>>,
4793 decl: Option<VarDeclKind>,
4794 pattern: &Pattern,
4795 ) -> Result<(), SyntaxError> {
4796 // `ToObject` is what refuses `null`/`undefined`, and it also puts the source
4797 // aside for the rest element below.
4798 self.emit(Opcode::ToObject, &[]);
4799 let mut taken: Vec<Wtf8> = Vec::new();
4800 // A computed key's *value* is only known at run time, so with a rest element the
4801 // exclusion list cannot be an `ArrayFrom` over literal atoms. It becomes a hidden
4802 // local array that every key is written into as the pattern is walked — literal
4803 // keys by name, computed ones by the value the expression produced. Without this,
4804 // `let { [k]: a, ...rest } = o` was refused outright.
4805 let needs_key_log = rest.is_some() && computed_key_count(properties) > 0;
4806 let key_log = if needs_key_log {
4807 let name = "<rest_exclude>";
4808 self.declare_hidden_local(name, VarKind::Normal);
4809 self.emit(Opcode::ArrayFrom, &[Op::Int(0)]);
4810 self.emit_var(VarAction::Put, name);
4811 Some(name)
4812 } else {
4813 None
4814 };
4815 for property in properties {
4816 let Some(PatternElement::Property {
4817 key, value, span, ..
4818 }) = property
4819 else {
4820 return Err(SyntaxError::new(
4821 "a bare pattern is not a valid object property",
4822 properties
4823 .iter()
4824 .flatten()
4825 .map(|element| match element {
4826 PatternElement::Pattern(pattern) => pattern.span,
4827 PatternElement::Property { span, .. } => *span,
4828 })
4829 .next()
4830 .unwrap_or(pattern.span),
4831 ));
4832 };
4833 // Every read needs the source twice: to read from, and to keep for the next
4834 // property. `get_field2` is that duplicate-and-read in one instruction, but it
4835 // leaves the copy *under* the value, so it is only usable when whatever
4836 // consumes the value tolerates that. See [`reads_with_get_field2`].
4837 let nested = reads_with_get_field2(decl, value);
4838 if !nested {
4839 self.emit(Opcode::Dup, &[]);
4840 }
4841 let slot = taken.len();
4842 match key {
4843 PropName::Literal(literal) => {
4844 let name = self.property_key_text(literal, *span)?;
4845 taken.push(name.clone());
4846 if let Some(log) = &key_log {
4847 // `arr index key -> arr`: the key is written into the log before
4848 // the read, so the order of observable operations is unchanged.
4849 self.emit_var(VarAction::Get, log);
4850 self.push_number(slot as f64);
4851 self.emit(Opcode::PushAtomValue, &[Op::Atom(Atom::from_wtf8(&name))]);
4852 self.emit(Opcode::PutArrayEl, &[]);
4853 }
4854 self.emit(
4855 if nested {
4856 Opcode::GetField2
4857 } else {
4858 Opcode::GetField
4859 },
4860 &[Op::Atom(Atom::from_wtf8(&name))],
4861 );
4862 }
4863 PropName::Computed(index) => {
4864 self.expr(index)?;
4865 // `key key`: one stays on the stack for the read, the other goes into
4866 // the exclusion log. The index is a compile-time constant, so no counter
4867 // local is needed.
4868 if let Some(log) = &key_log {
4869 taken.push(Wtf8::default());
4870 self.emit(Opcode::Dup, &[]);
4871 self.emit_var(VarAction::Get, log);
4872 self.emit(Opcode::Swap, &[]);
4873 self.push_number(slot as f64);
4874 self.emit(Opcode::Swap, &[]);
4875 self.emit(Opcode::PutArrayEl, &[]);
4876 }
4877 self.emit(Opcode::GetArrayEl, &[]);
4878 }
4879 PropName::Private(_) => {
4880 return Err(SyntaxError::new(
4881 "private fields are not supported by the compiler yet",
4882 value.span,
4883 ));
4884 }
4885 }
4886 self.destructure(value, decl)?;
4887 }
4888 match rest {
4889 Some(rest) => {
4890 // `target src exclude`: the exclusion list is an array of the keys the
4891 // literal part already took, so the rest object gets only the others.
4892 self.emit(Opcode::Object, &[]);
4893 self.emit(Opcode::Swap, &[]);
4894 match &key_log {
4895 // Built while walking the pattern; see `needs_key_log`.
4896 Some(log) => {
4897 self.emit_var(VarAction::Get, log);
4898 }
4899 None => {
4900 for name in &taken {
4901 self.emit(Opcode::PushAtomValue, &[Op::Atom(Atom::from_wtf8(name))]);
4902 }
4903 self.emit(Opcode::ArrayFrom, &[Op::Int(taken.len() as i32)]);
4904 }
4905 }
4906 self.emit(Opcode::CopyDataProperties, &[Op::Int(COPY_ALL_PROPERTIES)]);
4907 self.emit(Opcode::Drop, &[]);
4908 self.emit(Opcode::Drop, &[]);
4909 self.destructure_rest(rest, decl)?;
4910 }
4911 // The source was only kept for a rest element.
4912 None => self.emit(Opcode::Drop, &[]),
4913 }
4914 Ok(())
4915 }
4916
4917 /// The pattern a rest element binds, as a target [`Self::destructure`] takes.
4918 fn destructure_rest(
4919 &mut self,
4920 rest: &RestElement,
4921 decl: Option<VarDeclKind>,
4922 ) -> Result<(), SyntaxError> {
4923 match rest {
4924 RestElement::Pattern(pattern) => self.destructure(pattern, decl),
4925 // `[...a.b] = c` stores into a property.
4926 RestElement::Member(member) => {
4927 let pattern = Pattern {
4928 kind: PatternKind::Member(member.clone()),
4929 span: member.span,
4930 };
4931 self.destructure(&pattern, decl)
4932 }
4933 }
4934 }
4935
4936 /// Compile a function declaration and queue it for instantiation at scope
4937 /// entry.
4938 ///
4939 /// A declaration is visible before the statement that declares it, so the
4940 /// code that creates the function object belongs at the top of the enclosing
4941 /// scope, not at the declaration.
4942 fn func_decl(&mut self, func: &ast::Function) -> Result<(), SyntaxError> {
4943 let name = func.name.as_ref().expect("a declaration has a name");
4944 let function = self.compile_function(func)?;
4945 let pool_index = self.push_constant(Constant::Function(Box::new(function)));
4946 let target = self.hoist_target(&name.name);
4947 let block = self.cur().current_block;
4948 self.state().hoisted.push((block, target, pool_index));
4949 Ok(())
4950 }
4951
4952 /// Where a name lives, for a hoisted declaration.
4953 fn hoist_target(&self, name: &str) -> HoistTarget {
4954 let state = self.cur();
4955 if let Some(index) = state.args.iter().position(|a| a.name == name) {
4956 return HoistTarget::Arg(index as u32);
4957 }
4958 if let Some(index) = state.vars.iter().position(|v| v.name == name) {
4959 return HoistTarget::Loc(index as u32);
4960 }
4961 // A global function declaration is not a slot at all.
4962 HoistTarget::Global(name.to_string())
4963 }
4964
4965 // -- expressions -------------------------------------------------------
4966
4967 /// Compile one expression, recording where its instructions sit.
4968 ///
4969 /// The position is the node's operator when it has one and its first token
4970 /// otherwise, and it is restored on the way out so a parent's own instructions —
4971 /// which are emitted *after* its children — are blamed on the parent. Without the
4972 /// restore the `add` in `a + b` would inherit `b`'s position instead of the `+`.
4973 fn expr(&mut self, expr: &Expr) -> Result<(), SyntaxError> {
4974 // `discard_value` belongs to the *statement* that is about to be compiled, so it
4975 // may only be honoured by that statement's own top-level expression. Taking it here
4976 // is what enforces that: `f(x = 1)` sets it for the call, and the assignment inside
4977 // the argument list is a different expression — it must still leave its value on the
4978 // stack. Without this the argument vanished, and `call` then consumed the callee as
4979 // its argument (`TypeError: undefined is not a function` from `f(x = 1)` inside any
4980 // function).
4981 self.discard_root = std::mem::take(&mut self.state().discard_value);
4982 let saved = self.cur().cur_pos;
4983 // Only the node kinds the reference calls `emit_source_pos` for record a position:
4984 // the operator a node exists for, and a variable *read*, which the reference
4985 // positions at the identifier itself (`case TOK_IDENT: … do_get_var:
4986 // emit_source_pos(s, source_ptr)`). Everything else — a literal, an object or array
4987 // start, a parenthesised group, an anonymous function expression — leaves the
4988 // previous position in place, because a table entry the reference never writes is
4989 // one we must not write either: the instruction that inherits a position (the
4990 // `using` epilogue, a template's `to_propkey`, a `super()` call) would otherwise
4991 // report a more recent token than the reference does.
4992 let pos = expr.op_pos.or(match &expr.kind {
4993 ExprKind::Ident(ident) => Some(ident.span.start),
4994 _ => None,
4995 });
4996 match pos {
4997 Some(pos) => self.state().cur_pos = Some(pos),
4998 // A node the reference records nothing for: its own instructions stay
4999 // unpositioned, so they inherit whatever was written last — which is what an
5000 // `emit_source_pos`-less stretch of the reference's bytecode does. Keeping the
5001 // enclosing position instead would blame them on a token the reference has not
5002 // reached yet: a spread's `iterator_open` reports the expression it follows, and
5003 // a template's `to_propkey` the interpolation.
5004 None => self.state().cur_pos = None,
5005 }
5006 // Note a direct `eval` call before compiling it, because the *whole* function
5007 // is affected: an eval can name any binding the function declares, so every one
5008 // of them has to live in a cell for a closure it creates to capture it.
5009 self.note_direct_eval(expr);
5010 let result = self.expr_inner(expr);
5011 self.discard_root = false;
5012 self.state().cur_pos = saved;
5013 result
5014 }
5015
5016 /// Record which bindings are in scope at a direct `eval` call.
5017 ///
5018 /// Ordinary name lookup happens at compile time; a direct `eval` bypasses that and
5019 /// resolves names from a string at run time, so the only chance to pin down *which*
5020 /// slot a name means is here. Visibility is the lexical rule: a binding counts when
5021 /// its block is the current block, an enclosing one, or the function scope.
5022 fn materialize_eval_sites(&mut self) {
5023 let pending = std::mem::take(&mut self.state().pending_eval_sites);
5024 for (span, site_block, in_params, private, arguments_allowed) in pending {
5025 self.resolve_eval_site(span, site_block, in_params, private, arguments_allowed);
5026 }
5027 }
5028
5029 /// Resolve the bindings visible at one `eval` call.
5030 fn resolve_eval_site(
5031 &mut self,
5032 span: Span,
5033 site_block: u64,
5034 site_in_params: bool,
5035 private_names: Vec<EvalPrivate>,
5036 arguments_allowed: bool,
5037 ) {
5038 /// How near a binding is: function distance first, then block depth, then the
5039 /// later declaration (which shadows the earlier one in the same block).
5040 type ScopePriority = (usize, usize, std::cmp::Reverse<u32>);
5041
5042 // `(sort key, binding)`, where a smaller key wins. The whole scope chain is
5043 // walked, innermost function first: a direct `eval` sees every enclosing
5044 // function's bindings, and none of them can be resolved at run time because the
5045 // runtime only has names to go on.
5046 let mut bindings: Vec<(ScopePriority, EvalVisible)> = Vec::new();
5047 let deepest = self.stack.len() - 1;
5048 for (level, state) in self.stack.iter().enumerate().rev() {
5049 let owner = (deepest - level) as u32;
5050 // The innermost function's block is the one the call sat in, which is not
5051 // the block the compiler is in now; the enclosing functions are still at
5052 // the point where this one was created.
5053 let here = if level == deepest {
5054 site_block
5055 } else {
5056 state.current_block
5057 };
5058 // The chain of live blocks, innermost first, with a depth for each. The walk
5059 // stops at `NO_PARENT`, which is a sentinel rather than `0` because a real
5060 // block can start at source offset zero.
5061 let mut live: Vec<(u64, usize)> = vec![(here, 0)];
5062 let mut block = here;
5063 while let Some(parent) = state
5064 .blocks
5065 .iter()
5066 .find(|candidate| candidate.key == block)
5067 .map(|candidate| candidate.parent)
5068 .filter(|parent| *parent != NO_PARENT)
5069 .filter(|parent| parent != &block)
5070 {
5071 live.push((parent, live.len()));
5072 block = parent;
5073 }
5074 let depth_of = |key: u64| {
5075 live.iter()
5076 .find(|(candidate, _)| *candidate == key)
5077 .map(|(_, depth)| *depth)
5078 // The function scope is the outermost depth there is. A binding of a
5079 // block this site is not inside lands here too, which pushes it
5080 // behind every live one — the right answer: it is out of scope.
5081 .unwrap_or(live.len())
5082 };
5083 for (index, arg) in state.args.iter().enumerate() {
5084 bindings.push((
5085 (owner as usize, live.len(), std::cmp::Reverse(index as u32)),
5086 EvalVisible {
5087 name: arg.name.clone(),
5088 is_arg: true,
5089 index: index as u32,
5090 owner,
5091 },
5092 ));
5093 }
5094 // A parameter list cannot see the body, so a body `var` is not a binding the
5095 // eval can name: `(a = eval("var c = 1"), p = () => c) => { var c = 2 }` must
5096 // not let that eval write the body's `c`.
5097 let hides_body = if level == deepest {
5098 site_in_params
5099 } else {
5100 state.created_in_params
5101 };
5102 for (index, var) in state.vars.iter().enumerate() {
5103 let block = state
5104 .var_block
5105 .get(index)
5106 .copied()
5107 .unwrap_or(FUNCTION_SCOPE);
5108 if hides_body && block == FUNCTION_SCOPE && !visible_in_params(var) {
5109 continue;
5110 }
5111 bindings.push((
5112 (
5113 owner as usize,
5114 depth_of(block),
5115 std::cmp::Reverse(index as u32),
5116 ),
5117 EvalVisible {
5118 name: var.name.clone(),
5119 is_arg: false,
5120 index: index as u32,
5121 owner,
5122 },
5123 ));
5124 }
5125 }
5126 // Innermost function first, then innermost block, then the later declaration
5127 // (which shadows the earlier one within a block).
5128 bindings.sort_by_key(|(priority, _)| *priority);
5129 let bindings = bindings.into_iter().map(|(_, visible)| visible).collect();
5130 self.state().eval_sites.push(EvalSite {
5131 line: span.start.line,
5132 column: span.start.column,
5133 bindings,
5134 private_names,
5135 arguments_allowed,
5136 });
5137 }
5138
5139 /// The private names visible from the compiler's current position, innermost last.
5140 ///
5141 /// A direct `eval` inherits these because private names are lexically scoped
5142 /// (§15.10.2). Flattened with the **first** occurrence winning as the scopes are walked
5143 /// outermost-first, so a nested class's `#x` shadows an outer class's — the same
5144 /// shadowing `ClassPlan::find` gives a use site inside the body.
5145 fn visible_private_names(&self) -> Vec<EvalPrivate> {
5146 let mut out: Vec<EvalPrivate> = Vec::new();
5147 for scope in &self.private_scopes {
5148 for (name, use_) in scope {
5149 if out.iter().any(|entry| &entry.name == name) {
5150 continue;
5151 }
5152 out.push(EvalPrivate {
5153 name: name.clone(),
5154 kind: match use_.kind {
5155 PrivateKind::Field => EvalPrivateKind::Field,
5156 PrivateKind::Method => EvalPrivateKind::Method,
5157 PrivateKind::Getter => EvalPrivateKind::Getter,
5158 PrivateKind::Setter => EvalPrivateKind::Setter,
5159 },
5160 setter: use_.setter.clone(),
5161 });
5162 }
5163 }
5164 out
5165 }
5166
5167 /// Whether `expr` is `eval(...)` — the direct form, which sees the caller's scope.
5168 ///
5169 /// `(0, eval)(…)` and `f.call(null, …)` are *indirect* and get no caller scope; only
5170 /// a bare identifier callee counts.
5171 /// Record everything a direct `eval` call site has to tell the runtime.
5172 ///
5173 /// Called from both places a call can be compiled: [`Compiler::expr`] for an ordinary
5174 /// one, and [`Compiler::expr_if_tail_call`] for a `return eval(…)`, which skips `expr`
5175 /// entirely. Missing the tail-call path is not hypothetical — it is why
5176 /// `class C { #m; f() { return eval("this.#m") } }` still failed after the private
5177 /// names were otherwise wired through.
5178 fn note_direct_eval(&mut self, expr: &Expr) {
5179 if !Self::is_direct_eval(expr) {
5180 return;
5181 }
5182 // Every enclosing function is affected too: the eval sees the whole scope chain,
5183 // and a closure it creates can capture a binding of any of them.
5184 // `for (let i …) { f() }` where `f` contains the eval still needs `i` in a cell,
5185 // because the closure the eval builds outlives the loop iteration.
5186 for state in &mut self.stack {
5187 state.has_direct_eval = true;
5188 }
5189 let block = self.cur().current_block;
5190 let in_params = self.cur().in_params;
5191 // The private names are snapshotted **here**, at the call site, not when the sites
5192 // are materialised: materialisation happens once the whole function is compiled, by
5193 // which point every class scope has been popped and the answer would always be
5194 // empty.
5195 let private = self.visible_private_names();
5196 // An arrow has no `arguments` of its own and inherits the restriction from the
5197 // nearest real function: `x = () => { () => eval('arguments') }` is still a
5198 // class field initializer's arrow, and still has no `arguments` to see.
5199 let arguments_allowed = !self
5200 .stack
5201 .iter()
5202 .rev()
5203 .find(|state| !state.is_arrow)
5204 .is_some_and(|state| state.no_arguments_binding);
5205 self.state().pending_eval_sites.push((
5206 expr.span,
5207 block,
5208 in_params,
5209 private,
5210 arguments_allowed,
5211 ));
5212 }
5213
5214 fn is_direct_eval(expr: &Expr) -> bool {
5215 matches!(
5216 &expr.kind,
5217 ExprKind::Call { callee, .. }
5218 if matches!(&callee.unparen().kind, ExprKind::Ident(name) if name.name == "eval")
5219 )
5220 }
5221
5222 fn expr_inner(&mut self, expr: &Expr) -> Result<(), SyntaxError> {
5223 match &expr.kind {
5224 ExprKind::Number(value) => self.push_number(*value),
5225 ExprKind::Bool(true) => self.emit(Opcode::PushTrue, &[]),
5226 ExprKind::Bool(false) => self.emit(Opcode::PushFalse, &[]),
5227 ExprKind::Null => self.emit(Opcode::Null, &[]),
5228 ExprKind::String(text) => self.push_string(text),
5229 ExprKind::BigInt { digits, radix } => self.push_bigint(digits, *radix),
5230 ExprKind::Ident(name) => self.emit_var(VarAction::Get, &name.name),
5231 ExprKind::This => self.this_expression(),
5232 ExprKind::NewTarget => self.new_target_expression(),
5233 ExprKind::Paren(inner) => self.expr(inner)?,
5234 ExprKind::Binary { op, left, right } => {
5235 self.expr(left)?;
5236 self.expr(right)?;
5237 self.emit(binary_opcode(*op), &[]);
5238 }
5239 ExprKind::Logical { op, left, right } => self.logical(*op, left, right)?,
5240 ExprKind::Unary {
5241 op: UnaryOp::Minus,
5242 argument,
5243 } if matches!(argument.unparen().kind, ExprKind::Number(_)) => {
5244 let ExprKind::Number(value) = argument.unparen().kind else {
5245 unreachable!("matched above")
5246 };
5247 // The reference folds a negative literal only when the negation is
5248 // exact in the integer range: `-1` becomes `push_minus1` and
5249 // `-1.5e3` becomes `push_i16 -1500`, but `-0` and `-2.5` keep a
5250 // runtime `neg`. Folding `-0` would lose the sign — `1/-0` is
5251 // `-Infinity`, not `Infinity` — and folding a fraction would change
5252 // which instruction the reference emits.
5253 let negated = -value;
5254 // `-2147483648` is deliberately excluded: its magnitude is one past
5255 // `i32::MAX`, so the reference sends it through the constant pool and
5256 // negates at run time instead.
5257 if value > 0.0
5258 && negated == negated.trunc()
5259 && negated >= -(i32::MAX as f64)
5260 && negated < 0.0
5261 {
5262 self.push_number(negated);
5263 } else {
5264 self.push_number(value);
5265 self.emit(Opcode::Neg, &[]);
5266 }
5267 }
5268 ExprKind::Unary { op, argument } => self.unary(*op, argument)?,
5269 ExprKind::Conditional { test, cons, alt } => {
5270 let else_label = self.new_label();
5271 let end_label = self.new_label();
5272 self.expr(test)?;
5273 self.emit_jump(Opcode::IfFalse, else_label, &[]);
5274 self.expr(cons)?;
5275 self.emit_jump(Opcode::Goto, end_label, &[]);
5276 self.place_label(else_label);
5277 self.expr(alt)?;
5278 self.place_label(end_label);
5279 }
5280 ExprKind::Assign { op, target, value } => {
5281 let discard = std::mem::take(&mut self.discard_root);
5282 self.assign(*op, target, value, discard)?
5283 }
5284 ExprKind::Update {
5285 op,
5286 argument,
5287 prefix,
5288 } => self.update(*op, argument, *prefix)?,
5289 ExprKind::Sequence(items) => {
5290 for (index, item) in items.iter().enumerate() {
5291 self.expr(item)?;
5292 if index + 1 != items.len() {
5293 self.emit(Opcode::Drop, &[]);
5294 }
5295 }
5296 }
5297 ExprKind::Call { .. } => self.chain_link_top(expr)?,
5298 ExprKind::Member { .. } => self.chain_link_top(expr)?,
5299 ExprKind::OptionalChain(inner) => self.optional_chain(inner)?,
5300 ExprKind::Array { elements } => self.array_literal(elements, expr.span)?,
5301 ExprKind::Object(properties) => self.object_literal(properties, expr.span)?,
5302 ExprKind::Template(template) => self.template_literal(template)?,
5303 ExprKind::TaggedTemplate { tag, quasi } => self.tagged_template(tag, quasi)?,
5304 ExprKind::New { callee, arguments } => {
5305 // `new C(args)` compiles to `C; dup; args…; call_constructor n`.
5306 // The `dup` is not redundant: `call_constructor` takes the
5307 // constructor twice, once as the target and once as `new.target`,
5308 // which is what makes `new.target === C` inside the body.
5309 self.expr(callee)?;
5310 self.emit(Opcode::Dup, &[]);
5311 let args = arguments.as_deref().unwrap_or(&[]);
5312 if Self::has_spread(args) {
5313 // `C C array`: the duplicated callee is already both the target
5314 // and `new.target`, so no reordering is needed before `apply 1`.
5315 self.argument_array(args)?;
5316 self.emit(Opcode::Apply, &[Op::Int(1)]);
5317 return Ok(());
5318 }
5319 for argument in args {
5320 self.expr(argument)?;
5321 }
5322 self.emit(Opcode::CallConstructor, &[Op::Int(args.len() as i32)]);
5323 }
5324 ExprKind::Class(class) => self.class_definition(class, true)?,
5325 ExprKind::SuperCall(arguments) => self.super_call(arguments)?,
5326 ExprKind::Yield { argument, delegate } => {
5327 self.yield_expression(argument.as_deref(), *delegate)?
5328 }
5329 ExprKind::Await(argument) => self.await_expression(argument)?,
5330 ExprKind::RegExp { pattern, flags } => {
5331 // A literal is compiled *here*, at parse time, not when the line runs. The
5332 // spec is explicit that an invalid pattern is an early error (§12.9.4:
5333 // "/ RegularExpressionLiteral /u — it is a Syntax Error if … the pattern does
5334 // not conform"), so `print(1); /\p{Nope}/u;` must not print anything. This
5335 // also validates `\p{…}` names: 163 conformance cases are patterns that have
5336 // to be rejected before any code runs.
5337 //
5338 // This is the whole reason the engine lives in its own crate rather than
5339 // inside `quickjs-pure`: the compiler could not depend on the interpreter
5340 // (`pure` depends on `compile`), but both need this.
5341 // The lexer already rejected an unknown or repeated flag, so an unparsable
5342 // flag string here would be a bug in the lexer rather than in the script;
5343 // fall back to the default flags instead of inventing a second message.
5344 let flags_parsed = quickjs_regexp::Flags::parse(flags).unwrap_or_default();
5345 let parsed = quickjs_regexp::parse(pattern, flags_parsed).map_err(|error| {
5346 SyntaxError::new(
5347 format!("invalid regular expression: {}", error.message),
5348 expr.span,
5349 )
5350 })?;
5351 // The tree is thrown away and rebuilt when the literal first runs: keeping it
5352 // would mean serialising the syntax tree into the function's constant pool,
5353 // and a literal is created once per evaluation of its expression anyway.
5354 let _ = parsed;
5355 // The pattern and its flags travel as two string constants; `regexp` builds
5356 // the object. A dedicated opcode (rather than a call to the constructor) is
5357 // what the reference does too, so that a literal never goes through the
5358 // public `RegExp` function and its string-coercion rules.
5359 self.push_string(&Wtf8::new(pattern));
5360 self.push_string(&Wtf8::new(flags));
5361 self.emit(Opcode::Regexp, &[]);
5362 }
5363 ExprKind::Arrow(func) => {
5364 let function = self.compile_function(func)?;
5365 let index = self.push_constant(Constant::Function(Box::new(function)));
5366 self.emit(Opcode::Fclosure, &[Op::Const(index)]);
5367 }
5368 ExprKind::Function(func) => {
5369 let function = self.compile_function_with_name(func, true)?;
5370 let index = self.push_constant(Constant::Function(Box::new(function)));
5371 self.emit(Opcode::Fclosure, &[Op::Const(index)]);
5372 }
5373 // `import.meta`: the host fills a per-module object at link time.
5374 ExprKind::ImportMeta => {
5375 self.emit(Opcode::SpecialObject, &[Op::Int(6)]);
5376 }
5377 // `import("x")` compiles to a two-slot push followed by one opcode: the
5378 // specifier, then the options object. Both are evaluated, in that order, because
5379 // §13.3.10.1 numbers them that way and their side effects are observable — the
5380 // absent second argument is a literal `undefined`, which evaluates to nothing.
5381 ExprKind::ImportCall(specifier, options, phase) => {
5382 self.expr(specifier)?;
5383 match options {
5384 Some(options) => self.expr(options)?,
5385 None => {
5386 self.emit(Opcode::Undefined, &[]);
5387 }
5388 }
5389 // The phase is the opcode, not an operand: `import(x)` and `import.defer(x)`
5390 // have the same stack shape, and a separate instruction keeps the ordinary
5391 // form byte-identical to the reference's.
5392 match phase {
5393 ImportPhase::Evaluation => self.emit(Opcode::Import, &[]),
5394 ImportPhase::Defer => self.emit(Opcode::ImportDefer, &[]),
5395 ImportPhase::Source => self.emit(Opcode::ImportSource, &[]),
5396 }
5397 }
5398 ExprKind::PrivateIn { name, object } => {
5399 // `#x in o`: the object, then the binding, then one opcode which decides what
5400 // to do with the second operand. A field's binding holds a symbol and the
5401 // answer is an own-property test; a method's holds a function and the answer
5402 // is a brand check — both live in `private_in`, so the compiler emits the
5403 // same instruction for either.
5404 self.expr(object)?;
5405 self.emit_var(VarAction::Get, &format!("#{}", name.name));
5406 self.emit(Opcode::PrivateIn, &[]);
5407 }
5408 _ => {
5409 return Err(SyntaxError::new(
5410 "this expression form is not supported by the compiler yet",
5411 expr.span,
5412 ));
5413 }
5414 }
5415 Ok(())
5416 }
5417
5418 /// Build one array holding the evaluated call arguments, which is how a call
5419 /// containing a spread is compiled: the reference does the same, building the
5420 /// list on the stack and handing it to `apply`.
5421 fn argument_array(&mut self, arguments: &[Expr]) -> Result<(), SyntaxError> {
5422 let elements: Vec<Option<ArrayElement>> = arguments
5423 .iter()
5424 .map(|argument| match &argument.unparen().kind {
5425 ExprKind::Spread(inner) => Some(ArrayElement::Spread(inner.clone())),
5426 _ => Some(ArrayElement::Expr(Box::new(argument.clone()))),
5427 })
5428 .collect();
5429 self.array_literal(&elements, Span::default())
5430 }
5431
5432 /// Whether any argument is a spread, which is what selects the `apply` form.
5433 fn has_spread(arguments: &[Expr]) -> bool {
5434 arguments
5435 .iter()
5436 .any(|argument| matches!(argument.unparen().kind, ExprKind::Spread(_)))
5437 }
5438
5439 /// Compile `a${x}b`.
5440 ///
5441 /// A template is a `+` chain built left to right: the leading chunk (or an empty
5442 /// string when the template starts with a substitution), then for each
5443 /// substitution its value, `to_propkey` and `add`, then the following chunk when
5444 /// it is not empty. `to_propkey` is what makes a number or object substitute the
5445 /// way `ToString` would while leaving the result a string for `add` to
5446 /// concatenate.
5447 ///
5448 /// The chunk is an atom rather than a constant-pool string, because a non-empty
5449 /// chunk always lands where a value is pushed and `push_atom_value` is the
5450 /// instruction the reference uses for it; the empty first chunk has its own
5451 /// zero-byte form.
5452 fn template_literal(&mut self, template: &TemplateLiteral) -> Result<(), SyntaxError> {
5453 let first = template.quasis.first();
5454 match first.and_then(|quasi| quasi.cooked.clone()) {
5455 Some(text) if !text.is_empty() => {
5456 self.emit(Opcode::PushAtomValue, &[Op::Atom(Atom::from_wtf8(&text))]);
5457 }
5458 // Either the template begins with a substitution, or the chunk is
5459 // empty — in both cases the chain needs a string to start from.
5460 _ => self.emit(Opcode::PushEmptyString, &[]),
5461 }
5462 for (index, expression) in template.expressions.iter().enumerate() {
5463 self.expr(expression)?;
5464 self.emit(Opcode::ToPropkey, &[]);
5465 self.emit(Opcode::Add, &[]);
5466 if let Some(text) = template
5467 .quasis
5468 .get(index + 1)
5469 .and_then(|quasi| quasi.cooked.clone())
5470 && !text.is_empty()
5471 {
5472 self.emit(Opcode::PushAtomValue, &[Op::Atom(Atom::from_wtf8(&text))]);
5473 self.emit(Opcode::Add, &[]);
5474 }
5475 }
5476 Ok(())
5477 }
5478
5479 /// Compile an object literal.
5480 ///
5481 /// The object is built in place: `object` pushes it, and each property leaves it
5482 /// on the stack with one field more, so no temporary is needed and later
5483 /// properties can overwrite earlier ones.
5484 ///
5485 /// The instruction depends on *how* the property was written, not on what kind
5486 /// of value it holds:
5487 ///
5488 /// | source | instruction |
5489 /// |---|---|
5490 /// | `{ a: v }` | `define_field a` |
5491 /// | `{ __proto__: v }` | `set_proto` |
5492 /// | `{ [k]: v }` | `to_propkey` … `define_array_el` + `drop` |
5493 /// | `{ m() {} }` | `define_method m,4` |
5494 /// | `{ get m() {} }` / `{ set m(v) {} }` | `define_method m,5` / `,6` |
5495 /// | `{ [k]() {} }` | `define_method_computed 4` |
5496 /// | `{ ...v }` | `null` … `copy_data_properties 6` + two `drop`s |
5497 ///
5498 /// A computed *method* skips `to_propkey`: `define_method_computed` converts the
5499 /// key itself, which is why the trailing `drop` is absent there too.
5500 /// `tag`…``: a call whose first argument is the call site's template object.
5501 ///
5502 /// The template object is a frozen array of the cooked chunks with a frozen `raw`
5503 /// array beside it, so `String.raw` can read the source text back. It is a constant
5504 /// because its contents never change; the reference builds one per call site and
5505 /// reuses it, while this builds one per evaluation, which only `tag` code that
5506 /// compares template objects across calls could tell apart.
5507 /// A fresh template site id. See [`Constant::Template`].
5508 fn tagged_template(&mut self, tag: &Expr, quasi: &TemplateLiteral) -> Result<(), SyntaxError> {
5509 let cooked = quasi
5510 .quasis
5511 .iter()
5512 .map(|chunk| chunk.cooked.clone())
5513 .collect();
5514 let raw = quasi.quasis.iter().map(|chunk| chunk.raw.clone()).collect();
5515 let index = self.push_constant(Constant::Template {
5516 site: next_template_site(),
5517 cooked,
5518 raw,
5519 });
5520 let count = quasi.expressions.len() + 1;
5521 // `o.m`…`` passes `o` as `this`, exactly as `o.m(…)` does.
5522 if let ExprKind::Member {
5523 object, property, ..
5524 } = &tag.unparen().kind
5525 {
5526 self.expr(object)?;
5527 match property {
5528 MemberProp::Ident(name) => {
5529 self.emit(Opcode::GetField2, &[Op::Atom(Atom::from_text(&name.name))]);
5530 }
5531 MemberProp::Computed(key) => {
5532 self.expr(key)?;
5533 self.emit(Opcode::GetArrayEl2, &[]);
5534 }
5535 MemberProp::Private(name) => {
5536 let binding = format!("#{}", name.name);
5537 let (kind, _) = self.private_use(&binding, tag.span)?;
5538 self.private_callee(&binding, kind)?;
5539 }
5540 }
5541 self.emit(Opcode::PushConst, &[Op::Const(index)]);
5542 for expression in &quasi.expressions {
5543 self.expr(expression)?;
5544 }
5545 self.emit(Opcode::CallMethod, &[Op::Int(count as i32)]);
5546 return Ok(());
5547 }
5548 self.expr(tag)?;
5549 self.emit(Opcode::PushConst, &[Op::Const(index)]);
5550 for expression in &quasi.expressions {
5551 self.expr(expression)?;
5552 }
5553 self.emit(Opcode::Call, &[Op::Int(count as i32)]);
5554 Ok(())
5555 }
5556
5557 fn object_literal(
5558 &mut self,
5559 properties: &[ObjectProperty],
5560 span: Span,
5561 ) -> Result<(), SyntaxError> {
5562 self.emit(Opcode::Object, &[]);
5563 for property in properties {
5564 match property {
5565 ObjectProperty::Spread(value) => {
5566 // `copy_data_properties` takes the target, the source and an
5567 // exclusion list; a literal `null` means "exclude nothing".
5568 // Flag bit 1 copies symbols, bits 2/5 pick the source and the
5569 // exclusion list by stack offset.
5570 self.expr(spread_argument(value))?;
5571 self.emit(Opcode::Null, &[]);
5572 self.emit(Opcode::CopyDataProperties, &[Op::Int(COPY_ALL_PROPERTIES)]);
5573 self.emit(Opcode::Drop, &[]);
5574 self.emit(Opcode::Drop, &[]);
5575 }
5576 ObjectProperty::Property {
5577 key,
5578 value,
5579 kind,
5580 shorthand,
5581 span: property_span,
5582 } => match key {
5583 PropName::Computed(key_expr) => {
5584 self.expr(key_expr)?;
5585 match kind {
5586 PropertyKind::Value => {
5587 self.emit(Opcode::ToPropkey, &[]);
5588 self.expr(value)?;
5589 self.set_name_if_anonymous_computed(value);
5590 self.emit(Opcode::DefineArrayEl, &[]);
5591 // `define_array_el` leaves the object and the key;
5592 // the key is no longer needed.
5593 self.emit(Opcode::Drop, &[]);
5594 }
5595 PropertyKind::Method | PropertyKind::Get | PropertyKind::Set => {
5596 self.emit_method_function(value)?;
5597 self.emit(
5598 Opcode::DefineMethodComputed,
5599 &[Op::Int(define_method_flags(*kind))],
5600 );
5601 }
5602 }
5603 }
5604 PropName::Literal(key) => {
5605 let name = self.property_key_text(key, *property_span)?;
5606 match kind {
5607 PropertyKind::Method | PropertyKind::Get | PropertyKind::Set => {
5608 self.emit_method_function(value)?;
5609 self.emit(
5610 Opcode::DefineMethod,
5611 &[
5612 Op::Atom(Atom::from_wtf8(&name)),
5613 Op::Int(define_method_flags(*kind)),
5614 ],
5615 );
5616 }
5617 PropertyKind::Value => {
5618 self.expr(value)?;
5619 // `{__proto__: x}` sets the prototype instead of
5620 // creating a property; the shorthand `{__proto__}`
5621 // is an ordinary property and does not.
5622 if name == "__proto__" && !shorthand {
5623 self.emit(Opcode::SetProto, &[]);
5624 } else {
5625 self.set_name_if_anonymous(value, &name);
5626 self.emit(
5627 Opcode::DefineField,
5628 &[Op::Atom(Atom::from_wtf8(&name))],
5629 );
5630 }
5631 }
5632 }
5633 }
5634 PropName::Private(_) => {
5635 return Err(SyntaxError::new(
5636 "private names are not valid in object literals",
5637 *property_span,
5638 ));
5639 }
5640 },
5641 }
5642 }
5643 let _ = span;
5644 Ok(())
5645 }
5646
5647 /// Emit the function a method/accessor property defines.
5648 fn emit_method_function(&mut self, value: &Expr) -> Result<(), SyntaxError> {
5649 self.expr(value)
5650 }
5651
5652 /// The name a literal property key contributes.
5653 ///
5654 /// String keys are used as written. A numeric key is converted the way
5655 /// `ToString` would convert it, because the atom is made from that spelling:
5656 /// `{ 1e2: x }` and `{ 0x10: x }` both become `define_field 100` / `16`.
5657 fn property_key_text(&self, key: &PropKey, span: Span) -> Result<Wtf8, SyntaxError> {
5658 match key {
5659 PropKey::Str(text) => Ok(text.clone()),
5660 PropKey::Num(value) => numeric_key_text(*value, span).map(Wtf8::new),
5661 }
5662 }
5663
5664 /// Compile an optional chain.
5665 ///
5666 /// `?.` short-circuits the *whole remaining spine*, not just its own link:
5667 /// `a?.b.c` yields `undefined` when `a` is null, it does not read `.c` of
5668 /// `undefined`. So the chain is compiled with one end label and every guard
5669 /// jumps to it. The parser hands us the extent of that spine as an
5670 /// [`ExprKind::OptionalChain`] wrapper around the outermost link, which is
5671 /// exactly the scope the label has to cover.
5672 fn optional_chain(&mut self, inner: &Expr) -> Result<(), SyntaxError> {
5673 let end = self.new_label();
5674 self.chain_link(inner, end)?;
5675 self.place_label(end);
5676 Ok(())
5677 }
5678
5679 /// A member access or call reached from outside any optional chain.
5680 ///
5681 /// Such a link cannot contain a `?.` — if it did, the parser would have wrapped
5682 /// it in [`ExprKind::OptionalChain`] — so there is no guard and no label; one is
5683 /// still created because [`Self::chain_link`] takes it, and placing it at the
5684 /// end is a no-op that keeps a single code path.
5685 fn chain_link_top(&mut self, expr: &Expr) -> Result<(), SyntaxError> {
5686 let end = self.new_label();
5687 self.chain_link(expr, end)?;
5688 self.place_label(end);
5689 Ok(())
5690 }
5691
5692 /// One link of a chain, where `end` is the label a `?.` guard jumps to.
5693 fn chain_link(&mut self, expr: &Expr, end: Label) -> Result<(), SyntaxError> {
5694 match &expr.kind {
5695 ExprKind::Member {
5696 object,
5697 property,
5698 optional,
5699 } => {
5700 // `super.x` is not a lookup on a value: it starts at the home object's
5701 // prototype and keeps `this` as the receiver, so it cannot go through
5702 // `chain_link` and the ordinary field read.
5703 if matches!(object.unparen().kind, ExprKind::SuperProp) {
5704 self.super_base();
5705 match property {
5706 MemberProp::Ident(name) => self.emit(
5707 Opcode::PushAtomValue,
5708 &[Op::Atom(Atom::from_text(&name.name))],
5709 ),
5710 MemberProp::Computed(index) => self.expr(index)?,
5711 MemberProp::Private(_) => {
5712 return Err(SyntaxError::new(
5713 "private fields are not supported by the compiler yet",
5714 expr.span,
5715 ));
5716 }
5717 }
5718 self.emit(Opcode::GetSuperValue, &[]);
5719 return Ok(());
5720 }
5721 self.chain_link(object, end)?;
5722 if *optional {
5723 self.optional_guard(end);
5724 }
5725 match property {
5726 // `.length` has its own opcode. The reference emits it for every
5727 // object, not just arrays, so a name-based rule is right and
5728 // cheaper than the generic field read.
5729 MemberProp::Ident(name) if name.name == "length" => {
5730 self.emit(Opcode::GetLength, &[]);
5731 }
5732 MemberProp::Ident(name) => {
5733 self.emit(Opcode::GetField, &[Op::Atom(Atom::from_text(&name.name))]);
5734 }
5735 MemberProp::Computed(index) => {
5736 self.expr(index)?;
5737 self.emit(Opcode::GetArrayEl, &[]);
5738 }
5739 MemberProp::Private(name) => {
5740 // The binding comes from the class scope, so a read from outside the
5741 // class cannot name it at all. `?.` checks the object, not the field:
5742 // `o?.#x` guards on `o` being nullish.
5743 let binding = format!("#{}", name.name);
5744 let (kind, _) = self.private_use(&binding, expr.span)?;
5745 self.private_load(&binding, kind, expr.span)?;
5746 }
5747 }
5748 Ok(())
5749 }
5750 ExprKind::Call {
5751 callee,
5752 arguments,
5753 optional,
5754 } => {
5755 // `o.m(args)` has to pass `o` as `this`, which a plain `call`
5756 // cannot: it reads the function and then calls it with no
5757 // receiver at all. The reference's answer is to keep the object
5758 // under the function value — `get_field2` reads a field and leaves
5759 // its base in place — and to use `call_method`, which takes the
5760 // receiver from the stack. Missing this does not just cost an
5761 // instruction, it loses the `this` binding.
5762 if let ExprKind::Member {
5763 object,
5764 property,
5765 optional: member_optional,
5766 } = &callee.unparen().kind
5767 {
5768 // `super.m()` reads the method off the home object's prototype but
5769 // calls it with `this`, so the receiver goes under the read instead of
5770 // being replaced by it.
5771 if matches!(object.unparen().kind, ExprKind::SuperProp) {
5772 self.super_base();
5773 match property {
5774 MemberProp::Ident(name) => self.emit(
5775 Opcode::PushAtomValue,
5776 &[Op::Atom(Atom::from_text(&name.name))],
5777 ),
5778 MemberProp::Computed(index) => self.expr(index)?,
5779 MemberProp::Private(_) => {
5780 return Err(SyntaxError::new(
5781 "private fields are not supported by the compiler yet",
5782 expr.span,
5783 ));
5784 }
5785 }
5786 // The two-output form would drop the receiver; this one replaces
5787 // the prototype and the key, leaving `this` underneath.
5788 self.emit(Opcode::GetArrayEl, &[]);
5789 if Self::has_spread(arguments) {
5790 self.argument_array(arguments)?;
5791 self.emit(Opcode::Perm3, &[]);
5792 self.emit(Opcode::Apply, &[Op::Int(0)]);
5793 return Ok(());
5794 }
5795 for argument in arguments {
5796 self.expr(argument)?;
5797 }
5798 self.emit(Opcode::CallMethod, &[Op::Int(arguments.len() as i32)]);
5799 return Ok(());
5800 }
5801 self.chain_link(object, end)?;
5802 if *member_optional {
5803 self.optional_guard(end);
5804 }
5805 match property {
5806 MemberProp::Ident(name) => {
5807 self.emit(Opcode::GetField2, &[Op::Atom(Atom::from_text(&name.name))])
5808 }
5809 MemberProp::Computed(index) => {
5810 self.expr(index)?;
5811 // The key is not needed after the read, so this is the
5812 // two-output form: object, value.
5813 self.emit(Opcode::GetArrayEl2, &[]);
5814 }
5815 MemberProp::Private(name) => {
5816 // The receiver is already under the callee, which is exactly the
5817 // shape `call_method` and `apply` want — so nothing is dropped.
5818 let binding = format!("#{}", name.name);
5819 let (kind, _) = self.private_use(&binding, expr.span)?;
5820 self.private_callee(&binding, kind)?;
5821 }
5822 }
5823 if Self::has_spread(arguments) {
5824 // Stack is `obj func`; the array goes on top, then `perm3`
5825 // reorders to the `func this array` that `apply` wants.
5826 self.argument_array(arguments)?;
5827 self.emit(Opcode::Perm3, &[]);
5828 self.emit(Opcode::Apply, &[Op::Int(0)]);
5829 return Ok(());
5830 }
5831 for argument in arguments {
5832 self.expr(argument)?;
5833 }
5834 self.emit(Opcode::CallMethod, &[Op::Int(arguments.len() as i32)]);
5835 return Ok(());
5836 }
5837 // `(a?.b)()` keeps `a` as the receiver: the reference reads the method
5838 // with `get_field2` so the base stays under it, and on the short-circuit
5839 // path pushes an extra `undefined` as a placeholder receiver — the call
5840 // then throws, which is what calling a missing optional chain should do.
5841 if let ExprKind::OptionalChain(inner) = &callee.unparen().kind
5842 && let ExprKind::Member {
5843 object,
5844 property,
5845 optional: member_optional,
5846 } = &inner.unparen().kind
5847 {
5848 let call = self.new_label();
5849 // A guard target of its own: the outer `end` skips the whole
5850 // expression, and a short-circuited receiver still has to reach the
5851 // call so that calling it throws.
5852 let short = self.new_label();
5853 self.chain_link(object, end)?;
5854 if *member_optional {
5855 self.optional_guard(short);
5856 }
5857 match property {
5858 MemberProp::Ident(name) => {
5859 self.emit(Opcode::GetField2, &[Op::Atom(Atom::from_text(&name.name))])
5860 }
5861 MemberProp::Computed(index) => {
5862 self.expr(index)?;
5863 self.emit(Opcode::GetArrayEl2, &[]);
5864 }
5865 MemberProp::Private(name) => {
5866 let binding = format!("#{}", name.name);
5867 let (kind, _) = self.private_use(&binding, expr.span)?;
5868 self.private_callee(&binding, kind)?;
5869 }
5870 }
5871 self.emit_jump(Opcode::Goto, call, &[]);
5872 self.place_label(short);
5873 self.emit(Opcode::Undefined, &[]);
5874 self.place_label(call);
5875 if Self::has_spread(arguments) {
5876 self.argument_array(arguments)?;
5877 self.emit(Opcode::Perm3, &[]);
5878 self.emit(Opcode::Apply, &[Op::Int(0)]);
5879 return Ok(());
5880 }
5881 for argument in arguments {
5882 self.expr(argument)?;
5883 }
5884 self.emit(Opcode::CallMethod, &[Op::Int(arguments.len() as i32)]);
5885 return Ok(());
5886 }
5887 self.chain_link(callee, end)?;
5888 if *optional {
5889 self.optional_guard(end);
5890 }
5891 if Self::has_spread(arguments) {
5892 // `func array -> func undefined array`, which is the plain-call
5893 // form of `apply`: the receiver is `undefined`.
5894 self.argument_array(arguments)?;
5895 self.emit(Opcode::Undefined, &[]);
5896 self.emit(Opcode::Swap, &[]);
5897 self.emit(Opcode::Apply, &[Op::Int(0)]);
5898 return Ok(());
5899 }
5900 for argument in arguments {
5901 self.expr(argument)?;
5902 }
5903 self.emit(Opcode::Call, &[Op::Int(arguments.len() as i32)]);
5904 Ok(())
5905 }
5906 _ => self.expr(expr),
5907 }
5908 }
5909
5910 /// Compile `expr` as a tail call when it is one, reporting whether it was.
5911 ///
5912 /// `tail_call` reuses the current frame instead of pushing a new one, so a
5913 /// tail-recursive function runs in constant stack space. It also has to be the
5914 /// *last* thing the function does, which is why only a `return` reaches here.
5915 fn expr_if_tail_call(&mut self, expr: &Expr) -> Result<bool, SyntaxError> {
5916 let ExprKind::Call {
5917 callee,
5918 arguments,
5919 optional: false,
5920 } = &expr.unparen().kind
5921 else {
5922 return Ok(false);
5923 };
5924 // A spread call has no tail form: `tail_call` takes its arguments one at a time off
5925 // the stack, while `f(...xs)` builds an array and goes through `apply`. Compiling it
5926 // as an ordinary call costs the one frame the optimisation was saving and keeps the
5927 // semantics — the alternative was reaching the spread expression below and failing
5928 // with "this expression form is not supported", which is how `return super.m(...a)`
5929 // stopped compiling. Checked before anything is emitted, because the decision cannot
5930 // be taken back once `super_base` or a `get_field2` is on the stack.
5931 if Self::has_spread(arguments) {
5932 return Ok(false);
5933 }
5934 let end = self.new_label();
5935 if let ExprKind::Member {
5936 object,
5937 property,
5938 optional: false,
5939 } = &callee.unparen().kind
5940 {
5941 // `super.m()` in tail position is still an ordinary method call with `this`
5942 // as the receiver; only the read of the method differs.
5943 if matches!(object.unparen().kind, ExprKind::SuperProp) {
5944 self.super_base();
5945 match property {
5946 MemberProp::Ident(name) => self.emit(
5947 Opcode::PushAtomValue,
5948 &[Op::Atom(Atom::from_text(&name.name))],
5949 ),
5950 MemberProp::Computed(index) => self.expr(index)?,
5951 MemberProp::Private(_) => return Ok(false),
5952 }
5953 self.emit(Opcode::GetArrayEl, &[]);
5954 for argument in arguments {
5955 self.expr(argument)?;
5956 }
5957 self.emit(Opcode::TailCallMethod, &[Op::Int(arguments.len() as i32)]);
5958 self.place_label(end);
5959 return Ok(true);
5960 }
5961 self.chain_link(object, end)?;
5962 match property {
5963 MemberProp::Ident(name) => {
5964 self.emit(Opcode::GetField2, &[Op::Atom(Atom::from_text(&name.name))])
5965 }
5966 MemberProp::Computed(index) => {
5967 self.expr(index)?;
5968 self.emit(Opcode::GetArrayEl2, &[]);
5969 }
5970 MemberProp::Private(_) => return Ok(false),
5971 }
5972 for argument in arguments {
5973 self.expr(argument)?;
5974 }
5975 self.emit(Opcode::TailCallMethod, &[Op::Int(arguments.len() as i32)]);
5976 self.place_label(end);
5977 return Ok(true);
5978 }
5979 self.chain_link(callee, end)?;
5980 for argument in arguments {
5981 self.expr(argument)?;
5982 }
5983 self.emit(Opcode::TailCall, &[Op::Int(arguments.len() as i32)]);
5984 self.place_label(end);
5985 Ok(true)
5986 }
5987
5988 /// The `?.` guard: keep the value if it is neither null nor undefined,
5989 /// otherwise replace it with `undefined` and leave the whole chain.
5990 fn optional_guard(&mut self, end: Label) {
5991 let cont = self.new_label();
5992 self.emit(Opcode::Dup, &[]);
5993 self.emit(Opcode::IsUndefinedOrNull, &[]);
5994 self.emit_jump(Opcode::IfFalse, cont, &[]);
5995 self.emit(Opcode::Drop, &[]);
5996 self.emit(Opcode::Undefined, &[]);
5997 self.emit_jump(Opcode::Goto, end, &[]);
5998 self.place_label(cont);
5999 }
6000
6001 fn push_number(&mut self, value: f64) {
6002 // `push_N` / `push_i8` / `push_i32` cover small integers; everything else
6003 // goes into the constant pool.
6004 if value == value.trunc() && value.abs() <= i32::MAX as f64 {
6005 let int = value as i32;
6006 if (-1..=7).contains(&int) {
6007 self.emit(Opcode::PushI32, &[Op::Int(int)]);
6008 return;
6009 }
6010 if (-128..=127).contains(&int) {
6011 self.emit(Opcode::PushI8, &[Op::Int(int)]);
6012 return;
6013 }
6014 if (-32768..=32767).contains(&int) {
6015 self.emit(Opcode::PushI16, &[Op::Int(int)]);
6016 return;
6017 }
6018 self.emit(Opcode::PushI32, &[Op::Int(int)]);
6019 return;
6020 }
6021 let index = self.push_constant(Constant::Number(value));
6022 self.emit(Opcode::PushConst, &[Op::Const(index)]);
6023 }
6024
6025 /// Push a `BigInt` literal.
6026 ///
6027 /// A value that fits an `i32` uses the immediate form, which is what the reference
6028 /// emits too; anything larger goes into the constant pool, because the operand of
6029 /// `push_bigint` is only four bytes wide.
6030 fn push_bigint(&mut self, digits: &str, radix: u32) {
6031 if radix == 10
6032 && let Ok(value) = digits.parse::<i64>()
6033 && (i32::MIN as i64..=i32::MAX as i64).contains(&value)
6034 {
6035 self.emit(Opcode::PushBigintI32, &[Op::Int(value as i32)]);
6036 return;
6037 }
6038 let index = self.push_constant(Constant::BigInt {
6039 digits: digits.to_string(),
6040 radix,
6041 });
6042 self.emit(Opcode::PushConst, &[Op::Const(index)]);
6043 }
6044
6045 fn push_string(&mut self, text: &Wtf8) {
6046 if text.is_empty() {
6047 self.emit(Opcode::PushEmptyString, &[]);
6048 return;
6049 }
6050 self.emit(Opcode::PushAtomValue, &[Op::Atom(Atom::from_wtf8(text))]);
6051 }
6052
6053 /// Name an anonymous function from the binding it is assigned to.
6054 ///
6055 /// `var f = function(){}` produces a function whose `name` is `f`, which the
6056 /// runtime cannot know without being told: the function object is created
6057 /// before the store. `set_name` carries the name across.
6058 fn set_name_if_anonymous(&mut self, value: &Expr, name: &Wtf8) {
6059 if !value.is_anonymous_function_definition() {
6060 return;
6061 }
6062 // A class cannot use `set_name`, because its static field initialisers have already
6063 // run by the time the store happens and they can see `this.name`:
6064 // `var E = class { static f = this.name }` has to answer `"E"`. The reference patches
6065 // the `define_class` instruction's name operand instead, which is why
6066 // `set_class_name` is a compile-time marker with no runtime effect
6067 // (`class-name-static-initializer-anonymous`).
6068 if matches!(value.unparen().kind, ExprKind::Class(_)) {
6069 if let Some(index) = self.last_define_class() {
6070 let atom = Atom::from_wtf8(name);
6071 if let Some(Insn::Fixed { operands, .. }) = self.state().insns.get_mut(index) {
6072 // `define_class <atom> <flags>`: the name is operand 0.
6073 operands[0] = Op::Atom(atom);
6074 }
6075 }
6076 return;
6077 }
6078 self.emit(Opcode::SetName, &[Op::Atom(Atom::from_wtf8(name))]);
6079 }
6080
6081 /// The index of the most recent `define_class` in this function's instruction stream.
6082 ///
6083 /// A backwards scan, because everything the class body emitted for the *enclosing*
6084 /// function is still there after it — the static initialiser's call, the class
6085 /// binding's store, `leave_scope` — and only the `define_class` carries the name.
6086 fn last_define_class(&self) -> Option<usize> {
6087 self.cur().insns.iter().rposition(|insn| {
6088 matches!(
6089 insn,
6090 Insn::Fixed {
6091 op: Opcode::DefineClass,
6092 ..
6093 }
6094 )
6095 })
6096 }
6097
6098 /// The same, for a computed key: the name comes from the value on the stack
6099 /// rather than from an atom, so a different instruction carries it.
6100 fn set_name_if_anonymous_computed(&mut self, value: &Expr) {
6101 if value.is_anonymous_function_definition() {
6102 self.emit(Opcode::SetNameComputed, &[]);
6103 }
6104 }
6105
6106 /// Compile a function body that exists only in the compiler's head — a class's
6107 /// implicit constructor or its field initialiser.
6108 ///
6109 /// Everything structural is the same as a written function: a fresh `FnState`, its
6110 /// own body block, and resolution while the frame is still on the stack. Only the
6111 /// statements differ.
6112 fn compile_synthetic_function(
6113 &mut self,
6114 name: &str,
6115 strict: bool,
6116 span: Span,
6117 body: impl FnOnce(&mut Self) -> Result<(), SyntaxError>,
6118 ) -> Result<CompiledFunction, SyntaxError> {
6119 let mut state = FnState::new(name.to_string(), FunctionKind::Normal);
6120 state.span = Some((span.start.offset as usize, span.end.offset as usize));
6121 state.strict = strict;
6122 state.created_in_block = self.cur().current_block;
6123 state.with_names = self.cur().with_names.clone();
6124 state.line = span.start.line;
6125 state.column = span.start.column;
6126 let depth = self.stack.len();
6127 self.stack.push(state);
6128 let body_key = span.start.offset as u64;
6129 self.push_block(body_key, NO_PARENT);
6130 self.state().body_block = body_key;
6131 let result = (|| {
6132 self.emit_scope_enter(body_key);
6133 body(self)?;
6134 if self.end_is_reachable() {
6135 self.emit(Opcode::ReturnUndef, &[]);
6136 }
6137 Ok(())
6138 })();
6139 if result.is_err() {
6140 self.stack.truncate(depth);
6141 return result.map(|()| unreachable!());
6142 }
6143 Ok(self.finish_current())
6144 }
6145
6146 /// The implicit return of a class constructor.
6147 ///
6148 /// A constructor that falls off the end initialises its instance fields first, and a
6149 /// derived one returns `this` — which is what makes `new D()` the object `super()`
6150 /// built rather than `undefined`.
6151 fn emit_class_constructor_tail(&mut self) {
6152 match self.cur().ctor_kind {
6153 CtorKind::None => self.emit(Opcode::ReturnUndef, &[]),
6154 // Nothing to install: a base constructor did it in its prologue and a derived
6155 // one at each `super()` site, which is where `this` first exists.
6156 CtorKind::Base => self.emit(Opcode::ReturnUndef, &[]),
6157 CtorKind::Derived => {
6158 // `get_loc_check` rather than `get_loc`: reaching the end without ever
6159 // running `super()` is a ReferenceError, not `undefined`.
6160 self.emit_var(VarAction::Get, "this");
6161 self.emit(Opcode::Return, &[]);
6162 }
6163 }
6164 }
6165
6166 /// `yield expr` / `yield* expr`.
6167 ///
6168 /// The suspension itself is one instruction: the value is on the stack, `yield` hands
6169 /// it to the caller and parks the frame. On resume the stack holds the value the
6170 /// caller passed *and* a "magic" number saying which method resumed it — `next`
6171 /// passes `0`, `return` passes `1`, `throw` passes `2` — so the emitted
6172 /// `if_false <continue>` asks whether this was an ordinary `next`:
6173 ///
6174 /// * `next(v)` → the magic is falsy, jump over the `return_async` and `drop` `v`.
6175 /// * `return(v)`/`throw(e)` → fall into `return_async`, which finishes the generator
6176 /// and uses the value sitting under the magic number.
6177 ///
6178 /// A `throw` never reaches here: the interpreter unwinds instead (see
6179 /// `Interp::resume_generator`), so the `return_async` arm only ever carries `return`.
6180 fn yield_expression(
6181 &mut self,
6182 argument: Option<&Expr>,
6183 delegate: bool,
6184 ) -> Result<(), SyntaxError> {
6185 if delegate {
6186 return self.yield_star(argument);
6187 }
6188 // `AsyncGeneratorYield` settles the value *before* suspending, and `AsyncGenerator`
6189 // does the same for the `return(v)` that can resume it — which is why an async
6190 // generator's `yield` is `await; yield; (…); await; return_async` and a synchronous
6191 // generator's is just `yield`.
6192 let is_async = self.cur().kind == FunctionKind::AsyncGenerator;
6193 match argument {
6194 Some(value) => self.expr(value)?,
6195 None => self.emit(Opcode::Undefined, &[]),
6196 }
6197 if is_async {
6198 self.emit(Opcode::Await, &[]);
6199 self.state().has_await = true;
6200 }
6201 self.emit(Opcode::Yield, &[]);
6202 let resume = self.new_label();
6203 self.emit_jump(Opcode::IfFalse, resume, &[]);
6204 // `return(v)` resumed us. It is a `return` from the *body's* point of view, so it
6205 // runs the same cleanup chain: without it, `it.return()` inside `try { yield }`
6206 // finished the generator and never ran the `finally`.
6207 if is_async {
6208 self.emit(Opcode::Await, &[]);
6209 }
6210 self.emit_unwind_for_return(true);
6211 self.emit(Opcode::ReturnAsync, &[]);
6212 self.place_label(resume);
6213 // Nothing is emitted here: the value the caller passed to `next` *is* the value
6214 // of the `yield` expression, so `var x = yield 1` stores it and `yield 1;` drops
6215 // it through the ordinary expression-statement discard.
6216 Ok(())
6217 }
6218
6219 /// `yield* iterable`.
6220 ///
6221 /// The shape is the reference's, and it is a fall-through chain rather than a
6222 /// decision tree: drive the inner iterator, forward each value with `yield_star`, and
6223 /// on resume decide what the caller asked for — `next` keeps looping, `return` closes
6224 /// the inner iterator and finishes, `throw` forwards the exception into it and
6225 /// continues only if it has a `throw` method.
6226 ///
6227 /// The stack is `iter next catch value` throughout, `catch` being the offset
6228 /// `for_of_start` pushed; the `nip`s at the end uncover the value that is returned.
6229 fn yield_star(&mut self, argument: Option<&Expr>) -> Result<(), SyntaxError> {
6230 match argument {
6231 Some(value) => self.expr(value)?,
6232 // The parser rejects a bare `yield*`, so this is unreachable in practice.
6233 None => return Err(SyntaxError::new("yield* needs an operand", Span::default())),
6234 }
6235 // `for await of` is the same protocol as `for of` with two differences that matter
6236 // here: the iterator comes from `@@asyncIterator` with a `@@iterator` fallback, and
6237 // every `next()` result is a promise the delegate has to await.
6238 let is_async = self.cur().kind.is_async();
6239 self.emit(
6240 if is_async {
6241 Opcode::ForAwaitOfStart
6242 } else {
6243 Opcode::ForOfStart
6244 },
6245 &[],
6246 );
6247 self.emit(Opcode::Drop, &[]);
6248 self.emit(Opcode::Undefined, &[]);
6249 self.emit(Opcode::Undefined, &[]);
6250 let next = self.new_label();
6251 let resume = self.new_label();
6252 let finished = self.new_label();
6253 let rethrow = self.new_label();
6254 let throw_no_method = self.new_label();
6255 let done = self.new_label();
6256 self.place_label(next);
6257 self.emit(Opcode::IteratorNext, &[]);
6258 if is_async {
6259 self.emit(Opcode::Await, &[]);
6260 self.state().has_await = true;
6261 }
6262 self.emit(Opcode::IteratorCheckObject, &[]);
6263 self.emit(Opcode::GetField2, &[Op::Atom(Atom::from_text("done"))]);
6264 self.emit_jump(Opcode::IfTrue, done, &[]);
6265 // The suspension. `resume` is both the label the return path jumps back to in order
6266 // to yield one more value and where the caller's answer arrives, as the value
6267 // followed by the magic number.
6268 //
6269 // The two forms differ in what they hand the suspension: `yield_star` takes the
6270 // result object itself, `async_yield_star` takes `.value`, because an async
6271 // generator awaits and re-wraps whatever it yields.
6272 self.place_label(resume);
6273 if is_async {
6274 self.emit(Opcode::GetField, &[Op::Atom(Atom::from_text("value"))]);
6275 self.emit(Opcode::AsyncYieldStar, &[]);
6276 } else {
6277 self.emit(Opcode::YieldStar, &[]);
6278 }
6279 self.emit(Opcode::Dup, &[]);
6280 self.emit_jump(Opcode::IfTrue, rethrow, &[]);
6281 self.emit(Opcode::Drop, &[]);
6282 self.emit_jump(Opcode::Goto, next, &[]);
6283
6284 // `return(v)` / `throw(e)`: `2 === magic` tells them apart.
6285 self.place_label(rethrow);
6286 self.emit(Opcode::PushI32, &[Op::Int(2)]);
6287 self.emit(Opcode::StrictEq, &[]);
6288 self.emit_jump(Opcode::IfTrue, throw_no_method, &[]);
6289 // A `return` closes the inner iterator; if it had none, the delegate simply
6290 // finishes with the requested value. In an async generator both the call and its
6291 // result are awaited, because the inner `return` may itself be async.
6292 if is_async {
6293 self.emit(Opcode::Await, &[]);
6294 }
6295 self.emit(Opcode::IteratorCall, &[Op::Int(0)]);
6296 self.emit_jump(Opcode::IfTrue, finished, &[]);
6297 if is_async {
6298 self.emit(Opcode::Await, &[]);
6299 }
6300 self.emit(Opcode::IteratorCheckObject, &[]);
6301 self.emit(Opcode::GetField2, &[Op::Atom(Atom::from_text("done"))]);
6302 self.emit_jump(Opcode::IfFalse, resume, &[]);
6303 self.emit(Opcode::GetField, &[Op::Atom(Atom::from_text("value"))]);
6304 self.place_label(finished);
6305 self.emit(Opcode::Nip, &[]);
6306 self.emit(Opcode::Nip, &[]);
6307 self.emit(Opcode::Nip, &[]);
6308 // This is the delegate finishing on the caller's `return(v)`, so it is a `return`
6309 // from the body's point of view: `emit_return(s, TRUE)` in the reference, which
6310 // awaits the value in an async generator and then runs the same `finally`/iterator
6311 // unwinding a written `return` would. Skipping the unwinding made
6312 // `try { yield* xs } finally { … }` return early and leave the `finally` unrun.
6313 if is_async {
6314 self.emit(Opcode::Await, &[]);
6315 }
6316 self.emit_unwind_for_return(true);
6317 self.emit(Opcode::ReturnAsync, &[]);
6318
6319 // `throw(e)`: forward it into the inner iterator.
6320 self.place_label(throw_no_method);
6321 self.emit(Opcode::IteratorCall, &[Op::Int(1)]);
6322 let no_throw = self.new_label();
6323 self.emit_jump(Opcode::IfTrue, no_throw, &[]);
6324 if is_async {
6325 self.emit(Opcode::Await, &[]);
6326 }
6327 self.emit(Opcode::IteratorCheckObject, &[]);
6328 self.emit(Opcode::GetField2, &[Op::Atom(Atom::from_text("done"))]);
6329 self.emit_jump(Opcode::IfFalse, resume, &[]);
6330 self.emit_jump(Opcode::Goto, done, &[]);
6331 // No `throw` method: close the iterator, then report the spec's TypeError. The
6332 // `if_true` before the `await` is the reference's shape — the flag it consumes is
6333 // what `iterator_call` leaves behind, and a close that *did* find no `return`
6334 // method has nothing to await.
6335 self.place_label(no_throw);
6336 self.emit(Opcode::IteratorCall, &[Op::Int(2)]);
6337 let no_close = self.new_label();
6338 self.emit_jump(Opcode::IfTrue, no_close, &[]);
6339 if is_async {
6340 self.emit(Opcode::Await, &[]);
6341 }
6342 self.place_label(no_close);
6343 self.emit(Opcode::ThrowError, &[Op::Atom(Atom::Null), Op::Int(4)]);
6344
6345 // The inner iterator finished: the delegate's value is the `yield*` expression's
6346 // value, so it is left on the stack for whatever consumes it.
6347 self.place_label(done);
6348 self.emit(Opcode::GetField, &[Op::Atom(Atom::from_text("value"))]);
6349 self.emit(Opcode::Nip, &[]);
6350 self.emit(Opcode::Nip, &[]);
6351 self.emit(Opcode::Nip, &[]);
6352 Ok(())
6353 }
6354
6355 /// `await expr`: exactly one instruction.
6356 ///
6357 /// No resume-magic branch follows it. The reference's `await` leaves a single value
6358 /// on the stack and completion is signalled by the `return_async` at the end of the
6359 /// body; an `if_false`/`return_async` pair here would be an instruction sequence the
6360 /// reference never emits, and a `for await` loop — which reaches `await` through the
6361 /// same opcode — would then spill a value the loop's unpacking does not expect.
6362 fn await_expression(&mut self, argument: &Expr) -> Result<(), SyntaxError> {
6363 self.expr(argument)?;
6364 self.emit(Opcode::Await, &[]);
6365 self.state().has_await = true;
6366 Ok(())
6367 }
6368
6369 /// The `super` base: the receiver followed by the home object's prototype.
6370 ///
6371 /// Everything `super` does needs both. A *read* starts at the prototype but reports
6372 /// to the receiver (so a getter sees `this`), and a *call* reads the method off the
6373 /// prototype but calls it with the receiver.
6374 fn super_base(&mut self) {
6375 self.this_expression();
6376 self.home_object();
6377 self.emit(Opcode::GetSuper, &[]);
6378 }
6379
6380 /// `[[HomeObject]]` as `super` sees it.
6381 ///
6382 /// A method, a constructor and a field initialiser each carry one — `set_home_object`
6383 /// put it there — so for them the special object *is* the answer. An arrow and a
6384 /// static block have none: they read the enclosing function's, which has to be
6385 /// materialised into a local, exactly as `this` is for an arrow.
6386 ///
6387 /// The name matches what the reference stores, so the disassembly agrees; it is not a
6388 /// name any program can write.
6389 fn home_object(&mut self) {
6390 if !self.cur().is_arrow {
6391 self.emit(Opcode::SpecialObject, &[Op::Int(4)]);
6392 return;
6393 }
6394 if let Some(target) = self.enclosing_function() {
6395 self.state_at(target).needs_home_object_local = true;
6396 self.declare_at(target, HOME_OBJECT);
6397 }
6398 self.emit_var(VarAction::Get, HOME_OBJECT);
6399 }
6400
6401 /// `super(args)`: construct the parent class and adopt the result as `this`.
6402 ///
6403 /// The parent is the prototype of the constructor that is running, which is exactly
6404 /// what `extends` set up. `new.target` is passed through unchanged so that
6405 /// `new.target` inside the parent is the class actually being constructed.
6406 fn super_call(&mut self, arguments: &[Expr]) -> Result<(), SyntaxError> {
6407 self.active_func_expression();
6408 self.emit(Opcode::GetSuper, &[]);
6409 self.new_target_expression();
6410 if Self::has_spread(arguments) {
6411 self.argument_array(arguments)?;
6412 self.emit(Opcode::Apply, &[Op::Int(1)]);
6413 } else {
6414 for argument in arguments {
6415 self.expr(argument)?;
6416 }
6417 self.emit(Opcode::CallConstructor, &[Op::Int(arguments.len() as i32)]);
6418 }
6419 // The value stays on the stack: `super()` is an expression, and a derived
6420 // constructor's `this` may only be initialised once.
6421 self.emit(Opcode::Dup, &[]);
6422 self.emit_var(VarAction::PutInitChecked, "this");
6423 // Instance fields are installed here, not at the top of the body: a derived
6424 // constructor has no `this` to install them on until `super()` returns. The
6425 // reference emits the same call at every `super()` site.
6426 self.call_field_initialiser();
6427 Ok(())
6428 }
6429
6430 /// `this` as a local, which every class constructor and field initialiser needs.
6431 ///
6432 /// The reference materialises the receiver into a local rather than reading
6433 /// `push_this` inline, because `super()` in a derived constructor *replaces* `this`
6434 /// and a field initialiser has to see the final value.
6435 fn begin_this_local(&mut self) {
6436 self.declare_hidden_local("this", VarKind::Normal);
6437 self.emit(Opcode::PushThis, &[]);
6438 self.emit_var(VarAction::Put, "this");
6439 // The store is already at the top of the body, so `provide_this_local` has
6440 // nothing left to prepend. Without this the initialiser ended up with
6441 // `push_this; put_loc0 this` twice whenever the class also held a field
6442 // initialiser whose body read `this` through an arrow.
6443 self.state().has_this_prologue = true;
6444 }
6445
6446 /// Compile a constructor the class wrote.
6447 ///
6448 /// The flags have to be in place before the body is compiled, but
6449 /// `compile_function_with_name` creates its own state — so the caller's state is
6450 /// marked instead and the new one inherits it. That is the same trick the parameter
6451 /// prologue uses, and it keeps one code path for both.
6452 fn compile_class_constructor(
6453 &mut self,
6454 func: &ast::Function,
6455 has_heritage: bool,
6456 ) -> Result<CompiledFunction, SyntaxError> {
6457 let saved = self.cur().ctor_kind;
6458 self.state().class_ctor_pending = Some(if has_heritage {
6459 CtorKind::Derived
6460 } else {
6461 CtorKind::Base
6462 });
6463 let result = self.compile_function_with_name(func, false);
6464 self.state().ctor_kind = saved;
6465 self.state().class_ctor_pending = None;
6466 result
6467 }
6468
6469 /// The constructor a class gets when it does not declare one.
6470 ///
6471 /// A base class's is empty; a derived class's forwards every argument to the parent
6472 /// and is expressed by `init_ctor`, which also keeps `new.target`. Both run the
6473 /// instance field initialiser afterwards when the class has fields, which is why the
6474 /// initialiser is captured rather than inlined.
6475 fn compile_implicit_constructor(
6476 &mut self,
6477 class: &Class,
6478 has_heritage: bool,
6479 ) -> Result<CompiledFunction, SyntaxError> {
6480 self.compile_synthetic_function(
6481 "",
6482 true,
6483 Span::new(class.body_end, class.body_end),
6484 |compiler| {
6485 if has_heritage {
6486 // A derived constructor's `this` does not exist until `super()` returns,
6487 // so it starts in the dead zone and `init_ctor` fills it.
6488 compiler.declare("this", VarDef::lexical("this"));
6489 compiler.emit(
6490 Opcode::SetLocUninitialized,
6491 &[Op::Slot(Slot::Loc(compiler.cur().vars.len() as u32 - 1))],
6492 );
6493 compiler.emit(Opcode::InitCtor, &[]);
6494 compiler.emit(
6495 Opcode::PutLocCheckInit,
6496 &[Op::Slot(Slot::Loc(compiler.cur().vars.len() as u32 - 1))],
6497 );
6498 } else {
6499 compiler.begin_this_local();
6500 compiler.emit(Opcode::CheckCtor, &[]);
6501 }
6502 compiler.call_field_initialiser();
6503 // A derived constructor returns `this`, the object `super()` built. Without
6504 // this the implicit constructor fell through to `return_undef`, and `new B()`
6505 // handed back the empty object `construct` had made instead of the one the
6506 // parent constructor initialised.
6507 if has_heritage {
6508 compiler.emit_var(VarAction::Get, "this");
6509 compiler.emit(Opcode::Return, &[]);
6510 }
6511 Ok(())
6512 },
6513 )
6514 }
6515
6516 /// Emit the call to `<class_fields_init>`, guarded by an `undefined` test.
6517 ///
6518 /// A class with no instance fields leaves the binding `undefined`, and calling it
6519 /// would throw; the reference emits the same guard rather than branching at compile
6520 /// time because a class can be extended by a subclass whose fields still have to run.
6521 fn call_field_initialiser(&mut self) {
6522 let skip = self.new_label();
6523 self.emit_var(VarAction::Get, "<class_fields_init>");
6524 self.emit(Opcode::Dup, &[]);
6525 self.emit_jump(Opcode::IfFalse, skip, &[]);
6526 self.emit_var(VarAction::Get, "this");
6527 self.emit(Opcode::Swap, &[]);
6528 self.emit(Opcode::CallMethod, &[Op::Int(0)]);
6529 self.place_label(skip);
6530 self.emit(Opcode::Drop, &[]);
6531 }
6532
6533 /// The function that defines one class's fields on `this`, and runs its static blocks.
6534 ///
6535 /// `define_field` rather than `put_field`: a field is an own property created
6536 /// without consulting a setter on the prototype, so `class C { set x(v){} }` with an
6537 /// `x = 1` field must not call the setter.
6538 ///
6539 /// One function serves the whole class: it is called once per instance (or once, for
6540 /// the static half) and walks the members in source order. Static blocks are compiled
6541 /// into the same function because they *are* part of the same sequence — `static a =
6542 /// 1; static { }` and `static { this.a = 1 }; static a = 2` leave `a` holding
6543 /// different values, so the two kinds cannot be split apart.
6544 fn compile_field_initialiser(
6545 &mut self,
6546 items: &[StaticInitItem<'_>],
6547 span: Span,
6548 instance: bool,
6549 add_brand: bool,
6550 ) -> Result<CompiledFunction, SyntaxError> {
6551 self.compile_synthetic_function("", true, span, |compiler| {
6552 // A field initialiser and a static block are not functions, so neither has an
6553 // `arguments` of its own; see `FnState::no_arguments_binding`.
6554 let current = compiler.stack.len() - 1;
6555 compiler.stack[current].no_arguments_binding = true;
6556 if instance {
6557 // An instance initialiser always carries a `<home_object>` local, because the
6558 // brand block below reads it — even when that block turns out to be dead. The
6559 // reference has the same artefact, and the store is visible in its dump.
6560 let current = compiler.stack.len() - 1;
6561 compiler.stack[current].needs_home_object_local = true;
6562 }
6563 compiler.begin_this_local();
6564 if instance {
6565 // `this` gets the brand the prototype created, before any field is defined —
6566 // which is what makes `#m()` usable from inside a field initialiser.
6567 //
6568 // The reference always emits `push_false; if_false L; this; home; add_brand;
6569 // L:` and patches the `push_false` to `push_true` from the class parse when
6570 // the class has private methods; either way the branch folds, but the *mark*
6571 // it leaves (a `goto`) is what keeps the `put_loc`/`get_loc` pair around the
6572 // `this` local from being fused into a `set_loc`.
6573 let skip = compiler.new_label();
6574 if add_brand {
6575 compiler.emit(Opcode::PushTrue, &[]);
6576 } else {
6577 compiler.emit(Opcode::PushFalse, &[]);
6578 }
6579 compiler.emit_jump(Opcode::IfFalse, skip, &[]);
6580 compiler.emit_var(VarAction::Get, "this");
6581 compiler.emit_var(VarAction::Get, HOME_OBJECT);
6582 compiler.emit(Opcode::AddBrand, &[]);
6583 compiler.place_label(skip);
6584 }
6585 for item in items {
6586 match item {
6587 StaticInitItem::Field(key, value) => {
6588 // A private field is *defined*, not assigned: `define_private_field`
6589 // reads `obj symbol value`, and its point is that it fails on a
6590 // receiver that is not this class's — which `put_field` would not.
6591 //
6592 // The three shapes are the reference's: `define_field <atom>` for a
6593 // static name, `define_array_el` for a key that is only known at run
6594 // time (`obj key value`), `define_private_field` for `#x`, and a
6595 // computed key is read from its binding rather than recomputed.
6596 compiler.emit_var(VarAction::Get, "this");
6597 match key {
6598 FieldKey::Private(binding) | FieldKey::Computed(binding) => {
6599 compiler.emit_var(VarAction::Get, binding);
6600 }
6601 FieldKey::Literal(_) => {}
6602 }
6603 match value {
6604 Some(value) => {
6605 compiler.expr(value)?;
6606 // A field initialiser is a `NamedEvaluation` target:
6607 // `x = function(){}` names the function `"x"`, and a private
6608 // field keeps its `#` (`static #f = () => 1` is named
6609 // `"#f"` (elements/static-field-anonymous-function-name).
6610 match key {
6611 FieldKey::Literal(literal) => {
6612 let text = compiler.property_key_text(literal, span)?;
6613 compiler.set_name_if_anonymous(value, &text);
6614 }
6615 FieldKey::Private(binding) => {
6616 compiler.set_name_if_anonymous(value, &Wtf8::new(binding));
6617 }
6618 // The key is a value on the stack, and `set_name_computed`
6619 // is exactly the instruction for that.
6620 FieldKey::Computed(_) => {
6621 compiler.set_name_if_anonymous_computed(value);
6622 }
6623 }
6624 }
6625 None => compiler.emit(Opcode::Undefined, &[]),
6626 }
6627 match key {
6628 FieldKey::Literal(literal) => {
6629 let text = compiler.property_key_text(literal, span)?;
6630 compiler
6631 .emit(Opcode::DefineField, &[Op::Atom(Atom::from_wtf8(&text))]);
6632 }
6633 FieldKey::Computed(_) => {
6634 compiler.emit(Opcode::DefineArrayEl, &[]);
6635 // `define_array_el` leaves `obj key`; the key is consumed by
6636 // the copy the pattern machinery wants, so both go.
6637 compiler.emit(Opcode::Drop, &[]);
6638 }
6639 FieldKey::Private(_) => {
6640 compiler.emit(Opcode::DefinePrivateField, &[]);
6641 }
6642 }
6643 compiler.emit(Opcode::Drop, &[]);
6644 }
6645 StaticInitItem::Block { body, body_start } => {
6646 let block = compiler.compile_static_block(body, *body_start)?;
6647 let index = compiler.push_constant(Constant::Function(Box::new(block)));
6648 // `this fclosure`, so `call_method` finds the receiver below the
6649 // callee: the block runs with `this` bound to the class.
6650 compiler.emit(Opcode::Fclosure, &[Op::Const(index)]);
6651 compiler.emit_var(VarAction::Get, "this");
6652 compiler.emit(Opcode::Swap, &[]);
6653 compiler.emit(Opcode::CallMethod, &[Op::Int(0)]);
6654 // Nothing the block evaluates is wanted; its effects are the point.
6655 compiler.emit(Opcode::Drop, &[]);
6656 }
6657 }
6658 }
6659 Ok(())
6660 })
6661 }
6662
6663 /// Compile a `static { … }` body into the function the class calls for it.
6664 ///
6665 /// Shaped like an arrow, because that is the one function form with no `this`,
6666 /// `new.target` or `arguments` of its own: all three reach the enclosing static
6667 /// initialiser, and through it the class. `arguments` never gets that far — the parser
6668 /// rejects the reference — but `this` and `super` both depend on it.
6669 ///
6670 /// The body is hoisted like a function body's, because the reference parses it as one:
6671 /// `var` inside a block is a local of the block's function, not of whatever encloses
6672 /// the class.
6673 fn compile_static_block(
6674 &mut self,
6675 body: &[Stmt],
6676 body_start: Position,
6677 ) -> Result<CompiledFunction, SyntaxError> {
6678 let mut state = FnState::new(String::new(), FunctionKind::Normal);
6679 // Class bodies are strict, so a static block is too.
6680 state.strict = true;
6681 // The one property that makes this an arrow: nothing of its own to bind `this` to,
6682 // so `this` and `super` come from the initialiser that calls it.
6683 state.is_arrow = true;
6684 state.created_in_block = self.cur().current_block;
6685 state.with_names = self.cur().with_names.clone();
6686 state.line = body_start.line;
6687 state.column = body_start.column;
6688 let depth = self.stack.len();
6689 self.stack.push(state);
6690 let body_key = body_start.offset as u64;
6691 self.push_block(body_key, NO_PARENT);
6692 self.state().body_block = body_key;
6693 let result = (|| {
6694 self.hoist(body, body_key)?;
6695 self.emit_scope_enter(body_key);
6696 for statement in body {
6697 self.stmt(statement)?;
6698 }
6699 if self.end_is_reachable() {
6700 self.emit(Opcode::ReturnUndef, &[]);
6701 }
6702 Ok(())
6703 })();
6704 if result.is_err() {
6705 self.stack.truncate(depth);
6706 return result.map(|()| unreachable!());
6707 }
6708 Ok(self.finish_current())
6709 }
6710
6711 /// Compile a class, leaving the constructor on the stack when `keep`.
6712 ///
6713 /// The shape follows the reference: the class body is its own scope holding the
6714 /// class's *inner* name as a `const` — which is what lets a method refer to the
6715 /// class by name — plus a `<class_fields_init>` binding for the initialiser function.
6716 /// `define_class` turns `parent ctor` into `ctor proto`, then the members are defined
6717 /// on the top of the stack: the prototype for instance members, the constructor
6718 /// itself for `static` ones, which is why a static member costs an extra `swap`.
6719 fn class_definition(&mut self, class: &Class, keep: bool) -> Result<(), SyntaxError> {
6720 let parent_block = self.cur().current_block;
6721 let key = class.span.start.offset as u64;
6722 self.push_block(key, parent_block);
6723 let name = class.name.as_ref().map(|ident| ident.name.clone());
6724 // The class's own name is bound inside the body, so `class E { static F(){ return E } }`
6725 // resolves `E` without a global lookup. An *unnamed* class expression has no such
6726 // binding, and `define_class` is handed the empty name.
6727 if let Some(name) = &name {
6728 self.declare(name, VarDef::constant(name.clone()));
6729 }
6730 self.emit_scope_enter(key);
6731
6732 // The heritage clause is evaluated **inside** the class's own scope.
6733 //
6734 // §15.7.14 `ClassDefinitionEvaluation` steps 2–5: the class binding is created in
6735 // `classEnv` first, then "Set the running execution context's LexicalEnvironment to
6736 // classEnv" and *only then* evaluate `ClassHeritage`. The binding is still in its
6737 // dead zone at that point, so reading it from the heritage is a `ReferenceError` —
6738 // but a function *created* there closes over it and sees the class once the binding
6739 // is filled. That is what
6740 // `statements/class/scope-name-lex-open-heritage` checks: `probeHeritage()` returns
6741 // the class itself, `setHeritage` throws `TypeError` because the binding is
6742 // immutable, and the outer `C` is untouched.
6743 //
6744 // Reverting to the enclosing block here made the heritage's nested functions
6745 // capture the *outer* `C` instead, and the two tests only passed while the
6746 // enclosing-scope search was unscoped enough to reach the class binding by accident.
6747 let _ = parent_block;
6748 match &class.super_class {
6749 Some(parent) => self.expr(parent)?,
6750 None => self.emit(Opcode::Undefined, &[]),
6751 }
6752 let has_heritage = class.super_class.is_some();
6753
6754 // `<class_fields_init>` is declared *after* the heritage, so its dead-zone mark
6755 // lands after the heritage's code — which is where the reference puts it, because it
6756 // calls `define_var(..., JS_VAR_DEF_CONST)` at that point rather than at class entry.
6757 // Declaring it before `emit_scope_enter` instead put both marks at the class entry,
6758 // and `block_vars_reversed` prints a block's bindings backwards, so the two lines
6759 // came out in the opposite order from the reference's.
6760 //
6761 // `const`, as in `define_var(..., JS_VAR_DEF_CONST)`: the binding is filled exactly
6762 // once, through `put_var_init`/`scope_put_var_init` — the *initialising* store, which
6763 // a const accepts — so the old comment's worry ("a const would refuse the second
6764 // store") did not apply: there is no second store.
6765 // Every `#name` the class declares gets a `const` binding in the class scope, and so
6766 // does every computed field key. That is how the reference does it
6767 // (`add_private_class_field` → `add_scope_var` with `is_lexical`/`is_const`), and it is
6768 // what makes a private name resolve like any other class-scope variable — including
6769 // through a nested function's closure — while remaining invisible outside.
6770 //
6771 // All of them are declared *before* `<class_fields_init>`, in member order, because
6772 // that is when the reference's parser creates them.
6773 let plan = ClassPlan::build(class);
6774 // The body's private names are visible from here to the end of the class, and shadow
6775 // any outer class's of the same spelling. Pushed *before* the constructor is compiled
6776 // — it is compiled first because `define_class` consumes it, but its body can name
6777 // `#x` like any other member's.
6778 self.private_scopes.push(plan.uses.clone());
6779 let mut class_slots: Vec<u32> = Vec::with_capacity(plan.bindings.len());
6780 for binding in &plan.bindings {
6781 class_slots.push(self.declare(binding, VarDef::constant(binding.clone())));
6782 }
6783 let fci = self.declare(
6784 "<class_fields_init>",
6785 VarDef::constant("<class_fields_init>"),
6786 );
6787 // Dead-zone marks in reverse slot order, which is how `enter_scope` emits a scope's
6788 // lexical bindings — so `<class_fields_init>` (the highest) is marked first and the
6789 // members' bindings follow in reverse.
6790 self.emit(Opcode::SetLocUninitialized, &[Op::Slot(Slot::Loc(fci))]);
6791 for slot in class_slots.iter().rev() {
6792 self.emit(Opcode::SetLocUninitialized, &[Op::Slot(Slot::Loc(*slot))]);
6793 }
6794
6795 // The constructor is compiled before `define_class` because that instruction
6796 // consumes it; a class without one gets the implicit version.
6797 let constructor = class.elements.iter().find_map(|element| match element {
6798 ClassElement::Method {
6799 kind: MethodKind::Constructor,
6800 func,
6801 ..
6802 } => Some(&**func),
6803 _ => None,
6804 });
6805 // A constructor is compiled differently from a method: it owns `this`. The flags
6806 // go on the *enclosing* state because a constructor is a nested function and
6807 // `compile_function_with_name` starts a fresh one.
6808 let ctor = match constructor {
6809 Some(func) => self.compile_class_constructor(func, has_heritage)?,
6810 None => self.compile_implicit_constructor(class, has_heritage)?,
6811 };
6812 // A closure, not the bare constant: the constructor captures
6813 // `<class_fields_init>`, which is only filled after `define_class` has run, so it
6814 // has to hold the cell rather than a copy of its value.
6815 //
6816 // The pool slot is left unassigned for now, because the reference gives the
6817 // constructor the *last* index of the members' range: `js_parse_class` emits a
6818 // `push_const` whose operand is patched at the end of the class parse, after every
6819 // method has taken a slot. Emitting the members first and the constant second is how
6820 // the numbering comes out the same; the instruction itself stays where it is.
6821 let ctor_insn = self.cur().insns.len();
6822 self.emit(Opcode::Fclosure, &[Op::Const(CTOR_INDEX_PLACEHOLDER)]);
6823 let flags = if has_heritage { 1 } else { 0 };
6824 self.emit(
6825 Opcode::DefineClass,
6826 &[
6827 Op::Atom(Atom::from_text(name.as_deref().unwrap_or(""))),
6828 Op::Int(flags),
6829 ],
6830 );
6831
6832 // Instance fields and static fields are two different functions: the first runs
6833 // per instance from the constructor, the second runs once, here.
6834 let mut instance_fields: Vec<StaticInitItem<'_>> = Vec::new();
6835 let mut static_items: Vec<StaticInitItem<'_>> = Vec::new();
6836 for (index, element) in class.elements.iter().enumerate() {
6837 match element {
6838 ClassElement::Method {
6839 key: member_key,
6840 is_static,
6841 kind,
6842 func,
6843 span,
6844 } => {
6845 if *kind == MethodKind::Constructor {
6846 continue;
6847 }
6848 // `static(x)` is a *method* named `static`, not a static method; the
6849 // parser already decided which by putting it in `kind`.
6850 if *is_static {
6851 self.emit(Opcode::Swap, &[]);
6852 }
6853 // A computed key is evaluated *here*, before the method's closure
6854 // exists, and stays under it: `define_method_computed` pops
6855 // `function, key, object`, so the stack has to read
6856 // `[class, prototype, key, function]`. Evaluating the key after the
6857 // `fclosure` and swapping the two put the prototype *below* the
6858 // closure, which defined the method on the function and lost the
6859 // prototype: `class C { [k]() {} }` left `C` undefined. The order is
6860 // also the spec's — a class body evaluates every element's name before
6861 // that element's function.
6862 if let PropName::Computed(key) = member_key {
6863 self.expr(key)?;
6864 }
6865 let function = self.compile_function_with_name(func, true)?;
6866 let index = self.push_constant(Constant::Function(Box::new(function)));
6867 self.emit(Opcode::Fclosure, &[Op::Const(index)]);
6868 match member_key {
6869 // A private method is not a property of the prototype: it is a
6870 // closure in the class scope, which is why nothing outside can reach
6871 // it and why a use site has to brand-check. `set_name` gives the
6872 // function its `name` (`#m`), which an accessor does not get — the
6873 // reference leaves that commented out.
6874 PropName::Private(ident) => {
6875 let name = format!("#{}", ident.name);
6876 // `set_home_object` first: the brand check reads the function's
6877 // home object, and for a method that is the prototype.
6878 self.emit(Opcode::SetHomeObject, &[]);
6879 let binding = if *kind == MethodKind::Set {
6880 format!("{name}<set>")
6881 } else {
6882 name.clone()
6883 };
6884 if *kind == MethodKind::Method {
6885 self.emit(Opcode::SetName, &[Op::Atom(Atom::from_text(&name))]);
6886 }
6887 self.emit_var(VarAction::PutInit, &binding);
6888 }
6889 PropName::Computed(_) => {
6890 self.emit(
6891 Opcode::DefineMethodComputed,
6892 &[Op::Int(class_method_flags(*kind))],
6893 );
6894 }
6895 PropName::Literal(literal) => {
6896 let text = self.property_key_text(literal, *span)?;
6897 self.emit(
6898 Opcode::DefineMethod,
6899 &[
6900 Op::Atom(Atom::from_wtf8(&text)),
6901 Op::Int(class_method_flags(*kind)),
6902 ],
6903 );
6904 }
6905 }
6906 if *is_static {
6907 self.emit(Opcode::Swap, &[]);
6908 }
6909 }
6910 ClassElement::Field {
6911 key: field_key,
6912 is_static,
6913 value,
6914 ..
6915 } => {
6916 // A private field's *symbol* is created here, at the member, and stored
6917 // in its binding: the field's property is keyed by it, so it has to exist
6918 // before any initialiser runs, and a fresh one per class body is what
6919 // makes two classes that both write `#x` independent.
6920 //
6921 // A computed key is evaluated once, here, and `to_propkey`'d once — a key
6922 // whose `toString` has a side effect must not run again per instance.
6923 let key = match field_key {
6924 PropName::Private(ident) => {
6925 let binding = format!("#{}", ident.name);
6926 if *is_static {
6927 self.emit(Opcode::Swap, &[]);
6928 }
6929 self.emit(
6930 Opcode::PrivateSymbol,
6931 &[Op::Atom(Atom::from_text(&binding))],
6932 );
6933 self.emit_var(VarAction::PutInit, &binding);
6934 if *is_static {
6935 self.emit(Opcode::Swap, &[]);
6936 }
6937 FieldKey::Private(binding)
6938 }
6939 PropName::Computed(expression) => {
6940 let binding = plan
6941 .computed
6942 .get(&index)
6943 .cloned()
6944 .expect("every computed key got a binding");
6945 if *is_static {
6946 self.emit(Opcode::Swap, &[]);
6947 }
6948 self.expr(expression)?;
6949 self.emit(Opcode::ToPropkey, &[]);
6950 self.emit_var(VarAction::PutInit, &binding);
6951 if *is_static {
6952 self.emit(Opcode::Swap, &[]);
6953 }
6954 FieldKey::Computed(binding)
6955 }
6956 PropName::Literal(literal) => FieldKey::Literal(literal),
6957 };
6958 if *is_static {
6959 static_items.push(StaticInitItem::Field(key, value.as_deref()));
6960 } else {
6961 instance_fields.push(StaticInitItem::Field(key, value.as_deref()));
6962 }
6963 }
6964 ClassElement::StaticBlock {
6965 body, body_start, ..
6966 } => static_items.push(StaticInitItem::Block {
6967 body,
6968 body_start: *body_start,
6969 }),
6970 }
6971 }
6972
6973 // Now that every member has its slot, the constructor can have the next one and the
6974 // `fclosure` above can name it.
6975 let ctor_index = self.push_constant(Constant::Function(Box::new(ctor)));
6976 match self.state().insns.get_mut(ctor_insn) {
6977 Some(Insn::Fixed { operands, .. }) => {
6978 operands[0] = Op::Const(ctor_index);
6979 }
6980 // `emit` always pushes exactly one `Insn::Fixed`, so this cannot happen; failing
6981 // loudly beats emitting a `fclosure` of slot 4294967295.
6982 _ => {
6983 return Err(SyntaxError::new(
6984 "the class constructor's fclosure went missing",
6985 class.span,
6986 ));
6987 }
6988 }
6989
6990 // The instance brand: a symbol created once on the prototype, which every instance
6991 // then carries. `add_brand(obj, home)` reads `home` for the symbol (creating it the
6992 // first time) and adds it to `obj` — here `obj` is `null`, so only the prototype's
6993 // copy is created. The prototype is on top of the stack at this point.
6994 if plan.instance_brand {
6995 self.emit(Opcode::Dup, &[]);
6996 self.emit(Opcode::Null, &[]);
6997 self.emit(Opcode::Swap, &[]);
6998 self.emit(Opcode::AddBrand, &[]);
6999 }
7000
7001 // `<class_fields_init>` holds the instance initialiser, or `undefined` when the
7002 // class has no instance fields. The constructor calls it only when it is defined.
7003 //
7004 // A class with private *methods* but no fields still needs one, because adding the
7005 // brand to each new instance is the initialiser's job.
7006 if instance_fields.is_empty() && !plan.instance_brand {
7007 self.emit(Opcode::Undefined, &[]);
7008 } else {
7009 let initialiser = self.compile_field_initialiser(
7010 &instance_fields,
7011 class.span,
7012 true,
7013 plan.instance_brand,
7014 )?;
7015 let index = self.push_constant(Constant::Function(Box::new(initialiser)));
7016 self.emit(Opcode::Fclosure, &[Op::Const(index)]);
7017 // `set_home_object` reads `obj func`, so the prototype stays where it is.
7018 self.emit(Opcode::SetHomeObject, &[]);
7019 }
7020 self.emit_var(VarAction::PutInit, "<class_fields_init>");
7021 // The prototype has done its job: every instance member is defined on it. What
7022 // is left under it is the constructor.
7023 self.emit(Opcode::Drop, &[]);
7024
7025 // The static brand, for `static #m() {}`: same opcode, but the home object is the
7026 // constructor itself, so the symbol lands on the class and the class carries it.
7027 if plan.static_brand {
7028 self.emit(Opcode::Dup, &[]);
7029 self.emit(Opcode::Dup, &[]);
7030 self.emit(Opcode::AddBrand, &[]);
7031 }
7032
7033 // The class binding is initialised *before* static fields run, so a static field
7034 // can refer to the class by name (`static y = S.x`).
7035 // `set_loc` leaves the constructor on the stack, which is what the static field
7036 // call and the outer store both consume.
7037 //
7038 // Only when there *is* such a binding: an anonymous class expression declares no
7039 // class-scope name, and asking for one by the empty string resolved to nothing —
7040 // which made `var x = class {}` assign `undefined` and put a bogus global store in
7041 // the instruction stream.
7042 if let Some(name) = &name {
7043 self.emit_var(VarAction::SetInit, name);
7044 }
7045 if !static_items.is_empty() {
7046 // The static half has no brand prologue of its own: the constructor got its
7047 // brand above, before this runs.
7048 let initialiser =
7049 self.compile_field_initialiser(&static_items, class.span, false, false)?;
7050 let index = self.push_constant(Constant::Function(Box::new(initialiser)));
7051 self.emit(Opcode::Dup, &[]);
7052 self.emit(Opcode::Fclosure, &[Op::Const(index)]);
7053 self.emit(Opcode::SetHomeObject, &[]);
7054 self.emit(Opcode::CallMethod, &[Op::Int(0)]);
7055 self.emit(Opcode::Drop, &[]);
7056 }
7057 // The body is over, and with it this class's private names.
7058 let _ = self.private_scopes.pop();
7059 self.emit_scope_leave(key);
7060 self.state().current_block = parent_block;
7061 if keep {
7062 // A class *expression* is its own value; the class-scope binding was only
7063 // ever an alias for it.
7064 return Ok(());
7065 }
7066 // A declaration stores into the binding the enclosing statement declared.
7067 self.emit_var(VarAction::PutInit, &name.unwrap_or_default());
7068 Ok(())
7069 }
7070
7071 fn push_this(&mut self) {
7072 self.emit(Opcode::PushThis, &[]);
7073 }
7074
7075 /// `this`, which an arrow does not have of its own.
7076 ///
7077 /// The reference gives the enclosing function a local named `this`, initialised from
7078 /// `push_this` at the top of its body, and the arrow then reads it as a captured
7079 /// variable. That is why `(() => this)()` inside `f` yields `f`'s receiver even when
7080 /// the arrow is called with none.
7081 fn this_expression(&mut self) {
7082 // In a class constructor `this` is a local: a derived constructor only gets one
7083 // when `super()` returns, and reading the raw receiver would give the *outer*
7084 // one instead.
7085 if self.cur().ctor_kind != CtorKind::None {
7086 self.emit_var(VarAction::Get, "this");
7087 return;
7088 }
7089 if !self.cur().is_arrow {
7090 self.push_this();
7091 return;
7092 }
7093 // An arrow at the **top level** of a script or module has no enclosing function,
7094 // but it still inherits `this` — the script's or module's own. Falling through to
7095 // `emit_var(Get, "this")` without a target made that a *global* lookup, so
7096 // `var f = () => typeof this` at top level reported
7097 // `ReferenceError: 'this' is not defined` instead of `"object"`
7098 // (`Set/prototype/forEach/this-arg-explicit-cannot-override-lexical-this-arrow`
7099 // is the test262 case that reaches it, through a native `forEach`).
7100 //
7101 // The script state is the bottom of the stack, so it is the fallback target. Its
7102 // own `provide_this_local` then prepends the `push_this` the arrow reads.
7103 let target = self.enclosing_function().unwrap_or(0);
7104 self.state_at(target).needs_this_local = true;
7105 self.declare_at(target, "this");
7106 self.emit_var(VarAction::Get, "this");
7107 }
7108
7109 /// `new.target`, which an arrow likewise does not own.
7110 fn new_target_expression(&mut self) {
7111 if !self.cur().is_arrow {
7112 self.emit(Opcode::SpecialObject, &[Op::Int(3)]);
7113 return;
7114 }
7115 if let Some(target) = self.enclosing_function() {
7116 self.state_at(target).needs_new_target_local = true;
7117 self.declare_at(target, NEW_TARGET);
7118 }
7119 self.emit_var(VarAction::Get, NEW_TARGET);
7120 }
7121
7122 /// `this.active_func`: the function `super()` resolves against.
7123 ///
7124 /// In a constructor or a method that is the function being run, so the special object
7125 /// answers directly. In an arrow it is whatever the enclosing function saw, read out of
7126 /// a closure variable — see [`FnState::needs_active_func_local`].
7127 fn active_func_expression(&mut self) {
7128 if !self.cur().is_arrow {
7129 self.emit(Opcode::SpecialObject, &[Op::Int(2)]);
7130 return;
7131 }
7132 if let Some(target) = self.enclosing_function() {
7133 self.state_at(target).needs_active_func_local = true;
7134 self.declare_at(target, ACTIVE_FUNC);
7135 }
7136 self.emit_var(VarAction::Get, ACTIVE_FUNC);
7137 }
7138
7139 /// Give the function a local `<active_func>`, for an arrow inside it to capture.
7140 fn provide_active_func_local(&mut self) {
7141 let current = self.stack.len() - 1;
7142 if !self.stack[current].needs_active_func_local {
7143 return;
7144 }
7145 if !self.stack[current]
7146 .vars
7147 .iter()
7148 .any(|var| var.name == ACTIVE_FUNC)
7149 {
7150 self.declare_hidden_local(ACTIVE_FUNC, VarKind::Normal);
7151 }
7152 self.prepend_initialiser(
7153 ACTIVE_FUNC,
7154 Insn::Fixed {
7155 op: Opcode::SpecialObject,
7156 operands: vec![Op::Int(2)],
7157 },
7158 );
7159 }
7160
7161 /// Give the function a local `new.target`, for an arrow inside it to capture.
7162 fn provide_new_target_local(&mut self) {
7163 let current = self.stack.len() - 1;
7164 if !self.stack[current].needs_new_target_local {
7165 return;
7166 }
7167 if !self.stack[current]
7168 .vars
7169 .iter()
7170 .any(|var| var.name == NEW_TARGET)
7171 {
7172 self.declare_hidden_local(NEW_TARGET, VarKind::Normal);
7173 }
7174 self.prepend_initialiser(
7175 NEW_TARGET,
7176 Insn::Fixed {
7177 op: Opcode::SpecialObject,
7178 operands: vec![Op::Int(3)],
7179 },
7180 );
7181 }
7182
7183 /// `arguments` reached from an arrow, which likewise belongs to the enclosing
7184 /// function.
7185 fn ensure_enclosing_arguments(&mut self) {
7186 // An arrow created in a parameter list needs the *parameter* scope's
7187 // `arguments`, not the body's: the two are separate bindings and the arrow was
7188 // born before the body existed.
7189 let from_params = self.cur().created_in_params;
7190 if let Some(target) = self.enclosing_function() {
7191 self.state_at(target).needs_arguments_local = true;
7192 if from_params {
7193 self.state_at(target).needs_param_arguments = true;
7194 // Declare it now, not at the enclosing function's `finish_current`: the
7195 // arrow resolves its own `arguments` before that runs, and a binding that
7196 // does not exist yet resolves as a global.
7197 declare_param_var_at(&mut self.stack[target], "arguments");
7198 }
7199 self.declare_at(target, "arguments");
7200 }
7201 }
7202
7203 /// The innermost enclosing frame that is a real function — an arrow inherits from it
7204 /// rather than starting a scope of its own.
7205 /// The innermost enclosing frame that can own a lexical binding an arrow reads —
7206 /// a real function, or a **script** top level.
7207 ///
7208 /// A script is in the list because an `eval` body is compiled as one and an arrow
7209 /// written in eval'd code still has to find the caller's `new.target`, `this.active_func`
7210 /// and `[[HomeObject]]`. Excluding it made `eval("() => new.target")` compile the read as
7211 /// a *global* lookup of `new.target`, which no frame provides — so it raised
7212 /// `ReferenceError` instead of answering the caller's value
7213 /// (`arrow-body-direct-eval-err-contains-newtarget`).
7214 fn enclosing_function(&self) -> Option<usize> {
7215 (0..self.stack.len())
7216 .rev()
7217 .find(|index| !self.stack[*index].is_arrow)
7218 }
7219
7220 fn state_at(&mut self, index: usize) -> &mut FnState {
7221 &mut self.stack[index]
7222 }
7223
7224 /// Declare a `var` binding directly in a specific frame.
7225 fn declare_at(&mut self, index: usize, name: &str) {
7226 let state = &mut self.stack[index];
7227 if state.vars.iter().any(|var| var.name == name) {
7228 return;
7229 }
7230 state.var_block.push(FUNCTION_SCOPE);
7231 state.vars.push(VarDef::var(name));
7232 }
7233
7234 /// Prepend `<value-producing insn>; put <name>` to the body, which is how a binding
7235 /// the reference calls a `special_object` gets initialised on entry.
7236 fn prepend_initialiser(&mut self, name: &str, producer: Insn) {
7237 let current = self.stack.len() - 1;
7238 let init = [
7239 producer,
7240 Insn::Var {
7241 action: VarAction::Put,
7242 name: name.to_string(),
7243 block: 0,
7244 // A prologue initialiser runs before the body proper, but it is body
7245 // code: `this` and `arguments` are provided for it, not by it.
7246 in_params: false,
7247 },
7248 ];
7249 let inserted = init.len();
7250 for (index, instruction) in init.into_iter().enumerate() {
7251 self.stack[current].insns.insert(index, instruction);
7252 }
7253 for placed in self.stack[current].labels.iter_mut().flatten() {
7254 *placed += inserted;
7255 }
7256 self.stack[current].label_since_insn = true;
7257 }
7258
7259 fn push_constant(&mut self, constant: Constant) -> u32 {
7260 let state = self.state();
7261 let index = state.cpool.len() as u32;
7262 state.cpool.push(constant);
7263 index
7264 }
7265
7266 /// Compile `a && b`, `a || b`, `a ?? b`.
7267 ///
7268 /// A run of the *same* operator shares one end label, so `a || b || c` tests
7269 /// `a` once and jumps past everything when it is truthy, instead of falling
7270 /// into `b`'s test. The parser builds such a run left-associated —
7271 /// `((a || b) || c)` — so the operands are collected off the left spine.
7272 ///
7273 /// A *different* operator starts its own chain: `(a || b) && c` keeps the inner
7274 /// `||`'s label, because the inner chain really does end before `&&` begins.
7275 fn logical(&mut self, op: LogicalOp, left: &Expr, right: &Expr) -> Result<(), SyntaxError> {
7276 let mut operands = Vec::new();
7277 collect_same_operator(op, left, &mut operands);
7278 operands.push(right);
7279
7280 let end = self.new_label();
7281 // Every operand but the last decides whether the chain stops here.
7282 let last = operands.pop().expect("the right operand is always present");
7283 for operand in operands {
7284 self.expr(operand)?;
7285 self.emit(Opcode::Dup, &[]);
7286 match op {
7287 LogicalOp::And => self.emit_jump(Opcode::IfFalse, end, &[]),
7288 LogicalOp::Or => self.emit_jump(Opcode::IfTrue, end, &[]),
7289 // `??` cannot reuse the truthiness jumps: `0 ?? b` is `0` while
7290 // `0 || b` is `b`. The dedicated test keeps the value unless it is
7291 // null-ish, so the jump is taken on `false`.
7292 LogicalOp::Coalesce => {
7293 self.emit(Opcode::IsUndefinedOrNull, &[]);
7294 self.emit_jump(Opcode::IfFalse, end, &[]);
7295 }
7296 }
7297 self.emit(Opcode::Drop, &[]);
7298 }
7299 self.expr(last)?;
7300 self.place_label(end);
7301 Ok(())
7302 }
7303
7304 fn unary(&mut self, op: UnaryOp, argument: &Expr) -> Result<(), SyntaxError> {
7305 match op {
7306 UnaryOp::Typeof => {
7307 // `typeof x` must not throw on an undeclared name.
7308 if let ExprKind::Ident(name) = &argument.kind {
7309 self.emit_var(VarAction::GetUndef, &name.name);
7310 } else {
7311 self.expr(argument)?;
7312 }
7313 self.emit(Opcode::Typeof, &[]);
7314 }
7315 UnaryOp::Delete => {
7316 // `delete obj.prop` really deletes, and answers whether it could.
7317 // Deleting a *binding* is always `false`: a local, an argument and a
7318 // declared global are all non-configurable, which the reference encodes
7319 // as a constant `push_false` rather than a runtime check. Only a
7320 // property access has anything to do at run time.
7321 // `delete super.x` is not a delete at all: the spec refuses it, and the
7322 // reference encodes the refusal as a `throw_error`. The receiver and the
7323 // key are still evaluated first, which is what keeps the evaluation order
7324 // of the operand intact.
7325 // `delete z?.b.c` answers `true` when the chain short-circuits: there is
7326 // nothing to delete, and a failed delete is not the same as a skipped
7327 // one. The reference emits the guards so they land on a `drop; push_true`
7328 // tail, which is what this reproduces.
7329 if let ExprKind::OptionalChain(inner) = &argument.unparen().kind
7330 && let ExprKind::Member {
7331 object, property, ..
7332 } = &inner.unparen().kind
7333 {
7334 let end = self.new_label();
7335 let done = self.new_label();
7336 self.chain_link(object, end)?;
7337 match property {
7338 MemberProp::Ident(name) => self.emit(
7339 Opcode::PushAtomValue,
7340 &[Op::Atom(Atom::from_text(&name.name))],
7341 ),
7342 MemberProp::Computed(index) => self.expr(index)?,
7343 MemberProp::Private(_) => {
7344 return Err(SyntaxError::new(
7345 "deleting a private field is not allowed",
7346 argument.span,
7347 ));
7348 }
7349 }
7350 self.emit(Opcode::Delete, &[]);
7351 self.emit_jump(Opcode::Goto, done, &[]);
7352 self.place_label(end);
7353 self.emit(Opcode::Drop, &[]);
7354 self.emit(Opcode::PushTrue, &[]);
7355 self.place_label(done);
7356 return Ok(());
7357 }
7358 if let ExprKind::Member { object, .. } = &argument.unparen().kind
7359 && matches!(object.unparen().kind, ExprKind::SuperProp)
7360 {
7361 self.super_base();
7362 self.emit(Opcode::ThrowError, &[Op::Atom(Atom::Null), Op::Int(3)]);
7363 return Ok(());
7364 }
7365 // Parentheses are transparent to `delete`: `(x)` is still a Reference to
7366 // the binding `x`, so `delete (x)` answers `false` exactly as `delete x`
7367 // does, and `delete (a().b)` still evaluates `a()`. Matching on the
7368 // unparenthesised operand is what keeps both — matching on `argument.kind`
7369 // sent every parenthesised form to the "not a Reference" arm, which cost
7370 // `delete(__variable) === false` in test262's `S12.2_A2`.
7371 match &argument.unparen().kind {
7372 ExprKind::Member {
7373 object, property, ..
7374 } => {
7375 self.expr(object)?;
7376 match property {
7377 MemberProp::Ident(name) => {
7378 self.emit(
7379 Opcode::PushAtomValue,
7380 &[Op::Atom(Atom::from_text(&name.name))],
7381 );
7382 }
7383 MemberProp::Computed(index) => self.expr(index)?,
7384 MemberProp::Private(_) => {
7385 return Err(SyntaxError::new(
7386 "deleting a private field is not allowed",
7387 argument.span,
7388 ));
7389 }
7390 }
7391 self.emit(Opcode::Delete, &[]);
7392 }
7393 ExprKind::Ident(name) => {
7394 self.delete_ident(&name.name);
7395 }
7396 // §13.5.1.2 step 2: an operand that is **not** a Reference Record
7397 // answers `true` — there is nothing to delete, and "nothing needed
7398 // deleting" is success. `delete !0`, `delete (1 + 2)` and
7399 // `delete typeof 0` are all `true`, and the operand is still evaluated
7400 // (which is why it is `Drop`ed rather than skipped:
7401 // `delete f()` must call `f`).
7402 //
7403 // Answering `false` here is the C reference's old behaviour and was
7404 // wrong in an observable way: test262's
7405 // `dynamic-import/assignment-expression/logical-and-expr` builds a
7406 // specifier out of `delete void typeof +-~! 0 && b`, and a `false` left
7407 // half turned the whole `&&` into `false`, so the import asked for a
7408 // module named "false".
7409 _ => {
7410 self.expr(argument)?;
7411 self.emit(Opcode::Drop, &[]);
7412 self.emit(Opcode::PushTrue, &[]);
7413 }
7414 }
7415 }
7416 UnaryOp::Void => {
7417 self.expr(argument)?;
7418 self.emit(Opcode::Drop, &[]);
7419 self.emit(Opcode::Undefined, &[]);
7420 }
7421 UnaryOp::Minus => {
7422 self.expr(argument)?;
7423 self.emit(Opcode::Neg, &[]);
7424 }
7425 UnaryOp::Plus => {
7426 self.expr(argument)?;
7427 self.emit(Opcode::Plus, &[]);
7428 }
7429 UnaryOp::Not => {
7430 self.expr(argument)?;
7431 self.emit(Opcode::Lnot, &[]);
7432 }
7433 UnaryOp::BitNot => {
7434 self.expr(argument)?;
7435 self.emit(Opcode::Not, &[]);
7436 }
7437 }
7438 Ok(())
7439 }
7440
7441 /// A store to `name` while a `with` may capture it.
7442 ///
7443 /// The reference is resolved **first**, before the right-hand side runs. That order is
7444 /// the whole point: in `x = (delete env.x, 0)` the resolution has already decided that
7445 /// `x` is `env`'s property, so `PutValue` then finds it gone and strict code throws
7446 /// `ReferenceError` (`set-mutable-binding-binding-deleted-with-typed-array-in-
7447 /// proto-chain-strict-mode`). The ordinary path evaluates the right-hand side before
7448 /// the guard runs, which put the guard *after* the mutation.
7449 ///
7450 /// Shapes mirror [`Compiler::assign_ident_plain`] and the member arms of
7451 /// [`Compiler::assign`], with `dup; with_get_var` in place of `get_field2` and
7452 /// `with_put_var` in place of `put_field` — the same stack effects, but each half also
7453 /// asks the `HasProperty` that `GetBindingValue`/`SetMutableBinding` require.
7454 fn with_assign(
7455 &mut self,
7456 with_local: &str,
7457 name: &Ident,
7458 op: AssignOp,
7459 value: &Expr,
7460 keep: bool,
7461 ) -> Result<(), SyntaxError> {
7462 let atom = Atom::from_text(&name.name);
7463 self.state().cur_pos = Some(name.span.start);
7464 match op {
7465 AssignOp::Assign => {
7466 self.expr(value)?;
7467 self.set_name_if_anonymous(value, &Wtf8::new(&name.name));
7468 if keep {
7469 self.emit(Opcode::Dup, &[]);
7470 }
7471 self.state().no_value = !keep;
7472 self.emit_var(VarAction::Get, with_local);
7473 self.emit(Opcode::Swap, &[]);
7474 self.emit(Opcode::WithPutVar, &[Op::Atom(atom)]);
7475 }
7476 AssignOp::And | AssignOp::Or | AssignOp::Coalesce => {
7477 let (keep_label, end) = (self.new_label(), self.new_label());
7478 self.emit_var(VarAction::Get, with_local);
7479 self.emit(Opcode::Dup, &[]);
7480 self.emit(Opcode::WithGetVar, &[Op::Atom(atom.clone())]);
7481 // `obj value` — the object stays underneath for the store.
7482 self.emit(Opcode::Dup, &[]);
7483 self.emit_logical_test(op);
7484 self.emit_jump(logical_jump(op), keep_label, &[]);
7485 self.emit(Opcode::Drop, &[]);
7486 self.expr(value)?;
7487 self.emit(Opcode::Insert2, &[]);
7488 self.emit(Opcode::WithPutVar, &[Op::Atom(atom)]);
7489 self.emit_jump(Opcode::Goto, end, &[]);
7490 self.place_label(keep_label);
7491 self.emit(Opcode::Nip, &[]);
7492 self.place_label(end);
7493 }
7494 _ => {
7495 self.emit_var(VarAction::Get, with_local);
7496 self.emit(Opcode::Dup, &[]);
7497 self.emit(Opcode::WithGetVar, &[Op::Atom(atom.clone())]);
7498 self.expr(value)?;
7499 self.state().cur_pos = Some(name.span.start);
7500 self.emit(compound_opcode(op), &[]);
7501 self.state().no_value = !keep;
7502 if keep {
7503 self.emit(Opcode::Insert2, &[]);
7504 }
7505 self.emit(Opcode::WithPutVar, &[Op::Atom(atom)]);
7506 }
7507 }
7508 Ok(())
7509 }
7510
7511 /// `x++` / `++x` while a `with` may capture `x`, with one resolution for both halves.
7512 fn with_update(
7513 &mut self,
7514 with_local: &str,
7515 name: &Ident,
7516 op: UpdateOp,
7517 prefix: bool,
7518 ) -> Result<(), SyntaxError> {
7519 let instruction = match (op, prefix) {
7520 (UpdateOp::Increment, true) => Opcode::Inc,
7521 (UpdateOp::Increment, false) => Opcode::PostInc,
7522 (UpdateOp::Decrement, true) => Opcode::Dec,
7523 (UpdateOp::Decrement, false) => Opcode::PostDec,
7524 };
7525 let atom = Atom::from_text(&name.name);
7526 self.state().cur_pos = Some(name.span.start);
7527 self.emit_var(VarAction::Get, with_local);
7528 self.emit(Opcode::Dup, &[]);
7529 self.emit(Opcode::WithGetVar, &[Op::Atom(atom.clone())]);
7530 self.emit(instruction, &[]);
7531 self.emit(
7532 if prefix {
7533 Opcode::Insert2
7534 } else {
7535 Opcode::Perm3
7536 },
7537 &[],
7538 );
7539 self.emit(Opcode::WithPutVar, &[Op::Atom(atom)]);
7540 Ok(())
7541 }
7542
7543 /// A store to a plain identifier, with no `with` in the way.
7544 fn assign_ident_plain(
7545 &mut self,
7546 op: AssignOp,
7547 name: &Ident,
7548 value: &Expr,
7549 discard: bool,
7550 ) -> Result<(), SyntaxError> {
7551 // `discard` was taken by [`Compiler::expr`] for the expression the statement asked
7552 // about, so it is set only when this assignment *is* that expression.
7553 let keep = !discard;
7554 // A *simple* store is blamed on the identifier, not on the `=`: a
7555 // strict-mode `not_def = 1` raises when the name is written, which the
7556 // reference reports at the name's column. A compound store is blamed on
7557 // the operator instead (`a += poisoned` raises inside `ToPrimitive`,
7558 // which the reference reports at the `+=`), so only the simple case
7559 // moves the position.
7560 let saved = self.cur().cur_pos;
7561 let name_pos = Some(name.span.start);
7562 if matches!(op, AssignOp::Assign) {
7563 self.state().cur_pos = name_pos;
7564 }
7565 // A *compound* store reads the binding before it combines, and that read
7566 // is blamed on the identifier: `not_def += 2` fails while reading
7567 // `not_def`, so the position is the name's, not the `+=`'s. The
7568 // combination that follows is blamed on the operator, which is why
7569 // `cur_pos` is put back to the operator position before it is emitted.
7570 self.state().cur_pos = name_pos;
7571 // A direct `eval` in the right-hand side can declare a `var` with this name in the
7572 // *caller's* variable environment, and from then on the name means that binding.
7573 // §13.15.3 resolves the lvalue once, at step 1, and stores through it at step 7 —
7574 // so the binding has to be pinned before the right-hand side runs.
7575 // `compound-assignment/S11.13.2_A6.*` and `assignment/S11.13.1_A6_*` are entirely
7576 // about this. One `__proto__`-shaped corner costs a reference object; every other
7577 // assignment is byte-for-byte what it was.
7578 let pinned = self.cur().eval_can_declare;
7579 if pinned {
7580 self.emit_var(VarAction::MakeRef, &name.name);
7581 }
7582 match op {
7583 AssignOp::Assign => {
7584 self.expr(value)?;
7585 self.set_name_if_anonymous(value, &Wtf8::new(&name.name));
7586 if pinned {
7587 // `[ref, v] -> [v, ref, v] -> [v]`, the same `insert2` fold the
7588 // member stores use.
7589 if keep {
7590 self.emit(Opcode::Insert2, &[]);
7591 }
7592 self.emit(Opcode::PutRefValue, &[]);
7593 self.state().no_value = !keep;
7594 self.state().cur_pos = saved;
7595 return Ok(());
7596 }
7597 // A discarded store to a *slot* consumes its value, so no copy
7598 // is needed. A global store goes through `put_var`, which the
7599 // reference always pairs with a `dup` — matching it keeps the
7600 // bytecode identical. Getting this wrong is not only an extra
7601 // instruction: a stray copy gives the peephole a chance to fold
7602 // the store into an unrelated later read.
7603 let slot = self.is_slot(&name.name);
7604 if keep || !slot {
7605 self.emit(Opcode::Dup, &[]);
7606 }
7607 self.state().no_value = !keep && slot;
7608 self.emit_var(VarAction::Put, &name.name);
7609 }
7610 AssignOp::And | AssignOp::Or | AssignOp::Coalesce => {
7611 let end = self.new_label();
7612 // The pinned read leaves `[ref, v]`, so the branch that skips the store has
7613 // to `nip` the reference away; the branch that stores consumes it.
7614 self.emit_var(
7615 if pinned {
7616 VarAction::GetRef
7617 } else {
7618 VarAction::Get
7619 },
7620 &name.name,
7621 );
7622 self.state().cur_pos = saved;
7623 self.emit(Opcode::Dup, &[]);
7624 self.emit_logical_test(op);
7625 self.emit_jump(logical_jump(op), end, &[]);
7626 self.emit(Opcode::Drop, &[]);
7627 self.expr(value)?;
7628 // `x ||= function(){}` is a `NamedEvaluation` of the right-hand side, so the
7629 // function is named `x` — the same rule plain assignment follows
7630 // (`lgcl-*-namedevaluation-function`).
7631 self.set_name_if_anonymous(value, &Wtf8::new(&name.name));
7632 if pinned {
7633 self.emit(Opcode::Insert2, &[]);
7634 self.emit(Opcode::PutRefValue, &[]);
7635 } else {
7636 self.emit(Opcode::Dup, &[]);
7637 self.emit_var(VarAction::Put, &name.name);
7638 }
7639 self.place_label(end);
7640 if pinned {
7641 self.emit(Opcode::Nip, &[]);
7642 }
7643 }
7644 _ => {
7645 self.emit_var(
7646 if pinned {
7647 VarAction::GetRef
7648 } else {
7649 VarAction::Get
7650 },
7651 &name.name,
7652 );
7653 self.expr(value)?;
7654 self.state().cur_pos = saved;
7655 self.emit(compound_opcode(op), &[]);
7656 if pinned {
7657 self.emit(Opcode::Insert2, &[]);
7658 self.emit(Opcode::PutRefValue, &[]);
7659 } else {
7660 self.emit(Opcode::Dup, &[]);
7661 self.emit_var(VarAction::Put, &name.name);
7662 }
7663 }
7664 }
7665 self.state().cur_pos = saved;
7666 Ok(())
7667 }
7668
7669 /// Compile an assignment.
7670 ///
7671 /// Three operator families, three shapes:
7672 ///
7673 /// * **plain** `=` — evaluate, store. A member needs `insert2`/`insert3` when
7674 /// the value is kept, because `put_field`/`put_array_el` consume both the
7675 /// object and the value: `insert2` is `obj a -> a obj a`, so the store sees
7676 /// the pair it wants and leaves a copy on top.
7677 /// * **compound** `+=` … — read the place, apply the operator, store. A member
7678 /// reads through `get_field2`/`get_array_el3`, which leave the object (and
7679 /// index) underneath the value precisely so the store can follow.
7680 /// * **logical** `||=`, `&&=`, `??=` — read, test, and only then evaluate the
7681 /// right-hand side. The test *keeps* the current value and skips the store
7682 /// entirely, which is the whole point: `a ||= b` must not evaluate `b` when
7683 /// `a` is already truthy.
7684 fn assign(
7685 &mut self,
7686 op: AssignOp,
7687 target: &Pattern,
7688 value: &Expr,
7689 discard: bool,
7690 ) -> Result<(), SyntaxError> {
7691 // `discard` was taken by [`Compiler::expr`] for the expression the statement asked
7692 // about, so it is set only when this assignment *is* that expression.
7693 let keep = !discard;
7694 match &target.kind {
7695 PatternKind::Ident(name) => {
7696 // Any store to a name a `with` may capture resolves the reference first and
7697 // keeps that resolution for both halves — see [`Compiler::with_assign`].
7698 // Plain `=` needs it just as much as `+=`: `x = (delete env.x, 0)` must
7699 // resolve `x` before the right-hand side deletes it.
7700 let plain_name = name.name.clone();
7701 if !self.visible_with_names(&plain_name).is_empty() {
7702 return self.with_reference(
7703 &plain_name,
7704 &mut |compiler, with_local| {
7705 compiler.with_assign(with_local, name, op, value, !discard)
7706 },
7707 &mut |compiler| compiler.assign_ident_plain(op, name, value, discard),
7708 );
7709 }
7710 self.assign_ident_plain(op, name, value, discard)
7711 }
7712 PatternKind::Member(member) => {
7713 // `super.x = v` is not a store through a value: it starts at the home
7714 // object's prototype but writes to `this`, so it goes through
7715 // `put_super_value` rather than `put_field`. The receiver, prototype, key
7716 // and value are handed over together.
7717 if matches!(member.object.unparen().kind, ExprKind::SuperProp) {
7718 return self.assign_super(member, op, value);
7719 }
7720 // A store is blamed on the selector punctuator (`.` or `[`), the same
7721 // token a load is blamed on — the reference records `put_field obj.a`
7722 // at the `.`, so a setter that throws reports that column and not the
7723 // `=` of the assignment it sits in. The inner expressions restore their
7724 // own positions, so the selector's sticks for the store instructions.
7725 let saved = self.cur().cur_pos;
7726 self.state().cur_pos = member.op_pos.or(Some(member.span.start));
7727 self.expr(&member.object)?;
7728 match &member.property {
7729 MemberProp::Ident(property) => {
7730 let atom = Atom::from_text(&property.name);
7731 match op {
7732 AssignOp::Assign => {
7733 self.expr(value)?;
7734 // `put_field` consumes the object and the value, so
7735 // without `insert2` nothing is left over for the
7736 // statement to drop.
7737 self.state().no_value = !keep;
7738 if keep {
7739 self.emit(Opcode::Insert2, &[]);
7740 }
7741 self.emit(Opcode::PutField, &[Op::Atom(atom.clone())]);
7742 }
7743 AssignOp::And | AssignOp::Or | AssignOp::Coalesce => {
7744 // `get_field2` leaves the object under the value, so
7745 // the keep path has an object to dispose of. The store
7746 // path must jump *over* that cleanup: falling into it
7747 // would `nip` a stack that only holds the value.
7748 let (keep_label, end) = (self.new_label(), self.new_label());
7749 self.emit(Opcode::GetField2, &[Op::Atom(atom.clone())]);
7750 self.emit(Opcode::Dup, &[]);
7751 self.emit_logical_test(op);
7752 self.emit_jump(logical_jump(op), keep_label, &[]);
7753 self.emit(Opcode::Drop, &[]);
7754 self.expr(value)?;
7755 self.emit(Opcode::Insert2, &[]);
7756 self.emit(Opcode::PutField, &[Op::Atom(atom.clone())]);
7757 self.emit_jump(Opcode::Goto, end, &[]);
7758 self.place_label(keep_label);
7759 self.emit(Opcode::Nip, &[]);
7760 self.place_label(end);
7761 }
7762 _ => {
7763 self.emit(Opcode::GetField2, &[Op::Atom(atom.clone())]);
7764 self.expr(value)?;
7765 self.emit(compound_opcode(op), &[]);
7766 self.state().no_value = !keep;
7767 if keep {
7768 self.emit(Opcode::Insert2, &[]);
7769 }
7770 self.emit(Opcode::PutField, &[Op::Atom(atom.clone())]);
7771 }
7772 }
7773 }
7774 MemberProp::Computed(index) => {
7775 self.expr(index)?;
7776 match op {
7777 AssignOp::Assign => {
7778 self.expr(value)?;
7779 self.state().no_value = !keep;
7780 if keep {
7781 self.emit(Opcode::Insert3, &[]);
7782 }
7783 self.emit(Opcode::PutArrayEl, &[]);
7784 }
7785 AssignOp::And | AssignOp::Or | AssignOp::Coalesce => {
7786 let (keep_label, end) = (self.new_label(), self.new_label());
7787 self.emit(Opcode::GetArrayEl3, &[]);
7788 self.emit(Opcode::Dup, &[]);
7789 self.emit_logical_test(op);
7790 self.emit_jump(logical_jump(op), keep_label, &[]);
7791 self.emit(Opcode::Drop, &[]);
7792 self.expr(value)?;
7793 self.emit(Opcode::Insert3, &[]);
7794 self.emit(Opcode::PutArrayEl, &[]);
7795 self.emit_jump(Opcode::Goto, end, &[]);
7796 self.place_label(keep_label);
7797 // Both the object and the index are left over.
7798 self.emit(Opcode::Nip, &[]);
7799 self.emit(Opcode::Nip, &[]);
7800 self.place_label(end);
7801 }
7802 _ => {
7803 self.emit(Opcode::GetArrayEl3, &[]);
7804 self.expr(value)?;
7805 self.emit(compound_opcode(op), &[]);
7806 self.state().no_value = !keep;
7807 if keep {
7808 self.emit(Opcode::Insert3, &[]);
7809 }
7810 self.emit(Opcode::PutArrayEl, &[]);
7811 }
7812 }
7813 }
7814 MemberProp::Private(name) => {
7815 // `obj value` is on the stack, and every private store wants exactly
7816 // that. A top-level private name cannot be assigned (the parser rejects
7817 // `#x = 1`), so the only way here is `this.#x = …` inside the class.
7818 //
7819 // The reference emits `insert2` whether or not the value is wanted,
7820 // so this does too: the copy left behind is the assignment expression's
7821 // value, and a discarded one is simply never read.
7822 let binding = format!("#{}", name.name);
7823 let (kind, setter) = self.private_use(&binding, member.span)?;
7824 match op {
7825 AssignOp::Assign => {
7826 self.expr(value)?;
7827 if keep {
7828 self.emit(Opcode::Insert2, &[]);
7829 }
7830 self.private_store(&binding, kind, setter.as_deref())?;
7831 self.state().no_value = !keep;
7832 }
7833 AssignOp::And | AssignOp::Or | AssignOp::Coalesce => {
7834 let (keep_label, end) = (self.new_label(), self.new_label());
7835 self.emit(Opcode::Dup, &[]);
7836 self.private_load(&binding, kind, member.span)?;
7837 self.emit(Opcode::Dup, &[]);
7838 self.emit_logical_test(op);
7839 self.emit_jump(logical_jump(op), keep_label, &[]);
7840 self.emit(Opcode::Drop, &[]);
7841 self.expr(value)?;
7842 self.emit(Opcode::Insert2, &[]);
7843 self.private_store(&binding, kind, setter.as_deref())?;
7844 self.emit_jump(Opcode::Goto, end, &[]);
7845 self.place_label(keep_label);
7846 self.emit(Opcode::Nip, &[]);
7847 self.place_label(end);
7848 }
7849 _ => {
7850 self.emit(Opcode::Dup, &[]);
7851 self.private_load(&binding, kind, member.span)?;
7852 self.expr(value)?;
7853 self.emit(compound_opcode(op), &[]);
7854 self.emit(Opcode::Insert2, &[]);
7855 self.private_store(&binding, kind, setter.as_deref())?;
7856 }
7857 }
7858 }
7859 }
7860 self.state().cur_pos = saved;
7861 Ok(())
7862 }
7863 // A destructuring assignment: the right-hand side is the expression's own
7864 // value, so it is evaluated once and kept under the pattern's stores.
7865 PatternKind::Array { .. } | PatternKind::Object { .. } => {
7866 self.expr(value)?;
7867 if keep {
7868 self.emit(Opcode::Dup, &[]);
7869 }
7870 self.destructure(target, None)?;
7871 self.state().no_value = !keep;
7872 Ok(())
7873 }
7874 _ => Err(SyntaxError::new(
7875 "this assignment target is not supported by the compiler yet",
7876 target.span,
7877 )),
7878 }
7879 }
7880
7881 /// `super.x = v`, `super[k] = v`, and their compound and logical forms.
7882 ///
7883 /// The stack has to carry four values — receiver, prototype, key, value — because
7884 /// `put_super_value` takes them together; the receiver is what makes a setter found on
7885 /// the prototype run with `this`, and the key has to survive until the store, which is
7886 /// why a compound form converts it to a property key once and `dup3`s rather than
7887 /// evaluating it twice.
7888 fn assign_super(
7889 &mut self,
7890 member: &MemberPattern,
7891 op: AssignOp,
7892 value: &Expr,
7893 ) -> Result<(), SyntaxError> {
7894 let saved = self.cur().cur_pos;
7895 self.state().cur_pos = member.op_pos.or(Some(member.span.start));
7896 self.super_base();
7897 match &member.property {
7898 MemberProp::Ident(property) => self.emit(
7899 Opcode::PushAtomValue,
7900 &[Op::Atom(Atom::from_text(&property.name))],
7901 ),
7902 MemberProp::Computed(index) => self.expr(index)?,
7903 MemberProp::Private(_) => {
7904 return Err(SyntaxError::new(
7905 "private fields are not supported by the compiler yet",
7906 member.span,
7907 ));
7908 }
7909 }
7910 match op {
7911 AssignOp::Assign => {
7912 // The key is only converted once, by `put_super_value` itself, so a
7913 // computed key's `toString` runs exactly once.
7914 self.expr(value)?;
7915 self.emit(Opcode::Insert4, &[]);
7916 self.emit(Opcode::PutSuperValue, &[]);
7917 }
7918 AssignOp::And | AssignOp::Or | AssignOp::Coalesce => {
7919 let (keep_label, end) = (self.new_label(), self.new_label());
7920 self.emit(Opcode::ToPropkey, &[]);
7921 self.emit(Opcode::Dup3, &[]);
7922 self.emit(Opcode::GetSuperValue, &[]);
7923 self.emit(Opcode::Dup, &[]);
7924 self.emit_logical_test(op);
7925 self.emit_jump(logical_jump(op), keep_label, &[]);
7926 self.emit(Opcode::Drop, &[]);
7927 self.expr(value)?;
7928 self.emit(Opcode::Insert4, &[]);
7929 self.emit(Opcode::PutSuperValue, &[]);
7930 self.emit_jump(Opcode::Goto, end, &[]);
7931 self.place_label(keep_label);
7932 // The prototype and the key are still under the value that was read.
7933 self.emit(Opcode::Nip, &[]);
7934 self.emit(Opcode::Nip, &[]);
7935 self.emit(Opcode::Nip, &[]);
7936 self.place_label(end);
7937 }
7938 _ => {
7939 self.emit(Opcode::ToPropkey, &[]);
7940 self.emit(Opcode::Dup3, &[]);
7941 self.emit(Opcode::GetSuperValue, &[]);
7942 self.expr(value)?;
7943 self.emit(compound_opcode(op), &[]);
7944 self.emit(Opcode::Insert4, &[]);
7945 self.emit(Opcode::PutSuperValue, &[]);
7946 }
7947 }
7948 // No `drop` here for a discarded value. `insert4` keeps a copy of the value, so it
7949 // is still on the stack when the store finishes, and the expression statement is
7950 // what disposes of it — the same arrangement as `put_field`, reached from the other
7951 // side: there the store consumes the value (`no_value`), here it leaves it
7952 // (`keep` already false, so nothing tells the statement otherwise).
7953 self.state().cur_pos = saved;
7954 Ok(())
7955 }
7956
7957 /// The test a logical assignment applies to the current value.
7958 ///
7959 /// `??=` needs a real opcode rather than a truthiness jump: `0 ??= b` must
7960 /// assign, while `0 ||= b` must not.
7961 fn emit_logical_test(&mut self, op: AssignOp) {
7962 if op == AssignOp::Coalesce {
7963 self.emit(Opcode::IsUndefinedOrNull, &[]);
7964 }
7965 }
7966
7967 /// The private name `#name` this use site resolves against.
7968 ///
7969 /// The parser has already rejected a name no enclosing class declares, so a miss here
7970 /// means the compiler lost track of a class scope — which is worth a real error rather
7971 /// than an `unwrap`.
7972 fn private_use(
7973 &self,
7974 binding: &str,
7975 span: Span,
7976 ) -> Result<(PrivateKind, Option<String>), SyntaxError> {
7977 ClassPlan::find(self, binding)
7978 .map(|use_| (use_.kind, use_.setter.clone()))
7979 .ok_or_else(|| {
7980 SyntaxError::new(
7981 format!("the private name '{binding}' is out of scope here"),
7982 span,
7983 )
7984 })
7985 }
7986
7987 /// `obj.#name` as a value: `obj` is on the stack, the value replaces it.
7988 ///
7989 /// The three readable kinds take three different instructions, because a private name
7990 /// holds three different things — a symbol, a method function, a getter function — and
7991 /// only the first one is a property read at all.
7992 fn private_load(
7993 &mut self,
7994 binding: &str,
7995 kind: PrivateKind,
7996 span: Span,
7997 ) -> Result<(), SyntaxError> {
7998 match kind {
7999 PrivateKind::Field => {
8000 self.emit_var(VarAction::Get, binding);
8001 self.emit(Opcode::GetPrivateField, &[]);
8002 }
8003 PrivateKind::Method => {
8004 self.emit_var(VarAction::Get, binding);
8005 self.emit(Opcode::CheckBrand, &[]);
8006 // `check_brand` reads `obj func` and leaves both; the method itself is what
8007 // `this.#m` evaluates to.
8008 self.emit(Opcode::Nip, &[]);
8009 }
8010 PrivateKind::Getter => {
8011 self.emit_var(VarAction::Get, binding);
8012 self.emit(Opcode::CheckBrand, &[]);
8013 self.emit(Opcode::CallMethod, &[Op::Int(0)]);
8014 }
8015 // `#a` is declared but never filled when only a setter exists, so reading it is
8016 // the same refusal as assigning to a `const`. The reference reports it with the
8017 // generic read-only wording and leaves the better message as a `XXX`.
8018 PrivateKind::Setter => self.emit(
8019 Opcode::ThrowError,
8020 &[Op::Atom(Atom::from_text(binding)), Op::Int(0)],
8021 ),
8022 }
8023 let _ = span;
8024 Ok(())
8025 }
8026
8027 /// `obj.#name(...)`: like [`Self::private_load`], but the receiver stays under the callee.
8028 fn private_callee(&mut self, binding: &str, kind: PrivateKind) -> Result<(), SyntaxError> {
8029 match kind {
8030 // A method *is* the callee, so only the check goes in between.
8031 PrivateKind::Method => {
8032 self.emit_var(VarAction::Get, binding);
8033 self.emit(Opcode::CheckBrand, &[]);
8034 }
8035 _ => self.private_load(binding, kind, Span::default())?,
8036 }
8037 Ok(())
8038 }
8039
8040 /// The store half of `obj.#name = value`, with `obj value` on the stack and nothing
8041 /// wanted back.
8042 ///
8043 /// A getter/setter pair is a *method call*, not a property store: the reference reads
8044 /// the setter out of its own binding and calls it with the receiver, which is why the
8045 /// three `rot`/`swap` instructions below are needed. `insert2` at the call site is what
8046 /// keeps the assignment's value for an expression context.
8047 fn private_store(
8048 &mut self,
8049 binding: &str,
8050 kind: PrivateKind,
8051 setter: Option<&str>,
8052 ) -> Result<(), SyntaxError> {
8053 match kind {
8054 PrivateKind::Field => {
8055 self.emit_var(VarAction::Get, binding);
8056 self.emit(Opcode::PutPrivateField, &[]);
8057 }
8058 PrivateKind::Method | PrivateKind::Getter | PrivateKind::Setter => match setter {
8059 Some(setter) => {
8060 self.emit_var(VarAction::Get, setter);
8061 // `obj func value` -> `value obj func` for the check, and back again for
8062 // the call, which wants `obj func arg`.
8063 self.emit(Opcode::Swap, &[]);
8064 self.emit(Opcode::Rot3r, &[]);
8065 self.emit(Opcode::CheckBrand, &[]);
8066 self.emit(Opcode::Rot3l, &[]);
8067 self.emit(Opcode::CallMethod, &[Op::Int(1)]);
8068 // The setter's return value is discarded; the assignment's own value is
8069 // whatever the caller left underneath.
8070 self.emit(Opcode::Drop, &[]);
8071 }
8072 None => self.emit(
8073 Opcode::ThrowError,
8074 &[Op::Atom(Atom::from_text(binding)), Op::Int(0)],
8075 ),
8076 },
8077 }
8078 Ok(())
8079 }
8080
8081 fn update(&mut self, op: UpdateOp, argument: &Expr, prefix: bool) -> Result<(), SyntaxError> {
8082 // `x++` inside a `with` is a read-modify-write of a *property*, so the object is
8083 // resolved once for both halves. See [`Compiler::with_reference`].
8084 let unparened = argument.unparen();
8085 if let ExprKind::Ident(ident) = &unparened.kind {
8086 let name = ident.name.clone();
8087 if !self.visible_with_names(&name).is_empty() {
8088 return self.with_reference(
8089 &name,
8090 &mut |compiler, with_local| compiler.with_update(with_local, ident, op, prefix),
8091 &mut |compiler| compiler.update_plain(op, unparened, prefix),
8092 );
8093 }
8094 }
8095 self.update_plain(op, argument, prefix)
8096 }
8097
8098 fn update_plain(
8099 &mut self,
8100 op: UpdateOp,
8101 argument: &Expr,
8102 prefix: bool,
8103 ) -> Result<(), SyntaxError> {
8104 let instruction = match (op, prefix) {
8105 (UpdateOp::Increment, true) => Opcode::Inc,
8106 (UpdateOp::Increment, false) => Opcode::PostInc,
8107 (UpdateOp::Decrement, true) => Opcode::Dec,
8108 (UpdateOp::Decrement, false) => Opcode::PostDec,
8109 };
8110 // `(y)++` and `((o.x))++` are the same updates as the unparenthesised forms: §13.4
8111 // evaluates the operand as a `LeftHandSideExpression` and the parentheses around a
8112 // reference change nothing — they do not copy the value. Reading `argument.kind`
8113 // directly therefore rejected every parenthesised target with "increment of a
8114 // non-variable", which is not a thing the language has (`target-cover-id`).
8115 let argument = argument.unparen();
8116 if let ExprKind::Member {
8117 object,
8118 property,
8119 optional: _,
8120 } = &argument.kind
8121 {
8122 // `o.x++` needs the receiver twice, so the last link is read with the
8123 // `get_*2`/`get_*3` form that keeps it, and the update is written back
8124 // with `put_field`/`put_array_el`. The reordering in between is what puts
8125 // the old value below the receiver for a postfix update and the new one
8126 // above it for a prefix one:
8127 //
8128 // `obj val` → `post_inc` → `obj old new` → `perm3` → `old obj new`
8129 // `obj val` → `inc` → `obj new new` → `insert2` → `new obj new`
8130 //
8131 // This mirrors the reference instruction for instruction.
8132 self.expr(object)?;
8133 match property {
8134 MemberProp::Ident(name) => {
8135 self.emit(Opcode::GetField2, &[Op::Atom(Atom::from_text(&name.name))]);
8136 self.emit(instruction, &[]);
8137 self.emit(
8138 if prefix {
8139 Opcode::Insert2
8140 } else {
8141 Opcode::Perm3
8142 },
8143 &[],
8144 );
8145 self.emit(Opcode::PutField, &[Op::Atom(Atom::from_text(&name.name))]);
8146 }
8147 MemberProp::Computed(index) => {
8148 self.expr(index)?;
8149 self.emit(Opcode::GetArrayEl3, &[]);
8150 self.emit(instruction, &[]);
8151 self.emit(
8152 if prefix {
8153 Opcode::Insert3
8154 } else {
8155 Opcode::Perm4
8156 },
8157 &[],
8158 );
8159 self.emit(Opcode::PutArrayEl, &[]);
8160 }
8161 MemberProp::Private(name) => {
8162 // The receiver is duplicated and the read keeps it, exactly as `get_field2`
8163 // does for a public field: `obj val` -> `post_inc` -> `obj old new` ->
8164 // `perm3` -> `old obj new` -> store.
8165 let binding = format!("#{}", name.name);
8166 let (kind, setter) = self.private_use(&binding, argument.span)?;
8167 self.emit(Opcode::Dup, &[]);
8168 self.private_load(&binding, kind, argument.span)?;
8169 self.emit(instruction, &[]);
8170 self.emit(
8171 if prefix {
8172 Opcode::Insert2
8173 } else {
8174 Opcode::Perm3
8175 },
8176 &[],
8177 );
8178 self.private_store(&binding, kind, setter.as_deref())?;
8179 }
8180 }
8181 return Ok(());
8182 }
8183 let ExprKind::Ident(name) = &argument.kind else {
8184 return Err(SyntaxError::new(
8185 "increment of a non-variable is not supported by the compiler yet",
8186 argument.span,
8187 ));
8188 };
8189 // A discarded `i++` keeps the plain `get`/`post_inc`/`put` shape. The
8190 // reference's `inc_loc` folds those three into one, but it does so only in some
8191 // positions (a `for` update and not a bare statement, and never for a lexical
8192 // binding), so emitting it unconditionally would move *away* from its output.
8193 // The instruction is equivalent either way; matching the reference matters more
8194 // than saving two instructions.
8195 let _ = !std::mem::take(&mut self.state().discard_value);
8196 self.emit_var(VarAction::Get, &name.name);
8197 self.emit(instruction, &[]);
8198 if prefix {
8199 self.emit(Opcode::Dup, &[]);
8200 }
8201 self.emit_var(VarAction::Put, &name.name);
8202 Ok(())
8203 }
8204
8205 /// Compile an array literal.
8206 ///
8207 /// The reference splits this into three phases, and the split is load-bearing
8208 /// rather than an optimisation detail:
8209 ///
8210 /// 1. **A leading run of plain elements** becomes `array_from n`, which builds
8211 /// the array in one instruction.
8212 /// 2. **Everything up to the first spread** is appended with explicit indices
8213 /// (`define_field <index>`), because a hole has no element to pass to
8214 /// `array_from`. A hole here is what makes `length` need fixing up: an
8215 /// explicit index does not extend the array the way a pushed element does.
8216 /// 3. **From the first spread on** the index lives on the stack, so `append` and
8217 /// `define_array_el` can consume it and `inc` advances it.
8218 ///
8219 /// So `[1,,3]` and `[1,2,3]` are not two spellings of one program: the hole
8220 /// forces phase 2, and `[...a]` forces phase 3.
8221 fn array_literal(
8222 &mut self,
8223 elements: &[Option<ArrayElement>],
8224 span: Span,
8225 ) -> Result<(), SyntaxError> {
8226 let _ = span;
8227 let mut index: u32 = 0;
8228 let mut cursor = 0usize;
8229
8230 // Phase 1: a leading run of plain elements, at most 32 of them.
8231 while let Some(Some(ArrayElement::Expr(element))) = elements.get(cursor) {
8232 if index >= 32 {
8233 break;
8234 }
8235 self.expr(element)?;
8236 index += 1;
8237 cursor += 1;
8238 }
8239 self.emit(Opcode::ArrayFrom, &[Op::Int(index as i32)]);
8240
8241 // Phase 2: explicit indices, up to the first spread.
8242 let mut need_length = false;
8243 while let Some(element) = elements.get(cursor) {
8244 if matches!(element, Some(ArrayElement::Spread(_))) {
8245 break;
8246 }
8247 need_length = true;
8248 if let Some(ArrayElement::Expr(expression)) = element {
8249 self.expr(expression)?;
8250 self.emit_define_index(index);
8251 need_length = false;
8252 }
8253 index += 1;
8254 cursor += 1;
8255 }
8256
8257 if cursor >= elements.len() {
8258 if need_length {
8259 // `define_field` cannot set `length`, which is not configurable.
8260 self.emit(Opcode::Dup, &[]);
8261 self.push_number(index as f64);
8262 self.emit(Opcode::PutField, &[Op::Atom(Atom::from_text("length"))]);
8263 }
8264 return Ok(());
8265 }
8266
8267 // Phase 3: the index moves onto the stack for the spreading tail.
8268 //
8269 // `need_length` deliberately carries over from phase 2: a hole before the
8270 // first spread still has to be reflected in `length`, and only the final
8271 // check can do it because the array is not finished until the tail is
8272 // appended.
8273 self.push_number(index as f64);
8274 while let Some(element) = elements.get(cursor) {
8275 match element {
8276 Some(ArrayElement::Spread(expression)) => {
8277 // `append` copies an iterable and leaves the next index behind,
8278 // so no `inc` is needed here.
8279 self.expr(spread_argument(expression))?;
8280 self.emit(Opcode::Append, &[]);
8281 }
8282 None | Some(ArrayElement::Expr(_)) => {
8283 need_length = true;
8284 if let Some(ArrayElement::Expr(expression)) = element {
8285 self.expr(expression)?;
8286 self.emit(Opcode::DefineArrayEl, &[]);
8287 need_length = false;
8288 }
8289 self.emit(Opcode::Inc, &[]);
8290 }
8291 }
8292 cursor += 1;
8293 }
8294 if need_length {
8295 self.emit(Opcode::Dup1, &[]);
8296 self.emit(Opcode::PutField, &[Op::Atom(Atom::from_text("length"))]);
8297 } else {
8298 self.emit(Opcode::Drop, &[]);
8299 }
8300 Ok(())
8301 }
8302
8303 /// `define_field` with an array-index atom, which is how phase 2 stores elements.
8304 fn emit_define_index(&mut self, index: u32) {
8305 self.emit(
8306 Opcode::DefineField,
8307 &[Op::Atom(Atom::from_text(&index.to_string()))],
8308 );
8309 }
8310
8311 // -- functions ---------------------------------------------------------
8312
8313 fn compile_function(&mut self, func: &ast::Function) -> Result<CompiledFunction, SyntaxError> {
8314 self.compile_function_with_name(func, false)
8315 }
8316
8317 /// Compile a function, recording whether it is a *named function expression*.
8318 ///
8319 /// `var f = function g(){ return g }` has to see `g` inside its own body, but `g`
8320 /// must not leak outside. The reference does that by declaring `g` as a local of
8321 /// the function itself and initialising it with `special_object 2` (the current
8322 /// function), which is why this has to be known at compile time.
8323 fn compile_function_with_name(
8324 &mut self,
8325 func: &ast::Function,
8326 is_expression: bool,
8327 ) -> Result<CompiledFunction, SyntaxError> {
8328 let kind = match (func.is_generator, func.is_async) {
8329 (false, false) => FunctionKind::Normal,
8330 (true, false) => FunctionKind::Generator,
8331 (false, true) => FunctionKind::Async,
8332 (true, true) => FunctionKind::AsyncGenerator,
8333 };
8334 let mut state = FnState::new(
8335 func.name
8336 .as_ref()
8337 .map(|n| n.name.clone())
8338 .unwrap_or_default(),
8339 kind,
8340 );
8341 // The function's own mode, recorded by the parser. Inheriting the enclosing
8342 // function's instead let a nested `"use strict"` directive be ignored, so the
8343 // body ran with sloppy `this`, sloppy `arguments` and no const checks.
8344 state.strict = func.strict;
8345 // A function defined inside a `with` block keeps seeing that object: the guard
8346 // chain names the enclosing `<with>` locals, which resolve outward into closure
8347 // variables exactly like any other captured binding.
8348 state.inherited_with_names = self.cur().with_names.len();
8349 state.with_names = self.cur().with_names.clone();
8350 state.is_arrow = func.is_arrow;
8351 // Known before the body is compiled, so an lvalue can decide whether to pin its
8352 // reference before emitting the read. See [`FnState::eval_can_declare`].
8353 state.eval_can_declare = func.has_direct_eval;
8354 state.created_in_block = self.cur().current_block;
8355 // A default anywhere in the parameter list is what gives the function two
8356 // variable environments. The reference decides this the same way: it scans the
8357 // parenthesis for a top-level `=`, so a destructured name without a default
8358 // stays a plain function-scope binding.
8359 state.in_params = false;
8360 // The reference scans the parenthesis for *any* `=`, including one nested inside
8361 // a pattern, so `function f({a = 1})` has parameter expressions even though the
8362 // parameter itself carries no initialiser.
8363 state.has_parameter_expressions = func.params.iter().any(pattern_has_default);
8364 // `IsSimpleParameterList`: no default, no rest, no destructuring. Unlike the
8365 // flag above this looks at the *shape* of each parameter, not just for `=`.
8366 state.simple_parameter_list = func
8367 .params
8368 .iter()
8369 .all(|pattern| matches!(pattern.kind, PatternKind::Ident(_)));
8370 // A function born inside a parameter list inherits the prohibition: it must not
8371 // see the body bindings of the function it was created in.
8372 state.created_in_params = self.cur().in_params || self.cur().created_in_params;
8373 // A class constructor knows what it is only because the class told it.
8374 if let Some(kind) = self.cur().class_ctor_pending {
8375 state.ctor_kind = kind;
8376 }
8377 // A named *expression* binds its own name; a declaration's name is already
8378 // bound in the enclosing scope.
8379 state.self_name = if is_expression && !func.is_arrow {
8380 func.name.as_ref().map(|n| n.name.clone())
8381 } else {
8382 None
8383 };
8384 // Keep the written range so `Function.prototype.toString` can answer with the
8385 // original text rather than `[native code]`.
8386 //
8387 // It starts at the *parameter list*, not at the function: §20.2.3.5 removes the
8388 // accessor and generator prefixes, and for a method it must not include the name
8389 // or a leading `static`. `params_span` is exactly that boundary.
8390 // A *method* keeps the old `[native code]` answer: its reported text is defined
8391 // by the method-definition grammar (no name, no `static`, no `get`/`set`, but
8392 // the comments in between kept verbatim), and reconstructing that from a byte
8393 // span got it wrong in more cases than it got right. A plain function and an
8394 // arrow are the shapes libraries actually introspect, and those are exact.
8395 // A method's reported text starts at its **key** — `m(){}`, `[expr](){}`,
8396 // `#f /* a */ ( /* b */ ) {}` — which is exactly where the parser put `span.start`,
8397 // so the same slice works for every form. (`Params_span` is the boundary that
8398 // excludes `static`/`async`/`get`, which the spec's method grammar also omits.)
8399 // `source_span` is set only where the reported text is not the function's own
8400 // range — a class's constructor reports the whole class definition.
8401 let reported = func.source_span.unwrap_or(func.span);
8402 state.span = Some((reported.start.offset as usize, reported.end.offset as usize));
8403 state.line = func.span.start.line;
8404 state.column = func.span.start.column;
8405 // A function body has no hidden `<ret>` local; the value comes back on
8406 // the stack. Only a script keeps one.
8407 // Parameters are positional, so even a pattern occupies one argument slot. A
8408 // simple name is that slot itself; anything else (a pattern, a default, a rest
8409 // parameter) takes an anonymous slot and is unpicked into locals at the top of
8410 // the body, which is the only way one argument can bind several names.
8411 let mut prologue: Vec<(usize, Pattern)> = Vec::new();
8412 // `.length` stops at the first parameter that can be substituted: a default
8413 // fills a missing argument in, and a rest parameter absorbs the rest.
8414 let mut defined_args = func.params.len() as u32;
8415 for (index, param) in func.params.iter().enumerate() {
8416 match simple_parameter(param) {
8417 Some(name) => state.args.push(VarDef::var(name.name.clone())),
8418 None => {
8419 state.args.push(VarDef::var(ANONYMOUS_BINDING));
8420 prologue.push((index, param.clone()));
8421 }
8422 }
8423 }
8424 // A default anywhere before the end also ends the count, which the loop above
8425 // only catches for the parameter that carries it; `(a, b = 1, c)` is arity 1.
8426 for (position, param) in func.params.iter().enumerate() {
8427 if matches!(
8428 param.kind,
8429 PatternKind::Assign { .. } | PatternKind::Rest(_)
8430 ) {
8431 defined_args = position as u32;
8432 break;
8433 }
8434 }
8435 state.defined_args = defined_args;
8436 state.param_prologue = prologue;
8437 let depth = self.stack.len();
8438 self.stack.push(state);
8439 let result = self.compile_function_body(func);
8440 if result.is_err() {
8441 // A failed compile must not leave its `FnState` behind. Every caller
8442 // reads `self.state()` as "the function being compiled", so a leftover
8443 // frame silently retargets all later bookkeeping at a dead function.
8444 self.stack.truncate(depth);
8445 }
8446 result
8447 }
8448
8449 /// The body of a function, with its frame already pushed.
8450 fn compile_function_body(
8451 &mut self,
8452 func: &ast::Function,
8453 ) -> Result<CompiledFunction, SyntaxError> {
8454 let body_key = func.params_span.end.offset as u64;
8455 // Where the body begins, in source order. The runtime needs this to tell a
8456 // closure created by a default expression from one the body creates — the two see
8457 // different variable environments — and a bytecode offset would not survive the
8458 // instruction shuffling that building the frame does. Positions are in source
8459 // order, so a comparison answers it.
8460 self.state().body_start = (func.params_span.end.line, func.params_span.end.column);
8461 self.push_block(body_key, NO_PARENT);
8462 self.state().body_block = body_key;
8463 // An arrow with an expression body has no statements; the expression is
8464 // its `return`. Building the statement here keeps one code path below, and
8465 // matters for correctness beyond convenience: returning early with the new
8466 // `FnState` still on the stack would leave the compiler looking at the
8467 // wrong function, which surfaces as an unrelated underflow later.
8468 let concise = match &func.body {
8469 js_parse::ast::FunctionBody::Expr(value) => Some(Stmt::new(
8470 StmtKind::Return(Some(Box::new((**value).clone()))),
8471 value.span,
8472 )),
8473 js_parse::ast::FunctionBody::Block(_) => None,
8474 };
8475 let body: &[Stmt] = match &concise {
8476 Some(stmt) => std::slice::from_ref(stmt),
8477 None => func
8478 .body
8479 .statements()
8480 .ok_or_else(|| SyntaxError::new("unsupported function body", func.span))?,
8481 };
8482 let prologue = std::mem::take(&mut self.state().param_prologue);
8483 let has_param_scope = self.cur().has_parameter_expressions;
8484 // The parameter scope's own bindings, declared in source order.
8485 //
8486 // With parameter expressions the list gets a variable environment of its own, and
8487 // every name it binds is a `let` there. That is what puts the *list* in the
8488 // temporal dead zone: `function f(a = a){}` reads an uninitialised `a` and throws,
8489 // and `function f(x = y, y){}` does the same, where a single shared environment
8490 // would answer `undefined` to both.
8491 if has_param_scope {
8492 let mut declared: Vec<String> = Vec::new();
8493 for param in &func.params {
8494 let mut names = Vec::new();
8495 param.bound_names(&mut names);
8496 for name in names {
8497 if declared.contains(&name.name) {
8498 continue;
8499 }
8500 declared.push(name.name.clone());
8501 self.declare_param_binding(&name.name);
8502 }
8503 }
8504 }
8505 // A pattern parameter binds its names as function-scope locals, so they have to
8506 // exist — and be unpicked from the argument — before the body runs. With a
8507 // parameter scope these are the *second* environment: the pattern fills the
8508 // parameter's copy, and the body's binding is filled from it afterwards.
8509 for (_, pattern) in &prologue {
8510 let mut names = Vec::new();
8511 pattern.bound_names(&mut names);
8512 for name in names {
8513 self.declare_var(&name.name.clone(), VarDef::var(name.name.clone()));
8514 }
8515 }
8516 self.hoist(body, body_key)?;
8517 // A constructor's prologue is not a parameter unpacking but the `this` binding:
8518 // a base constructor takes the receiver, a derived one starts in the dead zone
8519 // because only `super()` may produce it.
8520 match self.cur().ctor_kind {
8521 CtorKind::None => {}
8522 CtorKind::Base => {
8523 self.begin_this_local();
8524 self.emit(Opcode::CheckCtor, &[]);
8525 // Instance fields are installed at the top of a base constructor's body,
8526 // before any statement — `class C { x = 1; constructor() { this.x } }` sees
8527 // `1`. This used to be emitted at the *tail*, which made every field read
8528 // `undefined` inside the constructor that declared it.
8529 self.call_field_initialiser();
8530 }
8531 CtorKind::Derived => {
8532 self.declare("this", VarDef::lexical("this"));
8533 let slot = self.cur().vars.len() as u32 - 1;
8534 self.emit(Opcode::SetLocUninitialized, &[Op::Slot(Slot::Loc(slot))]);
8535 self.emit(Opcode::CheckCtor, &[]);
8536 }
8537 }
8538 // Entering the parameter list: everything it binds starts in the dead zone.
8539 // The order is the reference's — it walks the scope chain, which is prepended, so
8540 // the bindings come out newest first.
8541 for name in self.param_binding_names().into_iter().rev() {
8542 if let Some(slot) = self.param_binding_slot(&name) {
8543 self.emit(Opcode::SetLocUninitialized, &[Op::Slot(Slot::Loc(slot))]);
8544 }
8545 }
8546 // The whole parameter list is one scope, and nothing in the body exists yet, so
8547 // every name it mentions resolves against the parameter bindings and outward.
8548 self.state().in_params = has_param_scope;
8549 for (index, param) in func.params.iter().enumerate() {
8550 if let Some(pattern) = prologue_pattern(&prologue, index) {
8551 // A destructuring parameter *initialises* its bindings: with a parameter
8552 // scope they are the list's own `let`s, which is why the stores skip the
8553 // dead-zone check, and why the reference reads their properties with
8554 // `get_field2` — a `let` needs no reference.
8555 let kind = if has_param_scope {
8556 VarDeclKind::Let
8557 } else {
8558 VarDeclKind::Var
8559 };
8560 match &pattern.kind {
8561 // `...rest` collects what is left rather than reading one slot.
8562 PatternKind::Rest(inner) => {
8563 self.emit(Opcode::Rest, &[Op::Int(index as i32)]);
8564 self.destructure(inner, Some(kind))?;
8565 }
8566 _ => {
8567 self.emit(Opcode::GetArg, &[Op::Slot(Slot::Arg(index as u32))]);
8568 self.destructure(pattern, Some(kind))?;
8569 }
8570 }
8571 continue;
8572 }
8573 // A plain name binds straight from its argument slot. With a parameter scope
8574 // the slot is also copied into the parameter binding, which is what a later
8575 // default (or a closure made among the defaults) reads.
8576 let Some(name) = simple_parameter(param) else {
8577 continue;
8578 };
8579 let target = self.param_binding_slot(&name.name);
8580 if matches!(param.kind, PatternKind::Rest(_)) {
8581 self.emit(Opcode::Rest, &[Op::Int(index as i32)]);
8582 if let Some(slot) = target {
8583 self.emit(Opcode::SetLoc, &[Op::Slot(Slot::Loc(slot))]);
8584 }
8585 // `put_arg` rather than `set_arg`: the array is the last thing on the
8586 // stack and nothing keeps it. Named by hand because a name in the
8587 // parameter list resolves to the parameter binding, and this store has to
8588 // reach the *argument* — that is what the body reads.
8589 self.emit(Opcode::PutArg, &[Op::Slot(Slot::Arg(index as u32))]);
8590 continue;
8591 }
8592 if let PatternKind::Assign { default, .. } = ¶m.kind {
8593 self.emit(Opcode::GetArg, &[Op::Slot(Slot::Arg(index as u32))]);
8594 let has_value = self.new_label();
8595 self.emit(Opcode::Dup, &[]);
8596 self.emit(Opcode::IsUndefined, &[]);
8597 self.emit_jump(Opcode::IfFalse, has_value, &[]);
8598 self.emit(Opcode::Drop, &[]);
8599 self.expr(default)?;
8600 self.set_name_if_anonymous(default, &Wtf8::new(&name.name));
8601 // The argument slot keeps the substituted value, because the *body* reads
8602 // the slot rather than the parameter binding — so this store is named
8603 // explicitly, like the rest parameter's.
8604 self.emit(Opcode::SetArg, &[Op::Slot(Slot::Arg(index as u32))]);
8605 self.place_label(has_value);
8606 if let Some(slot) = target {
8607 self.emit(Opcode::PutLoc, &[Op::Slot(Slot::Loc(slot))]);
8608 }
8609 continue;
8610 }
8611 if let Some(slot) = target {
8612 self.emit(Opcode::GetArg, &[Op::Slot(Slot::Arg(index as u32))]);
8613 self.emit(Opcode::PutLoc, &[Op::Slot(Slot::Loc(slot))]);
8614 }
8615 }
8616 // Copy the parameter scope into the body. A plain parameter needs nothing: the
8617 // body reads its argument slot, and the list kept the two in step. A name a
8618 // pattern bound has no argument slot of its own, so the body gets a `var` filled
8619 // from the parameter's copy — and *that* is why an assignment inside a default
8620 // does not reach the body.
8621 if has_param_scope {
8622 for (_, pattern) in &prologue {
8623 let mut names = Vec::new();
8624 pattern.bound_names(&mut names);
8625 for name in names {
8626 let Some(slot) = self.param_binding_slot(&name.name) else {
8627 continue;
8628 };
8629 let Some(body) = self.body_var_slot(&name.name) else {
8630 continue;
8631 };
8632 self.emit(Opcode::GetLocCheck, &[Op::Slot(Slot::Loc(slot))]);
8633 self.emit(Opcode::PutLoc, &[Op::Slot(Slot::Loc(body))]);
8634 }
8635 }
8636 }
8637 // The parameter list is over; from here on a direct `eval` belongs to the body.
8638 self.state().in_params = false;
8639 // Entering the body's own scope comes *after* the parameter list: the body's
8640 // `let`s are not in existence while the defaults run, and the reference emits
8641 // their `set_loc_uninitialized` only once the parameters are bound.
8642 self.emit_scope_enter(body_key);
8643 // A generator starts suspended: `initial_yield` parks the body so that creating one
8644 // runs no body code until the first `next()`.
8645 //
8646 // It comes *after* the parameter unpacking, not before, because a parameter
8647 // initialiser is not body code — `function* g(a = sideEffect())` must run
8648 // `sideEffect()` when `g` is *called*. Emitting `initial_yield` first parked the
8649 // defaults too, so `function* g(a = (() => { throw new Error })())` did not throw
8650 // until the first `next()` and 29 test262 cases that check for a synchronous throw
8651 // saw none at all.
8652 //
8653 // An async function does **not** get one. Its body runs synchronously up to the
8654 // first `await` — `async function f(){ log.push("a"); await 0 }` records `a`
8655 // before its caller's next statement — so an `initial_yield` here would park the
8656 // body before it started, which is not fixable at run time: the suspension looks
8657 // exactly like a real `await`.
8658 if self.cur().kind.is_generator() {
8659 self.emit(Opcode::InitialYield, &[]);
8660 }
8661 // Through `stmts`: the body is a block, and a `using` declaration in it is a
8662 // disposal region.
8663 self.stmts(body)?;
8664 // The implicit return only exists if control can actually get here: an
8665 // infinite loop never falls off the end.
8666 if self.end_is_reachable() {
8667 if self.cur().is_suspending() {
8668 // Falling off the end finishes the generator with `undefined`, and the
8669 // value is what tells the resume machinery "completed" rather than
8670 // "suspended".
8671 self.emit(Opcode::Undefined, &[]);
8672 self.emit(Opcode::ReturnAsync, &[]);
8673 } else {
8674 self.emit_class_constructor_tail();
8675 }
8676 }
8677 // Resolution runs while this function is still on the stack: capturing a
8678 // variable from an enclosing function means reaching into that
8679 // function's state, which requires the whole chain to be present.
8680 Ok(self.finish_current())
8681 }
8682
8683 /// Put every binding of a function that contains a direct `eval` into a cell.
8684 ///
8685 /// A direct eval can name any binding in scope, and any closure it creates has to
8686 /// keep sharing that binding after the function returns — `for (let i …)
8687 /// eval("push(() => i)")` collects one closure per iteration and each must read its
8688 /// own `i`. A copy in a side table would freeze the value, so the binding has to be
8689 /// a cell. Doing this unconditionally for such functions is the cheap, honest
8690 /// answer: the alternative is knowing at compile time which names a string will
8691 /// mention.
8692 fn capture_everything_for_eval(&mut self) {
8693 let current = self.stack.len() - 1;
8694 if !self.stack[current].has_direct_eval {
8695 return;
8696 }
8697 for arg in &mut self.stack[current].args {
8698 arg.is_captured = true;
8699 }
8700 for var in &mut self.stack[current].vars {
8701 var.is_captured = true;
8702 }
8703 }
8704
8705 /// Whether the current position in the instruction stream can be reached.
8706 ///
8707 /// A walk over the control-flow graph, using labels as instruction indices.
8708 /// The reference does the same thing to decide whether an implicit
8709 /// `return_undef` is needed.
8710 fn end_is_reachable(&self) -> bool {
8711 let state = self.cur();
8712 reachable_instructions(state, state.insns.len())[state.insns.len()]
8713 }
8714
8715 /// Resolve and assemble the function on top of the compiler stack, then pop
8716 /// it.
8717 fn finish_current(&mut self) -> CompiledFunction {
8718 self.provide_param_arguments();
8719 self.provide_arguments();
8720 self.provide_this_local();
8721 self.provide_new_target_local();
8722 self.provide_home_object_local();
8723 self.provide_active_func_local();
8724 self.provide_self_name();
8725 self.materialize_eval_sites();
8726 self.capture_everything_for_eval();
8727 let (mut resolved, resolved_pos) = resolve(&mut self.stack);
8728 // Captured bindings need a reference cell; the count goes in the header so
8729 // the runtime knows how many cells to allocate on entry.
8730 let current = self.stack.len() - 1;
8731 let captured = self.stack[current]
8732 .args
8733 .iter()
8734 .filter(|a| a.is_captured)
8735 .count()
8736 + self.stack[current]
8737 .vars
8738 .iter()
8739 .filter(|v| v.is_captured)
8740 .count();
8741 self.stack[current].var_ref_count = captured as u32;
8742 // The scope chain is only final now that every binding is known.
8743 rebuild_scope_chain(&mut self.stack[current]);
8744 let (code, stack_size, positions) =
8745 assemble(&mut resolved, &resolved_pos, &mut self.stack[current]);
8746 let _ = &mut resolved;
8747 let mut state = self.stack.pop().expect("a function is being compiled");
8748 CompiledFunction {
8749 name: state.name,
8750 kind: state.kind,
8751 strict: state.strict,
8752 is_derived_constructor: matches!(state.ctor_kind, CtorKind::Derived),
8753 // `is_script`/`is_module` are set only on the outermost function, which is
8754 // exactly the "script, eval or module body" the flag names.
8755 is_script_body: state.is_script || state.is_module,
8756 is_arrow: state.is_arrow,
8757 has_parameter_expressions: state.has_parameter_expressions,
8758 simple_parameter_list: state.simple_parameter_list,
8759 body_start: state.body_start,
8760 args: state.args,
8761 defined_args: state.defined_args,
8762 vars: state.vars,
8763 closure_vars: state.closure_vars,
8764 cpool: state.cpool,
8765 atoms: state.atoms,
8766 code,
8767 stack_size,
8768 var_ref_count: state.var_ref_count,
8769 positions,
8770 source: self.function_source(state.span, state.line, state.column),
8771 line: state.line,
8772 column: state.column,
8773 filename: None,
8774 eval_sites: state.eval_sites,
8775 module: state.module.take().map(Box::new),
8776 }
8777 }
8778}
8779
8780/// Assign each binding a scope level and rebuild the scope chains.
8781///
8782/// Levels are numbered in the order the blocks appear, with 0 reserved for the
8783/// function scope where `var` and hoisted functions live. Every binding outside
8784/// level 0 gets a `scope_next` link to the next binding visible from the same
8785/// point, so walking a block's chain enumerates exactly the bindings live there.
8786///
8787/// The links cannot be filled in while hoisting: `{ let a } let b` needs `a` to
8788/// point at `b`, which is declared later in the source but earlier in the chain.
8789fn rebuild_scope_chain(state: &mut FnState) {
8790 // Block key -> level. Level 0 is the function scope, keyed by the sentinel so a
8791 // real block that happens to start at offset zero keeps its own level instead of
8792 // being merged into the function scope.
8793 let mut levels: Vec<u64> = vec![FUNCTION_SCOPE];
8794 for block in &state.blocks {
8795 if !levels.contains(&block.key) {
8796 levels.push(block.key);
8797 }
8798 }
8799 let level_of = |key: u64| -> usize { levels.iter().position(|k| *k == key).unwrap_or(0) };
8800 let parent_level = |level: usize| -> usize {
8801 if level == 0 {
8802 return 0;
8803 }
8804 let key = levels[level];
8805 let parent = state
8806 .blocks
8807 .iter()
8808 .find(|b| b.key == key)
8809 .map(|b| b.parent)
8810 .unwrap_or(FUNCTION_SCOPE);
8811 level_of(parent)
8812 };
8813
8814 // Own bindings per level, in declaration order.
8815 let mut own: Vec<Vec<usize>> = vec![Vec::new(); levels.len()];
8816 let keys: Vec<u64> = (0..state.vars.len())
8817 .map(|index| {
8818 state
8819 .var_block
8820 .get(index)
8821 .copied()
8822 .unwrap_or(FUNCTION_SCOPE)
8823 })
8824 .collect();
8825 for (index, key) in keys.into_iter().enumerate() {
8826 // The parameter scope is not a block: it is a level of its own with no parent,
8827 // assigned below. Letting it land in level 0 would chain the body's bindings onto
8828 // it, which the reference does not do — the two environments are siblings.
8829 if key == PARAM_SCOPE {
8830 continue;
8831 }
8832 let level = level_of(key);
8833 state.vars[index].scope_level = level as u32;
8834 // A `catch` parameter is part of the runtime scope chain even though it is
8835 // not lexical: the handler's own bindings chain on to it, which is why the
8836 // reference prints `let y [next:1]` with `e` at 1.
8837 if state.vars[index].is_lexical || state.vars[index].kind == crate::bytecode::VarKind::Catch
8838 {
8839 own[level].push(index);
8840 }
8841 }
8842
8843 // A scope's chain is its own bindings in reverse declaration order followed
8844 // by the enclosing scope's chain.
8845 let mut head = vec![-1i32; levels.len()];
8846 for level in 0..levels.len() {
8847 let inherited = if level == 0 {
8848 -1
8849 } else {
8850 head[parent_level(level)]
8851 };
8852 let chain: Vec<usize> = own[level].iter().rev().copied().collect();
8853 head[level] = chain.first().map_or(inherited, |first| *first as i32);
8854 for (position, &index) in chain.iter().enumerate() {
8855 let next = chain
8856 .get(position + 1)
8857 .map_or(inherited, |next| *next as i32);
8858 state.vars[index].scope_next = if next < 0 { None } else { Some(next) };
8859 }
8860 }
8861 state.block_heads = head;
8862
8863 // The parameter list is a scope of its own, and it has no parent: the reference pops
8864 // it before the body exists, so its chain ends in `ARG_SCOPE_END` (`-2`) rather than
8865 // the `-1` a block uses. A level past every real block keeps it out of the walk above
8866 // — nothing but the dump reads it — and the links run newest-to-oldest through the
8867 // bindings themselves, which is the order `set_loc_uninitialized` walks.
8868 let param_level = levels.len() as u32;
8869 let mut previous: Option<usize> = None;
8870 for index in 0..state.vars.len() {
8871 if state.var_block.get(index).copied() != Some(PARAM_SCOPE) || !state.vars[index].is_lexical
8872 {
8873 continue;
8874 }
8875 state.vars[index].scope_level = param_level;
8876 state.vars[index].scope_next = Some(previous.map_or(-2, |previous| previous as i32));
8877 previous = Some(index);
8878 }
8879}
8880
8881/// This is where names become slots and where the temporal dead zone shows up in
8882/// the instruction stream: a read of a `let`/`const` binding compiles to
8883/// `get_loc_check`, which throws if the binding is still uninitialised.
8884///
8885/// The peephole pass from the reference implementation is applied at the end,
8886/// for the same reason it is applied to resolved bytecode there: the patterns are
8887/// stated in terms of `put_loc`/`set_loc` pairs, which only exist after
8888/// resolution. Deleted instructions stay in the list as `None` so that label
8889/// indices remain valid; [`Assembler`] maps them to byte offsets.
8890/// A resolved instruction and the source position it came from.
8891type ResolvedInsn = Option<(Opcode, Vec<Op>)>;
8892
8893/// A resolved instruction paired with its position, which is what `assemble` consumes.
8894type PositionedInsn = (Opcode, Vec<Op>);
8895
8896fn resolve(stack: &mut [FnState]) -> (Vec<ResolvedInsn>, Vec<Option<Position>>) {
8897 let current = stack.len() - 1;
8898 // Dead-code elimination, on the symbolic form where labels are still
8899 // instruction indices. A `break` inside a loop leaves the trailing `goto`
8900 // unreachable, and a `return` leaves everything after it unreachable; the
8901 // reference drops both. Doing it here means the emitter never has to think
8902 // about reachability.
8903 strip_empty_gosubs(stack, current);
8904 eliminate_dead_code(stack, current);
8905 let insns = std::mem::take(&mut stack[current].insns);
8906 // One entry per instruction, carried alongside: `insn_pos` is index-aligned with
8907 // `insns`, and every arm below pushes exactly one instruction, so the positions
8908 // stay aligned with `out`.
8909 let positions = std::mem::take(&mut stack[current].insn_pos);
8910 let mut out: Vec<Option<(Opcode, Vec<Op>)>> = Vec::with_capacity(insns.len());
8911 let mut out_pos: Vec<Option<Position>> = Vec::with_capacity(insns.len());
8912 for (index, insn) in insns.iter().enumerate() {
8913 let pos = positions.get(index).copied().flatten();
8914 out_pos.push(pos);
8915 match insn {
8916 Insn::Fixed { op, operands } => {
8917 let operands = operands
8918 .iter()
8919 .map(|operand| match operand {
8920 Op::Atom(atom) => {
8921 Op::AtomId(intern_atom_value(&mut stack[current], atom.clone()))
8922 }
8923 other => other.clone(),
8924 })
8925 .collect();
8926 out.push(Some((*op, operands)));
8927 }
8928 Insn::Var {
8929 action,
8930 name,
8931 block,
8932 in_params,
8933 } => {
8934 // Both reads and writes in the parameter list address the parameter
8935 // scope. That is what puts the list in the temporal dead zone — a read of
8936 // a later parameter is `get_loc_check` on an uninitialised slot — and it
8937 // is also what keeps an assignment made inside a default away from the
8938 // body, which sees a separate environment.
8939 let slot = resolve_slot(stack, current, name, *block, *in_params);
8940 // A store to the name of a named function expression is special: the
8941 // reference drops it in sloppy mode and throws in strict mode, because
8942 // the binding is immutable but only *checked* when the body is strict.
8943 // The same rule applies when the name is reached through a closure:
8944 // `var f = function myfunc() { (() => { myfunc = 1 })() }` has to drop
8945 // the store in the arrow too, not just in the function that owns the
8946 // binding. Reaching the owner means walking the chain of closure
8947 // entries, which is what `self_name_binding` does.
8948 let self_name = matches!(action, VarAction::Put | VarAction::Set)
8949 .then(|| {
8950 // A local of this function is the common case and needs no
8951 // chain walk; only an access that resolves elsewhere can be
8952 // pointing at an enclosing function's name binding.
8953 if let Slot::Loc(index) = slot {
8954 stack[current]
8955 .vars
8956 .get(index as usize)
8957 .filter(|var| var.kind == VarKind::FunctionName)
8958 .map(|var| var.is_const)
8959 } else {
8960 self_name_binding(stack, current, name, *block)
8961 }
8962 })
8963 .flatten();
8964 if let Some(is_const) = self_name {
8965 out.push(Some(if is_const {
8966 (
8967 Opcode::ThrowError,
8968 vec![
8969 Op::AtomId(intern_atom(&mut stack[current], name)),
8970 Op::Int(0),
8971 ],
8972 )
8973 } else {
8974 (Opcode::Drop, Vec::new())
8975 }));
8976 continue;
8977 }
8978 if *action == VarAction::MakeRef {
8979 // A reference to a *local* has to keep working after the enclosing
8980 // frame is gone, and `get_ref_value` reads a cell — so the binding is
8981 // forced into one, exactly as the reference implementation's
8982 // `capture_var` does. Only an access that a direct `eval` in the same
8983 // function can shadow ever asks for this, so the cost is confined to
8984 // functions that contain one.
8985 match slot {
8986 Slot::Loc(index) => {
8987 if let Some(var) = stack[current].vars.get_mut(index as usize) {
8988 var.is_captured = true;
8989 }
8990 }
8991 Slot::Arg(index) => {
8992 if let Some(arg) = stack[current].args.get_mut(index as usize) {
8993 arg.is_captured = true;
8994 }
8995 }
8996 _ => {}
8997 }
8998 }
8999 let (opcode, mut operands) = variable_instruction(stack, current, *action, slot);
9000 if *action == VarAction::MakeRef {
9001 // Operand 0 is the placeholder `variable_instruction` could not fill
9002 // in; the name is in hand here, and it has to be *interned* — this arm
9003 // bypasses `Insn::Fixed`, which is where `Op::Atom` normally becomes an
9004 // `Op::AtomId`.
9005 operands[0] = Op::AtomId(intern_atom(&mut stack[current], name));
9006 }
9007 out.push(Some((opcode, operands)));
9008 }
9009 Insn::CloseCaptured { name, block } => {
9010 // The block matters: a loop variable is scoped to the `for` head's own
9011 // block, so resolving it against block 0 would miss it entirely and
9012 // silently emit nothing.
9013 let slot = resolve_slot(stack, current, name, *block, false);
9014 // Only a local with a reference cell has anything to close. A global
9015 // or a never-captured local resolves to no instruction at all, which
9016 // keeps the bytecode identical to the reference's.
9017 if let Slot::Loc(index) = slot
9018 && stack[current]
9019 .vars
9020 .get(index as usize)
9021 .is_some_and(|v| v.is_captured)
9022 {
9023 out.push(Some((Opcode::CloseLoc, vec![Op::Slot(slot)])));
9024 } else {
9025 out.push(None);
9026 }
9027 }
9028 Insn::DeleteVar { name } => {
9029 // A binding — a local, an argument, or a declared global — cannot be
9030 // deleted, and the reference encodes that as a constant `push_false`.
9031 // Only an implicit global needs the runtime lookup.
9032 // `GlobalDecl` counts: a script-level `var` is a property of the global
9033 // object and the delete is answered there (non-configurable, so `false`),
9034 // but a `var` an `eval` created lives in the caller's `LocalVars` and *is*
9035 // deletable (§19.2.1.3 creates it with `deletable = true`). Emitting a
9036 // constant `false` decided that at compile time and made
9037 // `eval("var x; delete x")` answer `false`
9038 // (`eval-code/direct/var-env-var-init-local-new-delete`).
9039 if matches!(
9040 resolve_slot(stack, current, name, 0, false),
9041 Slot::Global(_) | Slot::GlobalDecl(_)
9042 ) {
9043 let atom = intern_atom(&mut stack[current], name);
9044 out.push(Some((Opcode::DeleteVar, vec![Op::AtomId(atom)])));
9045 } else {
9046 out.push(Some((Opcode::PushFalse, Vec::new())));
9047 }
9048 }
9049 Insn::Dead => out.push(None),
9050 }
9051 }
9052 // Which label (if any) sits on each instruction, so the jump patterns can
9053 // tell whether they would cross a jump target.
9054 let mut label_at: Vec<Option<u32>> = vec![None; out.len() + 1];
9055 for (id, placed) in stack[current].labels.iter().enumerate() {
9056 if let Some(index) = *placed
9057 && index < label_at.len()
9058 && label_at[index].is_none()
9059 {
9060 label_at[index] = Some(id as u32);
9061 }
9062 }
9063 if std::env::var_os("QJS_DEBUG").is_some() {
9064 eprintln!("--- peephole entry ---");
9065 for (i, e) in out.iter().enumerate() {
9066 eprintln!("{i}: {e:?}");
9067 }
9068 eprintln!("label_at: {label_at:?}");
9069 }
9070 peephole(&mut out, &label_at, &stack[current].labels);
9071 (out, out_pos)
9072}
9073
9074/// Find where `name` lives, capturing it in an enclosing function when needed.
9075///
9076/// The search runs outward through the enclosing functions' states, which are
9077/// still on the compiler stack while a nested function is resolved. Finding the
9078/// name in an enclosing function is what creates a closure reference, and every
9079/// function in between has to forward it — a function can only reach its own
9080/// parent's frame.
9081///
9082/// A name declared nowhere is a global. The reference does *not* look it up by
9083/// name from the inner function: the top-level function gets one `[global]`
9084/// entry and every nested function gets a `[global_ref<n>]` pointing at its
9085/// parent's entry, which is why `function f(){ g(); }` shows `[global_ref0]`
9086/// rather than `[global]`.
9087/// The lexical blocks enclosing `block`, innermost first.
9088fn block_chain(state: &FnState, block: u64) -> Vec<u64> {
9089 let mut chain = Vec::new();
9090 let mut current = Some(block);
9091 while let Some(key) = current {
9092 // `NO_PARENT` is not a block, so the walk ends here. Stopping on the sentinel
9093 // explicitly (rather than on "no block with this key") is what keeps a block
9094 // that happens to sit at offset zero from being mistaken for the terminator.
9095 if key == NO_PARENT || chain.contains(&key) {
9096 break;
9097 }
9098 chain.push(key);
9099 current = state.blocks.iter().find(|b| b.key == key).map(|b| b.parent);
9100 }
9101 chain
9102}
9103
9104/// The `const`-ness of a named function expression's own name, if `name` resolves to one.
9105///
9106/// The binding may be several functions away: an arrow nested in `function myfunc`
9107/// reaches `myfunc` through a chain of closure entries, so finding out *what* it names
9108/// means following `Ref` entries down and then reading the owning function's var table.
9109fn self_name_binding(stack: &[FnState], current: usize, name: &str, block: u64) -> Option<bool> {
9110 let state = stack.get(current)?;
9111 // A parameter shadows everything and is never a function-expression name.
9112 if state.args.iter().any(|arg| arg.name == name) {
9113 return None;
9114 }
9115 // A local of this very function: the answer is in its var table.
9116 if let Some(index) = local_slot_index(state, name, block) {
9117 let var = state.vars.get(index)?;
9118 return (var.kind == VarKind::FunctionName).then_some(var.is_const);
9119 }
9120 // Otherwise the name lives further out, and the closure entry says how to get
9121 // there. `Local` names the owner's slot directly; `Ref` names the next level's
9122 // closure entry, so the walk continues downwards.
9123 let mut level = current;
9124 let mut index = state
9125 .closure_vars
9126 .iter()
9127 .position(|closure| closure.name == name)?;
9128 loop {
9129 let state = stack.get(level)?;
9130 let closure = state.closure_vars.get(index)?;
9131 match closure.closure_type {
9132 ClosureType::Local => {
9133 let owner = stack.get(level.checked_sub(1)?)?;
9134 let var = owner.vars.get(closure.var_idx as usize)?;
9135 return (var.kind == VarKind::FunctionName).then_some(var.is_const);
9136 }
9137 ClosureType::Arg => return None,
9138 ClosureType::Ref => {
9139 level -= 1;
9140 index = closure.var_idx as usize;
9141 }
9142 // A global is never a function-expression name.
9143 ClosureType::Global
9144 | ClosureType::GlobalDecl
9145 | ClosureType::GlobalRef
9146 | ClosureType::ModuleDecl
9147 | ClosureType::ModuleImport => return None,
9148 }
9149 }
9150}
9151
9152/// The index of `name`'s binding in `state`, looked up the way [`resolve_slot`] does.
9153fn local_slot_index(state: &FnState, name: &str, block: u64) -> Option<usize> {
9154 block_chain(state, block).into_iter().find_map(|scope| {
9155 state.vars.iter().enumerate().find_map(|(index, var)| {
9156 (var.name == name && state.var_block.get(index).copied() == Some(scope))
9157 .then_some(index)
9158 })
9159 })
9160}
9161
9162/// Declare `name` as a binding of `state`'s parameter scope, returning its slot.
9163fn declare_param_var_at(state: &mut FnState, name: &str) -> u32 {
9164 if let Some(index) = state.vars.iter().enumerate().position(|(index, var)| {
9165 var.name == name && state.var_block.get(index).copied() == Some(PARAM_SCOPE)
9166 }) {
9167 return index as u32;
9168 }
9169 state.var_block.push(PARAM_SCOPE);
9170 state.vars.push(VarDef::var(name));
9171 state.vars.len() as u32 - 1
9172}
9173
9174/// The name a parameter binds straight from its argument slot, if it has one.
9175///
9176/// A plain name does — with or without a default, and with or without `...`. Everything
9177/// else is a pattern, which takes an anonymous slot for the parameter list to unpick; the
9178/// reference names the argument in the first case and leaves it `<null>` in the second,
9179/// so both the dump and the closures that capture the argument depend on this.
9180fn simple_parameter(param: &Pattern) -> Option<&Ident> {
9181 match ¶m.kind {
9182 PatternKind::Ident(name) => Some(name),
9183 PatternKind::Assign { target, .. } => match &target.kind {
9184 PatternKind::Ident(name) => Some(name),
9185 _ => None,
9186 },
9187 PatternKind::Rest(inner) => match &inner.kind {
9188 PatternKind::Ident(name) => Some(name),
9189 _ => None,
9190 },
9191 _ => None,
9192 }
9193}
9194
9195/// The pattern a parameter list has to unpick, if `index` is one of them.
9196fn prologue_pattern(prologue: &[(usize, Pattern)], index: usize) -> Option<&Pattern> {
9197 prologue
9198 .iter()
9199 .find(|(at, _)| *at == index)
9200 .map(|(_, pattern)| pattern)
9201}
9202
9203fn pattern_has_default(pattern: &Pattern) -> bool {
9204 match &pattern.kind {
9205 PatternKind::Assign { .. } => true,
9206 PatternKind::Rest(inner) => pattern_has_default(inner),
9207 PatternKind::Array { elements, rest } => {
9208 elements.iter().flatten().any(element_has_default)
9209 || rest.as_deref().is_some_and(rest_has_default)
9210 }
9211 PatternKind::Object { properties, rest } => {
9212 properties.iter().flatten().any(element_has_default)
9213 || rest.as_deref().is_some_and(rest_has_default)
9214 }
9215 _ => false,
9216 }
9217}
9218
9219fn element_has_default(element: &PatternElement) -> bool {
9220 match element {
9221 PatternElement::Pattern(pattern) => pattern_has_default(pattern),
9222 PatternElement::Property { value, .. } => pattern_has_default(value),
9223 }
9224}
9225
9226fn rest_has_default(rest: &RestElement) -> bool {
9227 match rest {
9228 RestElement::Pattern(pattern) => pattern_has_default(pattern),
9229 RestElement::Member(_) => false,
9230 }
9231}
9232
9233/// Whether a function-scope binding is visible to the parameter list.
9234///
9235/// The parameter list runs before the body, so the body's `var`s and function
9236/// declarations do not exist yet — a name that only the body declares has to resolve
9237/// outward instead. What *does* exist by then is the compiler's own prologue: the
9238/// self-name of a named function expression (bound by `special_object 2` before anything
9239/// else), `this` and `new.target`. Those stay visible, which is what makes
9240/// `function f(a = this)` and `var f = function f(a = f)` work.
9241///
9242/// `arguments` is handled separately, as a binding of the parameter scope itself: with
9243/// parameter expressions the reference creates two of them, and the one the parameter
9244/// list sees is not the one the body sees (`function f(a = eval("var arguments = 1"))`).
9245fn visible_in_params(var: &VarDef) -> bool {
9246 var.kind == VarKind::FunctionName || var.name == "this" || var.name == "new.target"
9247}
9248
9249fn resolve_slot(
9250 stack: &mut [FnState],
9251 current: usize,
9252 name: &str,
9253 block: u64,
9254 in_params: bool,
9255) -> Slot {
9256 // The parameter list's own bindings. They are consulted first because they shadow
9257 // the argument slots they were copied from: `function f(a = 1, p = () => a)` keeps
9258 // `a` in the parameter scope, so a closure made there reads the parameter even after
9259 // the body assigns to its own `a`.
9260 if in_params
9261 && let Some(index) = stack[current]
9262 .vars
9263 .iter()
9264 .enumerate()
9265 .position(|(index, var)| {
9266 var.name == name
9267 && stack[current].var_block.get(index).copied() == Some(PARAM_SCOPE)
9268 })
9269 {
9270 return Slot::Loc(index as u32);
9271 }
9272 // A name can be bound more than once: two `catch` parameters in nested
9273 // handlers are two slots. The binding that wins is the one whose scope encloses
9274 // the access, and among those the innermost — so the blocks are walked outward
9275 // and the first binding found on the way is the one that counts. A binding in
9276 // no block (`var`) is reachable from anywhere, which is why the function scope
9277 // is the end of the walk.
9278 //
9279 // The block walk comes *before* the argument slots, because a block may shadow a
9280 // parameter: `function f(a){ { let a = 2 } }` writes the inner `a`, and the argument
9281 // slot is only the answer once nothing nearer claims the name.
9282 let chain = block_chain(&stack[current], block);
9283 for scope in &chain {
9284 let found = stack[current]
9285 .vars
9286 .iter()
9287 .enumerate()
9288 .find(|(index, var)| {
9289 var.name == name && stack[current].var_block.get(*index).copied() == Some(*scope)
9290 })
9291 .map(|(index, _)| index);
9292 if let Some(index) = found {
9293 return Slot::Loc(index as u32);
9294 }
9295 }
9296 // A parameter, which is neither block-scoped nor a plain function-scope `var`: it has
9297 // its own slot, and `var` of the same name in the body is the same binding.
9298 if let Some(index) = stack[current].args.iter().position(|a| a.name == name) {
9299 return Slot::Arg(index as u32);
9300 }
9301 // Function-scope bindings — `var` and function declarations — are recorded with
9302 // the sentinel block `0`, which no real scope uses, so the walk above cannot see
9303 // them. They are reachable from anywhere in the function, which is exactly what
9304 // the sentinel means.
9305 //
9306 // This pass is *only* for those. A lexical binding has to be found through the
9307 // chain or not at all, and looking a name up without its block is precisely how
9308 // `var x = 1; { let x = 2; } x` used to see the inner `x`, and how a `let` in a
9309 // block leaked out of it.
9310 let function_scoped = stack[current]
9311 .vars
9312 .iter()
9313 .enumerate()
9314 .find(|(index, var)| {
9315 var.name == name
9316 && stack[current].var_block.get(*index).copied() == Some(FUNCTION_SCOPE)
9317 && (!in_params || visible_in_params(var))
9318 })
9319 .map(|(index, _)| index);
9320 if let Some(index) = function_scoped {
9321 return Slot::Loc(index as u32);
9322 }
9323 if let Some(index) = stack[current]
9324 .closure_vars
9325 .iter()
9326 .position(|c| c.name == name)
9327 {
9328 return slot_for_closure(&stack[current].closure_vars[index], index as u32);
9329 }
9330
9331 for owner in (0..current).rev() {
9332 // The nested function was created inside one of this frame's blocks, and the
9333 // outermost visible binding is the innermost block on that chain — not whatever
9334 // comes first in the variable table. `function f(){ class S{} }` has two `S`
9335 // bindings: the `let S` inside `f` and the `const S` inside the class body, and
9336 // the class body is the one a method may see.
9337 let entry = stack
9338 .get(owner + 1)
9339 .map(|s| s.created_in_block)
9340 .unwrap_or(0);
9341 let visible_blocks = block_chain(&stack[owner], entry);
9342 let lexical = visible_blocks
9343 .iter()
9344 .copied()
9345 .into_iter()
9346 .find_map(|scope| {
9347 stack[owner]
9348 .vars
9349 .iter()
9350 .enumerate()
9351 .find(|(index, var)| {
9352 var.name == name
9353 && stack[owner].var_block.get(*index).copied() == Some(scope)
9354 })
9355 .map(|(index, _)| index)
9356 });
9357 // A function born in a parameter list sees that list's bindings, not the body's:
9358 // the parameter scope is the environment it was created in.
9359 let in_param_scope = stack
9360 .get(owner + 1)
9361 .is_some_and(|child| child.created_in_params)
9362 .then(|| {
9363 stack[owner]
9364 .vars
9365 .iter()
9366 .enumerate()
9367 .position(|(index, var)| {
9368 var.name == name
9369 && stack[owner].var_block.get(index).copied() == Some(PARAM_SCOPE)
9370 })
9371 })
9372 .flatten();
9373 let found = if let Some(index) = in_param_scope {
9374 let var = &stack[owner].vars[index];
9375 Some(Found::Local(
9376 ClosureType::Local,
9377 index as u32,
9378 var.is_const,
9379 var.needs_check(),
9380 ))
9381 } else if let Some(index) = stack[owner].args.iter().position(|a| a.name == name) {
9382 Some(Found::Local(ClosureType::Arg, index as u32, false, false))
9383 } else if let Some(index) = lexical {
9384 let var = &stack[owner].vars[index];
9385 Some(Found::Local(
9386 ClosureType::Local,
9387 index as u32,
9388 var.is_const,
9389 var.needs_check(),
9390 ))
9391 } else if let Some(index) = stack[owner]
9392 .vars
9393 .iter()
9394 .enumerate()
9395 .find_map(|(index, var)| {
9396 // A function created inside a parameter list must not see the body of the
9397 // function it was born in; see [`FnState::created_in_params`].
9398 let hidden = stack
9399 .get(owner + 1)
9400 .is_some_and(|child| child.created_in_params);
9401 // Only a binding this frame can actually see: the function scope, or a
9402 // block the creating function was born inside.
9403 //
9404 // This pass exists for the `var` and function declarations the block walk
9405 // above cannot see — they carry the `FUNCTION_SCOPE` sentinel rather than a
9406 // block key — and for a block whose key is not yet on the chain, which is
9407 // how a class name is reachable from its own heritage expression. What it
9408 // must **not** do is match any same-named binding regardless of scope:
9409 // that made every `let` in an enclosing function visible from outside its
9410 // block, so `var x; var p = () => x; { let x = 1 } p()` answered the block's
9411 // value. That is the whole `scope-lex-open` family.
9412 let visible = match stack[owner].var_block.get(index).copied() {
9413 Some(FUNCTION_SCOPE) => true,
9414 Some(block) => visible_blocks.contains(&block),
9415 None => false,
9416 };
9417 (var.name == name && visible && (!hidden || visible_in_params(var)))
9418 .then_some(index)
9419 })
9420 {
9421 let var = &stack[owner].vars[index];
9422 Some(Found::Local(
9423 ClosureType::Local,
9424 index as u32,
9425 var.is_const,
9426 var.needs_check(),
9427 ))
9428 } else if stack[owner].self_name.as_deref() == Some(name) {
9429 // A named function expression's own name. The reference declares it here,
9430 // on the first lookup that fails, rather than up front — and that is what
9431 // makes it reachable from a *nested* function: the nested lookup is what
9432 // walks out and creates the binding. A direct reference in the body is
9433 // caught the same way, which is why `provide_self_name` only has to add
9434 // the prologue.
9435 let strict = stack[owner].strict;
9436 stack[owner].var_block.push(FUNCTION_SCOPE);
9437 stack[owner].vars.push(VarDef {
9438 kind: VarKind::FunctionName,
9439 // In strict mode the name is immutable, so a store raises; sloppy
9440 // mode drops the store instead (see `variable_instruction`).
9441 is_const: strict,
9442 ..VarDef::var(name)
9443 });
9444 let index = stack[owner].vars.len() as u32 - 1;
9445 Some(Found::Local(ClosureType::Local, index, strict, false))
9446 } else if let Some(index) = stack[owner]
9447 .closure_vars
9448 .iter()
9449 .position(|c| c.name == name)
9450 {
9451 let closure = &stack[owner].closure_vars[index];
9452 Some(match closure.closure_type {
9453 // `GlobalRef` belongs here too: it is a *global* reached through this
9454 // frame's reference table, so treating it as a `Ref` to a local cell makes
9455 // the reader look for a cell no frame ever fills. That is how a second
9456 // function using `eval` in its parameter list read `undefined` after a
9457 // sibling had already made `eval` a closure entry.
9458 ClosureType::Global | ClosureType::GlobalDecl | ClosureType::GlobalRef => {
9459 Found::Global(index as u32)
9460 }
9461 // A module variable is a cell in the *module's* environment, which is
9462 // the module body's parent as far as a nested function is concerned — so
9463 // it is captured as a plain reference, not looked up as a global.
9464 ClosureType::ModuleDecl | ClosureType::ModuleImport => Found::Local(
9465 ClosureType::Ref,
9466 index as u32,
9467 closure.is_const,
9468 closure.is_lexical,
9469 ),
9470 _ => Found::Local(
9471 ClosureType::Ref,
9472 index as u32,
9473 closure.is_const,
9474 closure.is_lexical,
9475 ),
9476 })
9477 } else {
9478 None
9479 };
9480 let Some(found) = found else { continue };
9481
9482 let (is_const, is_lexical) = match found {
9483 Found::Local(_, _, is_const, is_lexical) => (is_const, is_lexical),
9484 Found::Global(_) => (false, false),
9485 };
9486 // Mark the owner's binding as captured so it moves into a reference cell.
9487 if let Found::Local(ClosureType::Arg | ClosureType::Local, index, _, _) = found {
9488 let slot = match found {
9489 Found::Local(ClosureType::Arg, _, _, _) => &mut stack[owner].args[index as usize],
9490 _ => &mut stack[owner].vars[index as usize],
9491 };
9492 slot.is_captured = true;
9493 }
9494 // Forward the reference through every function in between.
9495 let mut previous = match found {
9496 Found::Local(kind, index, _, _) => (kind, index),
9497 Found::Global(index) => (ClosureType::Global, index),
9498 };
9499 for level in owner + 1..=current {
9500 let kind = match (previous.0, level) {
9501 // A global stays a global at *every* level. Without `GlobalRef` in
9502 // this arm the second nested function over the same global got a
9503 // `Ref` to a cell no frame ever held, so the innermost closure read
9504 // `undefined` — which is how a two-deep getter lost its outer
9505 // variable.
9506 (ClosureType::Global | ClosureType::GlobalDecl | ClosureType::GlobalRef, _) => {
9507 ClosureType::GlobalRef
9508 }
9509 (ClosureType::Arg | ClosureType::Local, level) if level == owner + 1 => previous.0,
9510 _ => ClosureType::Ref,
9511 };
9512 let index = ensure_closure(stack, level, name, is_const, is_lexical, kind, previous.1);
9513 previous = (kind, index);
9514 }
9515 let index = previous.1;
9516 return slot_for_closure(&stack[current].closure_vars[index as usize], index);
9517 }
9518
9519 // Declared nowhere: a dynamic global lookup, which sloppy mode may satisfy by
9520 // creating a property. The top-level function holds the entry.
9521 let mut previous = (
9522 ClosureType::Global,
9523 ensure_closure(stack, 0, name, false, false, ClosureType::Global, 0),
9524 );
9525 for level in 1..=current {
9526 let index = ensure_closure(
9527 stack,
9528 level,
9529 name,
9530 false,
9531 false,
9532 ClosureType::GlobalRef,
9533 previous.1,
9534 );
9535 previous = (ClosureType::GlobalRef, index);
9536 }
9537 Slot::Global(previous.1)
9538}
9539
9540/// What an outward search turned up.
9541#[derive(Debug, Clone, Copy)]
9542enum Found {
9543 /// A binding in an enclosing function, reachable through a closure of this
9544 /// type, with its const/lexical flags.
9545 Local(ClosureType, u32, bool, bool),
9546 /// A global, reached through the enclosing function's closure entry.
9547 Global(u32),
9548}
9549
9550/// Add a closure entry to `level` if it is not there yet.
9551fn ensure_closure(
9552 stack: &mut [FnState],
9553 level: usize,
9554 name: &str,
9555 is_const: bool,
9556 is_lexical: bool,
9557 closure_type: ClosureType,
9558 var_idx: u32,
9559) -> u32 {
9560 if let Some(index) = stack[level]
9561 .closure_vars
9562 .iter()
9563 .position(|c| c.name == name)
9564 {
9565 return index as u32;
9566 }
9567 stack[level].closure_vars.push(ClosureVar {
9568 name: name.to_string(),
9569 is_const,
9570 is_lexical,
9571 // Only a declaration in the script's own scope can be one, and that path records
9572 // it directly (`declare_global`); a capture of it forwards the name, not the kind.
9573 is_function_decl: false,
9574 closure_type,
9575 var_idx: var_idx as u16,
9576 });
9577 stack[level].closure_vars.len() as u32 - 1
9578}
9579
9580fn slot_for_closure(closure: &ClosureVar, index: u32) -> Slot {
9581 match closure.closure_type {
9582 // A `global_ref` only says *how* the binding is found (through the
9583 // parent's closure table); the access itself is an ordinary global one.
9584 ClosureType::Global | ClosureType::GlobalRef => Slot::Global(index),
9585 ClosureType::GlobalDecl => Slot::GlobalDecl(index),
9586 // A module variable is a real cell in the module's environment, so it is reached
9587 // exactly like a captured local — the host, not the global object, is what fills
9588 // the slot.
9589 ClosureType::ModuleDecl | ClosureType::ModuleImport => Slot::VarRef(index),
9590 _ => Slot::VarRef(index),
9591 }
9592}
9593
9594/// Pick the opcode for one variable access.
9595///
9596/// The `_check` variants are what enforce the temporal dead zone. They are used
9597/// for every access to a `let`/`const` binding except its own initialisation —
9598/// which is exactly the operation that takes the binding out of the dead zone.
9599fn variable_instruction(
9600 stack: &[FnState],
9601 current: usize,
9602 action: VarAction,
9603 slot: Slot,
9604) -> (Opcode, Vec<Op>) {
9605 let lexical = match slot {
9606 Slot::Loc(index) => stack[current]
9607 .vars
9608 .get(index as usize)
9609 .is_some_and(|v| v.needs_check()),
9610 Slot::VarRef(index) => stack[current]
9611 .closure_vars
9612 .get(index as usize)
9613 .is_some_and(|c| c.is_lexical),
9614 _ => false,
9615 };
9616 let operand = vec![Op::Slot(slot)];
9617 // `make_*_ref` carries the name as well as the slot: the reference's runtime resolution
9618 // consults the names a direct `eval` has declared in this frame, which is a by-name
9619 // question, so the atom cannot be dropped. `variable_instruction` never sees the name, so
9620 // the caller patches operand 0 in (see `Compiler::emit_var`).
9621 //
9622 // Operand 1 is a *bare* slot index, not an `Op::Slot`: the opcode already says which
9623 // table it counts in, and `OpFormat::AtomU16`'s second operand is written by the plain
9624 // `u16` encoder, which an `Op::Slot` would silently skip — leaving the instruction two
9625 // bytes short and the whole stream desynchronised.
9626 let ref_slot = match slot {
9627 Slot::Arg(index)
9628 | Slot::Loc(index)
9629 | Slot::VarRef(index)
9630 | Slot::Global(index)
9631 | Slot::GlobalDecl(index) => index,
9632 };
9633 let ref_operand = vec![Op::AtomId(0), Op::Int(ref_slot as i32)];
9634 match (action, slot) {
9635 (VarAction::Get, Slot::Loc(index)) => (
9636 if lexical {
9637 Opcode::GetLocCheck
9638 } else {
9639 Opcode::GetLoc
9640 },
9641 vec![Op::Slot(Slot::Loc(index))],
9642 ),
9643 (VarAction::Get, Slot::Arg(index)) => (Opcode::GetArg, vec![Op::Slot(Slot::Arg(index))]),
9644 (VarAction::Get, Slot::VarRef(index)) => (
9645 if lexical {
9646 Opcode::GetVarRefCheck
9647 } else {
9648 Opcode::GetVarRef
9649 },
9650 vec![Op::Slot(Slot::VarRef(index))],
9651 ),
9652 (VarAction::Get, Slot::Global(_)) => (Opcode::GetVar, operand),
9653 (VarAction::Get, Slot::GlobalDecl(_)) => (Opcode::GetVar, operand),
9654 // `typeof x` is a *reading* of `x` (§13.5.3 evaluates the operand as a Reference and
9655 // then `GetValue`s it), so a lexical binding still has its dead zone checked. Only
9656 // the *unresolvable* case is different: `typeof undeclared` answers `"undefined"`
9657 // instead of throwing, and that is what `GetVarUndef` is for. Skipping the check for
9658 // every slot made `typeof x; let x;` print `"undefined"` where the spec requires a
9659 // `ReferenceError`.
9660 (VarAction::GetUndef, Slot::Loc(index)) => (
9661 if lexical {
9662 Opcode::GetLocCheck
9663 } else {
9664 Opcode::GetLoc
9665 },
9666 vec![Op::Slot(Slot::Loc(index))],
9667 ),
9668 (VarAction::GetUndef, Slot::Arg(_)) => (Opcode::GetArg, operand),
9669 (VarAction::GetUndef, Slot::VarRef(index)) => (
9670 if lexical {
9671 Opcode::GetVarRefCheck
9672 } else {
9673 Opcode::GetVarRef
9674 },
9675 vec![Op::Slot(Slot::VarRef(index))],
9676 ),
9677 (VarAction::GetUndef, Slot::Global(_) | Slot::GlobalDecl(_)) => {
9678 (Opcode::GetVarUndef, operand)
9679 }
9680
9681 (VarAction::Put, Slot::Loc(_)) => (
9682 if lexical {
9683 Opcode::PutLocCheck
9684 } else {
9685 Opcode::PutLoc
9686 },
9687 operand,
9688 ),
9689 (VarAction::Put, Slot::Arg(_)) => (Opcode::PutArg, operand),
9690 (VarAction::Put, Slot::VarRef(_)) => (
9691 if lexical {
9692 Opcode::PutVarRefCheck
9693 } else {
9694 Opcode::PutVarRef
9695 },
9696 operand,
9697 ),
9698 (VarAction::Put, Slot::Global(_)) => (Opcode::PutVar, operand),
9699 (VarAction::Put, Slot::GlobalDecl(_)) => (Opcode::PutVar, operand),
9700 // Initialisation is what ends the dead zone, so it never checks.
9701 (VarAction::PutInit, Slot::Loc(_)) => (Opcode::PutLoc, operand),
9702 (VarAction::PutInitChecked, Slot::Loc(_)) => (Opcode::PutLocCheckInit, operand),
9703 // `this` in a derived constructor is always a local, so these cannot happen;
9704 // routing them to the ordinary forms keeps the match total without inventing
9705 // opcodes the reference does not have.
9706 (VarAction::PutInitChecked, Slot::Arg(_)) => (Opcode::PutArg, operand),
9707 // The captured form of `PutLocCheckInit`: `super()` inside an arrow that closes over
9708 // the constructor's `this` still has to refuse a second initialisation, and the
9709 // plain store accepted it (`fields-run-once-on-double-super`).
9710 (VarAction::PutInitChecked, Slot::VarRef(_)) => (Opcode::PutVarRefCheckInit, operand),
9711 (VarAction::PutInitChecked, Slot::Global(_) | Slot::GlobalDecl(_)) => {
9712 (Opcode::PutVarInit, operand)
9713 }
9714 (VarAction::PutInit, Slot::Arg(_)) => (Opcode::PutArg, operand),
9715 (VarAction::PutInit, Slot::VarRef(_)) => (Opcode::PutVarRef, operand),
9716 (VarAction::PutInit, Slot::Global(_) | Slot::GlobalDecl(_)) => {
9717 (Opcode::PutVarInit, operand)
9718 }
9719 (VarAction::Set, Slot::Loc(_)) => (
9720 if lexical {
9721 Opcode::SetLocCheck
9722 } else {
9723 Opcode::SetLoc
9724 },
9725 operand,
9726 ),
9727 (VarAction::SetInit, Slot::Loc(_)) => (Opcode::SetLoc, operand),
9728 (VarAction::SetInit, Slot::Arg(_)) => (Opcode::SetArg, operand),
9729 (VarAction::SetInit, Slot::VarRef(_)) => (Opcode::SetVarRef, operand),
9730 (VarAction::SetInit, Slot::Global(_) | Slot::GlobalDecl(_)) => (Opcode::PutVar, operand),
9731 (VarAction::Set, Slot::Arg(_)) => (Opcode::SetArg, operand),
9732 (VarAction::Set, Slot::VarRef(_)) => (Opcode::SetVarRef, operand),
9733 (VarAction::Set, Slot::Global(_)) => (Opcode::PutVar, operand),
9734 (VarAction::Set, Slot::GlobalDecl(_)) => (Opcode::SetVarRef, operand),
9735 (VarAction::PutRef, Slot::Loc(_)) => (Opcode::PutLoc, operand),
9736 (VarAction::PutRef, Slot::Arg(_)) => (Opcode::PutArg, operand),
9737 (VarAction::PutRef, Slot::VarRef(_)) => (Opcode::PutVarRef, operand),
9738 (VarAction::PutRef, Slot::Global(_) | Slot::GlobalDecl(_)) => (Opcode::PutVarRef, operand),
9739 // A reference pins the binding so that one lvalue can be read and stored without
9740 // resolving the name in between. Which opcode builds it depends on where the
9741 // binding lives; the atom rides along because the *runtime* resolution can still
9742 // override the static answer — see `Interp::make_var_ref`.
9743 (VarAction::MakeRef, Slot::Loc(_)) => (Opcode::MakeLocRef, ref_operand),
9744 (VarAction::MakeRef, Slot::Arg(_)) => (Opcode::MakeArgRef, ref_operand),
9745 (VarAction::MakeRef, Slot::VarRef(_)) => (Opcode::MakeVarRefRef, ref_operand),
9746 (VarAction::MakeRef, Slot::Global(_) | Slot::GlobalDecl(_)) => {
9747 (Opcode::MakeVarRef, vec![ref_operand[0].clone()])
9748 }
9749 // Reading through a reference does not consult the binding at all — the reference
9750 // already points at it — so the slot plays no part.
9751 (VarAction::GetRef, _) => (Opcode::GetRefValue, Vec::new()),
9752 }
9753}
9754
9755/// The instruction-rewriting pass.
9756///
9757/// These are the reference implementation's patterns, restricted to the ones the
9758/// constructs this compiler supports can produce. Each entry is a comment on the
9759/// bytecode it removes, because the whole point is that the result is one
9760/// instruction shorter than the literal translation of the AST.
9761fn peephole(
9762 insns: &mut [Option<(Opcode, Vec<Op>)>],
9763 label_at: &[Option<u32>],
9764 placed: &[Option<usize>],
9765) {
9766 fold_dup_patterns(insns, label_at);
9767
9768 // `drop` before `return_undef` is dead: the return discards the whole frame
9769 // anyway. This runs *after* the `dup` folds, because a `dup; put; drop` there
9770 // consumes its own `drop`; removing the drop first would leave the `dup` and
9771 // produce a `set_` where the reference has a `put_`.
9772 for index in 0..insns.len() {
9773 if opcode_at(insns, index) != Some(Opcode::Drop) {
9774 continue;
9775 }
9776 // Skip over a run of drops, but stop at a jump target: removing code on
9777 // one side of a label would silently retarget the jump.
9778 let mut next = index + 1;
9779 while opcode_at(insns, next) == Some(Opcode::Drop) && !is_label_at(label_at, next) {
9780 next += 1;
9781 }
9782 if is_label_at(label_at, next) {
9783 continue;
9784 }
9785 if opcode_at(insns, next) == Some(Opcode::ReturnUndef) {
9786 for entry in &mut insns[index..next] {
9787 *entry = None;
9788 }
9789 }
9790 }
9791
9792 // The rewrites below all decide against one fixed snapshot, which is what the
9793 // reference sees: `code_match` reads the bytecode buffer as it was on entry to
9794 // the pass, so a rule never observes what an earlier rule removed. Gathering
9795 // every deletion first and applying them together reproduces that.
9796 let snapshot: Vec<Option<Opcode>> = insns
9797 .iter()
9798 .map(|entry| entry.as_ref().map(|(op, _)| *op))
9799 .collect();
9800 // The next instruction that is still there. Holes left by dead-code
9801 // elimination are not instructions, so a rule looks past them.
9802 let next_op = |index: usize| -> Option<usize> {
9803 (index + 1..snapshot.len()).find(|position| snapshot[*position].is_some())
9804 };
9805
9806 let mut doomed = vec![false; insns.len()];
9807 for index in 0..insns.len() {
9808 // A constant pushed only to be dropped does nothing at all. This is what a
9809 // comma expression with a literal left operand compiles to — `(0, f)()` — and
9810 // the reference removes the pair rather than making the reader step over it.
9811 let constant = matches!(
9812 snapshot[index],
9813 Some(
9814 Opcode::Undefined
9815 | Opcode::Null
9816 | Opcode::PushMinus1
9817 | Opcode::Push0
9818 | Opcode::Push1
9819 | Opcode::Push2
9820 | Opcode::Push3
9821 | Opcode::Push4
9822 | Opcode::Push5
9823 | Opcode::Push6
9824 | Opcode::Push7
9825 | Opcode::PushTrue
9826 | Opcode::PushFalse
9827 | Opcode::PushI32
9828 )
9829 );
9830 if constant
9831 && let Some(next) = next_op(index)
9832 && snapshot[next] == Some(Opcode::Drop)
9833 {
9834 doomed[index] = true;
9835 doomed[next] = true;
9836 }
9837 }
9838 for (index, entry) in insns.iter_mut().enumerate() {
9839 if doomed[index] {
9840 *entry = None;
9841 }
9842 }
9843
9844 // A conditional whose destination is the very next instruction just pops its
9845 // condition, so it becomes a plain `drop`. This is what an empty `case` clause
9846 // compiles to.
9847 //
9848 // Order matters, and it is the reference's order: this runs *before* the
9849 // folding below, on the instruction the conditional originally had. Folding
9850 // moves a conditional's destination, and the reference never re-examines it
9851 // afterwards — which is why `if (c) continue;` at the end of a `do` body stays
9852 // a conditional even though folding leaves it pointing at the next
9853 // instruction.
9854 for (index, entry) in insns.iter_mut().enumerate() {
9855 let Some((op, operands)) = entry.clone() else {
9856 continue;
9857 };
9858 if !matches!(op, Opcode::IfTrue | Opcode::IfFalse) {
9859 continue;
9860 }
9861 let Some(id) = label_id(&operands) else {
9862 continue;
9863 };
9864 if placed.get(id as usize).copied().flatten() == Some(index + 1) {
9865 *entry = Some((Opcode::Drop, Vec::new()));
9866 }
9867 }
9868
9869 // A constant condition is decided here rather than at run time.
9870 fold_constant_conditions(insns, label_at);
9871 // The conditional folding below is about pairs of *real* branches, so it runs
9872 // before a jump to the next instruction is dropped: `do { … if (c) continue }
9873 // while (t)` puts `continue` exactly on the condition, and the reference inverts
9874 // the branch first and only then notices the jump goes nowhere.
9875 fold_conditional_jumps(insns, label_at, placed);
9876
9877 // A jump whose destination is the very next instruction does nothing, which is
9878 // what constant folding leaves behind for `while (1) { … }`.
9879 remove_jump_to_next(insns, placed);
9880
9881 // `put_x(n) get_x(n)` -> `set_x(n)`, which is what a declaration followed by
9882 // a use of the same variable boils down to.
9883 for index in 0..insns.len() {
9884 let Some((put_op, _)) = insns[index].clone() else {
9885 continue;
9886 };
9887 if !is_foldable_put(put_op) {
9888 continue;
9889 }
9890 if is_label_at(label_at, index + 1) {
9891 continue;
9892 }
9893 let Some((get_op, get_operands)) = insns.get(index + 1).cloned().flatten() else {
9894 continue;
9895 };
9896 if get_op != get_form_of(put_op) {
9897 continue;
9898 }
9899 let put_slot = insns[index].as_ref().and_then(|(_, o)| o.first().cloned());
9900 if put_slot.is_none() || put_slot != get_operands.first().cloned() {
9901 continue;
9902 }
9903 insns[index] = Some((set_form_of(put_op), get_operands));
9904 insns[index + 1] = None;
9905 }
9906}
9907
9908/// Drop `gosub`s that call an empty subroutine.
9909///
9910/// A `gosub` whose target starts with `ret` returns immediately, so the reference
9911/// drops the call. This is how `try`/`catch` without a `finally` loses its
9912/// finalizer plumbing: the finalizer block is empty, its first instruction is
9913/// `ret`, and every `gosub` to it disappears — leaving the `ret` unreachable, which
9914/// [`eliminate_dead_code`] then removes.
9915fn strip_empty_gosubs(stack: &mut [FnState], current: usize) {
9916 let state = &stack[current];
9917 let mut targets = Vec::new();
9918 for insn in &state.insns {
9919 if let Insn::Fixed { op, operands } = insn
9920 && *op == Opcode::Gosub
9921 && let Some(id) = label_id(operands)
9922 && let Some(target) = state.labels.get(id as usize).copied().flatten()
9923 {
9924 targets.push(target);
9925 }
9926 }
9927 let empty: Vec<usize> = targets
9928 .into_iter()
9929 .filter(|target| {
9930 stack[current]
9931 .insns
9932 .get(*target)
9933 .map(|insn| {
9934 matches!(
9935 insn,
9936 Insn::Fixed {
9937 op: Opcode::Ret,
9938 ..
9939 }
9940 )
9941 })
9942 .unwrap_or(false)
9943 })
9944 .collect();
9945 if empty.is_empty() {
9946 return;
9947 }
9948 for insn in stack[current].insns.iter_mut() {
9949 if let Insn::Fixed { op, operands } = insn
9950 && *op == Opcode::Gosub
9951 && let Some(id) = label_id(operands)
9952 && let Some(target) = stack[current].labels.get(id as usize).copied().flatten()
9953 && empty.contains(&target)
9954 {
9955 *insn = Insn::Dead;
9956 }
9957 }
9958}
9959
9960/// Replace unreachable instructions with [`Insn::Dead`].
9961fn eliminate_dead_code(stack: &mut [FnState], current: usize) {
9962 let reachable = reachable_instructions(&stack[current], stack[current].insns.len());
9963 for (index, insn) in stack[current].insns.iter_mut().enumerate() {
9964 if !reachable[index] {
9965 *insn = Insn::Dead;
9966 }
9967 }
9968}
9969
9970/// Mark every instruction index reachable from the entry, plus the index one past
9971/// the last instruction.
9972///
9973/// `seen[len]` answers "can control reach the end of this function", and the
9974/// entries before it identify dead code. Both DCE and the implicit-return decision
9975/// read the same result, which keeps them from disagreeing.
9976fn reachable_instructions(state: &FnState, count: usize) -> Vec<bool> {
9977 let mut seen = vec![false; count + 1];
9978 let mut worklist = vec![0usize];
9979 while let Some(index) = worklist.pop() {
9980 if index > count || seen[index] {
9981 continue;
9982 }
9983 seen[index] = true;
9984 if index == count {
9985 continue;
9986 }
9987 let (op, operands) = match &state.insns[index] {
9988 Insn::Fixed { op, operands } => (*op, operands.as_slice()),
9989 // A variable access never transfers control, and a removed
9990 // instruction is only reachable if it is already marked.
9991 Insn::Var { .. } | Insn::CloseCaptured { .. } | Insn::DeleteVar { .. } | Insn::Dead => {
9992 worklist.push(index + 1);
9993 continue;
9994 }
9995 };
9996 match op {
9997 // A return, a throw and a `ret` all leave this instruction stream: the
9998 // first two give control to the caller or the handler, and `ret`
9999 // returns to a `gosub` elsewhere.
10000 // A tail call leaves the function too: the callee's result becomes this
10001 // function's result, so nothing after it runs.
10002 Opcode::Return
10003 | Opcode::ReturnUndef
10004 | Opcode::ReturnAsync
10005 | Opcode::TailCall
10006 | Opcode::TailCallMethod
10007 | Opcode::Throw
10008 | Opcode::ThrowError
10009 | Opcode::Ret => {}
10010 // A `catch` records where exceptions from the code that follows go.
10011 // That code is not reachable through normal control flow, but it is
10012 // reachable — through the exception edge — so the walk has to follow
10013 // it, or dead-code elimination would delete every handler.
10014 Opcode::Catch => {
10015 if let Some(target) = placed_label(state, operands) {
10016 worklist.push(target);
10017 }
10018 worklist.push(index + 1);
10019 }
10020 // A `gosub` calls a subroutine and then continues, so both edges count.
10021 Opcode::Gosub => {
10022 if let Some(target) = placed_label(state, operands) {
10023 worklist.push(target);
10024 }
10025 worklist.push(index + 1);
10026 }
10027 Opcode::Goto => {
10028 if let Some(target) = placed_label(state, operands) {
10029 worklist.push(target);
10030 }
10031 }
10032 Opcode::IfTrue | Opcode::IfFalse => {
10033 if let Some(target) = placed_label(state, operands) {
10034 worklist.push(target);
10035 }
10036 worklist.push(index + 1);
10037 }
10038 _ => worklist.push(index + 1),
10039 }
10040 }
10041 seen
10042}
10043
10044/// The instruction index a jump operand points at, resolved through the label
10045/// placement table.
10046fn placed_label(state: &FnState, operands: &[Op]) -> Option<usize> {
10047 let id = label_id(operands)?;
10048 state.labels.get(id as usize).copied().flatten()
10049}
10050
10051/// The label an instruction refers to.
10052fn label_id(operands: &[Op]) -> Option<u32> {
10053 operands.iter().find_map(|operand| match operand {
10054 Op::Label(label) => Some(label.0),
10055 _ => None,
10056 })
10057}
10058
10059/// Turn `if_false L; goto M; L:` into `if_true M`.
10060///
10061/// A conditional whose alternate branch is an unconditional jump needs one jump,
10062/// not two. This is the shape `if (c) break;` produces, so folding it removes an
10063/// instruction and a label from every conditional `break`.
10064/// The boolean a constant-push instruction produces, or `None` if it is not one.
10065///
10066/// Only the operators whose truthiness is decided by the opcode are covered; a
10067/// constant that needs the constant pool (a string) is left alone, because reading it
10068/// would mean threading the pool through the peephole for a case the reference also
10069/// skips.
10070fn constant_truth(op: Opcode, operands: &[Op]) -> Option<bool> {
10071 match op {
10072 // `push_0` returns -1 for zero, `push_1` 1, and so on.
10073 Opcode::PushMinus1 => Some(true),
10074 Opcode::Push0 => Some(false),
10075 Opcode::Push1
10076 | Opcode::Push2
10077 | Opcode::Push3
10078 | Opcode::Push4
10079 | Opcode::Push5
10080 | Opcode::Push6
10081 | Opcode::Push7 => Some(true),
10082 Opcode::PushTrue => Some(true),
10083 Opcode::PushFalse => Some(false),
10084 Opcode::Undefined | Opcode::Null => Some(false),
10085 Opcode::PushI32 => match operands.first() {
10086 Some(Op::Int(value)) => Some(*value != 0),
10087 _ => None,
10088 },
10089 _ => None,
10090 }
10091}
10092
10093/// Fold a branch on a constant condition.
10094///
10095/// `if (0) a() else b()` must not test anything at run time, and the reference
10096/// compiles it to a plain `goto`. Removing the test also removes the unreachable arm,
10097/// which is why the bytecode for a `while (1)` loop has no condition at all.
10098///
10099/// Two instructions become one, so the slot the test occupied is left empty rather
10100/// than shifting everything after it: labels have already been resolved to indices.
10101fn fold_constant_conditions(insns: &mut [Option<(Opcode, Vec<Op>)>], label_at: &[Option<u32>]) {
10102 for index in 0..insns.len() {
10103 let Some((push_op, push_operands)) = insns[index].clone() else {
10104 continue;
10105 };
10106 let Some(truth) = constant_truth(push_op, &push_operands) else {
10107 continue;
10108 };
10109 let Some((branch_op, branch_operands)) = insns.get(index + 1).cloned().flatten() else {
10110 continue;
10111 };
10112 // A label on the branch means something else jumps *here* — the value is on the
10113 // stack and the conditional is what pops it. Deleting the branch would leave that
10114 // jump with no instruction, and a label whose slot is empty resolves to the next
10115 // one that is not, i.e. to the far side of the branch. That is how
10116 // `if (a && false) then else` jumped to `then`: `&&` ends its chain on a label, and
10117 // the constant `false` sits directly in front of the statement's own conditional.
10118 if is_label_at(label_at, index + 1) {
10119 continue;
10120 }
10121 let (destination, taken) = match branch_op {
10122 Opcode::IfTrue => (branch_operands.first().cloned(), truth),
10123 Opcode::IfFalse => (branch_operands.first().cloned(), !truth),
10124 _ => continue,
10125 };
10126 let Some(destination) = destination else {
10127 continue;
10128 };
10129 insns[index] = if taken {
10130 // The branch is always taken, so it becomes an unconditional jump.
10131 Some((Opcode::Goto, vec![destination]))
10132 } else {
10133 // The branch never runs: both instructions disappear and control falls
10134 // through to what came after.
10135 None
10136 };
10137 insns[index + 1] = None;
10138 }
10139}
10140
10141/// Remove a jump whose destination is the instruction right after it.
10142///
10143/// Folding a constant condition leaves these behind often: `while (1) { ... }` turns
10144/// its test into nothing, and the loop-end jump then points at the following
10145/// instruction. The reference drops them, so `stack_size` and the listing agree.
10146fn remove_jump_to_next(insns: &mut [Option<(Opcode, Vec<Op>)>], placed: &[Option<usize>]) {
10147 for index in 0..insns.len() {
10148 let Some((op, operands)) = insns[index].clone() else {
10149 continue;
10150 };
10151 if !is_goto(op) {
10152 continue;
10153 }
10154 let Some(id) = label_id(&operands) else {
10155 continue;
10156 };
10157 // The next instruction that still exists, which is what "the instruction
10158 // after this jump" means once earlier folds have punched holes.
10159 let next = (index + 1..insns.len()).find(|position| insns[*position].is_some());
10160 if placed.get(id as usize).copied().flatten() == next {
10161 insns[index] = None;
10162 }
10163 }
10164}
10165
10166fn fold_conditional_jumps(
10167 insns: &mut [Option<(Opcode, Vec<Op>)>],
10168 label_at: &[Option<u32>],
10169 placed: &[Option<usize>],
10170) {
10171 for index in 0..insns.len() {
10172 let Some((op, operands)) = insns[index].clone() else {
10173 continue;
10174 };
10175 let inverted = match op {
10176 Opcode::IfFalse => Opcode::IfTrue,
10177 Opcode::IfTrue => Opcode::IfFalse,
10178 _ => continue,
10179 };
10180 // Next must be an unconditional jump that is not itself a target, and the
10181 // instruction after it must be exactly where the conditional goes.
10182 let Some((next_op, next_operands)) = insns.get(index + 1).cloned().flatten() else {
10183 continue;
10184 };
10185 if !is_goto(next_op) || is_label_at(label_at, index + 1) {
10186 continue;
10187 }
10188 // The conditional must land on the instruction *after* the jump. Several
10189 // labels can share a position, so this asks where *this* label was put
10190 // rather than what label happens to sit there.
10191 let Some(taken) = label_id(&operands) else {
10192 continue;
10193 };
10194 if placed.get(taken as usize).copied().flatten() != Some(index + 2) {
10195 continue;
10196 }
10197 let Some(destination) = next_operands.first().cloned() else {
10198 continue;
10199 };
10200 insns[index] = Some((inverted, vec![destination]));
10201 insns[index + 1] = None;
10202 }
10203}
10204
10205/// Whether a jump target is placed at this instruction index.
10206fn is_label_at(label_at: &[Option<u32>], index: usize) -> bool {
10207 label_at.get(index).copied().flatten().is_some()
10208}
10209
10210fn fold_dup_patterns(insns: &mut [Option<(Opcode, Vec<Op>)>], label_at: &[Option<u32>]) {
10211 // `dup put_x(n)` -> `set_x(n)`
10212 // `dup put_x(n) drop` -> `put_x(n)`
10213 // `dup put_x(n) drop get_x(n)` -> `set_x(n)`
10214 for index in 0..insns.len() {
10215 if opcode_at(insns, index) != Some(Opcode::Dup) {
10216 continue;
10217 }
10218 if is_label_at(label_at, index + 1) {
10219 continue;
10220 }
10221 let Some((put_op, put_operands)) = insns[index + 1].clone() else {
10222 continue;
10223 };
10224 if !is_foldable_put(put_op) {
10225 continue;
10226 }
10227 let Some(Op::Slot(slot)) = put_operands.first().cloned() else {
10228 continue;
10229 };
10230 let mut new_op = set_form_of(put_op);
10231 let mut end = index + 2;
10232 if is_label_at(label_at, end) {
10233 // The `put` has to stay as it is; only the `dup` can be folded.
10234 insns[index] = Some((set_form_of(put_op), vec![Op::Slot(slot)]));
10235 insns[index + 1] = None;
10236 continue;
10237 }
10238 // A `drop` or a `get` that is the target of a jump must stay exactly where it is.
10239 // Deleting it moves the label's target onto whatever follows, and the code that
10240 // jumps there arrives with a different stack than the fall-through path: that is
10241 // how `p = "x"; if (c) { p = "a"; } return p;` came to return `undefined` — the
10242 // `get_x` the `if` jumped to was folded away, so the jump landed on `return` with
10243 // an empty stack. The store had already consumed the value it was supposed to
10244 // leave behind.
10245 if opcode_at(insns, end) == Some(Opcode::Drop) && !is_label_at(label_at, end) {
10246 new_op = put_op;
10247 end += 1;
10248 if opcode_at(insns, end) == Some(get_form_of(put_op))
10249 && !is_label_at(label_at, end)
10250 && insns[end]
10251 .as_ref()
10252 .is_some_and(|(_, operands)| operands.first() == Some(&Op::Slot(slot)))
10253 {
10254 new_op = set_form_of(put_op);
10255 end += 1;
10256 }
10257 }
10258 insns[index] = Some((new_op, vec![Op::Slot(slot)]));
10259 for entry in &mut insns[index + 1..end] {
10260 *entry = None;
10261 }
10262 }
10263}
10264
10265fn opcode_at(insns: &[Option<(Opcode, Vec<Op>)>], index: usize) -> Option<Opcode> {
10266 insns
10267 .get(index)
10268 .and_then(|entry| entry.as_ref())
10269 .map(|(op, _)| *op)
10270}
10271
10272/// The four `put_` families that have a `set_` twin. Deliberately not including
10273/// the global forms or `put_var_ref_check`: the reference's peephole lists exactly
10274/// these, and folding the others would produce instructions that do not exist.
10275fn is_foldable_put(op: Opcode) -> bool {
10276 matches!(
10277 op,
10278 Opcode::PutLoc | Opcode::PutLocCheck | Opcode::PutArg | Opcode::PutVarRef
10279 )
10280}
10281
10282fn set_form_of(op: Opcode) -> Opcode {
10283 match op {
10284 Opcode::PutLoc => Opcode::SetLoc,
10285 Opcode::PutLocCheck => Opcode::SetLocCheck,
10286 Opcode::PutArg => Opcode::SetArg,
10287 Opcode::PutVarRef => Opcode::SetVarRef,
10288 other => other,
10289 }
10290}
10291
10292fn get_form_of(op: Opcode) -> Opcode {
10293 match op {
10294 Opcode::PutLoc => Opcode::GetLoc,
10295 Opcode::PutLocCheck => Opcode::GetLocCheck,
10296 Opcode::PutArg => Opcode::GetArg,
10297 Opcode::PutVarRef => Opcode::GetVarRef,
10298 other => other,
10299 }
10300}
10301
10302/// Atom interning, per function.
10303///
10304/// Everything the reference interns goes through `JS_NewAtomStr`, including plain
10305/// identifiers, so the array-index rule applies here rather than at the handful of
10306/// call sites that build property keys.
10307fn intern_atom(state: &mut FnState, name: &str) -> u32 {
10308 intern_atom_value(state, Atom::from_text(name))
10309}
10310
10311/// [`intern_atom`] for an operand that is already an [`Atom`].
10312///
10313/// Separate because `Atom::Null` has no text form: going through `Display` turned it into
10314/// the *string* `"null"`, which is what `throw_error` printed and what a `delete super.x`
10315/// would have looked up.
10316fn intern_atom_value(state: &mut FnState, atom: Atom) -> u32 {
10317 if let Some(index) = state.atoms.iter().position(|a| *a == atom) {
10318 return index as u32;
10319 }
10320 state.atoms.push(atom);
10321 state.atoms.len() as u32 - 1
10322}
10323
10324fn binary_opcode(op: BinaryOp) -> Opcode {
10325 match op {
10326 BinaryOp::Add => Opcode::Add,
10327 BinaryOp::Sub => Opcode::Sub,
10328 BinaryOp::Mul => Opcode::Mul,
10329 BinaryOp::Div => Opcode::Div,
10330 BinaryOp::Mod => Opcode::Mod,
10331 BinaryOp::Pow => Opcode::Pow,
10332 BinaryOp::BitOr => Opcode::Or,
10333 BinaryOp::BitXor => Opcode::Xor,
10334 BinaryOp::BitAnd => Opcode::And,
10335 BinaryOp::Shl => Opcode::Shl,
10336 BinaryOp::Shr => Opcode::Sar,
10337 BinaryOp::UShr => Opcode::Shr,
10338 BinaryOp::Lt => Opcode::Lt,
10339 BinaryOp::LtEq => Opcode::Lte,
10340 BinaryOp::Gt => Opcode::Gt,
10341 BinaryOp::GtEq => Opcode::Gte,
10342 BinaryOp::Eq => Opcode::Eq,
10343 BinaryOp::NotEq => Opcode::Neq,
10344 BinaryOp::StrictEq => Opcode::StrictEq,
10345 BinaryOp::StrictNotEq => Opcode::StrictNeq,
10346 BinaryOp::In => Opcode::In,
10347 BinaryOp::Instanceof => Opcode::Instanceof,
10348 }
10349}
10350
10351fn compound_opcode(op: AssignOp) -> Opcode {
10352 match op {
10353 AssignOp::Add => Opcode::Add,
10354 AssignOp::Sub => Opcode::Sub,
10355 AssignOp::Mul => Opcode::Mul,
10356 AssignOp::Div => Opcode::Div,
10357 AssignOp::Mod => Opcode::Mod,
10358 AssignOp::Pow => Opcode::Pow,
10359 AssignOp::Shl => Opcode::Shl,
10360 AssignOp::Shr => Opcode::Sar,
10361 AssignOp::UShr => Opcode::Shr,
10362 AssignOp::BitOr => Opcode::Or,
10363 AssignOp::BitXor => Opcode::Xor,
10364 AssignOp::BitAnd => Opcode::And,
10365 AssignOp::Assign | AssignOp::And | AssignOp::Or | AssignOp::Coalesce => Opcode::Nop,
10366 }
10367}
10368
10369/// Encode the resolved instruction stream, choosing short forms where possible.
10370///
10371/// The peephole pass leaves holes in the instruction list so that label indices
10372/// stay valid. A label names an *instruction index*, and an index that was
10373/// deleted has to resolve to the next surviving instruction, which is what
10374/// [`resolve_label`] does before the byte offsets are known.
10375fn assemble(
10376 insns: &mut [Option<(Opcode, Vec<Op>)>],
10377 insn_pos: &[Option<Position>],
10378 state: &mut FnState,
10379) -> (Vec<u8>, u32, Vec<LineCol>) {
10380 // Compaction: surviving instructions in order, plus the index mapping.
10381 //
10382 // `spans` runs parallel to `kept` and is compacted in lock step with it, at every
10383 // point below where instructions are removed — otherwise a stack trace would point
10384 // at the wrong source line as soon as dead-code elimination kicked in.
10385 let mut kept: Vec<(Opcode, Vec<Op>)> = Vec::with_capacity(insns.len());
10386 let mut spans: Vec<Option<Position>> = Vec::with_capacity(insns.len());
10387 let mut original_to_kept: Vec<Option<usize>> = vec![None; insns.len()];
10388 for (original, entry) in insns.iter_mut().enumerate() {
10389 if let Some((op, operands)) = entry.take() {
10390 original_to_kept[original] = Some(kept.len());
10391 kept.push((op, operands));
10392 spans.push(insn_pos.get(original).copied().flatten());
10393 }
10394 }
10395
10396 if std::env::var_os("QJS_DEBUG").is_some() {
10397 eprintln!("--- assemble entry --- {kept:?}");
10398 }
10399 // How many labels are real, as opposed to the per-instruction ones allocated
10400 // just below. Only a real label marks a spot in the source program.
10401 let real_labels = state.labels.len();
10402
10403 // Give every surviving instruction a label of its own. Jump cleanup below
10404 // redirects jumps to arbitrary instructions, and a jump target has to be a
10405 // label; pre-allocating one per index means a redirect never has to invent
10406 // anything.
10407 let existing = state.labels.len();
10408 let base = kept.len();
10409 let mut index_label: Vec<Label> = Vec::with_capacity(kept.len() + 1);
10410 for offset in 0..=kept.len() {
10411 state.labels.push(Some(0));
10412 index_label.push(Label((existing + offset) as u32));
10413 }
10414 // Point each pre-allocated label at its instruction, reusing the count from
10415 // `original_to_kept` so the mapping survives compaction.
10416 let place_index_labels = |state: &mut FnState,
10417 original_to_kept: &[Option<usize>],
10418 kept_len: usize,
10419 index_label: &[Label]| {
10420 for (original, mapped) in original_to_kept.iter().enumerate() {
10421 if let Some(kept_index) = mapped {
10422 let label = index_label[*kept_index].0 as usize;
10423 state.labels[label] = Some(original);
10424 }
10425 }
10426 state.labels[index_label[kept_len].0 as usize] = Some(usize::MAX);
10427 };
10428 place_index_labels(state, &original_to_kept, base, &index_label);
10429
10430 // Resolve every label to a kept index once; the placement table maps labels
10431 // to original indices, so a second hop lands in kept space.
10432 let mut label_kept: Vec<Option<usize>> = vec![None; state.labels.len()];
10433 for (id, placed) in state.labels.iter().enumerate() {
10434 let Some(original) = placed else { continue };
10435 label_kept[id] = if *original == usize::MAX {
10436 Some(base)
10437 } else {
10438 (*original..original_to_kept.len()).find_map(|i| original_to_kept[i])
10439 };
10440 }
10441
10442 // Code after an unconditional transfer is unreachable, and the reference drops it
10443 // as it walks past the transfer — the `skip_dead_code` in its first pass. It
10444 // scans forward until it finds a label something still jumps to, so a run of
10445 // dead instructions between a `throw` and the next live target disappears.
10446 //
10447 // The scan repeats because dropping a jump lowers the reference count of the
10448 // label it pointed at, which can strand what follows. Only a real label keeps an
10449 // instruction alive here; the per-instruction labels allocated above belong to
10450 // this pass, not to the program.
10451 loop {
10452 let mut references = vec![false; kept.len() + 1];
10453 for (_, operands) in &kept {
10454 if let Some(target) = target_kept_index(operands, &label_kept)
10455 && target < references.len()
10456 {
10457 references[target] = true;
10458 }
10459 }
10460 let mut doomed = vec![false; kept.len()];
10461 let mut any = false;
10462 for (index, (op, _)) in kept.iter().enumerate() {
10463 if !is_transfer(*op) {
10464 continue;
10465 }
10466 for next in index + 1..kept.len() {
10467 if references[next] {
10468 break;
10469 }
10470 doomed[next] = true;
10471 any = true;
10472 }
10473 }
10474 if !any {
10475 break;
10476 }
10477 (kept, spans) = drop_instructions(kept, spans, &mut label_kept, &doomed);
10478 }
10479
10480 // A label that lands on an unconditional jump stands for wherever that jump
10481 // goes, so retarget it once and every jump to the label follows for free.
10482 // This is what makes `continue` in a `for` head reach the loop top instead of
10483 // stopping at the update's trailing jump.
10484 let folded: Vec<Option<usize>> = label_kept
10485 .iter()
10486 .map(|slot| slot.map(|target| follow_jump_chain(&kept, &label_kept, target)))
10487 .collect();
10488 label_kept = folded;
10489
10490 // Jump cleanup, in compacted index space. Two rewrites the reference also
10491 // applies while it resolves labels:
10492 // * a jump whose destination is the very next instruction does nothing;
10493 // * a jump to a jump is redirected to its final destination.
10494 // The second can expose the first, so this repeats until it settles.
10495 loop {
10496 let mut delete = vec![false; kept.len()];
10497 let mut changed = false;
10498 for index in 0..kept.len() {
10499 let (op, operands) = &kept[index];
10500 if !is_goto(*op) {
10501 continue;
10502 }
10503 let Some(immediate) = target_kept_index(operands, &label_kept) else {
10504 continue;
10505 };
10506 let target = follow_jump_chain(&kept, &label_kept, immediate);
10507 if target == index + 1 {
10508 delete[index] = true;
10509 changed = true;
10510 } else if matches!(
10511 kept.get(target).map(|(op, _)| *op),
10512 Some(Opcode::Return | Opcode::ReturnUndef | Opcode::Throw)
10513 ) {
10514 // Jumping straight to a return or throw is the same as doing it
10515 // here, so the jump becomes that instruction.
10516 kept[index] = (kept[target].0, Vec::new());
10517 changed = true;
10518 } else if target != immediate {
10519 // Redirect to the end of the chain.
10520 let label = index_label[target];
10521 kept[index].1 = vec![Op::Label(label)];
10522 changed = true;
10523 }
10524 }
10525 if !changed {
10526 break;
10527 }
10528 if !delete.iter().any(|deleted| *deleted) {
10529 break;
10530 }
10531 // Drop the deleted instructions and renumber everything.
10532 let mut next: Vec<(Opcode, Vec<Op>)> = Vec::with_capacity(kept.len());
10533 let mut next_spans: Vec<Option<Position>> = Vec::with_capacity(kept.len());
10534 let mut moved: Vec<Option<usize>> = vec![None; kept.len()];
10535 for (old, entry) in kept.into_iter().enumerate() {
10536 if delete[old] {
10537 continue;
10538 }
10539 moved[old] = Some(next.len());
10540 next.push(entry);
10541 next_spans.push(spans[old]);
10542 }
10543 for (id, slot) in label_kept.iter_mut().enumerate() {
10544 let Some(old) = *slot else { continue };
10545 *slot = match moved.get(old).copied().flatten() {
10546 Some(new) => Some(new),
10547 // The target was deleted: the jump now lands on whatever follows.
10548 None => (old..moved.len())
10549 .find_map(|i| moved[i])
10550 .or(Some(next.len())),
10551 };
10552 let _ = id;
10553 }
10554 kept = next;
10555 spans = next_spans;
10556 }
10557
10558 // The same walk at the end of the function: `try`/`catch`'s `goto end` becomes a
10559 // jump to the next instruction and is deleted, leaving the label at the end with
10560 // nothing pointing at it. If that also strands the last instruction, it goes
10561 // too — which is how a `try` whose body always returns ends on its `ret` rather
10562 // than an implicit `return_undef`.
10563 // Which instructions something still jumps to. Reading the surviving jumps is
10564 // what the reference's reference counts amount to: once a jump has been folded
10565 // away the label it named is unreferenced, even though the program still has a
10566 // label there.
10567 let mut references = vec![false; kept.len() + 1];
10568 let _ = real_labels;
10569 for (_, operands) in &kept {
10570 if let Some(target) = target_kept_index(operands, &label_kept)
10571 && target < references.len()
10572 {
10573 references[target] = true;
10574 }
10575 }
10576 let mut end = kept.len();
10577 while end > 0 {
10578 let last = end - 1;
10579 let reachable = references[last] || end < kept.len();
10580 if reachable {
10581 break;
10582 }
10583 let after_transfer = last
10584 .checked_sub(1)
10585 .map(|previous| {
10586 matches!(
10587 kept[previous].0,
10588 Opcode::Goto | Opcode::Return | Opcode::ReturnUndef | Opcode::Throw
10589 )
10590 })
10591 .unwrap_or(false);
10592 if !after_transfer {
10593 break;
10594 }
10595 end = last;
10596 }
10597 kept.truncate(end);
10598 spans.truncate(end);
10599
10600 // Choose an opcode for each instruction and its size, so label offsets can be
10601 // computed.
10602 let chosen = choose_opcodes(&kept, &label_kept);
10603 let offsets = instruction_offsets(&chosen);
10604 let offset = *offsets.last().unwrap_or(&0);
10605
10606 let mut code = Vec::with_capacity(offset);
10607 for (position, (_, operands)) in kept.iter().enumerate() {
10608 let op = chosen[position];
10609 code.push(op as u8);
10610 let operands = retarget_labels(operands, &label_kept, kept.len());
10611 encode_operands(&mut code, op, &operands, offsets[position], &offsets);
10612 }
10613 let stack_size = compute_stack_size(&code);
10614 // Keep only the offsets where the position actually changes: a run of
10615 // instructions on one line is one table entry, and the runtime binary searches
10616 // the table for the frame's pc.
10617 //
10618 // The table always starts at pc 0 with the *function's own* position, because the
10619 // reference's `compute_pc2line_info` seeds it that way: `dbuf_put_leb128(&s->pc2line,
10620 // last_line_num)` from `fd->source_pos`, the token the function definition starts at
10621 // (`function`, `async`, a method's property name). An instruction before the first
10622 // recorded operator therefore reports the function's own start, which is what makes a
10623 // `using` epilogue with a plain initialiser report `1:2` rather than nothing at all.
10624 let mut positions: Vec<LineCol> = vec![LineCol {
10625 pc: 0,
10626 line: state.line,
10627 column: state.column,
10628 }];
10629 let mut last: Option<Position> = None;
10630 for (index, span) in spans.iter().enumerate() {
10631 let Some(pos) = *span else { continue };
10632 if last == Some(pos) {
10633 continue;
10634 }
10635 last = Some(pos);
10636 if pos.line == state.line && pos.column == state.column {
10637 // Already the seed entry above.
10638 continue;
10639 }
10640 positions.push(LineCol {
10641 pc: offsets[index] as u32,
10642 line: pos.line,
10643 column: pos.column,
10644 });
10645 }
10646 (code, stack_size, positions)
10647}
10648
10649/// Whether an instruction always transfers control away, so anything after it in the
10650/// same stream is unreachable.
10651fn is_transfer(op: Opcode) -> bool {
10652 matches!(
10653 op,
10654 Opcode::Goto
10655 | Opcode::Goto8
10656 | Opcode::Goto16
10657 | Opcode::Return
10658 | Opcode::ReturnUndef
10659 | Opcode::Throw
10660 | Opcode::ThrowError
10661 | Opcode::Ret
10662 )
10663}
10664
10665/// Remove the marked instructions and renumber the label table so it keeps pointing
10666/// at the same instructions. A label whose instruction went away moves to whatever
10667/// follows it, since a jump is never left with nowhere to land.
10668fn drop_instructions(
10669 kept: Vec<(Opcode, Vec<Op>)>,
10670 spans: Vec<Option<Position>>,
10671 label_kept: &mut [Option<usize>],
10672 doomed: &[bool],
10673) -> (Vec<PositionedInsn>, Vec<Option<Position>>) {
10674 let mut result: Vec<(Opcode, Vec<Op>)> = Vec::with_capacity(kept.len());
10675 let mut result_spans: Vec<Option<Position>> = Vec::with_capacity(kept.len());
10676 let mut moved: Vec<Option<usize>> = vec![None; kept.len()];
10677 for (old, entry) in kept.into_iter().enumerate() {
10678 if doomed.get(old).copied().unwrap_or(false) {
10679 continue;
10680 }
10681 moved[old] = Some(result.len());
10682 result.push(entry);
10683 result_spans.push(spans[old]);
10684 }
10685 for slot in label_kept.iter_mut() {
10686 let Some(old) = *slot else { continue };
10687 *slot = match moved.get(old).copied().flatten() {
10688 Some(new) => Some(new),
10689 None => (old..moved.len())
10690 .find_map(|i| moved[i])
10691 .or(Some(result.len())),
10692 };
10693 }
10694 (result, result_spans)
10695}
10696
10697fn is_goto(op: Opcode) -> bool {
10698 matches!(op, Opcode::Goto | Opcode::Goto8 | Opcode::Goto16)
10699}
10700
10701/// The kept index a jump operand points at.
10702fn target_kept_index(operands: &[Op], label_kept: &[Option<usize>]) -> Option<usize> {
10703 let id = label_id(operands)?;
10704 label_kept.get(id as usize).copied().flatten()
10705}
10706
10707/// Follow a chain of unconditional jumps to its first real destination.
10708fn follow_jump_chain(
10709 kept: &[(Opcode, Vec<Op>)],
10710 label_kept: &[Option<usize>],
10711 start: usize,
10712) -> usize {
10713 let mut current = start;
10714 // `for(;;)` jumps to itself, so the walk has to be bounded.
10715 for _ in 0..kept.len() {
10716 let Some((op, operands)) = kept.get(current) else {
10717 return current;
10718 };
10719 if !is_goto(*op) {
10720 return current;
10721 }
10722 let Some(next) = target_kept_index(operands, label_kept) else {
10723 return current;
10724 };
10725 if next == current {
10726 return current;
10727 }
10728 current = next;
10729 }
10730 current
10731}
10732
10733/// Rewrite label operands from label ids to kept instruction indices.
10734fn retarget_labels(operands: &[Op], label_kept: &[Option<usize>], kept_len: usize) -> Vec<Op> {
10735 operands
10736 .iter()
10737 .map(|operand| match operand {
10738 Op::Label(label) => {
10739 let target = label_kept
10740 .get(label.0 as usize)
10741 .copied()
10742 .flatten()
10743 .unwrap_or(kept_len);
10744 Op::Label(Label(target as u32))
10745 }
10746 other => other.clone(),
10747 })
10748 .collect()
10749}
10750
10751/// Encode the resolved instruction stream, choosing short forms where possible.
10752///
10753/// Compute the maximum value-stack depth by exploring the control-flow graph.
10754///
10755/// This is a breadth-first walk from the first instruction, tracking the stack
10756/// depth on entry to each instruction. Every instruction has at most two
10757/// successors (fall through, and a jump target), so a worklist over byte offsets
10758/// is enough. The reference does the same thing in `compute_stack_size`, which is
10759/// why the resulting numbers match exactly.
10760///
10761/// Instructions that pop a variable number of values (`call`, `array_from`, …)
10762/// encode that count in their operand, which is added to the static `n_pop`.
10763fn compute_stack_size(code: &[u8]) -> u32 {
10764 let mut depth_at = vec![u16::MAX; code.len()];
10765 // Each entry carries the enclosing `catch` levels, innermost last, because
10766 // `nip_catch` needs them: it rewinds the stack to just above the innermost catch
10767 // offset and forgets that level.
10768 let mut worklist: Vec<(usize, u32, Vec<u32>)> = vec![(0, 0, Vec::new())];
10769 let mut max_depth = 0u32;
10770
10771 while let Some((pc, depth, catch_levels)) = worklist.pop() {
10772 if pc >= code.len() {
10773 continue;
10774 }
10775 if depth_at[pc] != u16::MAX {
10776 continue;
10777 }
10778 force_depth(&mut depth_at, pc, depth);
10779
10780 let Some(op) = Opcode::from_u8(code[pc]) else {
10781 break;
10782 };
10783 let info = op.info();
10784 let next = pc + info.size as usize;
10785 if next > code.len() {
10786 break;
10787 }
10788 let mut n_pop = info.n_pop as u32;
10789 let mut n_push = info.n_push as u32;
10790 // Variable-length forms carry their count in the operand.
10791 match info.format {
10792 crate::opcode::OpFormat::Npop | crate::opcode::OpFormat::NpopU16 => {
10793 n_pop += read_u16(code, pc + 1) as u32;
10794 }
10795 crate::opcode::OpFormat::Npopx => {
10796 n_pop += op.specialised_index().unwrap_or(0).max(0) as u32;
10797 }
10798 _ => {}
10799 }
10800 // `put_loc`/`put_arg`/`put_var_ref` keep the value on the stack when they
10801 // are the `set_` variant; the table already records that, so nothing to
10802 // adjust here.
10803 let _ = &mut n_push;
10804
10805 // The depth before this instruction's own push, which is what a `catch`
10806 // records as its level.
10807 let depth_before = depth;
10808 let mut depth = depth.saturating_sub(n_pop) + n_push;
10809 let mut catch_levels = catch_levels;
10810 if op == Opcode::NipCatch {
10811 // Discard everything above the innermost catch offset, keeping the value
10812 // on top: the frame the code after this sees is the same shape it would
10813 // have had if the `try` were not there.
10814 if let Some(base) = catch_levels.pop() {
10815 depth = base + 1;
10816 }
10817 }
10818 max_depth = max_depth.max(depth);
10819
10820 // Successors.
10821 let target = jump_target_of(code, pc, op);
10822 match op {
10823 Opcode::Goto | Opcode::Goto8 | Opcode::Goto16 => {
10824 if let Some(target) = target {
10825 worklist.push((target, depth, catch_levels));
10826 }
10827 }
10828 Opcode::IfFalse | Opcode::IfFalse8 | Opcode::IfTrue | Opcode::IfTrue8 => {
10829 if let Some(target) = target {
10830 worklist.push((target, depth, catch_levels.clone()));
10831 }
10832 worklist.push((next, depth, catch_levels));
10833 }
10834 // A `catch` records an exception edge to the handler. The handler is
10835 // entered with the thrown value on top of the stack, in the slot the
10836 // catch offset occupies on the normal path — which is why the handler's
10837 // first instruction can `put_loc` the exception away, and why the depth
10838 // is the same on both paths.
10839 Opcode::Catch => {
10840 if let Some(target) = target {
10841 // The handler is protected by the *enclosing* catch, not by this
10842 // one: an error raised inside it is what the handler's own
10843 // `catch` catches.
10844 worklist.push((target, depth, catch_levels.clone()));
10845 }
10846 catch_levels.push(depth_before);
10847 worklist.push((next, depth, catch_levels));
10848 }
10849 // A `for`/`of` loop keeps its own catch offset, and `nip_catch` has to
10850 // rewind past it too. Its level sits one slot higher than a `catch`'s:
10851 // the iterator and next-method slots occupy the offset's place.
10852 Opcode::ForOfStart | Opcode::ForAwaitOfStart => {
10853 if let Some(target) = target {
10854 worklist.push((target, depth, catch_levels.clone()));
10855 }
10856 catch_levels.push(depth_before + 1);
10857 worklist.push((next, depth, catch_levels));
10858 }
10859 // `gosub` calls a subroutine with the return address on top. The opcode
10860 // table records no push for it — `ret` is what pops the slot — so the
10861 // extra one is added here, where the depth of the subroutine's first
10862 // instruction is being computed.
10863 Opcode::Gosub => {
10864 if let Some(target) = target {
10865 worklist.push((target, depth + 1, catch_levels.clone()));
10866 }
10867 worklist.push((next, depth, catch_levels));
10868 }
10869 // `ret` goes back to a `gosub`; nothing here follows it.
10870 Opcode::Ret
10871 | Opcode::Return
10872 | Opcode::ReturnUndef
10873 | Opcode::Throw
10874 | Opcode::ThrowError => {}
10875 _ => worklist.push((next, depth, catch_levels)),
10876 }
10877 }
10878 max_depth
10879}
10880
10881/// Record the stack depth on entry to `pc`, keeping the deeper value if the
10882/// instruction is reachable more than once.
10883fn force_depth(depth_at: &mut [u16], pc: usize, depth: u32) {
10884 let clamped = depth.min(u16::MAX as u32 - 1) as u16;
10885 if depth_at[pc] == u16::MAX || depth_at[pc] < clamped {
10886 depth_at[pc] = clamped;
10887 }
10888}
10889
10890fn read_u16(code: &[u8], at: usize) -> u16 {
10891 let mut value = 0u16;
10892 for i in 0..2 {
10893 value = (value << 8) | code.get(at + i).copied().unwrap_or(0) as u16;
10894 }
10895 value
10896}
10897
10898/// The absolute target of a jump instruction, if it has one.
10899fn jump_target_of(code: &[u8], pc: usize, op: Opcode) -> Option<usize> {
10900 let info = op.info();
10901 let position = pc + 1;
10902 match info.format {
10903 crate::opcode::OpFormat::Label8 => {
10904 let offset = *code.get(position)? as i8 as i64;
10905 Some((position as i64 + offset) as usize)
10906 }
10907 crate::opcode::OpFormat::Label16 => {
10908 let offset = read_u16(code, position) as i16 as i64;
10909 Some((position as i64 + offset) as usize)
10910 }
10911 crate::opcode::OpFormat::Label => {
10912 let mut offset = 0i32;
10913 for i in 0..4 {
10914 offset = (offset << 8) | *code.get(position + i).unwrap_or(&0) as i32;
10915 }
10916 Some((position as i64 + offset as i64) as usize)
10917 }
10918 _ => None,
10919 }
10920}
10921
10922fn choose_short_form(op: Opcode, operands: &[Op]) -> Opcode {
10923 use Opcode::*;
10924 match (op, operands.first()) {
10925 (PushI32, Some(Op::Int(value))) if (-1..=7).contains(value) => {
10926 op.short_form(*value as u32).unwrap_or(op)
10927 }
10928 (PushConst, Some(Op::Const(index))) if *index < 256 => Opcode::PushConst8,
10929 (Fclosure, Some(Op::Const(index))) if *index < 256 => Opcode::Fclosure8,
10930 (GetLoc | PutLoc | SetLoc, Some(Op::Slot(Slot::Loc(index))))
10931 | (GetArg | PutArg | SetArg, Some(Op::Slot(Slot::Arg(index))))
10932 | (GetVarRef | PutVarRef | SetVarRef, Some(Op::Slot(Slot::VarRef(index))))
10933 // A declared global is reached through its reference cell, so it shares
10934 // the `var_ref` encodings, short forms included.
10935 | (GetVarRef | PutVarRef | SetVarRef, Some(Op::Slot(Slot::GlobalDecl(index)))) => {
10936 op.short_form(*index).unwrap_or(op)
10937 }
10938 (Call, Some(Op::Int(count))) if (0..=3).contains(count) => {
10939 op.short_form(*count as u32).unwrap_or(op)
10940 }
10941 _ => op,
10942 }
10943}
10944
10945/// The byte offset each instruction will start at, plus the total code size.
10946fn instruction_offsets(chosen: &[Opcode]) -> Vec<usize> {
10947 let mut offsets = Vec::with_capacity(chosen.len() + 1);
10948 let mut offset = 0usize;
10949 for op in chosen {
10950 offsets.push(offset);
10951 offset += op.size() as usize;
10952 }
10953 offsets.push(offset);
10954 offsets
10955}
10956
10957/// Pick an encoding for every instruction, shrinking a jump to its 8-bit form only when
10958/// the offset actually fits.
10959///
10960/// The choice is circular: an instruction's size decides the offsets of everything after
10961/// it, and the offsets decide whether a jump may be short. So this starts with every jump
10962/// in its widest form and shrinks what fits, repeating until a pass changes nothing.
10963/// Shrinking only ever *shortens* distances, so the loop converges.
10964///
10965/// Doing it in one pass instead — which is what this used to do — silently truncated any
10966/// jump further than 127 bytes: `goto8` with a mangled offset lands in the middle of the
10967/// bytecode, and the VM treats running off the end as a return. That is how a nested loop
10968/// with four closures in its body simply stopped, with no error and no output past the
10969/// first iteration.
10970fn choose_opcodes(kept: &[(Opcode, Vec<Op>)], label_kept: &[Option<usize>]) -> Vec<Opcode> {
10971 let mut chosen: Vec<Opcode> = kept
10972 .iter()
10973 .map(|(op, operands)| choose_short_form(*op, operands))
10974 .collect();
10975 // A jump the compiler emitted in its widest form, and the forms it may shrink to.
10976 let candidates = |op: Opcode| match op {
10977 Opcode::Goto => Some((Opcode::Goto8, Opcode::Goto16, true)),
10978 Opcode::IfFalse => Some((Opcode::IfFalse8, Opcode::IfFalse, false)),
10979 Opcode::IfTrue => Some((Opcode::IfTrue8, Opcode::IfTrue, false)),
10980 _ => None,
10981 };
10982 loop {
10983 let offsets = instruction_offsets(&chosen);
10984 let mut changed = false;
10985 for index in 0..kept.len() {
10986 let (op, operands) = &kept[index];
10987 let Some((short, medium, has_medium)) = candidates(*op) else {
10988 continue;
10989 };
10990 if chosen[index] == short {
10991 continue;
10992 }
10993 let Some(target) = target_kept_index(operands, label_kept) else {
10994 continue;
10995 };
10996 let Some(&target_offset) = offsets.get(target) else {
10997 continue;
10998 };
10999 // A jump is relative to the byte after its opcode, which is the convention
11000 // `jump_target_of` decodes with.
11001 let relative = target_offset as i64 - (offsets[index] as i64 + 1);
11002 if (-128..=127).contains(&relative) {
11003 chosen[index] = short;
11004 changed = true;
11005 } else if has_medium
11006 && chosen[index] == Opcode::Goto
11007 && (-32_768..=32_767).contains(&relative)
11008 {
11009 // Too far for 8 bits and close enough for 16. Only `goto` has a medium
11010 // form: `if_false`/`if_true` jump straight from 8 to 32 bits, exactly as
11011 // the reference encodes them.
11012 chosen[index] = medium;
11013 changed = true;
11014 }
11015 }
11016 if !changed {
11017 return chosen;
11018 }
11019 }
11020}
11021
11022fn encode_operands(
11023 code: &mut Vec<u8>,
11024 op: Opcode,
11025 operands: &[Op],
11026 position: usize,
11027 offsets: &[usize],
11028) {
11029 use crate::opcode::OpFormat::*;
11030 let info = op.info();
11031 let write_slot = |code: &mut Vec<u8>, slot: Slot| {
11032 let index = match slot {
11033 Slot::Arg(i)
11034 | Slot::Loc(i)
11035 | Slot::VarRef(i)
11036 | Slot::Global(i)
11037 | Slot::GlobalDecl(i) => i,
11038 };
11039 code.extend_from_slice(&(index as u16).to_be_bytes());
11040 };
11041 match info.format {
11042 None | NoneInt | NoneLoc | NoneArg | NoneVarRef | Npopx => {}
11043 U8 | Const8 => {
11044 if let Some(value) = operands.first().and_then(operand_uint) {
11045 code.push(value as u8);
11046 }
11047 }
11048 // The narrow slot forms (`inc_loc8` and friends) take a slot operand just
11049 // like their wide counterparts, only one byte wide.
11050 Loc8 => {
11051 if let Some(Op::Slot(slot)) = operands.first() {
11052 let index = match slot {
11053 Slot::Arg(i)
11054 | Slot::Loc(i)
11055 | Slot::VarRef(i)
11056 | Slot::Global(i)
11057 | Slot::GlobalDecl(i) => *i,
11058 };
11059 code.push(index as u8);
11060 }
11061 }
11062 I8 => {
11063 if let Some(value) = operands.first().and_then(operand_int) {
11064 code.push(value as i8 as u8);
11065 }
11066 }
11067 U16 | Npop => {
11068 if let Some(value) = operands.first().and_then(operand_int) {
11069 code.extend_from_slice(&(value as u16).to_be_bytes());
11070 }
11071 }
11072 I16 => {
11073 if let Some(value) = operands.first().and_then(operand_int) {
11074 code.extend_from_slice(&(value as i16 as u16).to_be_bytes());
11075 }
11076 }
11077 I32 => {
11078 if let Some(value) = operands.first().and_then(operand_int) {
11079 code.extend_from_slice(&value.to_be_bytes());
11080 }
11081 }
11082 U32 | Const => {
11083 if let Some(value) = operands.first().and_then(operand_uint) {
11084 code.extend_from_slice(&value.to_be_bytes());
11085 }
11086 }
11087 Loc | Arg | VarRef => {
11088 if let Some(Op::Slot(slot)) = operands.first() {
11089 write_slot(code, *slot);
11090 }
11091 }
11092 Atom | AtomU8 | AtomU16 | AtomLabelU8 | AtomLabelU16 => {
11093 if let Some(Op::AtomId(index)) = operands.first() {
11094 code.extend_from_slice(&index.to_be_bytes());
11095 }
11096 // The trailing immediate means different things per format, and the
11097 // atom forms that carry a *label* have to resolve it like any other
11098 // jump, so they cannot share the `U8`/`U16` arms above.
11099 match info.format {
11100 AtomU8 | AtomLabelU8 => {
11101 if let Some(value) = operands.get(1).and_then(operand_uint) {
11102 code.push(value as u8);
11103 }
11104 }
11105 AtomU16 | AtomLabelU16 => {
11106 if let Some(value) = operands.get(1).and_then(operand_uint) {
11107 code.extend_from_slice(&(value as u16).to_be_bytes());
11108 }
11109 }
11110 _ => {}
11111 }
11112 }
11113 NpopU16 => {
11114 for operand in operands.iter().take(2) {
11115 if let Some(value) = operand_uint(operand) {
11116 code.extend_from_slice(&(value as u16).to_be_bytes());
11117 }
11118 }
11119 }
11120 Label | Label8 | Label16 | LabelU16 => {
11121 if let Some(Op::Label(label)) = operands.first() {
11122 // Labels were already remapped to kept-instruction indices.
11123 let Some(&target) = offsets.get(label.0 as usize) else {
11124 debug_assert!(false, "label {} is past the end", label.0);
11125 return;
11126 };
11127 let relative = target as i64 - (position as i64 + 1);
11128 match info.format {
11129 Label8 => code.push(relative as i8 as u8),
11130 Label16 => code.extend_from_slice(&(relative as i16 as u16).to_be_bytes()),
11131 // `label_u16` stores the target followed by an unrelated u16.
11132 LabelU16 => {
11133 code.extend_from_slice(&(relative as i32).to_be_bytes());
11134 if let Some(value) = operands.get(1).and_then(operand_uint) {
11135 code.extend_from_slice(&(value as u16).to_be_bytes());
11136 }
11137 }
11138 _ => code.extend_from_slice(&(relative as i32).to_be_bytes()),
11139 }
11140 }
11141 }
11142 }
11143}
11144
11145fn operand_int(op: &Op) -> Option<i32> {
11146 match op {
11147 Op::Int(value) => Some(*value),
11148 _ => None,
11149 }
11150}
11151
11152fn operand_uint(op: &Op) -> Option<u32> {
11153 match op {
11154 Op::Const(value) | Op::AtomId(value) => Some(*value),
11155 Op::Int(value) => Some(*value as u32),
11156 _ => None,
11157 }
11158}
11159
11160/// Disassemble a compiled function.
11161pub fn disassemble(function: &CompiledFunction) -> String {
11162 disasm::disassemble_program(function)
11163}
11164
11165/// How many of an object pattern's keys are computed.
11166///
11167/// Only the count matters: a rest element needs a run-time key log exactly when at least one
11168/// key is not a literal, and the log is sized by walking the pattern anyway.
11169fn computed_key_count(properties: &[Option<PatternElement>]) -> usize {
11170 properties
11171 .iter()
11172 .flatten()
11173 .filter(|element| {
11174 matches!(
11175 element,
11176 PatternElement::Property {
11177 key: PropName::Computed(_),
11178 ..
11179 }
11180 )
11181 })
11182 .count()
11183}