js_compile/compiler.rs
1//! The bytecode compiler.
2//!
3//! Compilation is a single walk over the AST that emits *symbolic* instructions
4//! (jump targets are label ids, variable references are names), followed by a
5//! resolution pass that turns them into final bytecode. Splitting it this way
6//! keeps the emitter readable: nothing has to know slot indices or byte offsets
7//! while it is still discovering them.
8//!
9//! Variable resolution follows the reference implementation's model:
10//!
11//! * every function has a flat table of arguments and locals;
12//! * block scopes form a chain through [`VarDef::scope_next`], which is what makes
13//! `let`/`const` bindings visible only inside their block and lets the runtime
14//! put them back into the temporal dead zone on entry;
15//! * a name that is not in the current function is looked up in the enclosing
16//! ones; if found, the variable is marked captured and reached through a
17//! closure reference;
18//! * a name found nowhere is a global, reached through a closure entry as well.
19//!
20//! Emission order and instruction choice deliberately mirror `quickjs.c`: the
21//! differential test compares disassembly with the reference opcode by opcode, so
22//! an unnecessary `dup` or a differently chosen short form shows up immediately.
23
24use crate::bytecode::LineCol;
25use crate::bytecode::{
26 ANONYMOUS_BINDING, Atom, ClosureType, ClosureVar, Constant, EvalPrivate, EvalPrivateKind,
27 EvalSite, EvalVisible, ExportEntry, Function as CompiledFunction, FunctionKind, ImportEntry,
28 ModuleMeta, ModuleRequest, VarDef, VarKind,
29};
30use crate::disasm;
31use crate::opcode::Opcode;
32use js_parse::Position;
33use js_parse::Span;
34use js_parse::SyntaxError;
35use js_parse::Wtf8;
36use js_parse::ast::{self, *};
37
38/// A label id, local to the function being compiled.
39#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
40pub struct Label(u32);
41
42/// The name of the hidden local that carries a function's `[[HomeObject]]` for `super`.
43///
44/// The reference calls the variable `home_object` and prints it as `"<home_object>"`, which
45/// is why the brackets are part of the name; nothing a program writes can collide with it.
46const HOME_OBJECT: &str = "<home_object>";
47
48/// The local holding the function `super()` constructs from.
49///
50/// The reference's `JS_ATOM_this_active_func`. Unlike `<home_object>` this one is printed
51/// with its dots, because that is the atom's text: its dump shows `1: var this.active_func`.
52const ACTIVE_FUNC: &str = "this.active_func";
53
54/// The local holding `new.target`, likewise spelled the way the reference's dump shows it.
55const NEW_TARGET: &str = "new.target";
56
57/// Stand-in for a constant-pool index that is only known later in the instruction stream.
58///
59/// One user: the class constructor's `fclosure`, whose slot the reference assigns after the
60/// members have taken theirs. `u32::MAX` is not a reachable pool index — a class with four
61/// billion members is not a thing — and the compiler patches it before resolution runs, so a
62/// missed patch is a panic-free compiler error rather than a wrong jump.
63const CTOR_INDEX_PLACEHOLDER: u32 = u32::MAX;
64
65/// One step of a class's initialisation, in source order.
66///
67/// A static block is not a member the class keeps — it is a run of statements that executes
68/// at the point the class definition reaches it — so it belongs *inside* the initialiser
69/// function rather than alongside the fields as a separate pass. Merging the two is what
70/// makes `static a = 1; static {}` and `static {}; static a = 1` order-sensitive in the
71/// same way the reference is.
72enum StaticInitItem<'a> {
73 /// `static x = value`, or `x = value` for the instance half.
74 Field(FieldKey<'a>, Option<&'a Expr>),
75 /// `static { … }`
76 Block {
77 body: &'a [Stmt],
78 /// Position of the `{`, which is where the reference puts the function.
79 body_start: Position,
80 },
81}
82
83/// The next template-site identity, process-wide.
84///
85/// A counter rather than something derived from the unit: two compilation units that both
86/// number their sites from zero would collide in the realm's registry, and a collision
87/// there is observable — it would hand the *same* template object to two unrelated sites.
88fn next_template_site() -> u32 {
89 static NEXT: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0);
90 NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed)
91}
92
93/// How one field names its property.
94///
95/// A computed key is *not* re-evaluated per instance: the reference evaluates it once at
96/// class definition and stores it in a `<computed_field>N` binding, because the key of a field
97/// is fixed when the class is created. Keeping the expression here instead made
98/// `class C { [k] = 1 }` re-read `k` on every `new`, which is a different program when `k`
99/// changes — and worse, the operand order was wrong, so `class C { ["a"] = 1 }` produced
100/// `{1: "a"}`.
101enum FieldKey<'a> {
102 /// `x`, `"x"`, `0` — the property name is static text.
103 Literal(&'a PropKey),
104 /// `#x`: the class-scope binding that holds the private symbol.
105 Private(String),
106 /// `[expr]`: the class-scope binding that holds the evaluated key.
107 Computed(String),
108}
109
110/// The `var_block` sentinel for a binding that lives at function scope.
111///
112/// It has to be a value a *real* block key can never take. Block keys are source
113/// offsets, so `0` is a perfectly ordinary key — the first block statement of a file
114/// gets it — and using `0` as the sentinel made `{ let y = 2 }` at offset zero look
115/// like a function-scoped `var`, which is how a top-level block's `let` leaked out of
116/// its block. The body block already uses `u64::MAX` to stay clear of offsets, so the
117/// sentinel takes the slot below it.
118const FUNCTION_SCOPE: u64 = u64::MAX - 3;
119
120/// The `var_block` sentinel for a binding of the parameter list.
121///
122/// A function whose parameter list contains a default expression gets *two* variable
123/// environments: one for the parameters and one for the body, so a `var` in the body
124/// that shares a name with a parameter is a different binding. The parameter bindings
125/// therefore need a scope key of their own: reachable while the defaults are
126/// evaluated, invisible to the body, and never merged with a body `var` of the same
127/// name.
128///
129/// Without this, `function f(a = 1, p = () => a) { var a = 2 }` made `p()` return 2:
130/// the closure and the body shared one slot, when only the parameters were in scope
131/// when it was created.
132const PARAM_SCOPE: u64 = u64::MAX - 4;
133
134/// The name of the hidden local a `using` declaration caches its dispose method in.
135///
136/// It has to be a name no source can produce, because a script may declare anything: the
137/// angle brackets keep it out of the identifier grammar, exactly like `<ret>`.
138fn using_method_name(name: &str) -> String {
139 format!("<using.method {name}>")
140}
141
142/// The `blocks` parent sentinel for "this block has no enclosing block".
143///
144/// Same reasoning as [`FUNCTION_SCOPE`]: `0` is a legal block key, and when it was
145/// also the terminator the chain walk from the script body reached the file's
146/// offset-zero block and treated it as an *enclosing* block — so that block's `let`
147/// leaked into the body scope.
148const NO_PARENT: u64 = u64::MAX - 2;
149
150/// The block key for a script body. Distinct from both sentinels and unreachable from
151/// any source offset.
152const SCRIPT_BODY: u64 = u64::MAX - 1;
153
154/// An operand of a symbolic instruction.
155#[derive(Debug, Clone, PartialEq)]
156enum Op {
157 /// An immediate integer.
158 Int(i32),
159 /// A jump target.
160 Label(Label),
161 /// A constant pool index.
162 Const(u32),
163 /// An atom, before interning.
164 Atom(Atom),
165 /// An interned atom, as an index into [`Function::atoms`].
166 AtomId(u32),
167 /// A resolved slot.
168 Slot(Slot),
169}
170
171/// Where a resolved variable lives.
172#[derive(Debug, Clone, Copy, PartialEq, Eq)]
173enum Slot {
174 Arg(u32),
175 Loc(u32),
176 VarRef(u32),
177 /// A global, by closure-var index.
178 Global(u32),
179 /// A global *declared* in this script. The reference keeps these bindings in
180 /// reference cells so that the script and any closure share one variable, so
181 /// a store goes through `put_var_ref` while a read uses `get_var`.
182 GlobalDecl(u32),
183}
184
185/// What a symbolic variable access does, which decides the final opcode.
186#[derive(Debug, Clone, Copy, PartialEq, Eq)]
187enum VarAction {
188 /// Read the value.
189 Get,
190 /// Read the value, yielding `undefined` for an undeclared global.
191 GetUndef,
192 /// Write, leaving nothing on the stack.
193 Put,
194 /// Write and initialise, leaving the value on the stack.
195 PutInit,
196 /// Write, leaving the value on the stack.
197 Set,
198 /// Initialise a binding that may only be initialised once, such as a derived
199 /// constructor's `this`.
200 PutInitChecked,
201 /// Initialise, leaving the value on the stack and without the `const` check.
202 ///
203 /// A class's own scope binding is a `const` that has to be initialised in the middle
204 /// of the definition — after the constructor exists but before the static fields run
205 /// — and the value has to survive for the outer store to use.
206 SetInit,
207 /// Write a binding that lives in a reference cell.
208 PutRef,
209 /// Read through a reference the caller already pushed: `[ref] -> [ref, value]`.
210 GetRef,
211 /// Push a **Reference** (§6.2.5) to the binding, so the same lvalue can be read and
212 /// written without resolving the name twice.
213 ///
214 /// Only emitted where a direct `eval` may run in between: `x *= (eval("var x = 2"), 4)`
215 /// must read the `x` of §13.15.3 step 2 and store to *that* one at step 7, and by then
216 /// the eval has declared a shadowing binding with the same name.
217 MakeRef,
218}
219
220#[derive(Debug, Clone)]
221enum Insn {
222 /// A fully determined instruction.
223 Fixed { op: Opcode, operands: Vec<Op> },
224 /// A variable access, resolved in the second pass.
225 ///
226 /// `block` is the lexical block the access appears in, which is what makes
227 /// shadowing work: two bindings can share a name, and the one that wins is
228 /// whichever scope encloses the access.
229 Var {
230 action: VarAction,
231 name: String,
232 block: u64,
233 /// Whether the access was written in the parameter list; see
234 /// [`FnState::in_params`].
235 in_params: bool,
236 },
237 /// Close a binding *if* it turned out to be captured.
238 ///
239 /// Whether a `for (let i ...)` loop variable needs a fresh per-iteration cell is
240 /// only known once the body has been compiled — a closure created there is the
241 /// thing that makes it necessary. The reference emits `close_loc` exactly in that
242 /// case and nothing otherwise, so the decision is deferred to [`resolve`] instead
243 /// of emitted blind.
244 CloseCaptured { name: String, block: u64 },
245 /// `delete name`, which can only answer `false` once the binding is known.
246 ///
247 /// It is not a `Var` action because `delete_var` carries an *atom*: the runtime
248 /// looks the name up on the global object, which is what distinguishes an implicit
249 /// global (configurable, deletable) from a declared one (a binding, always `false`).
250 DeleteVar { name: String },
251 /// An instruction that dead-code elimination removed. It keeps its slot so
252 /// that label indices stay valid, and resolves to no bytecode.
253 Dead,
254}
255
256/// Where `break` and `continue` jump to.
257///
258/// Targets are stacked as the compiler enters loops and labelled statements, so a
259/// bare `break` needs no analysis: it is simply the innermost target. A labelled
260/// one searches outward by name.
261#[derive(Debug, Clone)]
262struct JumpTarget {
263 /// The labels attached to this target. `l: for(;;)` gives one name; a bare
264 /// loop gives none; `a: b: for(;;)` gives two, because both labels name the
265 /// same statement and `break a` must reach the same place as `break b`.
266 names: Vec<String>,
267 /// Where `break` lands. `None` for a construct `break` may only leave, not
268 /// target — a `try`, whose entry exists purely to unwind.
269 break_label: Option<Label>,
270 /// Where `continue` lands. `None` for anything that is not a loop.
271 continue_label: Option<Label>,
272 /// Stack slots to discard when control leaves this construct by a jump.
273 ///
274 /// Both `switch` and `try` leave something on the value stack for the duration
275 /// of the construct — the discriminant, or the `catch` offset — and a jump out
276 /// has to take it with it. A loop leaves nothing.
277 drop_count: u32,
278 /// The finalizer to run when control leaves this construct.
279 ///
280 /// Set on a `try` even when it has no `finally`: the label is always emitted and
281 /// the empty-subroutine removal cleans up afterwards, so the code that unwinds
282 /// does not have to know whether a finalizer exists.
283 finally_label: Option<Label>,
284 /// Whether this is a labelled non-loop statement, which an unlabelled `break`
285 /// does not reach.
286 is_regular_stmt: bool,
287 /// Whether leaving this construct has to close an iterator.
288 ///
289 /// A `for`/`of` loop keeps an iterator on the value stack, and leaving early has
290 /// to run its `return` method. `for`/`in` keeps only an enumeration object, which
291 /// is dropped rather than closed.
292 has_iterator: bool,
293 /// Whether that iterator speaks the *async* protocol.
294 ///
295 /// An async close has to `await` the inner `return`, so it is an inline instruction
296 /// sequence rather than one opcode — the reference's `emit_iterator_close`.
297 is_async_iterator: bool,
298}
299
300/// Whether a named property read should be `get_field2` rather than `dup; get_field`.
301///
302/// Both leave `source value` on the stack, so this is purely which spelling the reference
303/// picked, and it picked it by whether it had to build a *reference* for the target:
304///
305/// * a target that is itself a pattern starts by boxing the value, so the copy is what it
306/// consumes — `get_field2` (and a default does not change that: `{a: {b} = {}}` still
307/// destructures);
308/// * a `let`/`const` binding needs no reference, so the reference takes the short form;
309/// * a `var`, and any assignment target, go through `dup; get_field`, because the
310/// reference builds a reference for them — which is what `with` needs.
311fn reads_with_get_field2(decl: Option<VarDeclKind>, value: &Pattern) -> bool {
312 nests_a_pattern(value) || matches!(decl, Some(VarDeclKind::Let) | Some(VarDeclKind::Const))
313}
314
315/// Whether binding this pattern starts by boxing the value it was handed.
316fn nests_a_pattern(pattern: &Pattern) -> bool {
317 match &pattern.kind {
318 PatternKind::Array { .. } | PatternKind::Object { .. } => true,
319 PatternKind::Assign { target, .. } => nests_a_pattern(target),
320 _ => false,
321 }
322}
323
324/// `copy_data_properties` flags for an object-literal spread.
325///
326/// The byte packs three fields: the low bits are the stack offset of the source,
327/// the next three the offset of the exclusion list, and bit 2 asks for symbol keys
328/// as well as string keys. A spread passes a literal `null` exclusion list right
329/// below the source, so that field stays zero and only the source offset and the
330/// symbol bit are set — hence `{...v}` copies symbols, which the flag name says.
331const COPY_ALL_PROPERTIES: i32 = 2 | (1 << 2);
332
333/// The expression a `...` introduces.
334///
335/// The parser marks the spread in two places — the element/property variant and an
336/// [`ExprKind::Spread`] wrapper around the argument — so the wrapper has to be
337/// stepped through before the argument can be compiled.
338fn spread_argument(spread: &Expr) -> &Expr {
339 match &spread.kind {
340 ExprKind::Spread(inner) => inner,
341 _ => spread,
342 }
343}
344
345/// The flag byte `define_method` takes.
346///
347/// The low two bits pick value/getter/setter; bit 2 marks the property
348/// enumerable, which every object-literal method is.
349/// What kind of class constructor a function is being compiled as.
350///
351/// A constructor is not an ordinary method: a base one materialises `this` and refuses
352/// to run without `new`, and a derived one starts with `this` in the dead zone until
353/// `super()` produces it.
354#[derive(Debug, Clone, Copy, PartialEq, Eq)]
355enum CtorKind {
356 /// Not a class constructor.
357 None,
358 /// A constructor of a class without `extends`.
359 Base,
360 /// A constructor of a class with `extends`.
361 Derived,
362}
363
364/// The flag byte `define_method` takes for a class member.
365///
366/// The low two bits pick value/getter/setter; bit 2 marks the property enumerable, which
367/// a class method is *not* — that is the whole difference from an object-literal method,
368/// and the reason `Object.keys(C.prototype)` stays empty.
369fn class_method_flags(kind: MethodKind) -> i32 {
370 match kind {
371 MethodKind::Constructor | MethodKind::Method => 0,
372 MethodKind::Get => 1,
373 MethodKind::Set => 2,
374 }
375}
376
377fn define_method_flags(kind: PropertyKind) -> i32 {
378 let base = match kind {
379 PropertyKind::Value | PropertyKind::Method => 0,
380 PropertyKind::Get => 1,
381 PropertyKind::Set => 2,
382 };
383 base | 4
384}
385
386/// Convert a numeric property key to the text an atom would be made from.
387///
388/// `PropertyKey` of a number is `ToString(number)`, the same conversion every other place
389/// uses — so this goes through [`crate::number::number_to_string`] rather than formatting
390/// the value here. It used to accept only `[1e-6, 1e21)` and reject the rest, on the
391/// theory that Rust's `{}` and JavaScript's spelling diverge at the extremes; they do, and
392/// that is exactly why the spec's own algorithm is the thing to call. `get 0.0000001() {}`
393/// binds the key `"1e-7"`, and the rejection made it a `SyntaxError` instead.
394///
395/// The `Result` is kept because the call sites are in a `?` chain, and a key conversion
396/// that could still fail (a non-finite value from a source literal, which the lexer does
397/// not produce) belongs on the same path as the rest of a property name's errors.
398fn numeric_key_text(value: f64, _span: Span) -> Result<String, SyntaxError> {
399 Ok(crate::number::number_to_string(value))
400}
401
402/// Collect the operands of a same-operator logical run, in source order.
403///
404/// Recurses down the left spine only: `((a || b) || c)` contributes `a`, `b`, then
405/// the caller appends `c`. A node with a different operator is one operand.
406fn collect_same_operator<'a>(op: LogicalOp, expr: &'a Expr, out: &mut Vec<&'a Expr>) {
407 if let ExprKind::Logical {
408 op: inner_op,
409 left,
410 right,
411 } = &expr.kind
412 && *inner_op == op
413 {
414 collect_same_operator(op, left, out);
415 out.push(right);
416 return;
417 }
418 out.push(expr);
419}
420
421/// The jump a logical assignment or `??` takes when the value is kept.
422///
423/// `||` and `&&` branch on truthiness, so the same opcode serves both the operator
424/// and `??` once [`Compiler::emit_logical_test`] has pushed a boolean. `??` keeps
425/// the value when it is *not* null-ish, so it is the `if_false` side.
426fn logical_jump(op: AssignOp) -> Opcode {
427 match op {
428 AssignOp::Or => Opcode::IfTrue,
429 AssignOp::And | AssignOp::Coalesce => Opcode::IfFalse,
430 _ => Opcode::IfFalse,
431 }
432}
433
434/// Whether a loop enumerates keys or values.
435#[derive(Debug, Clone, Copy, PartialEq, Eq)]
436enum ForLoopKind {
437 /// `for (x in o)` — the keys of an object.
438 In,
439 /// `for (x of o)` — the values of an iterable.
440 Of,
441 /// `for await (x of o)` — the values of an async iterable, or of a sync one.
442 AwaitOf,
443}
444
445/// Which part of a `try` statement a block key refers to.
446#[derive(Debug, Clone, Copy)]
447enum TryPart {
448 /// The guarded block.
449 Block = 0,
450 /// The handler body, excluding the catch parameter.
451 Catch = 1,
452 /// The finalizer block.
453 Finally = 2,
454 /// The catch parameter's own scope.
455 Param = 3,
456}
457
458/// A lexical scope, identified while hoisting and numbered at the end.
459///
460/// Scope identity is needed in two passes that must agree: declarations are
461/// hoisted in source order (so slots come out in source order, as in the
462/// reference), but a binding belongs to the block it was written in, which is only
463/// entered later. Blocks are therefore keyed by the source position of their
464/// opening brace, which is stable across both walks.
465#[derive(Debug, Clone, Copy)]
466struct Block {
467 /// Source position of the block.
468 key: u64,
469 /// The block this one is nested in; `0` for the function scope.
470 parent: u64,
471}
472
473/// One function under construction.
474struct FnState {
475 /// The function's own source range, used to record its text for
476 /// `Function.prototype.toString`.
477 span: Option<(usize, usize)>,
478 name: String,
479 kind: FunctionKind,
480 strict: bool,
481 args: Vec<VarDef>,
482 vars: Vec<VarDef>,
483 closure_vars: Vec<ClosureVar>,
484 cpool: Vec<Constant>,
485 atoms: Vec<Atom>,
486 /// Every lexical scope, in creation order.
487 blocks: Vec<Block>,
488 /// The block currently being parsed or compiled.
489 current_block: u64,
490 /// The block a *nested* function was created in, so a capture made from here can be
491 /// resolved against the enclosing function's lexical scopes rather than against a
492 /// flat name table. Without it, `function f(){ class S{} }` capturing `S` found the
493 /// function's own `let S` instead of the class body's `const S`.
494 created_in_block: u64,
495 /// The block each local was declared in, parallel to `vars`. `0` means the
496 /// function scope, where `var` bindings live.
497 var_block: Vec<u64>,
498 /// Set when the expression just compiled left no value on the stack.
499 ///
500 /// Only a store can do that: `put_field` consumes the object and the value, so
501 /// an assignment whose result is unused emits nothing extra. The expression
502 /// statement then has nothing to drop.
503 no_value: bool,
504 /// Whether a label was placed since the last instruction was emitted.
505 ///
506 /// The `put`/`get` fold is only valid when the two are adjacent in the final
507 /// stream; a label in between means a jump can land on the read, so the store has
508 /// to keep consuming its value. A flag is enough and avoids having to reason about
509 /// which index a label recorded.
510 label_since_insn: bool,
511 /// Whether the value of the expression being compiled is thrown away.
512 ///
513 /// Only an expression *statement* discards its value, and only the outermost
514 /// assignment in it may act on that: in `x = (o.a = 1)` the inner assignment
515 /// still has to produce a value. Consumed by [`Compiler::assign`], which is
516 /// the one construct whose bytecode depends on it.
517 discard_value: bool,
518 /// The block that holds the function body.
519 body_block: u64,
520 /// Head of each scope's binding chain, indexed by level. Filled in by
521 /// [`rebuild_scope_chain`]; the scope chain is only needed at run time.
522 block_heads: Vec<i32>,
523 /// Enclosing `break`/`continue` targets, innermost last.
524 jump_targets: Vec<JumpTarget>,
525 insns: Vec<Insn>,
526 labels: Vec<Option<usize>>,
527 /// Captured locals, which need a reference cell.
528 var_ref_count: u32,
529 line: u32,
530 column: u32,
531 /// Whether this is a script body. A script's top-level declarations create
532 /// global properties rather than locals, which is why they show up as
533 /// closure variables with `[global_decl]`.
534 is_script: bool,
535 /// Whether this is a module body.
536 ///
537 /// A module body is a script in every respect that matters here — no `arguments`,
538 /// no `this` of its own — but its top-level declarations are *module*-scoped
539 /// instead of global, which is what this flag changes.
540 is_module: bool,
541 /// Whether this frame is an `eval` body; see [`Compiler::eval_body`].
542 is_eval_body: bool,
543 /// Whether the function is an arrow, which never gets its own `arguments`.
544 is_arrow: bool,
545 /// The name a *named function expression* binds inside its own body.
546 /// How many parameters count towards `.length`.
547 defined_args: u32,
548 /// Parameters that are not a plain name, with the argument slot each came from.
549 param_prologue: Vec<(usize, Pattern)>,
550 /// What kind of class constructor this function is, if any.
551 ctor_kind: CtorKind,
552 /// Whether the class has instance fields, so the constructor has to run their
553 /// initialiser before it returns.
554 /// What the nested function about to be compiled should be told about its class.
555 class_ctor_pending: Option<CtorKind>,
556 /// Whether this function needs the hidden `this` local, because an arrow inside it
557 /// refers to `this`.
558 ///
559 /// An arrow has no `this` of its own, so the reference materialises the enclosing
560 /// function's receiver into a local and lets the arrow capture it as an ordinary
561 /// closure variable. Declaring the local is not enough on its own: the store that
562 /// fills it has to be prepended to the body, which is what this flag arranges.
563 needs_this_local: bool,
564 /// The same, for `arguments`.
565 needs_arguments_local: bool,
566 /// The same, for `new.target`.
567 needs_new_target_local: bool,
568 /// Whether the body already opens by filling a `this` local, which
569 /// [`Compiler::begin_this_local`] does for a constructor and a field initialiser.
570 has_this_prologue: bool,
571 /// The same, for `<home_object>`: the object `super` resolves against.
572 ///
573 /// An arrow and a static block have no home object of their own — only the method or
574 /// initialiser they were written in does — so `super.x` inside one is a read of the
575 /// enclosing function's `[[HomeObject]]`. The value is materialised into a local there
576 /// by `special_object 4`, the same way `this` is.
577 needs_home_object_local: bool,
578 /// Whether this function has an `arguments` binding of its own.
579 ///
580 /// False for a class field initialiser and a static block: §15.7 puts them outside any
581 /// function, so `arguments` does not exist there and `eval('arguments')` inside one is a
582 /// `SyntaxError` rather than the caller's arguments object. The parser already enforces
583 /// that for written code; this carries the same fact to the `eval` call site, which has
584 /// to compile the eval'd source under the caller's restriction.
585 no_arguments_binding: bool,
586 /// The same, for `this.active_func`: the function `super()` constructs from.
587 ///
588 /// An arrow has no `super` of its own, so it reads the enclosing function's — and that
589 /// is a *lexical* relationship, not a stack one. The reference keeps `this_active_func`
590 /// as a local of the enclosing function; an arrow that escaped the constructor
591 /// (`iter.return = () => super()`) then finds it in its closure even with the
592 /// constructor nowhere on the call stack.
593 needs_active_func_local: bool,
594 /// Hidden locals of the `with` blocks currently open, innermost last.
595 with_names: Vec<String>,
596 /// How many of [`FnState::with_names`] were already open when this function was
597 /// created, i.e. belong to an *enclosing* function.
598 ///
599 /// The distinction decides shadowing, and it is positional rather than lexical. A
600 /// `with` opened **inside** this function's body sits nearer than the function's own
601 /// environment, so it shadows even a `var` of this function:
602 /// `function f(){ with(o){ var v = 1 } }` writes `o.v`. A `with` opened **outside**
603 /// does not: `with(o){ function f(){ var v = 1 } }` writes `f`'s local `v`, because
604 /// `f`'s environment is the inner one. Treating both alike broke one family or the
605 /// other — `S12.10_A1.2` and `S12.10_A1.7` are these two cases.
606 inherited_with_names: usize,
607 /// Set while a with-guard is being emitted, so the guard's own accesses are not
608 /// wrapped in another guard.
609 emitting_with_guard: bool,
610 self_name: Option<String>,
611 /// Where the function body starts, in source order; see [`Function::body_start`].
612 body_start: (u32, u32),
613 /// Whether the body contains a *direct* `eval(...)` call.
614 ///
615 /// A direct eval sees every binding of the function that called it, including ones
616 /// no other code mentions. It also hands those bindings to any closure it creates,
617 /// which can outlive the function. Both need the bindings to live in cells, so this
618 /// flag makes the function treat all of them as captured.
619 has_direct_eval: bool,
620 /// Whether this function's body contains a direct `eval` **anywhere**, known before any
621 /// of it is compiled.
622 ///
623 /// [`Self::has_direct_eval`] is learned as the eval call is compiled, which is too late
624 /// for an lvalue that must be resolved *before* the right-hand side that contains the
625 /// eval. This one is seeded from the AST, so `x *= (eval("var x = 2"), 4)` knows to pin
626 /// the reference before it emits the read.
627 eval_can_declare: bool,
628 /// Whether the parameter list contains a default expression, which is what gives
629 /// the function a second variable environment (see [`PARAM_SCOPE`]).
630 has_parameter_expressions: bool,
631 /// `IsSimpleParameterList`: every parameter is a plain binding identifier.
632 simple_parameter_list: bool,
633 /// Whether the instructions being emitted belong to the parameter list.
634 ///
635 /// References made here must not see the body's `var`s: the body has not run yet,
636 /// and the reference's own model keeps the two scopes apart.
637 in_params: bool,
638 /// Whether an arrow created in this function's parameter list needs the parameter
639 /// scope's `arguments` binding.
640 needs_param_arguments: bool,
641 /// Whether this function was *created* inside a parameter list.
642 ///
643 /// Inherited, so `f(a = () => () => c)` hides `f`'s body bindings from the inner
644 /// arrow too. The name reference is the arrow's, but the scope it must not see
645 /// belongs to the function the arrow was born in.
646 created_in_params: bool,
647 /// What each direct `eval(...)` in this function can see; see [`EvalSite`].
648 ///
649 /// Only filled in by [`Compiler::materialize_eval_sites`], because the answer is not
650 /// final while the body is still being compiled: a named function expression declares
651 /// its own name binding *after* the body, and that binding is exactly what
652 /// `eval("myfunc = 1")` has to find.
653 eval_sites: Vec<EvalSite>,
654 /// Direct `eval` call sites seen so far: where, and the block that was current.
655 pending_eval_sites: Vec<(Span, u64, bool, Vec<EvalPrivate>, bool)>,
656 /// Whether this body contains `await`.
657 ///
658 /// For a *module* this decides whether its body is an async function: top-level
659 /// `await` makes the whole graph's evaluation asynchronous, which is why the flag has
660 /// to survive to the compiled function rather than being a local of the compiler.
661 has_await: bool,
662 /// The module tables, when this body is a module.
663 ///
664 /// Only the top-level state ever has one: `export` and `import` are top-level
665 /// statements, so nothing nested can add to these tables.
666 module: Option<ModuleMeta>,
667 /// Whether the self-name prologue (`special_object 2` then the store) has been
668 /// emitted for this function.
669 ///
670 /// A *nested* function's lookup declares the binding early (see
671 /// [`resolve_slot`]), so `provide_self_name` cannot decide on its own whether the
672 /// prologue is still needed — the binding existing is not the same as it being
673 /// initialised.
674 self_name_initialized: bool,
675 /// Whether the code emitted so far leaves the program's result on the stack.
676 /// The reference tracks this for the hidden `<ret>` local of an eval script.
677 leaves_value: bool,
678 /// Statement nesting depth, used to tell top-level statements apart.
679 stmt_depth: u32,
680 /// Function declarations waiting to be instantiated at scope entry, as
681 /// (target slot, constant pool index). The reference emits these from
682 /// `instantiate_hoisted_definitions` rather than at the statement, because a
683 /// declaration is visible before it is reached.
684 hoisted: Vec<(u64, HoistTarget, u32)>,
685 /// Function declarations whose bodies are compiled only once the enclosing scope
686 /// has finished hoisting, as (owning block, declaration).
687 ///
688 /// Compiling a body at the declaration makes the result depend on source order: in
689 /// `function f(){ return t } var t`, `t` is not declared yet when `f` is compiled,
690 /// so the read resolved to a *global* instead of the enclosing `var`. Hoisting the
691 /// names first and the bodies second is what removes that dependence.
692 deferred_funcs: Vec<(u64, Box<ast::Function>)>,
693 /// The source position of the node being compiled. Every instruction emitted
694 /// takes it, which is how the position table that feeds stack traces is built.
695 cur_pos: Option<Position>,
696 /// One position per entry in `insns`, index-aligned.
697 insn_pos: Vec<Option<Position>>,
698}
699
700/// Where a hoisted function declaration is stored.
701#[derive(Debug, Clone)]
702enum HoistTarget {
703 Arg(u32),
704 Loc(u32),
705 /// A global, which the resolver looks up by name.
706 Global(String),
707}
708
709impl FnState {
710 /// Whether this function suspends: a generator or an async function.
711 ///
712 /// A suspending function's `return` is a `return_async` and its body starts with an
713 /// `initial_yield`, so almost every statement that touches control flow asks this.
714 fn is_suspending(&self) -> bool {
715 self.kind.is_generator() || self.kind.is_async()
716 }
717
718 fn new(name: impl Into<String>, kind: FunctionKind) -> FnState {
719 FnState {
720 span: None,
721 name: name.into(),
722 kind,
723 strict: false,
724 args: Vec::new(),
725 vars: Vec::new(),
726 closure_vars: Vec::new(),
727 cpool: Vec::new(),
728 atoms: Vec::new(),
729 blocks: Vec::new(),
730 current_block: 0,
731 created_in_block: NO_PARENT,
732 var_block: Vec::new(),
733 no_value: false,
734 label_since_insn: false,
735 discard_value: false,
736 body_block: 0,
737 block_heads: Vec::new(),
738 jump_targets: Vec::new(),
739 insns: Vec::new(),
740 labels: Vec::new(),
741 var_ref_count: 0,
742 line: 1,
743 column: 1,
744 is_script: false,
745 is_eval_body: false,
746 is_module: false,
747 is_arrow: false,
748 defined_args: 0,
749 param_prologue: Vec::new(),
750 ctor_kind: CtorKind::None,
751 class_ctor_pending: None,
752 needs_this_local: false,
753 needs_arguments_local: false,
754 needs_new_target_local: false,
755 has_this_prologue: false,
756 needs_home_object_local: false,
757 no_arguments_binding: false,
758 needs_active_func_local: false,
759 with_names: Vec::new(),
760 inherited_with_names: 0,
761 emitting_with_guard: false,
762 self_name: None,
763 has_direct_eval: false,
764 eval_can_declare: false,
765 body_start: (0, 0),
766 has_parameter_expressions: false,
767 simple_parameter_list: true,
768 in_params: false,
769 needs_param_arguments: false,
770 created_in_params: false,
771 eval_sites: Vec::new(),
772 pending_eval_sites: Vec::new(),
773 has_await: false,
774 module: None,
775 self_name_initialized: false,
776 leaves_value: false,
777 stmt_depth: 0,
778 hoisted: Vec::new(),
779 deferred_funcs: Vec::new(),
780 cur_pos: None,
781 insn_pos: Vec::new(),
782 }
783 }
784
785 /// The scope a declaration lands in: a script's top-level declarations are
786 /// globals, everything else gets a slot.
787 /// Whether a binding declared *now* becomes a property of the global object.
788 ///
789 /// For a script, a top-level `var` and the top-level `let`/`const` are globals.
790 /// The `var` case is decided by the keyword rather than by the cursor position:
791 /// `var` is function-scoped, so a `var i` in a `for` head is still the same
792 /// binding as a `var i` in the body, even though the head has its own block.
793 fn declares_globally(&self, def: &VarDef) -> bool {
794 // A module's top-level declarations are *module*-scoped: they live in the module
795 // record, never on the global object. Two modules can both declare `var x`
796 // without seeing each other, which is the whole point.
797 if self.is_module {
798 return false;
799 }
800 // An `eval` body's lexical declarations belong to the environment §19.2.1.3 creates
801 // for that one evaluation, so they stay locals of the eval's own frame. Its `var`s
802 // do declare globally here — the runtime moves them into the caller's variable
803 // environment — because the compiler cannot tell whether the caller has a function.
804 if self.is_eval_body && def.is_lexical {
805 return false;
806 }
807 self.is_script && (!def.is_lexical || self.current_block == self.body_block)
808 }
809}
810
811/// The compiler's entry point.
812pub struct Compiler {
813 /// The text being compiled, kept so each function can record its own slice for
814 /// `Function.prototype.toString`.
815 source: Option<String>,
816 module: bool,
817 /// Whether the program is an **`eval` body** rather than a script.
818 ///
819 /// §19.2.1.3 declares an eval's `let`/`const`/`class` in a fresh declarative environment
820 /// created for that one evaluation, so they must not reach the realm's global lexical
821 /// table: `eval("let x = 3")` leaves `x` unbound afterwards, and judging by
822 /// `typeof xNonStrict` is exactly what `eval-code/direct/lex-env-distinct-let` does.
823 /// The `var`s are a separate matter — those belong to the caller's variable environment,
824 /// which the *runtime* resolves.
825 eval_body: bool,
826 /// Whether the program itself is the body of an `async` function.
827 ///
828 /// This is the reference's `JS_EVAL_FLAG_ASYNC`: the body may `await`, and its
829 /// completion value is wrapped so a returned promise is not adopted.
830 async_body: bool,
831 /// Enclosing functions, outermost first. The last entry is the current one.
832 stack: Vec<FnState>,
833 /// The private names visible at this point, innermost class body last.
834 ///
835 /// A stack rather than a field of `FnState` because a private name is *lexically* scoped
836 /// to the class body: a method, an arrow inside it and a class nested inside that arrow
837 /// all resolve against the same entries, and the parser accepts exactly that set
838 /// (`self.private` in `parser.rs`). `FnState` is per-function, so it would lose the outer
839 /// class's names the moment a method started.
840 private_scopes: Vec<std::collections::HashMap<String, PrivateUse>>,
841 /// Whether the expression [`Compiler::expr`] is about to compile is the one its
842 /// statement asked to discard.
843 ///
844 /// `FnState::discard_value` says "the statement's value is thrown away", which is only
845 /// ever true of the statement's own expression — an assignment nested inside it, as in
846 /// `f(x = 1)`, has a value that is very much used. Clearing the flag on the way in and
847 /// keeping the answer here is what tells the two apart; without it the nested store
848 /// consumed its value, `call` took the callee as its argument, and `f(x = 1)` inside a
849 /// function threw `undefined is not a function`.
850 discard_root: bool,
851}
852
853/// How a use site of a private name compiles.
854///
855/// The four cases come straight from the reference's `JSVarKindEnum`: the binding holds a
856/// symbol for a field, a function for a method or getter, and nothing at all for the `#a` half
857/// of a setter-only accessor pair.
858#[derive(Clone, Copy, PartialEq, Eq)]
859enum PrivateKind {
860 /// `#x = 1`: an own property keyed by the symbol in the binding.
861 Field,
862 /// `#m() {}`: the binding holds the function; a use site brand-checks the receiver.
863 Method,
864 /// `get #a() {}`: the binding holds the getter, and a read calls it.
865 Getter,
866 /// `set #a(v) {}` with no getter: `#a` is declared but never filled, and reading it is
867 /// the same `TypeError` as reading an uninitialised `const`.
868 Setter,
869}
870
871/// What the compiler knows about one `#name` where it is used.
872#[derive(Clone)]
873struct PrivateUse {
874 kind: PrivateKind,
875 /// `#a<set>` when the class defines a setter for this name.
876 ///
877 /// A second binding, not a second field of the first: the reference stores the setter
878 /// closure under `#a<set>` (`get_private_setter_name`) and reads it back by that name.
879 setter: Option<String>,
880}
881
882/// The class-scope bindings one class body needs, in declaration order.
883#[derive(Default)]
884struct ClassPlan {
885 /// `#x`, `#m`, `#a`, `#a<set>`, `<computed_field>0`, … — everything declared in a `const`
886 /// at class entry, in member order.
887 bindings: Vec<String>,
888 /// The private names, for the use sites inside the body.
889 uses: std::collections::HashMap<String, PrivateUse>,
890 /// Computed field keys, by element index, so the emission pass does not have to redo the
891 /// per-half counter that names them.
892 computed: std::collections::HashMap<usize, String>,
893 /// Whether the instance initialiser has to add the brand to `this`.
894 instance_brand: bool,
895 /// Whether the constructor itself has to carry the brand.
896 static_brand: bool,
897}
898
899impl ClassPlan {
900 /// Walk a class body once and decide every class-scope binding it needs.
901 ///
902 /// Order is the reference's: a member's binding is created when the member is parsed, so
903 /// `class C { #m(){} #x = 1 }` declares `#m` before `#x`, and a setter adds `#a<set>`
904 /// immediately after `#a`. Getting this order wrong renumbers every slot in the class and
905 /// the disassembly stops matching even when every instruction is right.
906 fn build(class: &Class) -> ClassPlan {
907 let mut plan = ClassPlan::default();
908 let mut instance_keys = 0usize;
909 let mut static_keys = 0usize;
910 for (index, element) in class.elements.iter().enumerate() {
911 match element {
912 ClassElement::Method {
913 key: PropName::Private(ident),
914 kind,
915 is_static,
916 ..
917 } => {
918 let name = format!("#{}", ident.name);
919 let first = !plan.uses.contains_key(&name);
920 if first {
921 plan.bindings.push(name.clone());
922 plan.uses.insert(
923 name.clone(),
924 PrivateUse {
925 kind: match kind {
926 MethodKind::Get => PrivateKind::Getter,
927 MethodKind::Set => PrivateKind::Setter,
928 _ => PrivateKind::Method,
929 },
930 setter: None,
931 },
932 );
933 }
934 match kind {
935 MethodKind::Set => {
936 let binding = format!("{name}<set>");
937 plan.bindings.push(binding.clone());
938 if let Some(use_) = plan.uses.get_mut(&name) {
939 use_.setter = Some(binding);
940 }
941 }
942 // A getter is what makes the name readable, so a pair that started
943 // as a setter becomes readable once the getter arrives.
944 MethodKind::Get => {
945 if let Some(use_) = plan.uses.get_mut(&name) {
946 use_.kind = PrivateKind::Getter;
947 }
948 }
949 _ => {}
950 }
951 if *is_static {
952 plan.static_brand = true;
953 } else {
954 plan.instance_brand = true;
955 }
956 }
957 ClassElement::Method {
958 key: PropName::Computed(_),
959 ..
960 } => {}
961 ClassElement::Method { .. } => {}
962 ClassElement::Field {
963 key: PropName::Private(ident),
964 ..
965 } => {
966 let name = format!("#{}", ident.name);
967 if !plan.uses.contains_key(&name) {
968 plan.bindings.push(name.clone());
969 plan.uses.insert(
970 name,
971 PrivateUse {
972 kind: PrivateKind::Field,
973 setter: None,
974 },
975 );
976 }
977 }
978 ClassElement::Field {
979 key: PropName::Computed(_),
980 is_static,
981 ..
982 } => {
983 let index_in_half = if *is_static {
984 static_keys += 1;
985 static_keys - 1
986 } else {
987 instance_keys += 1;
988 instance_keys - 1
989 };
990 let binding = computed_field_binding(index_in_half, *is_static);
991 plan.bindings.push(binding.clone());
992 plan.computed.insert(index, binding);
993 }
994 ClassElement::Field { .. } | ClassElement::StaticBlock { .. } => {}
995 }
996 }
997 plan
998 }
999
1000 /// How a private name used inside the body compiles, or `None` if no enclosing class
1001 /// declares it.
1002 fn find<'a>(compiler: &'a Compiler, name: &str) -> Option<&'a PrivateUse> {
1003 compiler
1004 .private_scopes
1005 .iter()
1006 .rev()
1007 .find_map(|scope| scope.get(name))
1008 }
1009}
1010
1011impl Compiler {
1012 /// The exact source text of a function, for `Function.prototype.toString`.
1013 ///
1014 /// §20.2.3.5 requires the *original* text: a function must stringify back to what
1015 /// was written, comments and odd spacing included. Slicing the recorded span out of
1016 /// the whole source is the only way to get that — rebuilding it from the AST would
1017 /// normalise the text, and answering `[native code]` for a script function (which is
1018 /// what this engine used to do) makes the result useless for feature detection and
1019 /// for libraries that read their own source.
1020 ///
1021 /// Top-level bodies have no single expression span, so their `source` stays `None`
1022 /// and `toString` falls back to the calling convention the spec allows.
1023 fn function_source(
1024 &self,
1025 span: Option<(usize, usize)>,
1026 line: u32,
1027 column: u32,
1028 ) -> Option<String> {
1029 let source = self.source.as_ref()?;
1030 let span = span?;
1031 let bytes = source.as_bytes();
1032 let start = span.0;
1033 let end = span.1;
1034 if start >= bytes.len() || end > bytes.len() || start >= end {
1035 let _ = (line, column);
1036 return None;
1037 }
1038 Some(source.get(start..end)?.to_string())
1039 }
1040}
1041
1042/// Compile a script.
1043pub fn compile_script(program: &Program) -> Result<CompiledFunction, SyntaxError> {
1044 Compiler::new(false).compile(program)
1045}
1046
1047/// Compile a script, keeping its text so `Function.prototype.toString` can answer with
1048/// the original source.
1049///
1050/// The separate entry point rather than a parameter on [`compile_script`] because the
1051/// tests and the disassembler compile from an AST they built themselves and have no
1052/// source to give; they keep the `None` behaviour they already relied on.
1053pub fn compile_script_with_source(
1054 program: &Program,
1055 source: &str,
1056) -> Result<CompiledFunction, SyntaxError> {
1057 let mut compiler = Compiler::new(false);
1058 compiler.source = Some(source.to_string());
1059 compiler.compile(program)
1060}
1061
1062/// [`compile_script_with_source`] for a module.
1063pub fn compile_module_with_source(
1064 program: &Program,
1065 source: &str,
1066) -> Result<CompiledFunction, SyntaxError> {
1067 let mut compiler = Compiler::new(true);
1068 compiler.source = Some(source.to_string());
1069 compiler.compile(program)
1070}
1071
1072/// Compile a script whose top level is the body of an `async` function.
1073/// The body is an ordinary script in every other way — it still reports a completion value
1074/// — but the value is wrapped in `{value}` and the function's kind is `Async`, so running
1075/// it answers a promise instead of a value. The wrapper is what keeps that promise from
1076/// being *adopted*: `await 1` completes with `1`, and the reference resolves to
1077/// `{value: 1}` rather than to `1` — the same shape `std.evalScript(…, {async: true})`
1078/// documents.
1079pub fn compile_script_suspensible(program: &Program) -> Result<CompiledFunction, SyntaxError> {
1080 Compiler::for_suspensible_script().compile(program)
1081}
1082
1083/// Compile a module.
1084pub fn compile_module(program: &Program) -> Result<CompiledFunction, SyntaxError> {
1085 Compiler::new(true).compile(program)
1086}
1087
1088/// Compile a direct `eval` body that inherits private names from its caller.
1089///
1090/// `class C { #m = 44; f() { return eval("this.#m") } }` is legal — private names are
1091/// lexically scoped and the eval runs inside the caller's scope — but the names live in the
1092/// *call site's* compilation unit, so they have to be handed over. Seeding them as the
1093/// outermost private scope is what lets the eval resolve `#m` to the caller's binding: the
1094/// read compiles as an ordinary name lookup of `#m`, which at run time finds the caller's
1095/// slot through the same `eval`-scope machinery every other inherited name uses.
1096///
1097/// `suspensible` selects the `{async: true}` form (`std.evalScript(s, {async: true})`), whose
1098/// body may `await`.
1099pub fn compile_eval_with_private(
1100 program: &Program,
1101 private: &[EvalPrivate],
1102 suspensible: bool,
1103 eval_body: bool,
1104) -> Result<CompiledFunction, SyntaxError> {
1105 let mut compiler = if suspensible {
1106 let mut compiler = Compiler::new(false);
1107 compiler.async_body = true;
1108 compiler
1109 } else {
1110 Compiler::new(false)
1111 };
1112 // `evalScript` reaches this same function but evaluates a *global script*, whose
1113 // top-level `let` is a global lexical binding; only a real `eval` gets the
1114 // per-evaluation environment §19.2.1.3 creates.
1115 compiler.eval_body = eval_body;
1116 if !private.is_empty() {
1117 let scope: std::collections::HashMap<String, PrivateUse> = private
1118 .iter()
1119 .map(|entry| {
1120 (
1121 entry.name.clone(),
1122 PrivateUse {
1123 kind: match entry.kind {
1124 EvalPrivateKind::Field => PrivateKind::Field,
1125 EvalPrivateKind::Method => PrivateKind::Method,
1126 EvalPrivateKind::Getter => PrivateKind::Getter,
1127 EvalPrivateKind::Setter => PrivateKind::Setter,
1128 },
1129 setter: entry.setter.clone(),
1130 },
1131 )
1132 })
1133 .collect();
1134 compiler.private_scopes.push(scope);
1135 }
1136 compiler.compile(program)
1137}
1138
1139impl Compiler {
1140 /// Create a compiler.
1141 pub fn new(module: bool) -> Compiler {
1142 Compiler {
1143 source: None,
1144 module,
1145 eval_body: false,
1146 async_body: false,
1147 stack: Vec::new(),
1148 private_scopes: Vec::new(),
1149 discard_root: false,
1150 }
1151 }
1152
1153 /// Create a compiler for an `eval` body.
1154 /// Create a compiler for a script whose top level is an `async` function body.
1155 fn for_suspensible_script() -> Compiler {
1156 Compiler {
1157 source: None,
1158 module: false,
1159 eval_body: false,
1160 async_body: true,
1161 stack: Vec::new(),
1162 private_scopes: Vec::new(),
1163 discard_root: false,
1164 }
1165 }
1166
1167 /// Compile a whole program into its top-level function.
1168 pub fn compile(mut self, program: &Program) -> Result<CompiledFunction, SyntaxError> {
1169 let mut state = FnState::new("<eval>", FunctionKind::Normal);
1170 // A module body is *not* a script: it has no completion value, so no hidden
1171 // `<ret>` local and no `put_loc0` before each statement. What it shares with one
1172 // is having no `arguments` of its own and no receiver — see `is_module`.
1173 state.is_script = !self.module;
1174 state.is_module = self.module;
1175 state.is_eval_body = self.eval_body;
1176 if self.module {
1177 state.module = Some(ModuleMeta::default());
1178 }
1179 state.strict = program.strict || self.module;
1180 state.line = program.span.start.line;
1181 state.column = program.span.start.column;
1182 // Locals are numbered in declaration order; `<ret>` is always slot 0.
1183 //
1184 // `var_block` has to grow in step with `vars`: it is indexed by slot, so a
1185 // slot that only appears in one of the two arrays shifts every later
1186 // binding's block and silently loses the temporal-dead-zone marking for
1187 // the script's own blocks. A function frame has no `<ret>`, which is why
1188 // the misalignment only showed up at the top level.
1189 if !self.module {
1190 state.vars.push(VarDef::var("<ret>"));
1191 state.var_block.push(FUNCTION_SCOPE);
1192 }
1193 self.stack.push(state);
1194 // The body is its own scope, keyed by the position of the program.
1195 // The script body needs a key no statement can produce. Statement keys are
1196 // source offsets, and the program's own start offset is `0` — which is also
1197 // the offset of the first statement, so a top-level `{ let x }` or
1198 // `for (let i …)` used to share the body's block and lose its scope.
1199 let body_key = SCRIPT_BODY;
1200 self.push_block(body_key, NO_PARENT);
1201 self.state().body_block = body_key;
1202 // A module body opens with a re-entry guard. The host evaluates a module exactly
1203 // once, so the guard never fires in practice — but the reference emits it, and a
1204 // module function called a second time (through `eval` of its own source, say)
1205 // must not run its body again.
1206 let module_guard = self.module.then(|| self.new_label());
1207 if let Some(body) = module_guard {
1208 // The guard wraps the *hoisting* too: a second evaluation of the same module
1209 // body must not even re-create its function declarations.
1210 self.emit(Opcode::PushThis, &[]);
1211 self.emit_jump(Opcode::IfFalse, body, &[]);
1212 }
1213 self.hoist(&program.body, body_key)?;
1214 // The scope entry is what emits the hoisted `fclosure`/store pairs, so it has to
1215 // come before the guard's `return_undef`: the reference's jump target sits past
1216 // both, and a second evaluation therefore re-creates nothing.
1217 self.emit_scope_enter(body_key);
1218 if let Some(body) = module_guard {
1219 self.emit(Opcode::ReturnUndef, &[]);
1220 self.place_label(body);
1221 }
1222 // Through `stmts` rather than the loop, so a `using` region at the top level of an
1223 // eval'd body or a module gets its disposal epilogue like any other block.
1224 self.stmts(&program.body)?;
1225 if self.module {
1226 // A module has no completion value; its body simply ends.
1227 self.emit(Opcode::Undefined, &[]);
1228 self.emit(Opcode::ReturnAsync, &[]);
1229 // Top-level `await` makes the body an async function, so the host runs it as
1230 // a coroutine and waits. Without this the `await` opcode would suspend in a
1231 // body that nothing knows how to resume — which is what "a generator body ran
1232 // as an ordinary call" was reporting.
1233 if self.cur().has_await {
1234 self.state().kind = FunctionKind::Async;
1235 }
1236 } else if self.async_body {
1237 // An async body reports its completion value the same way, but through an
1238 // object: the function answers a promise, and resolving that promise *with*
1239 // the completion value would adopt a promise completion instead of reporting
1240 // it. `{value}` is what makes `evalScript("Promise.resolve(7)", {async:true})`
1241 // resolve to `{value: <promise>}` rather than to `7`.
1242 //
1243 // The shape is the reference's, byte for byte (`quickjs.c`: "wrap the return
1244 // value in an object so that promises can be safely returned").
1245 self.emit(Opcode::Object, &[]);
1246 self.emit(Opcode::Dup, &[]);
1247 self.emit(Opcode::GetLoc, &[Op::Slot(Slot::Loc(0))]);
1248 self.emit(Opcode::PutField, &[Op::Atom(Atom::from_text("value"))]);
1249 self.emit(Opcode::Return, &[]);
1250 self.state().kind = FunctionKind::Async;
1251 } else {
1252 // The program's value is whatever the last expression statement stored in
1253 // the hidden `<ret>` local; `put_loc0`/`get_loc0` folding turns the common
1254 // case into a single `set_loc0`.
1255 self.emit(Opcode::GetLoc, &[Op::Slot(Slot::Loc(0))]);
1256 self.emit(Opcode::Return, &[]);
1257 }
1258 Ok(self.finish_current())
1259 }
1260
1261 // -- emitting ----------------------------------------------------------
1262
1263 fn state(&mut self) -> &mut FnState {
1264 self.stack.last_mut().expect("a function is being compiled")
1265 }
1266
1267 fn cur(&self) -> &FnState {
1268 self.stack.last().expect("a function is being compiled")
1269 }
1270
1271 fn emit(&mut self, op: Opcode, operands: &[Op]) {
1272 self.state().label_since_insn = false;
1273 let pos = self.cur().cur_pos;
1274 self.state().insns.push(Insn::Fixed {
1275 op,
1276 operands: operands.to_vec(),
1277 });
1278 self.state().insn_pos.push(pos);
1279 }
1280
1281 /// Reset the script's hidden return value to `undefined`.
1282 ///
1283 /// Called at the start of every statement that does not itself produce the
1284 /// program's value, which is how the reference keeps `if`/loop results from
1285 /// leaking into an eval result.
1286 fn reset_value(&mut self) {
1287 if !self.cur().is_script {
1288 return;
1289 }
1290 self.emit(Opcode::Undefined, &[]);
1291 self.emit(Opcode::PutLoc, &[Op::Slot(Slot::Loc(0))]);
1292 self.state().leaves_value = false;
1293 }
1294
1295 /// Whether `name` is a local or argument slot rather than a global.
1296 fn is_slot(&self, name: &str) -> bool {
1297 self.cur().vars.iter().any(|v| v.name == name)
1298 || self.cur().args.iter().any(|a| a.name == name)
1299 }
1300
1301 /// `with (object) body`
1302 ///
1303 /// The boxed object lives in a hidden local marked [`VarKind::With`]. A local is
1304 /// what makes the object reachable from a closure created inside the block, and it
1305 /// is also what lets an `eval` find it: the runtime collects the active `With`
1306 /// locals of every frame and resolves names against them before the realm.
1307 ///
1308 /// Inside the block every name reference is spelled as "look in the with objects
1309 /// first", innermost outwards, and falls through to the ordinary access. The test is
1310 /// `in`, which is `HasProperty` — the same question the spec's Object Environment
1311 /// Record asks.
1312 fn with_stmt(&mut self, object: &Expr, body: &Stmt) -> Result<(), SyntaxError> {
1313 // `with (e) s` completes with `UpdateEmpty(s, undefined)` — an *empty* body still
1314 // produces `undefined`, it does not inherit the previous statement's value. So
1315 // `eval("1; with({}){}")` is `undefined` while `eval("1; with({}){2;}")` is `2`.
1316 // Without this the sticky `<ret>` local leaked the `1` through, the same way it
1317 // would for an `if` or a loop.
1318 self.reset_value();
1319 let name = self.next_with_name();
1320 // The object expression is evaluated *outside* the scope it introduces, so no
1321 // wrapper may be emitted for the names it mentions.
1322 let saved = std::mem::take(&mut self.state().with_names);
1323 self.expr(object)?;
1324 self.state().with_names = saved;
1325 self.emit(Opcode::ToObject, &[]);
1326 self.declare_hidden_local(&name, VarKind::With);
1327 // Pushed before the store so the store itself is not guarded by an *outer*
1328 // `with` — the object being stored is the new one, not something to look up.
1329 self.state().with_names.push(name.clone());
1330 self.emit_var(VarAction::Put, &name);
1331 let result = self.stmt(body);
1332 self.state().with_names.pop();
1333 result
1334 }
1335
1336 /// A hidden-local name for one `with` block, distinct from every enclosing one.
1337 fn next_with_name(&self) -> String {
1338 let depth = self.cur().with_names.len();
1339 if depth == 0 {
1340 "<with>".to_string()
1341 } else {
1342 format!("<with{depth}>")
1343 }
1344 }
1345
1346 /// Declare a hidden local that must stay a *local* even in a script.
1347 ///
1348 /// A script's `var` is a property of the global object, but the `with` object is not
1349 /// part of the source program's name space at all — it only exists for the compiler
1350 /// and the runtime — so it goes straight into the frame's slot list.
1351 fn declare_hidden_local(&mut self, name: &str, kind: VarKind) {
1352 let state = self.state();
1353 if state.vars.iter().any(|v| v.name == name) {
1354 return;
1355 }
1356 state.var_block.push(FUNCTION_SCOPE);
1357 state.vars.push(VarDef {
1358 kind,
1359 ..VarDef::var(name)
1360 });
1361 }
1362
1363 /// Emit a name access, guarded by every active `with` object.
1364 ///
1365 /// Each guard is `get_loc <with>; push_atom_value name; in; if_false <next>` and then
1366 /// the read itself; the outer guards and the plain access are what the `if_false`
1367 /// jumps to, so the innermost object wins.
1368 fn emit_with_guarded(&mut self, action: VarAction, name: &str) {
1369 let names = self.visible_with_names(name);
1370 let done = self.new_label();
1371 let mut starts = Vec::new();
1372 // Innermost object first: the last `with` opened is the one that shadows the
1373 // others, so its guard has to be the first chance to satisfy the name.
1374 for with_name in names.iter().rev() {
1375 let next = self.new_label();
1376 // `with_has_var` takes the object and carries the name as an atom. It is not
1377 // `in`: an Object Environment Record also consults `Symbol.unscopables`, so
1378 // `globalThis[Symbol.unscopables] = {v: true}` leaves `v` to the outer scope.
1379 self.emit_var(VarAction::Get, with_name);
1380 self.emit(Opcode::WithHasVar, &[Op::Atom(Atom::from_text(name))]);
1381 self.emit_jump(Opcode::IfFalse, next, &[]);
1382 starts.push(next);
1383 // The operation is `with_get_var`/`with_put_var`, not a plain property access:
1384 // `GetBindingValue`/`SetMutableBinding` ask `HasProperty` **again** before
1385 // getting or setting. That second question is observable — a proxy's `has`
1386 // trap runs one more time (`get-binding-value-call-with-proxy-env` logs
1387 // `has, get unscopables, has, get`) and an `unscopables` getter that deletes
1388 // the property leaves a binding that has gone, which strict code must report
1389 // as a `ReferenceError` rather than write to.
1390 match action {
1391 // A store already has its value on the stack, and `with_put_var` takes the
1392 // pair in `put_field`'s order: object first, then the value.
1393 VarAction::Put | VarAction::PutInit => {
1394 self.emit_var(VarAction::Get, with_name);
1395 self.emit(Opcode::Swap, &[]);
1396 self.emit(Opcode::WithPutVar, &[Op::Atom(Atom::from_text(name))]);
1397 }
1398 _ => {
1399 self.emit_var(VarAction::Get, with_name);
1400 self.emit(Opcode::WithGetVar, &[Op::Atom(Atom::from_text(name))]);
1401 }
1402 }
1403 self.emit_jump(Opcode::Goto, done, &[]);
1404 self.place_label(next);
1405 }
1406 self.emit_var(action, name);
1407 self.place_label(done);
1408 }
1409
1410 /// The `with` blocks that can shadow `name`, innermost last.
1411 ///
1412 /// A parameter or a local of this function is *inside* every `with` this function
1413 /// opened, so those shadow it; a `with` that was already open when this function was
1414 /// created is outside the function's own environment, so the local wins and that
1415 /// block is skipped. See [`FnState::inherited_with_names`].
1416 fn visible_with_names(&self, name: &str) -> Vec<String> {
1417 let state = self.cur();
1418 // The hidden `<with…>` locals are how the guard reaches its own objects, so they
1419 // must never be guarded themselves — not by their own block (which would recurse)
1420 // and not by an enclosing one (which would ask a `with` object whether it has a
1421 // property called `<with>`, always answer no, and waste the chain). Source can
1422 // never spell these names, so exempting all of them changes nothing else.
1423 if state.with_names.iter().any(|hidden| hidden == name) {
1424 return Vec::new();
1425 }
1426 let start = if self.is_slot(name) {
1427 state.inherited_with_names
1428 } else {
1429 0
1430 };
1431 state.with_names[start..]
1432 .iter()
1433 .filter(|hidden| hidden.as_str() != name)
1434 .cloned()
1435 .collect()
1436 }
1437
1438 /// Compile `x` as a **reference** to the with object's property, resolving the object
1439 /// once for the whole read-modify-write.
1440 ///
1441 /// `x += 1`, `x++` and `x ||= v` read and then write the same name. Two independent
1442 /// guards get that wrong the moment the read changes the answer: with
1443 /// `{ get x(){ delete this.x; return 2 } }`, `with (o) { x++ }` reads through the
1444 /// getter — which removes the property — and then the write's own guard no longer
1445 /// finds it, so the store landed on the *global* `x` and `o.x` stayed `undefined`. The
1446 /// reference resolves the base once (`with_make_ref`) and reuses it for both halves.
1447 ///
1448 /// The same shape comes out of compiling the name as a **member** of the with object:
1449 /// `get_field2`/`put_field` already evaluate their receiver once, and the hidden
1450 /// `<with>` local holds exactly the object the guard just tested. So each candidate
1451 /// object gets `if the name is bound here, compile as `this.name`; otherwise fall
1452 /// through to the next object`, and the last fallback is the ordinary name.
1453 fn with_reference(
1454 &mut self,
1455 name: &str,
1456 guarded: &mut dyn FnMut(&mut Self, &str) -> Result<(), SyntaxError>,
1457 plain: &mut dyn FnMut(&mut Self) -> Result<(), SyntaxError>,
1458 ) -> Result<(), SyntaxError> {
1459 let targets = self.visible_with_names(name);
1460 if targets.is_empty() {
1461 return plain(self);
1462 }
1463 let done = self.new_label();
1464 let result = self.with_reference_inner(name, &targets, guarded, plain, done);
1465 self.place_label(done);
1466 result
1467 }
1468
1469 fn with_reference_inner(
1470 &mut self,
1471 name: &str,
1472 targets: &[String],
1473 guarded: &mut dyn FnMut(&mut Self, &str) -> Result<(), SyntaxError>,
1474 plain: &mut dyn FnMut(&mut Self) -> Result<(), SyntaxError>,
1475 done: Label,
1476 ) -> Result<(), SyntaxError> {
1477 let Some((innermost, outer)) = targets.split_last() else {
1478 return plain(self);
1479 };
1480 let next = self.new_label();
1481 self.emit_var(VarAction::Get, innermost);
1482 self.emit(Opcode::WithHasVar, &[Op::Atom(Atom::from_text(name))]);
1483 self.emit_jump(Opcode::IfFalse, next, &[]);
1484 guarded(self, innermost)?;
1485 self.emit_jump(Opcode::Goto, done, &[]);
1486 self.place_label(next);
1487 self.with_reference_inner(name, outer, guarded, plain, done)
1488 }
1489
1490 /// `delete name`, honouring any enclosing `with`.
1491 ///
1492 /// Inside a `with` the name may be a property of the with object, and then `delete`
1493 /// removes *that* property instead of touching the outer binding —
1494 /// `with (o) { delete p }` answers `true` and leaves `o` without `p` even when a
1495 /// global `p` exists. Left to the resolver it deleted the global instead, so the
1496 /// `statements/with/S12.10_A1.*` family then saw a `ReferenceError` on every later
1497 /// `p`.
1498 ///
1499 /// Emitted as a sequence here rather than during resolution because a resolution slot
1500 /// holds one instruction, and this is a loop over the with objects plus a fallback.
1501 fn delete_ident(&mut self, name: &str) {
1502 let names = self.cur().with_names.clone();
1503 let done = self.new_label();
1504 let mut starts = Vec::new();
1505 if !names.is_empty() {
1506 self.state().emitting_with_guard = true;
1507 // Innermost object first, like the read/write guard: the last `with` opened is
1508 // the one that shadows the others.
1509 for with_name in names.iter().rev() {
1510 let next = self.new_label();
1511 self.emit_var(VarAction::Get, with_name);
1512 self.emit(Opcode::WithHasVar, &[Op::Atom(Atom::from_text(name))]);
1513 self.emit_jump(Opcode::IfFalse, next, &[]);
1514 // `delete` takes the receiver then the key.
1515 self.emit_var(VarAction::Get, with_name);
1516 self.emit(Opcode::PushAtomValue, &[Op::Atom(Atom::from_text(name))]);
1517 self.emit(Opcode::Delete, &[]);
1518 self.emit_jump(Opcode::Goto, done, &[]);
1519 self.place_label(next);
1520 starts.push(next);
1521 }
1522 self.state().emitting_with_guard = false;
1523 }
1524 // The fallback: not a property of any with object, so the ordinary rule applies.
1525 let pos = self.cur().cur_pos;
1526 self.state().insns.push(Insn::DeleteVar {
1527 name: name.to_string(),
1528 });
1529 self.state().insn_pos.push(pos);
1530 if !names.is_empty() {
1531 self.place_label(done);
1532 }
1533 }
1534
1535 fn emit_var(&mut self, action: VarAction, name: &str) {
1536 // Peephole: `put_x v` followed by `get_x v` becomes `set_x v`, which
1537 // stores and keeps the value in one instruction. The reference does this
1538 // in a post-pass; folding it at emit time keeps instruction indices
1539 // stable, which matters because labels are recorded as indices.
1540 //
1541 // Only slots have a `set_` form: a global is stored with `put_var` and
1542 // read with `get_var`, and the reference does not fold those.
1543 //
1544 // A label between the two cancels the fold. `set_x v` leaves the value on
1545 // the stack, which is only equivalent when the read immediately follows the
1546 // store; when a jump target sits in between, the store must *consume* the
1547 // value and the read must fetch it afresh. A loop head is exactly that
1548 // case — `for (var i = 0; i < 3; i++)` stores the initialiser, then the
1549 // condition re-reads it — and folding across the label would make the
1550 // condition compare whatever the previous iteration left on the stack.
1551 if action == VarAction::Get {
1552 let is_slot = self.is_slot(name);
1553 let at_label = std::mem::take(&mut self.state().label_since_insn);
1554 //
1555 // `arguments` is excluded because the reference treats it as a special
1556 // binding: it is initialised once and read many times, and folding its
1557 // initialisation into a `set_` would leave the object on the stack where
1558 // the reference leaves nothing.
1559 if is_slot
1560 && name != "arguments"
1561 && !at_label
1562 && let Some(Insn::Var {
1563 action: previous,
1564 name: previous_name,
1565 ..
1566 }) = self.state().insns.last_mut()
1567 && *previous == VarAction::Put
1568 && previous_name == name
1569 {
1570 *previous = VarAction::Set;
1571 return;
1572 }
1573 }
1574 // Inside a `with`, every name lookup consults the with objects first. Two names
1575 // are exempt:
1576 //
1577 // * the hidden `<with…>` locals themselves, or the guard would recurse;
1578 // * a name this function **declares** — a parameter, a `var`, or a `let` of the
1579 // current body. `with` sits *outside* the function's own environment, so a
1580 // function declared inside a `with` still resolves its own bindings first:
1581 // `with (o) { function f(){ var value = "x" } }` writes `f`'s local `value`, not
1582 // `o.value`. Guarding it anyway wrote through to the with object whenever it
1583 // happened to have the name, which is why
1584 // `statements/with/S12.10_A1.7` saw `myObj.value` change. The runtime's
1585 // `eval_binding_value` already models the same order.
1586 let guarded = !self.visible_with_names(name).is_empty()
1587 && matches!(action, VarAction::Get | VarAction::Put | VarAction::PutInit)
1588 && !self.state().emitting_with_guard;
1589 if guarded {
1590 self.state().emitting_with_guard = true;
1591 self.emit_with_guarded(action, name);
1592 self.state().emitting_with_guard = false;
1593 return;
1594 }
1595 let block = self.cur().current_block;
1596 self.state().label_since_insn = false;
1597 let pos = self.cur().cur_pos;
1598 let in_params = self.cur().in_params;
1599 self.state().insns.push(Insn::Var {
1600 action,
1601 name: name.to_string(),
1602 block,
1603 in_params,
1604 });
1605 self.state().insn_pos.push(pos);
1606 }
1607
1608 fn new_label(&mut self) -> Label {
1609 let state = self.state();
1610 state.labels.push(None);
1611 Label(state.labels.len() as u32 - 1)
1612 }
1613
1614 fn place_label(&mut self, label: Label) {
1615 let index = self.cur().insns.len();
1616 self.state().label_since_insn = true;
1617 self.state().labels[label.0 as usize] = Some(index);
1618 }
1619
1620 fn emit_jump(&mut self, op: Opcode, label: Label, extra: &[Op]) {
1621 let mut operands = vec![Op::Label(label)];
1622 operands.extend_from_slice(extra);
1623 self.emit(op, &operands);
1624 }
1625
1626 // -- scopes ------------------------------------------------------------
1627
1628 /// Start a new lexical scope inside `parent`.
1629 fn push_block(&mut self, key: u64, parent: u64) {
1630 let state = self.state();
1631 if !state.blocks.iter().any(|b| b.key == key) {
1632 state.blocks.push(Block { key, parent });
1633 }
1634 state.current_block = key;
1635 }
1636
1637 /// Emit the code that runs when a lexical scope is entered.
1638 ///
1639 /// Every `let`/`const`/`class` binding starts out in the temporal dead zone,
1640 /// so entering its block marks it uninitialised. Hoisted function
1641 /// declarations are created here instead, which is why a call before the
1642 /// declaration still works.
1643 ///
1644 /// The order is not obvious: bindings are emitted in *reverse* declaration
1645 /// order, because the reference walks its scope chain, which is built by
1646 /// prepending.
1647 fn emit_scope_enter(&mut self, block: u64) {
1648 // Only *this* scope's hoisted declarations are consumed here; the rest stay in the
1649 // list for the scope that owns them. `std::mem::take` used to empty the whole list,
1650 // so entering an outer scope threw away every nested block's function
1651 // declarations: `function h(){ { function k(){} } return k; }` answered
1652 // `undefined`, and `{ function g(){} }` was `undefined` even *inside* the block.
1653 // That is one Annex B rule the engine otherwise implements (a sloppy-mode function
1654 // in a block is also a `var` of the enclosing function), and it is what makes the
1655 // `for (const ctor of ctors) { function f(){} … }` shape in test262 work.
1656 let mut hoisted = std::mem::take(&mut self.state().hoisted);
1657 let mut rest = Vec::with_capacity(hoisted.len());
1658 let mut mine: Vec<(HoistTarget, u32)> = Vec::new();
1659 for (owner, target, pool_index) in hoisted.drain(..) {
1660 if owner == block {
1661 mine.push((target, pool_index));
1662 } else {
1663 rest.push((owner, target, pool_index));
1664 }
1665 }
1666 self.state().hoisted = rest;
1667 mine.sort_by_key(|(target, _)| match target {
1668 HoistTarget::Arg(index) | HoistTarget::Loc(index) => *index,
1669 HoistTarget::Global(_) => u32::MAX,
1670 });
1671 for (target, pool_index) in mine {
1672 self.emit(Opcode::Fclosure, &[Op::Const(pool_index)]);
1673 match target {
1674 HoistTarget::Arg(index) => self.emit(Opcode::PutArg, &[Op::Slot(Slot::Arg(index))]),
1675 HoistTarget::Loc(index) => self.emit(Opcode::PutLoc, &[Op::Slot(Slot::Loc(index))]),
1676 HoistTarget::Global(name) => {
1677 // A global binding lives in a reference cell, so the store
1678 // goes through `put_var_ref` while reads use `get_var`.
1679 let block = self.cur().current_block;
1680 let pos = self.cur().cur_pos;
1681 let in_params = self.cur().in_params;
1682 self.state().insns.push(Insn::Var {
1683 action: VarAction::PutRef,
1684 name,
1685 block,
1686 in_params,
1687 });
1688 self.state().insn_pos.push(pos);
1689 }
1690 }
1691 }
1692 for index in self.block_vars_reversed(block) {
1693 self.emit(
1694 Opcode::SetLocUninitialized,
1695 &[Op::Slot(Slot::Loc(index as u32))],
1696 );
1697 }
1698 }
1699
1700 /// Emit the code that runs when a lexical scope is exited.
1701 ///
1702 /// A captured binding has to be closed: detaching its reference cell freezes
1703 /// the value the binding had when the block ended, which is what a closure
1704 /// created inside the block must keep seeing.
1705 fn emit_scope_leave(&mut self, block: u64) {
1706 for index in self.block_vars_reversed(block) {
1707 if self.cur().vars[index].is_captured {
1708 self.emit(Opcode::CloseLoc, &[Op::Slot(Slot::Loc(index as u32))]);
1709 }
1710 }
1711 }
1712
1713 /// Locals declared in `block`, in reverse declaration order.
1714 fn block_vars_reversed(&self, block: u64) -> Vec<usize> {
1715 let state = self.cur();
1716 let mut out: Vec<usize> = (0..state.vars.len())
1717 .filter(|index| {
1718 state.var_block.get(*index).copied() == Some(block)
1719 && state.vars[*index].is_lexical
1720 // A derived constructor's `this` is lexical but is not initialised by
1721 // entering the scope: `check_ctor` proves it, so its dead-zone marker
1722 // was emitted with the constructor's own prologue.
1723 && state.vars[*index].name != "this"
1724 })
1725 .collect();
1726 out.reverse();
1727 out
1728 }
1729
1730 /// Declare a local, even at the top level of a script.
1731 ///
1732 /// A `catch` parameter is always a local: the reference puts it in the
1733 /// function's own variable list (`1: catch e`), never in the global object,
1734 /// because it only exists while the handler runs.
1735 fn declare_local(&mut self, _name: &str, def: VarDef) -> u32 {
1736 let state = self.state();
1737 let index = state.vars.len() as u32;
1738 // A `catch` parameter belongs to a scope even though it is not lexical: the
1739 // runtime instantiates it per handler entry, but it never sits in the
1740 // temporal dead zone.
1741 let block = if def.is_lexical || def.kind == crate::bytecode::VarKind::Catch {
1742 state.current_block
1743 } else {
1744 0
1745 };
1746 state.var_block.push(block);
1747 state.vars.push(def);
1748 index
1749 }
1750
1751 fn declare(&mut self, name: &str, def: VarDef) -> u32 {
1752 if self.cur().is_module
1753 && self.cur().current_block == self.cur().body_block
1754 && !matches!(def.kind, VarKind::Using | VarKind::UsingMethod)
1755 {
1756 // Only the body's own block: a `let` inside a module-level `{}` is still an
1757 // ordinary local of that block, not a module variable.
1758 //
1759 // A `using` binding is excluded on purpose, and the reference excludes it in
1760 // the same place (`var_def_type != JS_VAR_DEF_USING`, with the comment
1761 // "'using' variables are currently not exported in modules"): a module-level
1762 // `using` is an ordinary *local* of the module body function, not a module
1763 // cell. Two things follow, and both are what the reference does — `export {a}`
1764 // of a `using` binding is "exported variable 'a' does not exist", and
1765 // disposal works, because the disposal epilogue addresses locals by slot.
1766 //
1767 // The hidden dispose-method variable is excluded for a stronger reason: it is
1768 // *always* a local (`add_scope_var` in the reference), and it must sit
1769 // immediately after its value so `using_dispose` can find it at `slot + 1`.
1770 return self.declare_module(name, &def);
1771 }
1772 if self.cur().declares_globally(&def) {
1773 self.declare_global(name, &def);
1774 return 0;
1775 }
1776 let state = self.state();
1777 let index = state.vars.len() as u32;
1778 let block = if def.is_lexical {
1779 state.current_block
1780 } else {
1781 0
1782 };
1783 state.var_block.push(block);
1784 state.vars.push(def);
1785 index
1786 }
1787
1788 /// Declare a `using` binding and its cached dispose method, returning both slots.
1789 ///
1790 /// The two are adjacent by construction, because `using_dispose` addresses the pair as
1791 /// `(value, value + 1)` — the reference does the same and documents the constraint.
1792 fn declare_using(&mut self, name: &str) -> (u32, u32) {
1793 let mut def = VarDef::lexical(name);
1794 def.kind = VarKind::Using;
1795 // A `using` binding is immutable, exactly like a `const`: assigning to one is a
1796 // `TypeError` at run time, which is what `using-invalid-assignment-*-for` assert.
1797 // `VarDef::lexical` leaves `is_const` false, so the store would have landed.
1798 def.is_const = true;
1799 let value = self.declare(name, def);
1800 let mut method = VarDef::lexical(using_method_name(name));
1801 method.kind = VarKind::UsingMethod;
1802 let method_slot = self.declare(&using_method_name(name), method);
1803 (value, method_slot)
1804 }
1805
1806 /// The slot a `using` binding's dispose method lives in.
1807 fn using_method_slot(&self, name: &str) -> Option<u32> {
1808 let hidden = using_method_name(name);
1809 self.cur()
1810 .vars
1811 .iter()
1812 .position(|var| var.name == hidden)
1813 .map(|index| index as u32)
1814 }
1815
1816 // -- statements --------------------------------------------------------
1817
1818 fn stmt(&mut self, stmt: &Stmt) -> Result<(), SyntaxError> {
1819 self.stmt_labelled(stmt, &[])
1820 }
1821
1822 /// Compile a statement that a chain of labels names.
1823 ///
1824 /// Only a loop consumes `labels`; every other statement ignores them (the
1825 /// parser has already rejected a label on a statement that cannot use it).
1826 fn stmt_labelled(&mut self, stmt: &Stmt, labels: &[String]) -> Result<(), SyntaxError> {
1827 // Only a *top-level* expression statement supplies the program's value.
1828 let saved = self.cur().leaves_value;
1829 self.state().leaves_value =
1830 matches!(stmt.kind, StmtKind::Expr(_)) && self.cur().stmt_depth == 0;
1831 self.state().stmt_depth += 1;
1832 let result = self.stmt_inner(stmt, labels);
1833 self.state().stmt_depth -= 1;
1834 // A nested statement never contributes the program's value, so the flag
1835 // the wrapper set above is what survives.
1836 let produced = self.cur().leaves_value && self.cur().stmt_depth == 0;
1837 self.state().leaves_value = produced;
1838 let _ = saved;
1839 result
1840 }
1841
1842 fn stmt_inner(&mut self, stmt: &Stmt, labels: &[String]) -> Result<(), SyntaxError> {
1843 match &stmt.kind {
1844 StmtKind::Empty | StmtKind::Debugger => {}
1845 StmtKind::Expr(expr) => {
1846 // The statement's first token is a position the reference records: an
1847 // expression statement is the `hasexpr:` arm of `js_parse_statement`,
1848 // which calls `emit_source_pos(s, s->token.ptr)` before parsing it. That
1849 // is why an error from a construct with no position of its own (`[...it]`
1850 // with a throwing iterator, `` `${x}` ``) reports the statement's start.
1851 let saved = self.cur().cur_pos;
1852 self.state().cur_pos = Some(expr.span.start);
1853 // An expression statement's value is thrown away — except in a
1854 // script, where it becomes the program's result. `assign` reads this
1855 // and clears it, so a nested assignment still produces a value.
1856 self.state().discard_value = !self.cur().is_script;
1857 let result = self.expr(expr);
1858 self.state().discard_value = false;
1859 result?;
1860 if std::mem::take(&mut self.state().no_value) {
1861 // A store whose value was discarded left nothing to drop.
1862 } else if self.cur().is_script {
1863 // The program's value lands in the hidden `<ret>` local.
1864 self.emit(Opcode::PutLoc, &[Op::Slot(Slot::Loc(0))]);
1865 } else {
1866 self.emit(Opcode::Drop, &[]);
1867 }
1868 // Restored last: the trailing `drop` is part of the statement, and in the
1869 // reference it simply inherits whatever the expression last recorded.
1870 self.state().cur_pos = saved;
1871 }
1872 StmtKind::Block(body) => {
1873 // The block's declarations were hoisted with its enclosing
1874 // statement list, so there is nothing left to declare here.
1875 let key = stmt.span.start.offset as u64;
1876 let parent = self.cur().current_block;
1877 self.push_block(key, parent);
1878 self.emit_scope_enter(key);
1879 // A block is where a `using` region lives, so its statements have to go
1880 // through `stmts`: that is what emits the disposal epilogue.
1881 self.stmts(body)?;
1882 self.emit_scope_leave(key);
1883 self.state().current_block = parent;
1884 }
1885 StmtKind::VarDecl(decl) => self.var_decl(decl)?,
1886 // A function declaration was already instantiated when its scope was
1887 // entered, so the statement itself emits nothing.
1888 StmtKind::FuncDecl(_) => {}
1889 StmtKind::If { test, cons, alt } => {
1890 self.reset_value();
1891 let else_label = self.new_label();
1892 let end_label = self.new_label();
1893 self.expr(test)?;
1894 self.emit_jump(Opcode::IfFalse, else_label, &[]);
1895 self.stmt(cons)?;
1896 if alt.is_some() {
1897 self.emit_jump(Opcode::Goto, end_label, &[]);
1898 }
1899 self.place_label(else_label);
1900 if let Some(alt) = alt {
1901 self.stmt(alt)?;
1902 self.place_label(end_label);
1903 }
1904 }
1905 StmtKind::While { test, body } => {
1906 self.reset_value();
1907 let top = self.new_label();
1908 let end = self.new_label();
1909 self.place_label(top);
1910 self.expr(test)?;
1911 // The condition's false branch and `break` share one target,
1912 // which is why a `while` loop needs only one end label.
1913 self.emit_jump(Opcode::IfFalse, end, &[]);
1914 self.loop_body(body, labels, top, end)?;
1915 self.emit_jump(Opcode::Goto, top, &[]);
1916 self.place_label(end);
1917 }
1918 StmtKind::DoWhile { body, test } => {
1919 self.reset_value();
1920 let top = self.new_label();
1921 let cont = self.new_label();
1922 let end = self.new_label();
1923 self.place_label(top);
1924 // `continue` in a `do…while` runs the test, so it lands on `cont`
1925 // rather than on the loop head.
1926 self.loop_body(body, labels, cont, end)?;
1927 self.place_label(cont);
1928 self.expr(test)?;
1929 self.emit_jump(Opcode::IfTrue, top, &[]);
1930 self.place_label(end);
1931 }
1932 StmtKind::For {
1933 init,
1934 test,
1935 update,
1936 body,
1937 } => {
1938 self.reset_value();
1939 let for_key = stmt.span.start.offset as u64;
1940 let for_parent = self.cur().current_block;
1941 self.push_block(for_key, for_parent);
1942 self.emit_scope_enter(for_key);
1943 let mut using_head = None;
1944 if let Some(init) = init {
1945 match init {
1946 ForInit::VarDecl(decl) if decl.kind.is_using() => {
1947 // A `using` resource declared in the head lives until the whole
1948 // statement ends, not one iteration, so the disposal region has
1949 // to wrap the loop — and there may be several of them, each
1950 // needing its own region so that a later initialiser that
1951 // throws still disposes the earlier resources
1952 // (`initializer-disposed-if-subsequent-initializer-throws-in-forstatement-head`).
1953 using_head = Some(decl);
1954 }
1955 ForInit::VarDecl(decl) => {
1956 self.var_decl(decl)?;
1957 }
1958 ForInit::Expr(expr) => {
1959 // The head's value is discarded. Saying so lets an
1960 // assignment store with `put` instead of `dup`+`put`, which
1961 // is what the reference emits — and the difference matters:
1962 // a `dup`/`drop` pair around the store gives the peephole a
1963 // chance to fold the store into the *condition's* read.
1964 self.state().discard_value = true;
1965 let result = self.expr(expr);
1966 self.state().discard_value = false;
1967 result?;
1968 if !std::mem::take(&mut self.state().no_value) {
1969 self.emit(Opcode::Drop, &[]);
1970 }
1971 }
1972 }
1973 }
1974 // A `using` head's resource is disposed when the statement ends, on every
1975 // way out: `break`, `return`, an exception, and reaching the end.
1976 let flow = match using_head {
1977 Some(decl) => self.for_using_head(
1978 decl, 0, init, test, update, body, labels, for_key, for_parent,
1979 ),
1980 None => {
1981 self.for_loop_tail(init, test, update, body, labels, for_key, for_parent)
1982 }
1983 };
1984 flow?;
1985 }
1986 StmtKind::Return(value) => self.return_stmt(value.as_deref())?,
1987 StmtKind::Throw(expr) => {
1988 self.expr(expr)?;
1989 self.emit(Opcode::Throw, &[]);
1990 }
1991 StmtKind::Break(_) | StmtKind::Continue(_) => {
1992 // Labels and loops are wired up in a later milestone; a bare
1993 // break/continue jumps to the innermost enclosing target, which
1994 // the loop helpers register.
1995 self.control_transfer(stmt)?;
1996 }
1997 StmtKind::Labeled { label, body } => {
1998 self.labeled(label, body, stmt)?;
1999 }
2000 StmtKind::Switch {
2001 discriminant,
2002 cases,
2003 } => {
2004 self.switch(discriminant, cases, stmt)?;
2005 }
2006 StmtKind::Try {
2007 block,
2008 handler,
2009 finalizer,
2010 } => {
2011 self.try_stmt(stmt, block, handler, finalizer.as_deref())?;
2012 }
2013 StmtKind::ForIn { left, right, body } => {
2014 self.for_in_of(stmt, left, right, body, ForLoopKind::In, labels)?;
2015 }
2016 StmtKind::ForOf {
2017 left,
2018 right,
2019 body,
2020 is_await,
2021 } => {
2022 let kind = if *is_await {
2023 ForLoopKind::AwaitOf
2024 } else {
2025 ForLoopKind::Of
2026 };
2027 self.for_in_of(stmt, left, right, body, kind, labels)?;
2028 }
2029 StmtKind::With { object, body } => self.with_stmt(object, body)?,
2030 StmtKind::ClassDecl(class) => self.class_definition(class, false)?,
2031 // `import` emits nothing: hoisting already bound its names, and the host
2032 // fills their cells before the body runs.
2033 StmtKind::Import(_) => {}
2034 StmtKind::Export(decl) => self.export_stmt(decl)?,
2035 }
2036 Ok(())
2037 }
2038
2039 /// Compile `return`, running every enclosing finalizer on the way out.
2040 ///
2041 /// `nip_catch` is what makes this possible: it discards everything on the stack
2042 /// down to and including the `catch` offset while keeping the return value on
2043 /// top, so the frame the finalizer sees has the same shape as on the normal
2044 /// path.
2045 fn return_stmt(&mut self, value: Option<&Expr>) -> Result<(), SyntaxError> {
2046 let mut has_value = value.is_some();
2047 if let Some(expr) = value {
2048 // `return f(x)` is a tail call *only* when nothing has to happen to the
2049 // value afterwards. A `finally` or an open iterator in scope forces the
2050 // normal path, because the cleanup has to run after the call returns —
2051 // which is exactly what a tail call refuses to do.
2052 //
2053 // A **generator or async function** never tail-calls either: its `return` is
2054 // not a return to the caller but `return_async`, which reads the value off the
2055 // stack and finishes the coroutine. A tail call replaces the frame and hands
2056 // the callee's result straight to whoever resumed us, so the value vanished and
2057 // `it.next(42)` answered `{done: true, value: undefined}` for
2058 // `function* g(){ return f(yield) }`. The reference emits `call1` plus
2059 // `return_async` there and has no tail form for a suspending body at all.
2060 let plain = !self.cur().is_suspending()
2061 // A derived constructor's return is not just the value: a non-object answer
2062 // becomes `this`, so the frame has to survive to run that.
2063 && self.cur().ctor_kind != CtorKind::Derived
2064 && self
2065 .cur()
2066 .jump_targets
2067 .iter()
2068 .all(|target| target.finally_label.is_none() && !target.has_iterator);
2069 if plain && self.expr_if_tail_call(expr)? {
2070 // A tail call never reaches `expr`, so the direct-eval bookkeeping has to
2071 // happen here as well.
2072 self.note_direct_eval(expr);
2073 return Ok(());
2074 }
2075 self.expr(expr)?;
2076 }
2077 // `return v` in an *async generator* awaits `v` before anything else happens —
2078 // `AsyncGeneratorYield`/`AsyncGeneratorReturn` settle the value first, and the
2079 // reference's `emit_return` puts the `await` ahead of the `finally` unwinding for
2080 // exactly that reason ("the await must be done before handling the finally in case
2081 // it raises an exception").
2082 if has_value && self.cur().kind == FunctionKind::AsyncGenerator {
2083 self.emit(Opcode::Await, &[]);
2084 self.state().has_await = true;
2085 }
2086 has_value = self.emit_unwind_for_return(has_value);
2087 // A generator or async function does not return to its caller: it either
2088 // finishes, and the value becomes `{value, done: true}`, or it suspends.
2089 // `return_async` is the "finished" half, and it reads the value off the stack
2090 // rather than carrying it, which is what the resume machinery expects.
2091 if self.cur().is_suspending() {
2092 if !has_value {
2093 self.emit(Opcode::Undefined, &[]);
2094 }
2095 self.emit(Opcode::ReturnAsync, &[]);
2096 return Ok(());
2097 }
2098 // A derived constructor's result is `this` whenever the body does not answer an
2099 // object, and `this` is a local in the dead zone until `super()` returns — which is
2100 // why reading it here is also what turns `constructor(){ return; }` into the
2101 // ReferenceError the reference reports. The interpreter could not do this on its
2102 // own: by the time it sees `undefined` come back, the frame that held `this` is
2103 // gone, and `construct`'s own idea of `this` is the placeholder it made before the
2104 // body ran (`derived-class-return-override-with-{undefined,empty}`).
2105 if self.cur().ctor_kind == CtorKind::Derived {
2106 if !has_value {
2107 self.emit_var(VarAction::Get, "this");
2108 self.emit(Opcode::Return, &[]);
2109 return Ok(());
2110 }
2111 // `return <expr>` is only *sometimes* `this`: `undefined` is, any other
2112 // primitive is a `TypeError` (raised by `construct`), and an object replaces
2113 // `this` outright. Which one it is can only be known at run time.
2114 let keep = self.new_label();
2115 self.emit(Opcode::Dup, &[]);
2116 self.emit(Opcode::IsUndefined, &[]);
2117 self.emit_jump(Opcode::IfFalse, keep, &[]);
2118 self.emit(Opcode::Drop, &[]);
2119 self.emit_var(VarAction::Get, "this");
2120 self.place_label(keep);
2121 self.emit(Opcode::Return, &[]);
2122 return Ok(());
2123 }
2124 if has_value {
2125 self.emit(Opcode::Return, &[]);
2126 } else {
2127 self.emit(Opcode::ReturnUndef, &[]);
2128 }
2129 Ok(())
2130 }
2131
2132 /// Close an iterator: the reference's `emit_iterator_close`.
2133 ///
2134 /// The synchronous form is one opcode. The asynchronous one has to *await* the inner
2135 /// `return` — §7.4.6 calls the method and then `Await`s its result — so it is an inline
2136 /// sequence, and three details in it are load-bearing:
2137 ///
2138 /// * the iterator object is compared against `undefined` first, because a loop that
2139 /// ran to completion clears that slot rather than closing an exhausted iterator;
2140 /// * a missing `return` method is not an error, so it is tested for `undefined`/`null`;
2141 /// * `preserve_completion` keeps whatever was underneath (the return value of the
2142 /// function being left), which is why one branch ends on `nip` and the other on `drop`.
2143 fn emit_iterator_close(&mut self, is_async: bool, preserve_completion: bool) {
2144 if !is_async {
2145 if preserve_completion {
2146 self.emit(Opcode::Rot3r, &[]);
2147 self.emit(Opcode::Undefined, &[]);
2148 }
2149 self.emit(Opcode::IteratorClose, &[]);
2150 return;
2151 }
2152 if preserve_completion {
2153 // `iter next completion -> completion iter`
2154 self.emit(Opcode::Nip, &[]);
2155 self.emit(Opcode::Swap, &[]);
2156 } else {
2157 // `iter next catch_offset -> iter`
2158 self.emit(Opcode::Drop, &[]);
2159 self.emit(Opcode::Drop, &[]);
2160 }
2161 let done = self.new_label();
2162 let no_return = self.new_label();
2163 self.emit(Opcode::Dup, &[]);
2164 self.emit(Opcode::IsUndefined, &[]);
2165 self.emit_jump(Opcode::IfTrue, done, &[]);
2166 self.emit(Opcode::GetField2, &[Op::Atom(Atom::from_text("return"))]);
2167 self.emit(Opcode::Dup, &[]);
2168 self.emit(Opcode::IsUndefinedOrNull, &[]);
2169 self.emit_jump(Opcode::IfTrue, no_return, &[]);
2170 self.emit(Opcode::CallMethod, &[Op::Int(0)]);
2171 self.emit(Opcode::Await, &[]);
2172 self.state().has_await = true;
2173 self.emit_jump(Opcode::Goto, done, &[]);
2174 self.place_label(no_return);
2175 self.emit(Opcode::Drop, &[]);
2176 self.place_label(done);
2177 self.emit(Opcode::Drop, &[]);
2178 }
2179
2180 /// Emit the finalizer/iterator cleanup for leaving the current position with a
2181 /// return, and report whether a value is now on the stack for it to carry.
2182 ///
2183 /// Shared by `return` and by the `return(v)` half of a `yield`: both abandon every
2184 /// enclosing `finally` at once, and the two used to be separate — the `yield` path
2185 /// simply emitted `return_async`, so `it.return()` ended the generator without ever
2186 /// running `finally` blocks the body was sitting inside.
2187 fn emit_unwind_for_return(&mut self, mut has_value: bool) -> bool {
2188 let targets = self.cur().jump_targets.clone();
2189 for target in targets.iter().rev() {
2190 if target.finally_label.is_none() && !target.has_iterator {
2191 continue;
2192 }
2193 if !has_value {
2194 // The cleanup expects a value to pass through; with nothing to
2195 // return, `undefined` stands in.
2196 self.emit(Opcode::Undefined, &[]);
2197 has_value = true;
2198 }
2199 self.emit(Opcode::NipCatch, &[]);
2200 if target.has_iterator {
2201 // Rewind to the loop's own slots and hand the close a dummy catch offset:
2202 // the loop is being abandoned, so there is nothing left to catch.
2203 self.emit_iterator_close(target.is_async_iterator, true);
2204 } else if let Some(finally) = target.finally_label {
2205 self.emit_jump(Opcode::Gosub, finally, &[]);
2206 }
2207 }
2208 has_value
2209 }
2210
2211 /// Compile a statement list, stopping at the first statement that cannot
2212 /// fall through.
2213 fn stmts(&mut self, body: &[Stmt]) -> Result<(), SyntaxError> {
2214 for (index, stmt) in body.iter().enumerate() {
2215 // A `using` declaration is not just a binding: everything after it, to the end
2216 // of the list, runs inside its disposal region. Compiling the rest of the list
2217 // recursively is what gives nested regions their innermost-first order.
2218 if Self::using_declaration(stmt).is_some() {
2219 return self.using_region(stmt, &body[index + 1..]);
2220 }
2221 self.stmt(stmt)?;
2222 if Self::terminates(stmt) {
2223 break;
2224 }
2225 }
2226 Ok(())
2227 }
2228
2229 /// The declaration a `using` statement carries, if it is one.
2230 fn using_declaration(stmt: &Stmt) -> Option<&VarDecl> {
2231 match &stmt.kind {
2232 StmtKind::VarDecl(decl) if decl.kind.is_using() => Some(decl),
2233 _ => None,
2234 }
2235 }
2236
2237 /// Compile `decl` and then the rest of its block, disposing when the block ends.
2238 ///
2239 /// The shape mirrors a `try`/`finally`, and deliberately so: the disposal has to run on
2240 /// every way out of the block — reaching its end, `return`, `break`, `continue`, and an
2241 /// exception — and this engine already funnels all of those through `catch` plus
2242 /// `gosub`. Registering the region as a jump target with a `finally_label` is what makes
2243 /// `return` and `break` dispose without knowing anything about `using`.
2244 ///
2245 /// ```text
2246 /// <declaration> value -> x, method -> x+1
2247 /// catch CATCH <- an exception in the rest lands here
2248 /// REST:
2249 /// <the rest of the block>
2250 /// drop <- the catch offset, on the fall-through path
2251 /// undefined; gosub DISPOSE; drop
2252 /// goto END
2253 /// CATCH:
2254 /// using_dispose x <- merges the failure into the pending exception
2255 /// throw
2256 /// DISPOSE:
2257 /// using_dispose_init
2258 /// using_dispose x
2259 /// using_dispose_end <- rethrows if a dispose failed
2260 /// ret
2261 /// END:
2262 /// ```
2263 fn using_region(&mut self, stmt: &Stmt, rest: &[Stmt]) -> Result<(), SyntaxError> {
2264 let Some(decl) = Self::using_declaration(stmt) else {
2265 unreachable!("using_region is only called for a using declaration");
2266 };
2267 self.using_declarator(stmt, decl, 0, rest)
2268 }
2269
2270 /// One declarator of a `using` declaration, plus the region around everything after it.
2271 ///
2272 /// A `using` may list several resources — `using a = x, b = y;` — and each one is
2273 /// disposed when the block ends, in **reverse** order: §14.3.1.4 pushes them onto
2274 /// `DisposableResourceStack` in source order and §9.5.5 disposes from the top. Nesting
2275 /// one region per declarator gives exactly that, because the inner region ends first
2276 /// (`multiple-resources-disposed-in-reverse-order`). Compiling only the first left the
2277 /// rest undisposed.
2278 fn using_declarator(
2279 &mut self,
2280 stmt: &Stmt,
2281 decl: &VarDecl,
2282 index: usize,
2283 rest: &[Stmt],
2284 ) -> Result<(), SyntaxError> {
2285 let Some(declarator) = decl.declarators.get(index) else {
2286 return self.stmts(rest);
2287 };
2288 // `using` binds a plain identifier and has no pattern form, which the parser
2289 // enforces; the region still has to know *which* slot to dispose.
2290 let name = match &declarator.target.kind {
2291 PatternKind::Ident(ident) => Some(ident.name.clone()),
2292 _ => None,
2293 };
2294 let single = Stmt {
2295 kind: StmtKind::VarDecl(VarDecl {
2296 kind: decl.kind,
2297 declarators: vec![declarator.clone()],
2298 span: declarator.span,
2299 }),
2300 span: declarator.span,
2301 };
2302 self.stmt(&single)?;
2303 let Some(name) = name else {
2304 // Unreachable for a well-formed `using`, but a bare `using` with no declarator
2305 // must not make the compiler panic.
2306 return self.using_declarator(stmt, decl, index + 1, rest);
2307 };
2308 let Some(value_slot) = self.using_value_slot(&name) else {
2309 // Declared globally, which the parser rules out for a script; a module's
2310 // top level is a scope, and there the disposal stays a known gap.
2311 return self.using_declarator(stmt, decl, index + 1, rest);
2312 };
2313 // A block that ends in a `return` or a `throw` never reaches its own epilogue; the
2314 // exit path already disposed.
2315 let live = !rest.last().is_some_and(Self::terminates);
2316 let _ = stmt;
2317 self.using_region_around(
2318 value_slot,
2319 live,
2320 decl.kind == VarDeclKind::AwaitUsing,
2321 |compiler| compiler.using_declarator(stmt, decl, index + 1, rest),
2322 )
2323 }
2324
2325 /// One `using` declarator of a `for` head, wrapped in its disposal region, and then the
2326 /// next — so the resources nest inside-out and dispose in reverse order.
2327 #[allow(clippy::too_many_arguments)]
2328 fn for_using_head(
2329 &mut self,
2330 decl: &VarDecl,
2331 index: usize,
2332 init: &Option<ForInit>,
2333 test: &Option<Box<Expr>>,
2334 update: &Option<Box<Expr>>,
2335 body: &Stmt,
2336 labels: &[String],
2337 for_key: u64,
2338 for_parent: u64,
2339 ) -> Result<(), SyntaxError> {
2340 let Some(declarator) = decl.declarators.get(index) else {
2341 return self.for_loop_tail(init, test, update, body, labels, for_key, for_parent);
2342 };
2343 let name = match &declarator.target.kind {
2344 PatternKind::Ident(ident) => Some(ident.name.clone()),
2345 _ => None,
2346 };
2347 self.var_decl(&VarDecl {
2348 kind: decl.kind,
2349 declarators: vec![declarator.clone()],
2350 span: declarator.span,
2351 })?;
2352 let Some(slot) = name.and_then(|name| self.using_value_slot(&name)) else {
2353 return self.for_using_head(
2354 decl,
2355 index + 1,
2356 init,
2357 test,
2358 update,
2359 body,
2360 labels,
2361 for_key,
2362 for_parent,
2363 );
2364 };
2365 self.using_region_around(
2366 slot,
2367 true,
2368 decl.kind == VarDeclKind::AwaitUsing,
2369 |compiler| {
2370 compiler.for_using_head(
2371 decl,
2372 index + 1,
2373 init,
2374 test,
2375 update,
2376 body,
2377 labels,
2378 for_key,
2379 for_parent,
2380 )
2381 },
2382 )
2383 }
2384
2385 /// The half of a `for` statement that runs inside its head's disposal region: the
2386 /// per-iteration bindings, the test, the body and the update.
2387 ///
2388 /// Split out so that a `using` head can wrap exactly this much — see the
2389 /// `StmtKind::For` arm — because the resource lives as long as the statement.
2390 #[allow(clippy::too_many_arguments)]
2391 fn for_loop_tail(
2392 &mut self,
2393 init: &Option<ForInit>,
2394 test: &Option<Box<Expr>>,
2395 update: &Option<Box<Expr>>,
2396 body: &Stmt,
2397 labels: &[String],
2398 for_key: u64,
2399 for_parent: u64,
2400 ) -> Result<(), SyntaxError> {
2401 // A `let`/`const` in the head gets a *fresh binding per iteration*,
2402 // so a closure made in the body captures that iteration's value
2403 // instead of sharing one. The reference expresses this with
2404 // `close_loc`, which swaps in a new reference cell holding the
2405 // current value; the three points below are the ones it uses — after
2406 // the initialiser, before the update, and after the loop.
2407 let loop_bindings = match init {
2408 Some(ForInit::VarDecl(decl)) if decl.kind != VarDeclKind::Var => {
2409 let mut names: Vec<String> = Vec::new();
2410 for declarator in &decl.declarators {
2411 let mut idents = Vec::new();
2412 declarator.target.bound_names(&mut idents);
2413 names.extend(idents.into_iter().map(|ident| ident.name));
2414 }
2415 names
2416 }
2417 _ => Vec::new(),
2418 };
2419 // The reference also closes right after the initialiser, so the first
2420 // iteration's closures get their own cell rather than sharing the one
2421 // the initialiser wrote into.
2422 for name in &loop_bindings {
2423 let pos = self.cur().cur_pos;
2424 self.state().insns.push(Insn::CloseCaptured {
2425 name: name.clone(),
2426 block: for_key,
2427 });
2428 self.state().insn_pos.push(pos);
2429 }
2430 let top = self.new_label();
2431 let cont = self.new_label();
2432 let end = self.new_label();
2433 self.place_label(top);
2434 if let Some(test) = test {
2435 self.expr(test)?;
2436 self.emit_jump(Opcode::IfFalse, end, &[]);
2437 }
2438 // `continue` runs the update expression first, so it lands on
2439 // `cont`, which sits just before the update.
2440 self.loop_body(body, labels, cont, end)?;
2441 self.place_label(cont);
2442 // Each iteration ends with a fresh cell, so the closures the body just
2443 // created keep the cell they captured and the update writes to a new
2444 // one. Without this every closure in the loop shares one binding.
2445 let binding_block = for_key;
2446 for name in &loop_bindings {
2447 let pos = self.cur().cur_pos;
2448 self.state().insns.push(Insn::CloseCaptured {
2449 name: name.clone(),
2450 block: binding_block,
2451 });
2452 self.state().insn_pos.push(pos);
2453 }
2454 if let Some(update) = update {
2455 self.state().discard_value = true;
2456 let result = self.expr(update);
2457 self.state().discard_value = false;
2458 result?;
2459 if !std::mem::take(&mut self.state().no_value) {
2460 self.emit(Opcode::Drop, &[]);
2461 }
2462 }
2463 self.emit_jump(Opcode::Goto, top, &[]);
2464 self.place_label(end);
2465 self.emit_scope_leave(for_key);
2466 self.state().current_block = for_parent;
2467 Ok(())
2468 }
2469
2470 /// The slot a `using` binding's value lives in.
2471 fn using_value_slot(&self, name: &str) -> Option<u32> {
2472 self.cur()
2473 .vars
2474 .iter()
2475 .position(|var| var.name == name && var.kind == VarKind::Using)
2476 .map(|index| index as u32)
2477 }
2478
2479 /// Wrap `inside` in a disposal region for the resource in `value_slot`.
2480 ///
2481 /// Shared between a `using` statement — which owns the rest of its block — and a
2482 /// `for (using x of …)` body, which owns only one iteration. The shape mirrors a
2483 /// `try`/`finally`, deliberately: the disposal has to run on every way out — reaching
2484 /// the end, `return`, `break`, `continue`, and an exception — and this engine already
2485 /// funnels all of those through `catch` plus `gosub`. Registering the region as a jump
2486 /// target with a `finally_label` is what makes `return` and `break` dispose without
2487 /// knowing anything about `using`.
2488 ///
2489 /// ```text
2490 /// catch CATCH <- an exception inside lands here
2491 /// <inside>
2492 /// drop <- the catch offset, on the fall-through path
2493 /// undefined; gosub DISPOSE; drop
2494 /// goto END
2495 /// CATCH:
2496 /// using_dispose slot <- merges the failure into the pending exception
2497 /// throw
2498 /// DISPOSE:
2499 /// using_dispose_init
2500 /// using_dispose slot
2501 /// using_dispose_end <- rethrows if a dispose failed
2502 /// ret
2503 /// END:
2504 /// ```
2505 fn using_region_around(
2506 &mut self,
2507 value_slot: u32,
2508 live: bool,
2509 is_await_using: bool,
2510 inside: impl FnOnce(&mut Self) -> Result<(), SyntaxError>,
2511 ) -> Result<(), SyntaxError> {
2512 let catch_label = self.new_label();
2513 let end_label = self.new_label();
2514 let dispose_label = self.new_label();
2515
2516 self.emit_jump(Opcode::Catch, catch_label, &[]);
2517 self.push_jump_target(JumpTarget {
2518 names: Vec::new(),
2519 break_label: None,
2520 continue_label: None,
2521 // The catch offset is the one thing on the stack that leaving has to remove.
2522 drop_count: 1,
2523 finally_label: Some(dispose_label),
2524 is_regular_stmt: false,
2525 has_iterator: false,
2526 is_async_iterator: false,
2527 });
2528 inside(self)?;
2529 self.pop_jump_target();
2530
2531 if live {
2532 self.emit(Opcode::Drop, &[]);
2533 self.emit(Opcode::Undefined, &[]);
2534 self.emit_jump(Opcode::Gosub, dispose_label, &[]);
2535 self.emit(Opcode::Drop, &[]);
2536 self.emit_jump(Opcode::Goto, end_label, &[]);
2537 }
2538
2539 // An exception unwinds to here with the thrown value on the stack, which is exactly
2540 // the shape `using_dispose` expects as its error state.
2541 self.place_label(catch_label);
2542 self.emit(Opcode::UsingDispose, &[Op::Slot(Slot::Loc(value_slot))]);
2543 self.emit(Opcode::Throw, &[]);
2544
2545 self.place_label(dispose_label);
2546 // Inside the subroutine the return value and the `gosub` return address are both
2547 // live, and neither an outer finalizer nor another region may run before this one
2548 // has finished.
2549 self.push_jump_target(JumpTarget {
2550 names: Vec::new(),
2551 break_label: None,
2552 continue_label: None,
2553 drop_count: 2,
2554 finally_label: None,
2555 is_regular_stmt: false,
2556 has_iterator: false,
2557 is_async_iterator: false,
2558 });
2559 self.emit(Opcode::UsingDisposeInit, &[]);
2560 if is_await_using {
2561 // `AsyncDisposableStack`'s order: call the method, **await** its result, and
2562 // fold a rejection into the error state. The catch is what turns that
2563 // rejection — which arrives as an exception from `await` — into the merged
2564 // error, so one failure is rethrown as itself and two become a
2565 // `SuppressedError` (§27.1.3.3's `DisposeResources` steps 5–6).
2566 //
2567 // The shape is the reference's `js_emit_dispose_scope`, adapted to this
2568 // engine's error-state protocol: `using_dispose_init` pushed the state and
2569 // `using_dispose_end` will consume it, so both arms have to leave it in place.
2570 let catch_label = self.new_label();
2571 let merged_label = self.new_label();
2572 self.emit_jump(Opcode::Catch, catch_label, &[]);
2573 self.emit(
2574 Opcode::UsingDisposeAsync,
2575 &[Op::Slot(Slot::Loc(value_slot))],
2576 );
2577 self.emit(Opcode::Await, &[]);
2578 // The awaited value, and the catch offset the successful path still holds.
2579 self.emit(Opcode::Drop, &[]);
2580 self.emit(Opcode::Drop, &[]);
2581 self.emit_jump(Opcode::Goto, merged_label, &[]);
2582 self.place_label(catch_label);
2583 self.emit(Opcode::UsingDisposeMerge, &[]);
2584 self.place_label(merged_label);
2585 self.state().has_await = true;
2586 } else {
2587 self.emit(Opcode::UsingDispose, &[Op::Slot(Slot::Loc(value_slot))]);
2588 }
2589 self.emit(Opcode::UsingDisposeEnd, &[]);
2590 self.pop_jump_target();
2591 self.emit(Opcode::Ret, &[]);
2592 self.place_label(end_label);
2593 Ok(())
2594 }
2595
2596 /// Declare every name a statement list introduces, before compiling any of
2597 /// it, so a reference that appears textually before a declaration still
2598 /// resolves.
2599 ///
2600 /// Declarations are walked in source order because that is the order the
2601 /// reference numbers its slots in: `let a; var b;` gives `a` slot 0 and `b`
2602 /// slot 1, while `var b; let a;` gives the opposite. `var` and function
2603 /// declarations hoist out to the function scope; lexical names belong to the
2604 /// block they were written in, which `block` records.
2605 fn hoist(&mut self, body: &[Stmt], block: u64) -> Result<(), SyntaxError> {
2606 let saved = self.cur().current_block;
2607 self.state().current_block = block;
2608 let result = self.hoist_list(body);
2609 // Only now is every binding of this scope known, so the deferred function
2610 // bodies can be compiled against the finished list. Compiled at its own
2611 // declaration instead, a body that names a `var` written further down would
2612 // have resolved that name as a global.
2613 if result.is_ok() {
2614 let deferred = std::mem::take(&mut self.state().deferred_funcs);
2615 let mut outcome = Ok(());
2616 for (owner, func) in deferred {
2617 let previous = self.cur().current_block;
2618 self.state().current_block = owner;
2619 outcome = self.func_decl(&func);
2620 self.state().current_block = previous;
2621 if outcome.is_err() {
2622 break;
2623 }
2624 }
2625 self.state().current_block = saved;
2626 return outcome;
2627 }
2628 // `current_block` is restored by the caller for a block statement, since
2629 // it needs it set while compiling; only clean up on the hoist path.
2630 self.state().current_block = saved;
2631 result
2632 }
2633
2634 fn hoist_list(&mut self, body: &[Stmt]) -> Result<(), SyntaxError> {
2635 for stmt in body {
2636 self.hoist_stmt(stmt)?;
2637 }
2638 Ok(())
2639 }
2640
2641 /// Whether a statement always transfers control away, making everything after
2642 /// it in the same list unreachable.
2643 ///
2644 /// The reference drops such statements in `skip_dead_code`, so `return 1;
2645 /// let x = 2;` compiles to the same bytecode as `return 1;`.
2646 fn terminates(stmt: &Stmt) -> bool {
2647 matches!(
2648 stmt.kind,
2649 StmtKind::Return(_) | StmtKind::Throw(_) | StmtKind::Break(_) | StmtKind::Continue(_)
2650 )
2651 }
2652
2653 fn hoist_stmt(&mut self, stmt: &Stmt) -> Result<(), SyntaxError> {
2654 match &stmt.kind {
2655 StmtKind::VarDecl(decl) => {
2656 for declarator in &decl.declarators {
2657 let mut names = Vec::new();
2658 declarator.target.bound_names(&mut names);
2659 for name in names {
2660 let text = name.name.clone();
2661 if decl.kind == VarDeclKind::Var {
2662 let def = VarDef::var(text.clone());
2663 self.declare_var(&text, def);
2664 } else if decl.kind.is_using() {
2665 // Two adjacent slots: the resource, then the dispose method
2666 // snapshotted at declaration. `using_dispose` reads them as a
2667 // pair `(slot, slot + 1)`, so nothing may be declared between
2668 // them — which is why both are declared here, in one step,
2669 // rather than the method being added at emission time.
2670 self.declare_using(&text);
2671 } else {
2672 let def = if decl.kind == VarDeclKind::Const {
2673 VarDef::constant(text.clone())
2674 } else {
2675 VarDef::lexical(text.clone())
2676 };
2677 self.declare(&text, def);
2678 }
2679 }
2680 }
2681 }
2682 StmtKind::FuncDecl(func) => {
2683 if let Some(name) = &func.name {
2684 // A function declaration is a `var` binding that happens to
2685 // hold a function, not a lexical one.
2686 let mut def = VarDef::var(name.name.clone());
2687 // Marked so that an `eval` establishing it can apply
2688 // `CanDeclareGlobalFunction` rather than the laxer `var` rule. Only
2689 // the *global* form is marked: the kind is printed by the
2690 // disassembler, and a local function declaration is `var g` there,
2691 // exactly like the reference.
2692 if self.cur().declares_globally(&def) {
2693 def.kind = crate::bytecode::VarKind::GlobalFunctionDecl;
2694 }
2695 self.declare_var(&name.name.clone(), def);
2696 }
2697 // The function object is created when the scope is entered, so it
2698 // exists before the declaration is reached. Its body is compiled
2699 // *after* this scope's hoisting finishes, so a name it uses resolves
2700 // even when the `var` that declares it comes later in the source.
2701 let owner = self.cur().current_block;
2702 self.state().deferred_funcs.push((owner, func.clone()));
2703 }
2704 StmtKind::ClassDecl(class) => {
2705 if let Some(name) = &class.name {
2706 self.declare(&name.name.clone(), VarDef::lexical(name.name.clone()));
2707 }
2708 }
2709 // A module's imports are bound before any of its code runs, and its exports
2710 // declare the very bindings they export — so both hoist the declarations
2711 // their `StmtKind` arm will later emit code for.
2712 StmtKind::Import(decl) => self.hoist_import(decl)?,
2713 StmtKind::Export(decl) => self.hoist_export(decl)?,
2714 StmtKind::Block(inner) => self.hoist_block(stmt.span.start.offset as u64, inner)?,
2715 StmtKind::If { cons, alt, .. } => {
2716 self.hoist_stmt(cons)?;
2717 if let Some(alt) = alt {
2718 self.hoist_stmt(alt)?;
2719 }
2720 }
2721 StmtKind::While { body, .. }
2722 | StmtKind::DoWhile { body, .. }
2723 | StmtKind::Labeled { body, .. }
2724 | StmtKind::With { body, .. } => self.hoist_stmt(body)?,
2725 StmtKind::For { init, body, .. } => {
2726 // A `for` head gets its own scope even when it declares nothing,
2727 // because `let` in the head is scoped to the loop.
2728 let key = stmt.span.start.offset as u64;
2729 let parent = self.cur().current_block;
2730 self.push_block(key, parent);
2731 if let Some(init) = init
2732 && let ForInit::VarDecl(decl) = init
2733 {
2734 self.hoist_stmt(&Stmt::new(StmtKind::VarDecl(decl.clone()), stmt.span))?;
2735 }
2736 self.hoist_stmt(body)?;
2737 self.state().current_block = parent;
2738 }
2739 StmtKind::ForIn { left, body, .. } | StmtKind::ForOf { left, body, .. } => {
2740 let key = stmt.span.start.offset as u64;
2741 let parent = self.cur().current_block;
2742 self.push_block(key, parent);
2743 if let ForHead::VarDecl(decl) = left {
2744 self.hoist_stmt(&Stmt::new(StmtKind::VarDecl(decl.clone()), stmt.span))?;
2745 }
2746 self.hoist_stmt(body)?;
2747 self.state().current_block = parent;
2748 }
2749 StmtKind::Try {
2750 block,
2751 handler,
2752 finalizer,
2753 } => {
2754 self.hoist_block(Self::try_block_key(stmt, TryPart::Block), block)?;
2755 let try_parent = self.cur().current_block;
2756 if let Some(handler) = handler {
2757 // The catch parameter belongs to the function scope, not to a
2758 // block: it is a `catch` binding rather than a `let`, so it is
2759 // never in the temporal dead zone and `emit_scope_enter` must
2760 // not mark it uninitialised. It still has to be declared before
2761 // the handler body is hoisted, so it takes the slot the
2762 // reference gives it (bindings are numbered in source order).
2763 if let Some(pattern) = &handler.param {
2764 // The parameter gets its own scope, so entering the handler
2765 // does not have to re-declare it. It is not lexical, so it
2766 // is never marked uninitialised.
2767 let key = Self::try_block_key(stmt, TryPart::Param);
2768 let parent = self.cur().current_block;
2769 self.push_block(key, parent);
2770 // A destructuring parameter binds several names, one slot each,
2771 // in the order they are written. The reference declares those as
2772 // `let`s rather than as one `catch` binding — its dump prints
2773 // `0: let e` for `catch ({e})` but `0: catch e` for `catch (e)` —
2774 // so the kind follows the shape of the parameter.
2775 //
2776 // Neither form is in the dead zone: the stores run as the handler
2777 // is entered, so both use the unchecked `put_loc`.
2778 let destructures = !matches!(pattern.kind, PatternKind::Ident(_));
2779 let mut names = Vec::new();
2780 pattern.bound_names(&mut names);
2781 for name in names {
2782 let def = VarDef {
2783 name: name.name.clone(),
2784 is_const: false,
2785 is_lexical: destructures,
2786 kind: if destructures {
2787 crate::bytecode::VarKind::LexicalCatch
2788 } else {
2789 crate::bytecode::VarKind::Catch
2790 },
2791 is_captured: false,
2792 scope_level: 0,
2793 scope_next: None,
2794 };
2795 self.declare_local(&name.name.clone(), def);
2796 }
2797 // The handler body nests inside the parameter's scope, so the
2798 // body's bindings chain on to the parameter (the reference
2799 // prints `let y [next:1]`, pointing at `e`).
2800 self.state().current_block = key;
2801 }
2802 self.hoist_block(Self::try_block_key(stmt, TryPart::Catch), &handler.body)?;
2803 // Back to the block the `try` itself lives in, so the finalizer
2804 // is a sibling of the handler rather than nested in it.
2805 self.state().current_block = try_parent;
2806 }
2807 if let Some(finalizer) = finalizer {
2808 self.hoist_block(Self::try_block_key(stmt, TryPart::Finally), finalizer)?;
2809 }
2810 }
2811 StmtKind::Switch { cases, .. } => {
2812 let key = stmt.span.start.offset as u64;
2813 let parent = self.cur().current_block;
2814 self.push_block(key, parent);
2815 for case in cases {
2816 self.hoist_list(&case.body)?;
2817 }
2818 self.state().current_block = parent;
2819 }
2820 _ => {}
2821 }
2822 Ok(())
2823 }
2824
2825 /// Hoist a nested statement list, which is its own lexical scope.
2826 fn hoist_block(&mut self, key: u64, body: &[Stmt]) -> Result<(), SyntaxError> {
2827 let parent = self.cur().current_block;
2828 self.push_block(key, parent);
2829 self.hoist_list(body)?;
2830 self.state().current_block = parent;
2831 Ok(())
2832 }
2833
2834 /// A block key for one part of a `try` statement.
2835 ///
2836 /// The three parts are three separate scopes, so they cannot share the key a
2837 /// statement's own offset would give them: the try block, the handler body and
2838 /// the finalizer would then look like one scope, and their `let` bindings would
2839 /// be marked uninitialised only on entering the first of them.
2840 fn try_block_key(stmt: &Stmt, part: TryPart) -> u64 {
2841 (stmt.span.start.offset as u64) * 4 + part as u64
2842 }
2843
2844 /// Declare a `var`: it lives in the function's own scope, not the block's.
2845 fn declare_var(&mut self, name: &str, def: VarDef) {
2846 if self.cur().is_module {
2847 self.declare_module(name, &def);
2848 return;
2849 }
2850 if self.cur().declares_globally(&def) {
2851 self.declare_global(name, &def);
2852 return;
2853 }
2854 let state = self.state();
2855 // A binding of the *parameter* scope does not count: the body's `var` of the
2856 // same name is a different binding and needs a slot of its own.
2857 if state.vars.iter().enumerate().any(|(index, v)| {
2858 v.name == name && state.var_block.get(index).copied() != Some(PARAM_SCOPE)
2859 }) {
2860 return;
2861 }
2862 // A `var` belongs to the function scope, never to the enclosing block.
2863 state.var_block.push(FUNCTION_SCOPE);
2864 state.vars.push(def);
2865 }
2866
2867 /// Declare `name` as a binding of the parameter scope, returning its slot.
2868 fn declare_param_var(&mut self, name: &str) -> u32 {
2869 declare_param_var_at(self.state(), name)
2870 }
2871
2872 /// Declare one of the parameter list's own bindings: a `let` of the parameter scope.
2873 ///
2874 /// The `scope_next` chain is the reference's. Bindings are prepended to their scope,
2875 /// so each points at the one declared before it and the oldest ends the chain with
2876 /// `-2` (`ARG_SCOPE_END`); the dump prints exactly that, and the chain is what the
2877 /// runtime walks when it instantiates them.
2878 fn declare_param_binding(&mut self, name: &str) -> u32 {
2879 let state = self.state();
2880 let previous = state
2881 .vars
2882 .iter()
2883 .enumerate()
2884 .rev()
2885 .find(|(index, var)| {
2886 state.var_block.get(*index).copied() == Some(PARAM_SCOPE) && var.is_lexical
2887 })
2888 .map(|(index, _)| index as i32);
2889 let index = state.vars.len() as u32;
2890 state.var_block.push(PARAM_SCOPE);
2891 let mut def = VarDef::lexical(name);
2892 // A scope of its own, so the dump prints `[next:…]`. The parameter scope is not
2893 // the function's, and its bindings are initialised one by one rather than all at
2894 // once — which is exactly what the dead zone needs.
2895 def.scope_level = 1;
2896 def.scope_next = Some(previous.unwrap_or(-2));
2897 state.vars.push(def);
2898 index
2899 }
2900
2901 /// The slot of a parameter-list binding, if the list has one by that name.
2902 fn param_binding_slot(&self, name: &str) -> Option<u32> {
2903 let state = self.cur();
2904 state
2905 .vars
2906 .iter()
2907 .enumerate()
2908 .position(|(index, var)| {
2909 var.name == name
2910 && var.is_lexical
2911 && state.var_block.get(index).copied() == Some(PARAM_SCOPE)
2912 })
2913 .map(|index| index as u32)
2914 }
2915
2916 /// Every parameter-list binding, in declaration order.
2917 fn param_binding_names(&self) -> Vec<String> {
2918 let state = self.cur();
2919 state
2920 .vars
2921 .iter()
2922 .enumerate()
2923 .filter(|(index, var)| {
2924 var.is_lexical && state.var_block.get(*index).copied() == Some(PARAM_SCOPE)
2925 })
2926 .map(|(_, var)| var.name.clone())
2927 .collect()
2928 }
2929
2930 /// The body's own binding for `name`, as opposed to the parameter's copy of it.
2931 fn body_var_slot(&self, name: &str) -> Option<u32> {
2932 let state = self.cur();
2933 state
2934 .vars
2935 .iter()
2936 .enumerate()
2937 .find(|(index, var)| {
2938 var.name == name && state.var_block.get(*index).copied() == Some(FUNCTION_SCOPE)
2939 })
2940 .map(|(index, _)| index as u32)
2941 }
2942
2943 /// Give the *parameter* scope an `arguments` binding if the parameter list mentions
2944 /// one.
2945 ///
2946 /// With parameter expressions the reference creates two: an unmapped one in the
2947 /// argument scope, for the defaults and anything they close over, and the body's own.
2948 /// They are separate bindings, which is what makes
2949 /// `(a = eval("var arguments = 1"), p = () => arguments) => { var arguments = 2 }`
2950 /// report 1 from `p` and 2 from the body.
2951 fn provide_param_arguments(&mut self) {
2952 if !self.cur().has_parameter_expressions {
2953 return;
2954 }
2955 let mentioned = self.cur().needs_param_arguments
2956 || self
2957 .cur()
2958 .insns
2959 .iter()
2960 .any(|insn| matches!(insn, Insn::Var { name, in_params: true, .. } if name == "arguments"));
2961 if !mentioned {
2962 return;
2963 }
2964 let slot = self.declare_param_var("arguments");
2965 let magic = if self.cur().strict || !self.cur().simple_parameter_list {
2966 0
2967 } else {
2968 1
2969 };
2970 self.prepend_initialiser_to(
2971 slot,
2972 Insn::Fixed {
2973 op: Opcode::SpecialObject,
2974 operands: vec![Op::Int(magic)],
2975 },
2976 );
2977 }
2978
2979 /// [`Compiler::prepend_initialiser`] for a slot rather than a name.
2980 fn prepend_initialiser_to(&mut self, slot: u32, producer: Insn) {
2981 let current = self.stack.len() - 1;
2982 let init = [
2983 producer,
2984 Insn::Fixed {
2985 op: Opcode::PutLoc,
2986 operands: vec![Op::Slot(Slot::Loc(slot))],
2987 },
2988 ];
2989 let inserted = init.len();
2990 for (index, instruction) in init.into_iter().enumerate() {
2991 self.stack[current].insns.insert(index, instruction);
2992 }
2993 for placed in self.stack[current].labels.iter_mut().flatten() {
2994 *placed += inserted;
2995 }
2996 self.state().label_since_insn = false;
2997 }
2998
2999 /// Give the function an `arguments` binding if its body mentions one.
3000 ///
3001 /// The check runs on the *instruction* stream rather than the AST: by this point
3002 /// every reference has become an `Insn::Var`, so scanning is exact and needs no
3003 /// AST walker. Declaring lazily matters for more than tidiness — always declaring
3004 /// would renumber every later local slot and stop the bytecode matching the
3005 /// reference, which only adds the binding when the body uses it.
3006 ///
3007 /// `arguments` is a local, initialised at the top of the body by
3008 /// `special_object`; that is the reference's shape, so the disassembly agrees.
3009 fn provide_arguments(&mut self) {
3010 let current = self.stack.len() - 1;
3011 if self.stack[current].is_script || self.stack[current].is_module {
3012 // A module has no `arguments` binding; referring to it is a ReferenceError,
3013 // which is exactly what an unbound name produces.
3014 return;
3015 }
3016 // An arrow has no `arguments` of its own: the binding belongs to the enclosing
3017 // function, which is why `() => arguments` sees the caller's arguments.
3018 if self.stack[current].is_arrow {
3019 if self.mentions("arguments") {
3020 self.ensure_enclosing_arguments();
3021 }
3022 return;
3023 }
3024 // Only a *body* mention needs the body's binding: the parameter list has one of
3025 // its own (see [`Compiler::provide_param_arguments`]).
3026 //
3027 // `delete arguments` counts too: it compiles to `DeleteVar`, which is not a
3028 // `Var`, so without this the body got no binding at all — the name resolved to
3029 // the global object and `delete` answered `true` for a binding that cannot be
3030 // deleted. The reference answers `false`.
3031 let mentioned = self.cur().insns.iter().any(|insn| match insn {
3032 Insn::Var {
3033 name, in_params, ..
3034 } => name == "arguments" && !*in_params,
3035 Insn::DeleteVar { name } => name == "arguments",
3036 _ => false,
3037 });
3038 // A mention that resolves to the body's *own* lexical `arguments` is not a request
3039 // for the implicit one — `function f(p = 1) { let arguments; }` shadows it, and the
3040 // implicit binding is not created at all. Providing it anyway was worse than useless:
3041 // its prologue store resolved past the shadowing `let` and landed on the **global**,
3042 // so `function f(p = eval("var arguments")) { let arguments; }` defined
3043 // `globalThis.arguments` as a side effect (`globalThis.arguments unchanged` in
3044 // test262's `fn-body-cntns-arguments-lex-bind` family).
3045 //
3046 // Lexical only. `var arguments = 1` in the body is a different thing entirely: the
3047 // var *is* the binding, and the implicit arguments object is initialised into it at
3048 // entry, which is why `function f(){ return typeof arguments; var arguments = 1 }`
3049 // answers `"object"` (`S13_A15_T4`). Suppressing the prologue for those two made
3050 // `typeof arguments` `"undefined"`.
3051 if self
3052 .cur()
3053 .vars
3054 .iter()
3055 .any(|var| var.name == "arguments" && var.needs_check())
3056 {
3057 return;
3058 }
3059 if !mentioned && !self.cur().needs_arguments_local {
3060 return;
3061 }
3062 // The request may have come only from a parameter-list arrow, in which case the
3063 // parameter scope's binding already answers for it and the body needs none.
3064 if !mentioned && self.cur().has_parameter_expressions && !self.body_mentions_arguments() {
3065 return;
3066 }
3067 // 0 is strict `arguments`, 1 is sloppy (mapped) `arguments`.
3068 //
3069 // With parameter expressions the list and the body are separate environments, so
3070 // an assignment to a parameter cannot be reflected into `arguments` at all — the
3071 // arguments object is unmapped whatever the mode, which is why the reference emits
3072 // `special_object 0` here even in sloppy code.
3073 // A non-simple parameter list (`[a]`, `...rest`, `a = 1`) makes the arguments
3074 // object unmapped whatever the mode — §10.4.4 keys the decision on
3075 // `IsSimpleParameterList`, not on strictness alone.
3076 let magic = if self.stack[current].strict || !self.stack[current].simple_parameter_list {
3077 0
3078 } else {
3079 1
3080 };
3081 // A mapped `arguments` shares storage with the parameters: `arguments[0] = 2`
3082 // has to be visible as `a`, and assigning `a` has to be visible as `arguments[0]`.
3083 // The only storage both sides can see is a reference cell, so every parameter the
3084 // object maps gets one — even a parameter no closure captured. Without this the
3085 // slot holds a plain copy and the mapping has nothing to write through.
3086 if magic == 1 {
3087 for arg in &mut self.stack[current].args {
3088 arg.is_captured = true;
3089 }
3090 }
3091 self.prepend_binding("arguments", magic);
3092 }
3093
3094 /// Whether a *body* instruction refers to `arguments`.
3095 fn body_mentions_arguments(&self) -> bool {
3096 self.cur()
3097 .insns
3098 .iter()
3099 .any(|insn| matches!(insn, Insn::Var { name, in_params, .. } if name == "arguments" && !*in_params))
3100 }
3101
3102 /// Whether the function body's instruction stream refers to `name`.
3103 fn mentions(&self, name: &str) -> bool {
3104 let current = self.stack.len() - 1;
3105 // A binding of the parameter scope does not answer for the body: the body's own
3106 // `arguments` (or self-name) still has to be provided for it.
3107 if self.stack[current]
3108 .vars
3109 .iter()
3110 .enumerate()
3111 .any(|(index, v)| {
3112 v.name == name
3113 && self.stack[current].var_block.get(index).copied() != Some(PARAM_SCOPE)
3114 })
3115 {
3116 return false;
3117 }
3118 self.stack[current]
3119 .insns
3120 .iter()
3121 .any(|insn| matches!(insn, Insn::Var { name: used, .. } if used == name))
3122 }
3123
3124 /// Bind the name a named function expression uses to refer to itself.
3125 ///
3126 /// The value is `special_object 2`, the function currently running, so the binding
3127 /// is the closure itself and not a copy. It is a local of this function, which is
3128 /// what keeps `g` out of the enclosing scope.
3129 /// Give the function a local `this`, for an arrow inside it to capture.
3130 fn provide_this_local(&mut self) {
3131 let current = self.stack.len() - 1;
3132 if !self.stack[current].needs_this_local || self.stack[current].has_this_prologue {
3133 return;
3134 }
3135 if !self.stack[current]
3136 .vars
3137 .iter()
3138 .any(|var| var.name == "this")
3139 {
3140 self.declare_hidden_local("this", VarKind::Normal);
3141 }
3142 self.prepend_initialiser(
3143 "this",
3144 Insn::Fixed {
3145 op: Opcode::PushThis,
3146 operands: vec![],
3147 },
3148 );
3149 }
3150
3151 /// Give the function a local `<home_object>`, for an arrow or a static block inside it
3152 /// to read through `super`.
3153 fn provide_home_object_local(&mut self) {
3154 let current = self.stack.len() - 1;
3155 if !self.stack[current].needs_home_object_local {
3156 return;
3157 }
3158 if !self.stack[current]
3159 .vars
3160 .iter()
3161 .any(|var| var.name == HOME_OBJECT)
3162 {
3163 self.declare_hidden_local(HOME_OBJECT, VarKind::Normal);
3164 }
3165 self.prepend_initialiser(
3166 HOME_OBJECT,
3167 Insn::Fixed {
3168 op: Opcode::SpecialObject,
3169 operands: vec![Op::Int(4)],
3170 },
3171 );
3172 }
3173
3174 fn provide_self_name(&mut self) {
3175 let current = self.stack.len() - 1;
3176 let Some(name) = self.stack[current].self_name.clone() else {
3177 return;
3178 };
3179 if self.stack[current].self_name_initialized {
3180 return;
3181 }
3182 // Either the body refers to the name, or a nested function already forced the
3183 // binding into existence while being resolved. A direct `eval` can name it
3184 // without mentioning it, so its presence is a third reason: in strict mode
3185 // `eval("f = 1")` has to raise a `TypeError` rather than a `ReferenceError`, and
3186 // that only happens if the binding exists.
3187 let declared = self.stack[current].vars.iter().any(|v| v.name == name);
3188 if !declared && !self.mentions(&name) && !self.stack[current].has_direct_eval {
3189 return;
3190 }
3191 self.stack[current].self_name_initialized = true;
3192 self.prepend_binding_with(&name, 2, VarKind::FunctionName);
3193 }
3194
3195 /// Insert `special_object magic` plus the store to `name` at the top of the body.
3196 ///
3197 /// Prepending shifts every label that has been placed, so they are all moved by
3198 /// the number of instructions inserted.
3199 fn prepend_binding(&mut self, name: &str, magic: i32) {
3200 self.prepend_binding_with(name, magic, VarKind::Normal);
3201 }
3202
3203 /// [`Compiler::prepend_binding`] for a binding that is more than a plain local.
3204 fn prepend_binding_with(&mut self, name: &str, magic: i32, kind: VarKind) {
3205 let current = self.stack.len() - 1;
3206 // A function-expression's own name is immutable in strict mode, which is what
3207 // makes `f = 1` inside a strict body throw instead of being dropped.
3208 let is_const = kind == VarKind::FunctionName && self.stack[current].strict;
3209 self.declare_var(
3210 name,
3211 VarDef {
3212 kind,
3213 is_const,
3214 ..VarDef::var(name)
3215 },
3216 );
3217 let init = [
3218 Insn::Fixed {
3219 op: Opcode::SpecialObject,
3220 operands: vec![Op::Int(magic)],
3221 },
3222 Insn::Var {
3223 // An initialisation, not an assignment: sloppy mode drops stores to a
3224 // function-expression's own name, and the prologue is what puts the
3225 // value there in the first place.
3226 action: if kind == VarKind::FunctionName {
3227 VarAction::PutInit
3228 } else {
3229 VarAction::Put
3230 },
3231 name: name.to_string(),
3232 block: 0,
3233 in_params: false,
3234 },
3235 ];
3236 let inserted = init.len();
3237 for (index, instruction) in init.into_iter().enumerate() {
3238 self.stack[current].insns.insert(index, instruction);
3239 }
3240 for placed in self.stack[current].labels.iter_mut().flatten() {
3241 *placed += inserted;
3242 }
3243 // A store sits at the insertion point now, so the `put`/`get` fold must not
3244 // reach across it.
3245 self.stack[current].label_since_insn = true;
3246 }
3247
3248 /// Record a top-level script declaration as a global.
3249 ///
3250 /// A script's top-level `var`/`let`/`function` create properties of the
3251 /// global object, not slots in the script's frame, so they show up as closure
3252 /// variables instead.
3253 fn declare_global(&mut self, name: &str, def: &VarDef) {
3254 let state = self.state();
3255 if let Some(existing) = state.closure_vars.iter_mut().find(|c| c.name == name) {
3256 // The name was already referenced, from a function compiled before this
3257 // declaration was reached — `function a(){ b() } function b(){}` resolves
3258 // `b` while `b` is still unknown, and that guess has to be corrected here.
3259 // Leaving it as a plain global meant the declaration was never registered,
3260 // so the binding did not exist at run time and `a()` threw
3261 // `b is not defined`.
3262 if matches!(existing.closure_type, ClosureType::Global) {
3263 existing.closure_type = ClosureType::GlobalDecl;
3264 existing.is_const = def.is_const;
3265 existing.is_lexical = def.is_lexical;
3266 existing.is_function_decl =
3267 def.kind == crate::bytecode::VarKind::GlobalFunctionDecl;
3268 }
3269 return;
3270 }
3271 state.closure_vars.push(ClosureVar {
3272 name: name.to_string(),
3273 is_const: def.is_const,
3274 is_lexical: def.is_lexical,
3275 is_function_decl: def.kind == crate::bytecode::VarKind::GlobalFunctionDecl,
3276 closure_type: ClosureType::GlobalDecl,
3277 var_idx: 0,
3278 });
3279 }
3280
3281 /// Record a module-level declaration as a module variable.
3282 ///
3283 /// The binding is a closure variable of the module body, so reads and writes are
3284 /// ordinary `var_ref` opcodes — the same shape a captured local has. What differs is
3285 /// *who fills the cell*: the module record does, before the body runs, and an import
3286 /// points its cell at the exporting module's, which is what makes bindings live and
3287 /// cycles work.
3288 fn declare_module(&mut self, name: &str, def: &VarDef) -> u32 {
3289 let state = self.state();
3290 if let Some(existing) = state.closure_vars.iter_mut().find(|c| c.name == name) {
3291 // The name may have been referenced before this declaration was hoisted,
3292 // which resolved it as a plain global. Correct that here, the way
3293 // `declare_global` does.
3294 if matches!(existing.closure_type, ClosureType::Global) {
3295 existing.closure_type = ClosureType::ModuleDecl;
3296 existing.is_const = def.is_const;
3297 existing.is_lexical = def.is_lexical;
3298 }
3299 return 0;
3300 }
3301 state.closure_vars.push(ClosureVar {
3302 name: name.to_string(),
3303 is_const: def.is_const,
3304 is_lexical: def.is_lexical,
3305 is_function_decl: false,
3306 closure_type: ClosureType::ModuleDecl,
3307 var_idx: 0,
3308 });
3309 0
3310 }
3311
3312 /// Declare a module variable and answer its closure-variable index.
3313 ///
3314 /// [`Compiler::declare_module`] answers `0` because its callers want a *slot*, and a
3315 /// module variable is not one. The import table needs the real index instead, because
3316 /// that is the position the host writes the cell into.
3317 fn declare_module_var(&mut self, name: &str, def: &VarDef) -> u32 {
3318 self.declare_module(name, def);
3319 self.cur()
3320 .closure_vars
3321 .iter()
3322 .position(|c| c.name == name)
3323 .map(|index| index as u32)
3324 .unwrap_or(0)
3325 }
3326
3327 /// Declare one imported binding as a module variable.
3328 ///
3329 /// Returns the closure-variable index, which is what the import table records: the
3330 /// host writes the exporter's cell into that slot before the body runs.
3331 fn declare_import(&mut self, name: &str, is_const: bool) -> u32 {
3332 let state = self.state();
3333 if let Some(index) = state.closure_vars.iter().position(|c| c.name == name) {
3334 // Keep the slot, fix the kind: the name may already have been referenced.
3335 state.closure_vars[index].closure_type = ClosureType::ModuleImport;
3336 state.closure_vars[index].is_const = is_const;
3337 return index as u32;
3338 }
3339 state.closure_vars.push(ClosureVar {
3340 name: name.to_string(),
3341 // An imported binding cannot be assigned: `x = 1` on an import is a
3342 // `TypeError` at run time, which the const flag is what produces.
3343 is_const: true,
3344 // Lexical, so reads go through `get_var_ref_check`: before linking has filled
3345 // the cell an import is in its dead zone, and reading it there must say so
3346 // rather than answer `undefined`.
3347 is_lexical: true,
3348 is_function_decl: false,
3349 closure_type: ClosureType::ModuleImport,
3350 var_idx: 0,
3351 });
3352 state.closure_vars.len() as u32 - 1
3353 }
3354
3355 /// Emit the code an `export` needs.
3356 ///
3357 /// Only `export default <expr>` has any: everything else is a table entry whose
3358 /// binding is declared elsewhere. The expression is stored into the hidden
3359 /// `*default*` variable rather than returned, because the module body has no value
3360 /// to speak of.
3361 fn export_stmt(&mut self, decl: &ExportDecl) -> Result<(), SyntaxError> {
3362 match &decl.kind {
3363 ExportKind::Declaration(stmt) => self.stmt(stmt),
3364 ExportKind::Default(expr) => {
3365 // `export default class Foo {}`: evaluate the declaration (which binds
3366 // `Foo`), then copy its value into the hidden `*default*` binding, because a
3367 // class declaration is a *statement* and `expr` cannot be compiled as one.
3368 if let ExprKind::Class(class) = &expr.kind
3369 && class.name.is_some()
3370 {
3371 self.stmt(&Stmt {
3372 kind: StmtKind::ClassDecl(class.clone()),
3373 span: expr.span,
3374 })?;
3375 let Some(name) = &class.name else {
3376 return Ok(());
3377 };
3378 self.emit_var(VarAction::Get, &name.name);
3379 let index = self.declare_export_default();
3380 self.emit(Opcode::PutVarRef, &[Op::Slot(Slot::VarRef(index))]);
3381 return Ok(());
3382 }
3383 // A named default function/class is already a module binding; the export
3384 // points at it and there is nothing to evaluate.
3385 if matches!(&expr.kind, ExprKind::Function(func) if func.name.is_some()) {
3386 return Ok(());
3387 }
3388 self.expr(expr)?;
3389 // §16.2.1.10 step 1.b: an *anonymous* default export is named `"default"`
3390 // by `SetFunctionName`, exactly as `var f = function(){}` is named `f`. The
3391 // name is observable — `imported.default.name` — and without this an
3392 // anonymous `export default class {}` arrived with the empty name.
3393 self.set_name_if_anonymous(expr, &Wtf8::new("default"));
3394 let index = self.declare_export_default();
3395 self.emit(Opcode::PutVarRef, &[Op::Slot(Slot::VarRef(index))]);
3396 Ok(())
3397 }
3398 ExportKind::Named { .. } | ExportKind::All { .. } => Ok(()),
3399 }
3400 }
3401
3402 /// A module name as the string it denotes.
3403 fn module_name_text(name: &ModuleName) -> &str {
3404 match name {
3405 ModuleName::Ident(ident) => &ident.name,
3406 ModuleName::Str(text) => text,
3407 }
3408 }
3409
3410 /// Bind `import`'s local names and record where each one comes from.
3411 ///
3412 /// Nothing is emitted: an import is not an instruction, it is a promise that the
3413 /// binding's cell will be filled before the body runs. The cell lands in the module's
3414 /// environment at a fixed index, and the host fills it from the exporter's cell —
3415 /// which is why a cyclic import can bind before the other module has evaluated.
3416 fn hoist_import(&mut self, decl: &ImportDecl) -> Result<(), SyntaxError> {
3417 let request = self.module_request(&decl.source, &decl.attributes);
3418 for specifier in &decl.specifiers {
3419 let (local, name, is_star) = match specifier {
3420 ImportSpecifier::Default(ident) => {
3421 (ident.name.clone(), "default".to_string(), false)
3422 }
3423 ImportSpecifier::Namespace(ident) => (ident.name.clone(), String::new(), true),
3424 ImportSpecifier::Named { imported, local } => (
3425 local.name.clone(),
3426 Self::module_name_text(imported).to_string(),
3427 false,
3428 ),
3429 };
3430 // `import * as ns` is *not* a live binding of another module's variable —
3431 // it is a value of its own, which is why the reference declares it like a
3432 // module variable and the host stores the namespace object in that cell.
3433 let var_idx = if is_star {
3434 // `const`: a namespace object is a value, and the binding is immutable.
3435 self.declare_module_var(&local, &VarDef::constant(local.clone()))
3436 } else {
3437 self.declare_import(&local, true)
3438 };
3439 self.module_meta().imports.push(ImportEntry {
3440 module: request,
3441 name,
3442 var_idx,
3443 is_star,
3444 });
3445 }
3446 Ok(())
3447 }
3448
3449 /// Record what an `export` offers, declaring the binding it exports.
3450 ///
3451 /// `export var x = 1` is a declaration like any other; only the table entry is extra.
3452 fn hoist_export(&mut self, decl: &ExportDecl) -> Result<(), SyntaxError> {
3453 match &decl.kind {
3454 ExportKind::Declaration(stmt) => {
3455 // The inner declaration keeps its own hoisting, then every name it binds
3456 // becomes an export of the same name.
3457 self.hoist_stmt(stmt)?;
3458 let mut names = Vec::new();
3459 Self::declared_names(stmt, &mut names);
3460 for name in names {
3461 let var_idx = self.module_binding_index(&name);
3462 self.exports_local(&name, var_idx);
3463 }
3464 }
3465 ExportKind::Default(expr) => {
3466 // The reference puts a default export in a hidden `*default*` variable,
3467 // so `export default function f(){}` can export a *value* while `f` stays
3468 // a binding of the module.
3469 if let ExprKind::Function(func) = &expr.kind
3470 && let Some(name) = &func.name
3471 {
3472 let text = name.name.clone();
3473 self.hoist_stmt(&Stmt {
3474 kind: StmtKind::FuncDecl(func.clone()),
3475 span: expr.span,
3476 })?;
3477 let var_idx = self.module_binding_index(&text);
3478 self.module_meta().exports.push(ExportEntry::Local {
3479 export_name: "default".to_string(),
3480 var_idx,
3481 });
3482 return Ok(());
3483 }
3484 if let ExprKind::Class(class) = &expr.kind
3485 && class.name.is_some()
3486 {
3487 // `export default class Foo {}` binds `Foo` in the module scope **and**
3488 // stores the class into the hidden `*default*` binding — it is a
3489 // declaration *and* a value, unlike `export default class {}` which is
3490 // only a value.
3491 //
3492 // Pointing the `default` export straight at `Foo` looked simpler and was
3493 // wrong twice over: `module_binding_index` did not find the lexical
3494 // binding the hoist had just made, so it declared a second one that
3495 // nothing ever wrote, and `export_stmt` then had no code to emit for the
3496 // declaration either. `imported.default` came out `undefined` and `Foo`
3497 // was not in scope inside its own module.
3498 self.hoist_stmt(&Stmt {
3499 kind: StmtKind::ClassDecl(class.clone()),
3500 span: expr.span,
3501 })?;
3502 let var_idx = self.declare_export_default();
3503 self.exports_local("default", var_idx);
3504 return Ok(());
3505 }
3506 let var_idx = self.declare_export_default();
3507 self.module_meta().exports.push(ExportEntry::Local {
3508 export_name: "default".to_string(),
3509 var_idx,
3510 });
3511 }
3512 ExportKind::Named {
3513 specifiers,
3514 source,
3515 attributes,
3516 } => match source {
3517 Some(source) => {
3518 let request = self.module_request(source, attributes);
3519 for specifier in specifiers {
3520 self.module_meta().exports.push(ExportEntry::Indirect {
3521 export_name: Self::module_name_text(&specifier.exported).to_string(),
3522 module: request,
3523 import_name: Self::module_name_text(&specifier.local).to_string(),
3524 });
3525 }
3526 }
3527 None => {
3528 for specifier in specifiers {
3529 let local = Self::module_name_text(&specifier.local).to_string();
3530 let export_name = Self::module_name_text(&specifier.exported).to_string();
3531 // `export { x }` where `x` is itself an **import** re-exports the
3532 // binding the import names, not a binding of this module
3533 // (§16.2.1.6.3: a local export whose local name is imported resolves
3534 // through the imported module). Recording it as a local made two
3535 // modules that both forward one import look like two different
3536 // bindings, and the name was reported ambiguous
3537 // (`import-and-export-propagates-binding`;
3538 // `namespace-unambiguous-if-import-star-as-and-export`).
3539 let closure_names: Vec<String> = self
3540 .cur()
3541 .closure_vars
3542 .iter()
3543 .map(|var| var.name.clone())
3544 .collect();
3545 let forwarded = self
3546 .module_meta()
3547 .imports
3548 .iter()
3549 .filter(|entry| {
3550 closure_names
3551 .get(entry.var_idx as usize)
3552 .is_some_and(|name| *name == local)
3553 })
3554 .map(|entry| (entry.module, entry.name.clone(), entry.is_star))
3555 .find(|(_, name, is_star)| !is_star || name.is_empty());
3556 if let Some((request, name, is_star)) = forwarded {
3557 // A namespace import has no export *name* of its own; the
3558 // resolution is `{ [[Module]]: m, [[BindingName]]: namespace }`,
3559 // which is what the marker below records.
3560 let import_name = if is_star {
3561 "*namespace*".to_string()
3562 } else {
3563 name
3564 };
3565 self.module_meta().exports.push(ExportEntry::Indirect {
3566 export_name,
3567 module: request,
3568 import_name,
3569 });
3570 continue;
3571 }
3572 let var_idx = self.module_binding_index(&local);
3573 self.module_meta().exports.push(ExportEntry::Local {
3574 export_name,
3575 var_idx,
3576 });
3577 }
3578 }
3579 },
3580 ExportKind::All {
3581 source,
3582 exported,
3583 attributes,
3584 } => {
3585 let request = self.module_request(source, attributes);
3586 match exported {
3587 Some(name) => {
3588 self.module_meta().exports.push(ExportEntry::StarAs {
3589 export_name: Self::module_name_text(name).to_string(),
3590 module: request,
3591 });
3592 }
3593 None => {
3594 self.module_meta()
3595 .exports
3596 .push(ExportEntry::Star { module: request });
3597 }
3598 }
3599 }
3600 }
3601 Ok(())
3602 }
3603
3604 /// The names a declaration binds, which is what `export <decl>` exports.
3605 fn declared_names(stmt: &Stmt, out: &mut Vec<String>) {
3606 match &stmt.kind {
3607 StmtKind::VarDecl(decl) => {
3608 for declarator in &decl.declarators {
3609 let mut names = Vec::new();
3610 declarator.target.bound_names(&mut names);
3611 out.extend(names.into_iter().map(|name| name.name));
3612 }
3613 }
3614 StmtKind::FuncDecl(func) => {
3615 if let Some(name) = &func.name {
3616 out.push(name.name.clone());
3617 }
3618 }
3619 StmtKind::ClassDecl(class) => {
3620 if let Some(name) = &class.name {
3621 out.push(name.name.clone());
3622 }
3623 }
3624 _ => {}
3625 }
3626 }
3627
3628 /// The closure-variable index of a module binding, declaring it if the name was
3629 /// exported without being declared here.
3630 ///
3631 /// `export { x }` where `x` is not declared in the module is a link-time
3632 /// `SyntaxError`, not a compile-time one, so the slot still has to exist.
3633 fn module_binding_index(&mut self, name: &str) -> u32 {
3634 if let Some(index) = self.cur().closure_vars.iter().position(|c| c.name == name) {
3635 return index as u32;
3636 }
3637 self.declare_module_var(name, &VarDef::lexical(name.to_string()))
3638 }
3639
3640 fn exports_local(&mut self, export_name: &str, var_idx: u32) {
3641 self.module_meta().exports.push(ExportEntry::Local {
3642 export_name: export_name.to_string(),
3643 var_idx,
3644 });
3645 }
3646
3647 /// The hidden `*default*` binding `export default <expr>` stores into.
3648 fn declare_export_default(&mut self) -> u32 {
3649 const DEFAULT: &str = "*default*";
3650 if let Some(index) = self
3651 .cur()
3652 .closure_vars
3653 .iter()
3654 .position(|c| c.name == DEFAULT)
3655 {
3656 return index as u32;
3657 }
3658 self.declare_module_var(DEFAULT, &VarDef::lexical(DEFAULT.to_string()))
3659 }
3660
3661 /// The module tables, which only the top-level state has.
3662 fn module_meta(&mut self) -> &mut ModuleMeta {
3663 self.state()
3664 .module
3665 .as_mut()
3666 .expect("module tables are only touched while compiling a module")
3667 }
3668
3669 /// The index of `specifier`'s request, adding it if it is new.
3670 ///
3671 /// Deduplicated on the specifier *and* its attributes: the same file imported once as
3672 /// JSON and once as text is two modules with two different contents, which is exactly
3673 /// what `hello_module.js` does.
3674 fn module_request(&mut self, specifier: &str, attributes: &[ImportAttribute]) -> u32 {
3675 let attributes: Vec<(String, String)> = attributes
3676 .iter()
3677 .map(|attribute| (attribute.key.clone(), attribute.value.clone()))
3678 .collect();
3679 let meta = self.module_meta();
3680 if let Some(index) = meta
3681 .requests
3682 .iter()
3683 .position(|request| request.specifier == specifier && request.attributes == attributes)
3684 {
3685 return index as u32;
3686 }
3687 meta.requests.push(ModuleRequest {
3688 specifier: specifier.to_string(),
3689 attributes,
3690 });
3691 meta.requests.len() as u32 - 1
3692 }
3693
3694 /// Compile a loop body with a `break`/`continue` target pushed for it.
3695 fn loop_body(
3696 &mut self,
3697 body: &Stmt,
3698 labels: &[String],
3699 continue_label: Label,
3700 break_label: Label,
3701 ) -> Result<(), SyntaxError> {
3702 self.push_jump_target(JumpTarget {
3703 names: labels.to_vec(),
3704 break_label: Some(break_label),
3705 continue_label: Some(continue_label),
3706 // A loop leaves nothing of its own on the value stack.
3707 drop_count: 0,
3708 finally_label: None,
3709 is_regular_stmt: false,
3710 has_iterator: false,
3711 is_async_iterator: false,
3712 });
3713 let result = self.stmt(body);
3714 self.pop_jump_target();
3715 result
3716 }
3717
3718 fn push_jump_target(&mut self, target: JumpTarget) {
3719 self.state().jump_targets.push(target);
3720 }
3721
3722 fn pop_jump_target(&mut self) {
3723 self.state().jump_targets.pop();
3724 }
3725
3726 fn control_transfer(&mut self, stmt: &Stmt) -> Result<(), SyntaxError> {
3727 let (label, is_break) = match &stmt.kind {
3728 StmtKind::Break(label) => (label.as_ref(), true),
3729 StmtKind::Continue(label) => (label.as_ref(), false),
3730 _ => unreachable!("control_transfer is only called for break and continue"),
3731 };
3732
3733 // Walk outward from the innermost construct. Everything considered before
3734 // the match is a construct control is leaving, and leaving it has a cost:
3735 // its stack slots go, and its finalizer runs.
3736 let targets = self.cur().jump_targets.clone();
3737 for target in targets.iter().rev() {
3738 let destination = match (label, is_break) {
3739 // An unlabelled `break` skips a labelled non-loop statement: `break`
3740 // may name one, but the bare form only means "leave the loop".
3741 (None, true) => target.break_label.filter(|_| !target.is_regular_stmt),
3742 (None, false) => target.continue_label,
3743 (Some(name), true) => target
3744 .break_label
3745 .filter(|_| target.names.contains(&name.name)),
3746 (Some(name), false) => target
3747 .continue_label
3748 .filter(|_| target.names.contains(&name.name)),
3749 };
3750
3751 if let Some(destination) = destination {
3752 self.emit_jump(Opcode::Goto, destination, &[]);
3753 return Ok(());
3754 }
3755
3756 // Closing the iterator consumes the three slots the loop keeps on the
3757 // stack (iterator, next method, catch offset), so those are not dropped
3758 // again below.
3759 let mut remaining = target.drop_count;
3760 if target.has_iterator {
3761 self.emit_iterator_close(target.is_async_iterator, false);
3762 remaining = remaining.saturating_sub(3);
3763 }
3764 for _ in 0..remaining {
3765 self.emit(Opcode::Drop, &[]);
3766 }
3767 if let Some(finally) = target.finally_label {
3768 // The finalizer runs as a subroutine and is handed a dummy return
3769 // value, which is dropped afterwards to keep the stack the depth it
3770 // had before.
3771 self.emit(Opcode::Undefined, &[]);
3772 self.emit_jump(Opcode::Gosub, finally, &[]);
3773 self.emit(Opcode::Drop, &[]);
3774 }
3775 }
3776
3777 // The parser rejects a break/continue with no target, so reaching here
3778 // means the compiler's own bookkeeping is wrong.
3779 Err(SyntaxError::new(
3780 if is_break {
3781 "break has no enclosing loop or switch"
3782 } else {
3783 "continue has no enclosing loop"
3784 },
3785 stmt.span,
3786 ))
3787 }
3788
3789 /// Compile a labelled statement.
3790 ///
3791 /// `a: b: for(…)` is a chain of labels on one loop; every name has to reach
3792 /// that loop's targets, so the chain is collected and handed to the loop. A
3793 /// label on a non-loop statement only provides a `break` target, because
3794 /// `continue` may not target it.
3795 fn labeled(&mut self, label: &Ident, body: &Stmt, stmt: &Stmt) -> Result<(), SyntaxError> {
3796 let mut names = vec![label.name.clone()];
3797 let mut inner = body;
3798 while let StmtKind::Labeled {
3799 label: next,
3800 body: deeper,
3801 } = &inner.kind
3802 {
3803 names.push(next.name.clone());
3804 inner = deeper;
3805 }
3806 if Self::is_loop(inner) {
3807 return self.stmt_labelled(inner, &names);
3808 }
3809 let end = self.new_label();
3810 self.push_jump_target(JumpTarget {
3811 names,
3812 break_label: Some(end),
3813 continue_label: None,
3814 drop_count: 0,
3815 finally_label: None,
3816 is_regular_stmt: true,
3817 has_iterator: false,
3818 is_async_iterator: false,
3819 });
3820 let result = self.stmt(inner);
3821 self.pop_jump_target();
3822 result?;
3823 self.place_label(end);
3824 let _ = stmt;
3825 Ok(())
3826 }
3827
3828 /// Whether a statement is a loop, i.e. a valid target for `continue`.
3829 fn is_loop(stmt: &Stmt) -> bool {
3830 matches!(
3831 stmt.kind,
3832 StmtKind::While { .. }
3833 | StmtKind::DoWhile { .. }
3834 | StmtKind::For { .. }
3835 | StmtKind::ForIn { .. }
3836 | StmtKind::ForOf { .. }
3837 )
3838 }
3839
3840 /// Compile `switch`.
3841 ///
3842 /// The discriminant is evaluated once and stays on the value stack while the
3843 /// clauses compare against copies of it, so it is dropped at the end — which is
3844 /// why `switch (x) { }` still leaves `x` behind. Fallthrough is real: a
3845 /// clause's body jumps over the *next* clause's tests straight into its body.
3846 ///
3847 /// The tests form a chain: each `case` run compares and, on a miss, hands over to
3848 /// the next run's tests. Only the last run's miss reaches the `default` body, or
3849 /// the end of the switch when there is no `default`. That failure path can point
3850 /// backwards (`default` written first), so the runs and their labels are worked
3851 /// out before any code is emitted.
3852 fn switch(
3853 &mut self,
3854 discriminant: &Expr,
3855 cases: &[SwitchCase],
3856 stmt: &Stmt,
3857 ) -> Result<(), SyntaxError> {
3858 self.reset_value();
3859 // The discriminant is evaluated outside the switch's block scope, before
3860 // any `case` clause exists.
3861 self.expr(discriminant)?;
3862
3863 let switch_key = stmt.span.start.offset as u64;
3864 let switch_parent = self.cur().current_block;
3865 self.push_block(switch_key, switch_parent);
3866 self.emit_scope_enter(switch_key);
3867
3868 let break_label = self.new_label();
3869 self.push_jump_target(JumpTarget {
3870 names: Vec::new(),
3871 break_label: Some(break_label),
3872 // `switch` is a valid `break` target but not a `continue` target.
3873 continue_label: None,
3874 // The discriminant stays on the value stack for the whole statement, so
3875 // a `break` aimed further out has to discard it.
3876 drop_count: 1,
3877 finally_label: None,
3878 is_regular_stmt: false,
3879 has_iterator: false,
3880 is_async_iterator: false,
3881 });
3882
3883 // Runs of tests. `case 1: case 2: body` is one run: the empty clause hands
3884 // its label to the clause after it, so both tests reach the same body.
3885 let mut runs: Vec<(usize, usize)> = Vec::new();
3886 let mut scan = 0;
3887 while scan < cases.len() {
3888 if cases[scan].test.is_some() {
3889 let mut last = scan;
3890 while last + 1 < cases.len()
3891 && cases[last].test.is_some()
3892 && cases[last].body.is_empty()
3893 && cases[last + 1].test.is_some()
3894 {
3895 last += 1;
3896 }
3897 runs.push((scan, last));
3898 scan = last + 1;
3899 } else {
3900 scan += 1;
3901 }
3902 }
3903
3904 let body_labels: Vec<Label> = cases.iter().map(|_| self.new_label()).collect();
3905 let run_labels: Vec<Label> = runs.iter().map(|_| self.new_label()).collect();
3906 let default_at = cases.iter().position(|case| case.test.is_none());
3907 // Where the last run sends control when nothing matched.
3908 let miss_target = match default_at {
3909 Some(index) => body_labels[index],
3910 None => break_label,
3911 };
3912
3913 // When `default` comes first, control has to jump over it to reach the
3914 // tests. It only needs to when some clause actually has a test; otherwise
3915 // the default body is the entry point.
3916 let mut entry = None;
3917 if default_at == Some(0) && !runs.is_empty() {
3918 self.emit_jump(Opcode::Goto, run_labels[0], &[]);
3919 entry = Some(run_labels[0]);
3920 }
3921
3922 let mut index = 0;
3923 let mut run = 0;
3924 let result = (|| -> Result<(), SyntaxError> {
3925 while index < cases.len() {
3926 if cases[index].test.is_some() {
3927 let (first, last) = runs[run];
3928 // Reaching these tests from the preceding body is a
3929 // fallthrough, which continues inside the body and skips them.
3930 if index > 0 {
3931 self.emit_jump(Opcode::Goto, body_labels[index], &[]);
3932 }
3933 if let Some(label) = entry.take() {
3934 self.place_label(label);
3935 }
3936 self.place_label(run_labels[run]);
3937
3938 for (offset, case) in cases[first..=last].iter().enumerate() {
3939 let test = case.test.as_ref().unwrap();
3940 self.emit(Opcode::Dup, &[]);
3941 self.expr(test)?;
3942 self.emit(Opcode::StrictEq, &[]);
3943 if first + offset < last {
3944 self.emit_jump(Opcode::IfTrue, body_labels[index], &[]);
3945 } else {
3946 // Hand over to the next run's tests, or give up.
3947 let next = match runs.get(run + 1) {
3948 Some(_) => run_labels[run + 1],
3949 None => miss_target,
3950 };
3951 self.emit_jump(Opcode::IfFalse, next, &[]);
3952 }
3953 }
3954
3955 self.place_label(body_labels[index]);
3956 for case in &cases[first..=last] {
3957 self.stmts(&case.body)?;
3958 }
3959 index = last + 1;
3960 run += 1;
3961 } else {
3962 // `default`: control arrives here either by falling through or
3963 // because every test missed.
3964 self.place_label(body_labels[index]);
3965 self.stmts(&cases[index].body)?;
3966 index += 1;
3967 }
3968 }
3969 Ok(())
3970 })();
3971
3972 if result.is_ok() {
3973 self.place_label(break_label);
3974 // Discard the discriminant now that no test needs it.
3975 self.emit(Opcode::Drop, &[]);
3976 }
3977
3978 self.pop_jump_target();
3979 self.emit_scope_leave(switch_key);
3980 self.state().current_block = switch_parent;
3981 result
3982 }
3983
3984 /// Compile `try`/`catch`/`finally`.
3985 ///
3986 /// The shape is an exception table built out of `catch` instructions, each of
3987 /// which records where control goes if the instructions that follow raise:
3988 ///
3989 /// ```text
3990 /// catch HANDLER <- if the guarded block throws, jump to HANDLER
3991 /// <guarded block>
3992 /// drop <- discard the catch offset
3993 /// undefined; gosub FINALLY; drop
3994 /// goto END
3995 /// HANDLER:
3996 /// <bind the catch parameter>
3997 /// catch CATCH2 <- if the handler itself throws, go to CATCH2
3998 /// <handler body>
3999 /// drop; undefined; gosub FINALLY; drop; goto END
4000 /// CATCH2:
4001 /// gosub FINALLY; throw <- run the finalizer, then let the error out
4002 /// FINALLY:
4003 /// <finalizer>
4004 /// ret <- return to the `gosub`
4005 /// END:
4006 /// ```
4007 ///
4008 /// `gosub` is a subroutine call and `ret` returns to it, which is how one copy
4009 /// of the finalizer serves the normal path, the handler path and the
4010 /// propagating-exception path.
4011 ///
4012 /// The `undefined` before each `gosub` is a dummy return value: the finalizer
4013 /// runs with `ret_value` on the stack, and the normal path has no value to
4014 /// keep, so it pushes one to keep the stack depth identical on every path.
4015 fn try_stmt(
4016 &mut self,
4017 stmt: &Stmt,
4018 block: &[Stmt],
4019 handler: &Option<CatchClause>,
4020 finalizer: Option<&[Stmt]>,
4021 ) -> Result<(), SyntaxError> {
4022 self.reset_value();
4023
4024 let catch_label = self.new_label();
4025 let catch2_label = self.new_label();
4026 let finally_label = self.new_label();
4027 let end_label = self.new_label();
4028
4029 self.emit_jump(Opcode::Catch, catch_label, &[]);
4030
4031 // The guarded block. `break` may not target it, so its entry exists purely
4032 // to unwind: a jump out has to discard the catch offset and run the
4033 // finalizer.
4034 self.push_jump_target(JumpTarget {
4035 names: Vec::new(),
4036 break_label: None,
4037 continue_label: None,
4038 drop_count: 1,
4039 finally_label: Some(finally_label),
4040 is_regular_stmt: false,
4041 has_iterator: false,
4042 is_async_iterator: false,
4043 });
4044
4045 let block_key = Self::try_block_key(stmt, TryPart::Block);
4046 let block_parent = self.cur().current_block;
4047 self.push_block(block_key, block_parent);
4048 self.emit_scope_enter(block_key);
4049 self.stmts(block)?;
4050 self.emit_scope_leave(block_key);
4051 self.state().current_block = block_parent;
4052 // A guarded block that ends in a `return`/`throw` never reaches the
4053 // epilogue, so the reference does not emit one.
4054 self.pop_jump_target();
4055 let block_live = !block.last().is_some_and(Self::terminates);
4056
4057 if block_live {
4058 self.emit(Opcode::Drop, &[]);
4059 self.emit(Opcode::Undefined, &[]);
4060 self.emit_jump(Opcode::Gosub, finally_label, &[]);
4061 self.emit(Opcode::Drop, &[]);
4062 self.emit_jump(Opcode::Goto, end_label, &[]);
4063 }
4064
4065 if let Some(handler) = handler {
4066 self.place_label(catch_label);
4067 // The thrown value is on top of the stack: bind it, or discard it for
4068 // `catch { }`.
4069 match &handler.param {
4070 Some(pattern) => {
4071 // The stores resolve the names, so they have to run inside the
4072 // parameter's own scope; otherwise a same-named `catch` further out
4073 // could win. A `catch` binding is never in the dead zone, so the store
4074 // is the unchecked `put_loc` — the same one a plain `catch (e)` uses.
4075 let param_key = Self::try_block_key(stmt, TryPart::Param);
4076 let param_parent = self.cur().current_block;
4077 self.push_block(param_key, param_parent);
4078 self.destructure(pattern, Some(VarDeclKind::Var))?;
4079 self.state().current_block = param_parent;
4080 }
4081 None => self.emit(Opcode::Drop, &[]),
4082 }
4083 self.emit_jump(Opcode::Catch, catch2_label, &[]);
4084
4085 self.push_jump_target(JumpTarget {
4086 names: Vec::new(),
4087 break_label: None,
4088 continue_label: None,
4089 drop_count: 1,
4090 finally_label: Some(finally_label),
4091 is_regular_stmt: false,
4092 has_iterator: false,
4093 is_async_iterator: false,
4094 });
4095 let catch_key = Self::try_block_key(stmt, TryPart::Catch);
4096 let catch_parent = self.cur().current_block;
4097 self.push_block(catch_key, catch_parent);
4098 self.emit_scope_enter(catch_key);
4099 self.stmts(&handler.body)?;
4100 self.emit_scope_leave(catch_key);
4101 self.state().current_block = catch_parent;
4102 self.pop_jump_target();
4103 let handler_live = !handler.body.last().is_some_and(Self::terminates);
4104
4105 if handler_live {
4106 self.emit(Opcode::Drop, &[]);
4107 self.emit(Opcode::Undefined, &[]);
4108 self.emit_jump(Opcode::Gosub, finally_label, &[]);
4109 self.emit(Opcode::Drop, &[]);
4110 self.emit_jump(Opcode::Goto, end_label, &[]);
4111 }
4112
4113 // An error raised inside the handler still has to run the finalizer.
4114 self.place_label(catch2_label);
4115 self.emit_jump(Opcode::Gosub, finally_label, &[]);
4116 self.emit(Opcode::Throw, &[]);
4117 } else {
4118 // `try`/`finally` with no handler: the finalizer runs, then the error
4119 // keeps propagating.
4120 self.place_label(catch_label);
4121 self.emit_jump(Opcode::Gosub, finally_label, &[]);
4122 self.emit(Opcode::Throw, &[]);
4123 }
4124
4125 self.place_label(finally_label);
4126 // Inside the finalizer, leaving has a different cost: the return value and
4127 // the `gosub` return address are both on the stack, and neither finalizer nor
4128 // any outer one may run before the block has finished.
4129 self.push_jump_target(JumpTarget {
4130 names: Vec::new(),
4131 break_label: None,
4132 continue_label: None,
4133 drop_count: 2,
4134 finally_label: None,
4135 is_regular_stmt: false,
4136 has_iterator: false,
4137 is_async_iterator: false,
4138 });
4139 // §14.15.3 step 7: a finalizer that completes **normally** is discarded — the
4140 // `try` block's completion is what the statement answers. Only an abrupt exit from
4141 // the finalizer (`break`, `return`, a throw) replaces it, and that path jumps out
4142 // before the restore below.
4143 //
4144 // Without this the finalizer's last expression statement won: `eval('4; try { }
4145 // catch { } finally { 5; }')` answered `5` where the spec says `undefined`
4146 // (`cptn-finally-skip-catch`, `completion-values`).
4147 let saved_completion = if finalizer.is_some() && self.completion_slot().is_some() {
4148 self.declare_hidden_local("<finally.ret>", VarKind::Normal);
4149 self.emit_var(VarAction::Get, "<ret>");
4150 self.emit_var(VarAction::Put, "<finally.ret>");
4151 // And the body starts from *empty*, because an abrupt exit from the finalizer
4152 // keeps whatever the finalizer itself produced: `finally { break; }` answers
4153 // `undefined`, not the `try` block's value, while `finally { 42; break; }`
4154 // answers `42`. §14.15.3's `UpdateEmpty(F, undefined)` is what fills the empty
4155 // one in.
4156 self.emit(Opcode::Undefined, &[]);
4157 self.emit_var(VarAction::Put, "<ret>");
4158 true
4159 } else {
4160 false
4161 };
4162 if let Some(finalizer) = finalizer {
4163 let finally_key = Self::try_block_key(stmt, TryPart::Finally);
4164 let finally_parent = self.cur().current_block;
4165 self.push_block(finally_key, finally_parent);
4166 self.emit_scope_enter(finally_key);
4167 self.stmts(finalizer)?;
4168 self.emit_scope_leave(finally_key);
4169 self.state().current_block = finally_parent;
4170 }
4171 if saved_completion {
4172 // The finalizer's own statements have already run, so restoring now is what
4173 // discards a normal completion.
4174 self.emit_var(VarAction::Get, "<finally.ret>");
4175 self.emit_var(VarAction::Put, "<ret>");
4176 }
4177 self.pop_jump_target();
4178 self.emit(Opcode::Ret, &[]);
4179 self.place_label(end_label);
4180 Ok(())
4181 }
4182
4183 /// The slot of the completion-value local, when this body has one.
4184 ///
4185 /// Only a script or `eval` body has `<ret>`: a function's completion value is not
4186 /// observable, so there is nothing to keep.
4187 fn completion_slot(&self) -> Option<u32> {
4188 self.cur()
4189 .vars
4190 .iter()
4191 .position(|var| var.name == "<ret>")
4192 .map(|index| index as u32)
4193 }
4194
4195 /// Compile `for`/`in` and `for`/`of`.
4196 ///
4197 /// Both keep an enumeration record on the value stack for the whole loop, which
4198 /// is what makes leaving early expensive: the record has to be dropped, or the
4199 /// iterator closed. The layout is
4200 ///
4201 /// ```text
4202 /// <iterated expression>
4203 /// for_in_start | for_of_start <- pushes the record
4204 /// goto TEST
4205 /// NEXT:
4206 /// <bind the loop variable>
4207 /// <body>
4208 /// TEST:
4209 /// for_in_next | for_of_next 0
4210 /// if_false NEXT <- not finished: next iteration
4211 /// drop <- finished: discard the leftover value
4212 /// BREAK:
4213 /// drop | iterator_close <- the one cleanup `break` also uses
4214 /// ```
4215 ///
4216 /// `BREAK` sits *on* the cleanup rather than after it, so an early exit and the
4217 /// normal exit share one copy — which is why `break` inside the loop emits nothing
4218 /// of its own, and only a jump that passes *through* the loop pays for its record.
4219 fn for_in_of(
4220 &mut self,
4221 stmt: &Stmt,
4222 left: &ForHead,
4223 right: &Expr,
4224 body: &Stmt,
4225 kind: ForLoopKind,
4226 labels: &[String],
4227 ) -> Result<(), SyntaxError> {
4228 self.reset_value();
4229
4230 let loop_key = stmt.span.start.offset as u64;
4231 let loop_parent = self.cur().current_block;
4232 self.push_block(loop_key, loop_parent);
4233 self.emit_scope_enter(loop_key);
4234
4235 // The iterated expression is evaluated inside the loop's scope, after the
4236 // bindings exist in the temporal dead zone.
4237 self.expr(right)?;
4238
4239 let next = self.new_label();
4240 let test = self.new_label();
4241 let break_target = self.new_label();
4242
4243 let has_iterator = matches!(kind, ForLoopKind::Of | ForLoopKind::AwaitOf);
4244 match kind {
4245 ForLoopKind::In => self.emit(Opcode::ForInStart, &[]),
4246 ForLoopKind::Of => self.emit(Opcode::ForOfStart, &[]),
4247 ForLoopKind::AwaitOf => self.emit(Opcode::ForAwaitOfStart, &[]),
4248 }
4249 self.emit_jump(Opcode::Goto, test, &[]);
4250
4251 self.push_jump_target(JumpTarget {
4252 // `outer: for (x of xs) … break outer` needs the name here. Without it the
4253 // loop had no label to break to, and the compiler reported "break has no
4254 // enclosing loop" for a loop that was plainly enclosing it.
4255 names: labels.to_vec(),
4256 break_label: Some(break_target),
4257 continue_label: Some(test),
4258 // Passing through the loop has to dispose of its record. A `for`/`of`
4259 // record is three slots, and closing the iterator consumes all of them.
4260 drop_count: if has_iterator { 3 } else { 1 },
4261 finally_label: None,
4262 is_regular_stmt: false,
4263 has_iterator,
4264 is_async_iterator: matches!(kind, ForLoopKind::AwaitOf),
4265 });
4266
4267 self.place_label(next);
4268 self.bind_loop_variable(left)?;
4269
4270 // The reference marks the body with its own label here. Nothing jumps to it
4271 // once the loop is laid out, but it is not decoration: a label between the
4272 // store and the body is why `put_loc v; get_loc v` does *not* fold into
4273 // `set_loc v` when the body starts by reading the loop variable.
4274 let body_label = self.new_label();
4275 self.place_label(body_label);
4276 // `for (using x of …)` disposes once per iteration, so the body is a disposal
4277 // region rather than the whole loop: the resource is the element that this
4278 // iteration produced.
4279 let using_head = match left {
4280 ForHead::VarDecl(decl) if decl.kind.is_using() => {
4281 let slot =
4282 decl.declarators
4283 .first()
4284 .and_then(|declarator| match &declarator.target.kind {
4285 PatternKind::Ident(ident) => self.using_value_slot(&ident.name),
4286 _ => None,
4287 });
4288 slot.map(|slot| (slot, decl.kind == VarDeclKind::AwaitUsing))
4289 }
4290 _ => None,
4291 };
4292 match using_head {
4293 Some((slot, awaited)) => {
4294 let live = !Self::terminates(body);
4295 self.using_region_around(slot, live, awaited, |compiler| compiler.stmt(body))?;
4296 }
4297 None => self.stmt(body)?,
4298 }
4299
4300 // §14.7.5.6 `ForIn/OfBodyEvaluation` step 6: a `let`/`const` head gets a **fresh
4301 // binding each iteration**, so a closure the body creates keeps that iteration's
4302 // value. `CloseCaptured` is the same instruction the C-style `for` uses: it swaps in
4303 // a new reference cell holding the current value.
4304 //
4305 // The position is the *end* of the body, not the start: closing before the body
4306 // would leave the closures pointing at the cell the next `put_loc` overwrites, and
4307 // `for (const x of [1,2,3]) fs.push(() => x)` answered `2,3,3` instead of `1,2,3`.
4308 for name in Self::loop_binding_names(left) {
4309 let pos = self.cur().cur_pos;
4310 self.state().insns.push(Insn::CloseCaptured {
4311 name,
4312 block: loop_key,
4313 });
4314 self.state().insn_pos.push(pos);
4315 }
4316 self.place_label(test);
4317 match kind {
4318 ForLoopKind::In => self.emit(Opcode::ForInNext, &[]),
4319 ForLoopKind::Of => self.emit(Opcode::ForOfNext, &[Op::Int(0)]),
4320 ForLoopKind::AwaitOf => {
4321 // The reference's shape: step, `await` the result, then unpack it.
4322 self.emit(Opcode::ForAwaitOfNext, &[Op::Int(0)]);
4323 self.emit(Opcode::Await, &[]);
4324 self.state().has_await = true;
4325 self.emit(Opcode::IteratorGetValueDone, &[]);
4326 }
4327 }
4328 self.emit_jump(Opcode::IfFalse, next, &[]);
4329 // The loop is finished; `for_xx_next` left an `undefined` behind.
4330 self.emit(Opcode::Drop, &[]);
4331
4332 self.pop_jump_target();
4333 self.place_label(break_target);
4334 if has_iterator {
4335 // A loop that ran to completion finds its iterator slot already cleared (see
4336 // `iterator_get_value_done`), so this closes only an iterator abandoned by a
4337 // `break` that jumped here.
4338 self.emit_iterator_close(matches!(kind, ForLoopKind::AwaitOf), false);
4339 } else {
4340 self.emit(Opcode::Drop, &[]);
4341 }
4342
4343 self.emit_scope_leave(loop_key);
4344 self.state().current_block = loop_parent;
4345 Ok(())
4346 }
4347
4348 /// The names a `for (let … of/in …)` head declares, which need a fresh cell per
4349 /// iteration. An assignment head (`for (x of …)`) declares nothing, so it is empty.
4350 fn loop_binding_names(left: &ForHead) -> Vec<String> {
4351 let ForHead::VarDecl(decl) = left else {
4352 return Vec::new();
4353 };
4354 if decl.kind == VarDeclKind::Var {
4355 return Vec::new();
4356 }
4357 let mut names = Vec::new();
4358 for declarator in &decl.declarators {
4359 let mut idents = Vec::new();
4360 declarator.target.bound_names(&mut idents);
4361 names.extend(idents.into_iter().map(|ident| ident.name));
4362 }
4363 names
4364 }
4365
4366 /// Store the value `for_xx_next` left on the stack into the loop variable.
4367 fn bind_loop_variable(&mut self, left: &ForHead) -> Result<(), SyntaxError> {
4368 // A declaration *initialises* the binding, which is what takes a `let` out of
4369 // the temporal dead zone, so the store is the unchecked form. Assigning to a
4370 // binding declared elsewhere is an ordinary write and keeps its check.
4371 let (pattern, action) = match left {
4372 ForHead::VarDecl(decl) => (&decl.declarators[0].target, VarAction::PutInit),
4373 ForHead::Assign(pattern) => (pattern.as_ref(), VarAction::Put),
4374 };
4375 match &pattern.kind {
4376 PatternKind::Ident(name) => {
4377 // `for (using x of …)` validates and snapshots each iteration's value
4378 // before the body runs, which is what makes a non-disposable element fail
4379 // on the iteration that produced it rather than at the end of the loop.
4380 if let ForHead::VarDecl(decl) = left
4381 && decl.kind.is_using()
4382 {
4383 let method_slot = self
4384 .using_method_slot(&name.name)
4385 .expect("a using binding was declared during hoisting");
4386 self.emit(
4387 Opcode::UsingCheck,
4388 &[Op::Int(if decl.kind.is_await_using() { 1 } else { 0 })],
4389 );
4390 self.emit(Opcode::PutLoc, &[Op::Slot(Slot::Loc(method_slot))]);
4391 }
4392 self.emit_var(action, &name.name);
4393 Ok(())
4394 }
4395 // Every other target stores through the same path an assignment pattern
4396 // uses, which is what makes `for (a[0] in obj)` write each key into the
4397 // property instead of refusing the loop outright.
4398 _ => self.destructure(
4399 pattern,
4400 match left {
4401 ForHead::VarDecl(decl) => Some(decl.kind),
4402 ForHead::Assign(_) => None,
4403 },
4404 ),
4405 }
4406 }
4407
4408 fn var_decl(&mut self, decl: &VarDecl) -> Result<(), SyntaxError> {
4409 for declarator in &decl.declarators {
4410 let Some(init) = &declarator.init else {
4411 // `var x;` stays `undefined`. A lexical binding is different: it
4412 // has to be *initialised* to leave the temporal dead zone, so the
4413 // compiler supplies an explicit `undefined`.
4414 if decl.kind.is_lexical() {
4415 // A lexical binding has to be *initialised* to leave the temporal
4416 // dead zone, and a destructuring one is no different — `let {a}`
4417 // with no initialiser is a syntax error, but `let [a] = []` still
4418 // needs `a` to be initialised from an empty source, which the
4419 // pattern does on its own.
4420 self.emit(Opcode::Undefined, &[]);
4421 self.destructure(&declarator.target, Some(decl.kind))?;
4422 }
4423 continue;
4424 };
4425 match &declarator.target.kind {
4426 PatternKind::Ident(name) => {
4427 self.expr(init)?;
4428 self.set_name_if_anonymous(init, &Wtf8::new(&name.name));
4429 if decl.kind.is_using() {
4430 // `using_check` validates the value and snapshots its dispose
4431 // method: `value -> value, method`. The snapshot is what makes a
4432 // later change to `Symbol.dispose` irrelevant, and validating here
4433 // is what keeps the body from running at all when the value is not
4434 // disposable.
4435 let method_slot = self
4436 .using_method_slot(&name.name)
4437 .expect("a using binding was declared during hoisting");
4438 self.emit(
4439 Opcode::UsingCheck,
4440 &[Op::Int(if decl.kind.is_await_using() { 1 } else { 0 })],
4441 );
4442 self.emit(Opcode::PutLoc, &[Op::Slot(Slot::Loc(method_slot))]);
4443 self.emit_var(VarAction::PutInit, &name.name);
4444 continue;
4445 }
4446 // A declaration statement produces no value, so nothing is
4447 // duplicated onto the stack.
4448 match decl.kind {
4449 VarDeclKind::Var => self.emit_var(VarAction::Put, &name.name),
4450 _ => self.emit_var(VarAction::PutInit, &name.name),
4451 }
4452 }
4453 _ => {
4454 // A destructuring declaration keeps nothing on the stack: the
4455 // pattern consumes the initialiser.
4456 self.expr(init)?;
4457 self.destructure(&declarator.target, Some(decl.kind))?;
4458 }
4459 }
4460 }
4461 Ok(())
4462 }
4463
4464 /// Bind a destructuring pattern from the value on top of the stack.
4465 ///
4466 /// `decl` picks the mode. `Some(kind)` is a *declaration*: every target is an
4467 /// identifier and the store is a binding write, `put_*` for `var` and `put_*_init`
4468 /// for `let`/`const` so the binding leaves its dead zone. `None` is a destructuring
4469 /// *assignment*, where a member expression is a legal target and the store is an
4470 /// ordinary property write.
4471 ///
4472 /// The value is consumed. An assignment expression's own result is the right-hand
4473 /// side, which the caller keeps separately — the spec does not make the pattern's
4474 /// last store produce it.
4475 fn destructure(
4476 &mut self,
4477 pattern: &Pattern,
4478 decl: Option<VarDeclKind>,
4479 ) -> Result<(), SyntaxError> {
4480 match &pattern.kind {
4481 PatternKind::Ident(name) => {
4482 match decl {
4483 Some(VarDeclKind::Var) | None => {
4484 self.emit_var(VarAction::Put, &name.name);
4485 }
4486 Some(_) => self.emit_var(VarAction::PutInit, &name.name),
4487 }
4488 Ok(())
4489 }
4490 PatternKind::Assign { target, default } => {
4491 // A default only applies to `undefined`, not to `null`: `[a = 1] = [null]`
4492 // keeps `null`.
4493 //
4494 // The shape is the reference's: test for `undefined`, and when the value is
4495 // present fall **through** to a single store both paths share. The
4496 // alternatives — branching to the store on each side — need a second store
4497 // and a jump between them, which is what the dump used to show.
4498 let has_value = self.new_label();
4499 self.emit(Opcode::Dup, &[]);
4500 self.emit(Opcode::IsUndefined, &[]);
4501 self.emit_jump(Opcode::IfFalse, has_value, &[]);
4502 self.emit(Opcode::Drop, &[]);
4503 self.expr(default)?;
4504 // `var {f = function(){}} = {}` names the function `f`, like a plain
4505 // `var f = function(){}` does. Both pattern forms do it:
4506 // `BindingInitialization` names the value for a *binding* target, and since
4507 // ES2018 `DestructuringAssignmentEvaluation` does the same, so
4508 // `[f = () => {}] = []` also leaves `f.name === "f"`. A member target has
4509 // no name to give, which is why only an identifier qualifies.
4510 if let PatternKind::Ident(name) = &target.kind {
4511 self.set_name_if_anonymous(default, &Wtf8::new(&name.name));
4512 }
4513 self.place_label(has_value);
4514 self.destructure(target, decl)
4515 }
4516 PatternKind::Array { elements, rest } => self.destructure_array(elements, rest, decl),
4517 PatternKind::Object { properties, rest } => {
4518 self.destructure_object(properties, rest, decl, pattern)
4519 }
4520 PatternKind::Member(member) if decl.is_none() => {
4521 // An assignment pattern may store into a property. The value is on the
4522 // stack, so the receiver and the key go above it and `rot3l`/`swap2`
4523 // put the three in the order `put_array_el`/`put_field` expect.
4524 self.expr(&member.object)?;
4525 match &member.property {
4526 MemberProp::Ident(name) => {
4527 // `value obj` -> `obj value`, the order `put_field` takes.
4528 // Nothing needs to be left behind: a pattern element's value is
4529 // consumed by its own store.
4530 self.emit(Opcode::Swap, &[]);
4531 self.emit(Opcode::PutField, &[Op::Atom(Atom::from_text(&name.name))]);
4532 }
4533 MemberProp::Computed(index) => {
4534 self.expr(index)?;
4535 // `value obj key` -> `obj key value`.
4536 self.emit(Opcode::Rot3l, &[]);
4537 self.emit(Opcode::PutArrayEl, &[]);
4538 }
4539 MemberProp::Private(name) => {
4540 // `value obj` -> `obj value`, and the store half of the assignment is
4541 // the same one `obj.#x = value` uses — only without `insert2`,
4542 // because a pattern element's value is not wanted back.
4543 let binding = format!("#{}", name.name);
4544 let (kind, setter) = self.private_use(&binding, member.span)?;
4545 self.emit(Opcode::Swap, &[]);
4546 self.private_store(&binding, kind, setter.as_deref())?;
4547 }
4548 }
4549 Ok(())
4550 }
4551 PatternKind::Rest(inner) => self.destructure(inner, decl),
4552 PatternKind::Invalid(expr) => {
4553 Err(SyntaxError::new("invalid assignment target", expr.span))
4554 }
4555 _ => Err(SyntaxError::new(
4556 "this destructuring target is not supported by the compiler yet",
4557 pattern.span,
4558 )),
4559 }
4560 }
4561
4562 /// `[…]` on the left: drain an iterator, binding one target per element.
4563 ///
4564 /// A target that stores into a **property** — `[o.p] = it` — has its reference worked
4565 /// out *before* the value is pulled. That ordering is observable twice over
4566 /// (`array-elem-iter-thrw-close`):
4567 ///
4568 /// * `next` must not have been called yet when the reference throws, so
4569 /// `[ {}[thrower()] ] = iterable` reports `nextCount === 0`;
4570 /// * the iterator must still be closed, because the throw happens while the record is
4571 /// live — which is `catch_here`'s `catch_offset 0` doing its work.
4572 ///
4573 /// Doing it the other way round — pull the value, then evaluate the reference — got
4574 /// both wrong: an extra `next` call, and, when the reference threw, an iterator that had
4575 /// already been drained past.
4576 fn destructure_array(
4577 &mut self,
4578 elements: &[Option<PatternElement>],
4579 rest: &Option<Box<RestElement>>,
4580 decl: Option<VarDeclKind>,
4581 ) -> Result<(), SyntaxError> {
4582 // The iterator protocol is the same one `for (… of …)` uses, so a destructuring
4583 // pattern accepts any iterable and closes the iterator when the pattern ends
4584 // early. `for_of_next` pushes the value and a `done` flag; the flag comes off
4585 // first because it is on top.
4586 //
4587 // It also counts as an open iterator for `return` and `break`: a pattern is not a
4588 // loop, but the record is live across everything the pattern evaluates, so
4589 // `function* g(){ [ {} = yield ] = it }` resumed with `return()` has to close it
4590 // (`array-elem-iter-rtrn-close`). `emit_unwind_for_return` finds it by this entry
4591 // and `nip_catch` uncovers exactly the `iter next` pairs it left behind.
4592 //
4593 // A `break`/`continue` cannot occur inside a pattern, so `names` and both labels
4594 // are empty and `drop_count` — read only by that unreachable path — keeps the
4595 // reference's 2.
4596 self.push_jump_target(JumpTarget {
4597 names: Vec::new(),
4598 break_label: None,
4599 continue_label: None,
4600 drop_count: 2,
4601 finally_label: None,
4602 is_regular_stmt: false,
4603 has_iterator: true,
4604 is_async_iterator: false,
4605 });
4606 self.emit(Opcode::ForOfStart, &[]);
4607 for element in elements {
4608 match element {
4609 Some(PatternElement::Pattern(pattern)) => {
4610 match Self::member_element_target(pattern, decl) {
4611 // A prepared reference sits above the record, so `for_of_next` is
4612 // told how many values are in the way.
4613 Some(member) => {
4614 let extra = self.prepare_member_target(member)?;
4615 self.emit(Opcode::ForOfNext, &[Op::Int(extra)]);
4616 self.emit(Opcode::Drop, &[]);
4617 self.destructure_prepared(pattern, member)?;
4618 }
4619 None => {
4620 self.emit(Opcode::ForOfNext, &[Op::Int(0)]);
4621 self.emit(Opcode::Drop, &[]);
4622 self.destructure(pattern, decl)?;
4623 }
4624 }
4625 }
4626 Some(PatternElement::Property { span, .. }) => {
4627 return Err(SyntaxError::new(
4628 "a property pattern is not a valid array element",
4629 *span,
4630 ));
4631 }
4632 // An elision skips the value, which is already on the stack.
4633 None => {
4634 self.emit(Opcode::ForOfNext, &[Op::Int(0)]);
4635 self.emit(Opcode::Drop, &[]);
4636 self.emit(Opcode::Drop, &[]);
4637 }
4638 }
4639 }
4640 if let Some(rest) = rest {
4641 // The remaining values go into a fresh array. The target and its running
4642 // index stay on the stack above the iterator, which is what the operand of
4643 // `for_of_next` accounts for: two values sit above the iterator triple.
4644 let prepared = match decl {
4645 None => Self::member_rest_target(rest),
4646 // A binding pattern cannot store into a property.
4647 Some(_) => None,
4648 };
4649 let extra = match prepared {
4650 Some(member) => 2 + self.prepare_member_target(member)?,
4651 None => 2,
4652 };
4653 self.emit(Opcode::ArrayFrom, &[Op::Int(0)]);
4654 self.emit(Opcode::Push0, &[]);
4655 let top = self.new_label();
4656 self.place_label(top);
4657 self.emit(Opcode::ForOfNext, &[Op::Int(extra)]);
4658 let done = self.new_label();
4659 self.emit_jump(Opcode::IfTrue, done, &[]);
4660 self.emit(Opcode::DefineArrayEl, &[]);
4661 self.emit(Opcode::Inc, &[]);
4662 self.emit_jump(Opcode::Goto, top, &[]);
4663 self.place_label(done);
4664 self.emit(Opcode::Drop, &[]);
4665 self.emit(Opcode::Drop, &[]);
4666 match prepared {
4667 Some(member) => self.store_member_value(member)?,
4668 None => self.destructure_rest(rest, decl)?,
4669 }
4670 }
4671 self.emit(Opcode::IteratorClose, &[]);
4672 self.pop_jump_target();
4673 Ok(())
4674 }
4675
4676 /// The property an array element stores into, when it stores into one at all.
4677 ///
4678 /// `Assign` is peeled because `[o.p = d] = it` evaluates `o.p`'s reference at the same
4679 /// point `[o.p] = it` does; the default value is applied afterwards, on the pulled
4680 /// value. Nothing deeper is: a nested pattern's own targets are reached by recursing
4681 /// into `destructure`, and those never straddle a `for_of_next`.
4682 fn member_element_target(
4683 pattern: &Pattern,
4684 decl: Option<VarDeclKind>,
4685 ) -> Option<&ast::MemberPattern> {
4686 if decl.is_some() {
4687 return None;
4688 }
4689 match &pattern.kind {
4690 PatternKind::Member(member) => Some(member),
4691 PatternKind::Assign { target, .. } => Self::member_element_target(target, decl),
4692 _ => None,
4693 }
4694 }
4695
4696 /// The same, for a rest element.
4697 fn member_rest_target(rest: &RestElement) -> Option<&ast::MemberPattern> {
4698 match rest {
4699 RestElement::Member(member) => Some(member),
4700 RestElement::Pattern(pattern) => match &pattern.kind {
4701 PatternKind::Member(member) => Some(member),
4702 _ => None,
4703 },
4704 }
4705 }
4706
4707 /// Push a member target's reference — the object, and the key when the property is
4708 /// computed — and answer how many values that put above the iterator record.
4709 fn prepare_member_target(&mut self, member: &ast::MemberPattern) -> Result<i32, SyntaxError> {
4710 self.expr(&member.object)?;
4711 match &member.property {
4712 MemberProp::Ident(_) | MemberProp::Private(_) => Ok(1),
4713 MemberProp::Computed(index) => {
4714 self.expr(index)?;
4715 Ok(2)
4716 }
4717 }
4718 }
4719
4720 /// Store the value on top of the stack through a prepared member reference.
4721 ///
4722 /// `obj value` for a named property, `obj key value` for a computed one — the orders
4723 /// `put_field` and `put_array_el` take, so no reordering is needed here. The `swap` and
4724 /// `rot3l` in [`Compiler::destructure`]'s member case exist only because *it* starts
4725 /// with the value already on the stack.
4726 fn store_member_value(&mut self, member: &ast::MemberPattern) -> Result<(), SyntaxError> {
4727 match &member.property {
4728 MemberProp::Ident(name) => {
4729 self.emit(Opcode::PutField, &[Op::Atom(Atom::from_text(&name.name))]);
4730 }
4731 MemberProp::Computed(_) => self.emit(Opcode::PutArrayEl, &[]),
4732 MemberProp::Private(name) => {
4733 let binding = format!("#{}", name.name);
4734 let (kind, setter) = self.private_use(&binding, member.span)?;
4735 self.private_store(&binding, kind, setter.as_deref())?;
4736 }
4737 }
4738 Ok(())
4739 }
4740
4741 /// The value of an array element whose member reference is already prepared.
4742 ///
4743 /// Only the default-value test differs from [`Compiler::destructure`]: the reference
4744 /// and the value are both on the stack while the test runs, which is why the object is
4745 /// evaluated before the default rather than after it.
4746 fn destructure_prepared(
4747 &mut self,
4748 pattern: &Pattern,
4749 member: &ast::MemberPattern,
4750 ) -> Result<(), SyntaxError> {
4751 if let PatternKind::Assign { default, .. } = &pattern.kind {
4752 let has_value = self.new_label();
4753 self.emit(Opcode::Dup, &[]);
4754 self.emit(Opcode::IsUndefined, &[]);
4755 self.emit_jump(Opcode::IfFalse, has_value, &[]);
4756 self.emit(Opcode::Drop, &[]);
4757 self.expr(default)?;
4758 self.place_label(has_value);
4759 }
4760 self.store_member_value(member)
4761 }
4762
4763 /// `{…}` on the left: read properties off one boxed source object.
4764 fn destructure_object(
4765 &mut self,
4766 properties: &[Option<PatternElement>],
4767 rest: &Option<Box<RestElement>>,
4768 decl: Option<VarDeclKind>,
4769 pattern: &Pattern,
4770 ) -> Result<(), SyntaxError> {
4771 // `ToObject` is what refuses `null`/`undefined`, and it also puts the source
4772 // aside for the rest element below.
4773 self.emit(Opcode::ToObject, &[]);
4774 let mut taken: Vec<Wtf8> = Vec::new();
4775 // A computed key's *value* is only known at run time, so with a rest element the
4776 // exclusion list cannot be an `ArrayFrom` over literal atoms. It becomes a hidden
4777 // local array that every key is written into as the pattern is walked — literal
4778 // keys by name, computed ones by the value the expression produced. Without this,
4779 // `let { [k]: a, ...rest } = o` was refused outright.
4780 let needs_key_log = rest.is_some() && computed_key_count(properties) > 0;
4781 let key_log = if needs_key_log {
4782 let name = "<rest_exclude>";
4783 self.declare_hidden_local(name, VarKind::Normal);
4784 self.emit(Opcode::ArrayFrom, &[Op::Int(0)]);
4785 self.emit_var(VarAction::Put, name);
4786 Some(name)
4787 } else {
4788 None
4789 };
4790 for property in properties {
4791 let Some(PatternElement::Property {
4792 key, value, span, ..
4793 }) = property
4794 else {
4795 return Err(SyntaxError::new(
4796 "a bare pattern is not a valid object property",
4797 properties
4798 .iter()
4799 .flatten()
4800 .map(|element| match element {
4801 PatternElement::Pattern(pattern) => pattern.span,
4802 PatternElement::Property { span, .. } => *span,
4803 })
4804 .next()
4805 .unwrap_or(pattern.span),
4806 ));
4807 };
4808 // Every read needs the source twice: to read from, and to keep for the next
4809 // property. `get_field2` is that duplicate-and-read in one instruction, but it
4810 // leaves the copy *under* the value, so it is only usable when whatever
4811 // consumes the value tolerates that. See [`reads_with_get_field2`].
4812 let nested = reads_with_get_field2(decl, value);
4813 if !nested {
4814 self.emit(Opcode::Dup, &[]);
4815 }
4816 let slot = taken.len();
4817 match key {
4818 PropName::Literal(literal) => {
4819 let name = self.property_key_text(literal, *span)?;
4820 taken.push(name.clone());
4821 if let Some(log) = &key_log {
4822 // `arr index key -> arr`: the key is written into the log before
4823 // the read, so the order of observable operations is unchanged.
4824 self.emit_var(VarAction::Get, log);
4825 self.push_number(slot as f64);
4826 self.emit(Opcode::PushAtomValue, &[Op::Atom(Atom::from_wtf8(&name))]);
4827 self.emit(Opcode::PutArrayEl, &[]);
4828 }
4829 self.emit(
4830 if nested {
4831 Opcode::GetField2
4832 } else {
4833 Opcode::GetField
4834 },
4835 &[Op::Atom(Atom::from_wtf8(&name))],
4836 );
4837 }
4838 PropName::Computed(index) => {
4839 self.expr(index)?;
4840 // `key key`: one stays on the stack for the read, the other goes into
4841 // the exclusion log. The index is a compile-time constant, so no counter
4842 // local is needed.
4843 if let Some(log) = &key_log {
4844 taken.push(Wtf8::default());
4845 self.emit(Opcode::Dup, &[]);
4846 self.emit_var(VarAction::Get, log);
4847 self.emit(Opcode::Swap, &[]);
4848 self.push_number(slot as f64);
4849 self.emit(Opcode::Swap, &[]);
4850 self.emit(Opcode::PutArrayEl, &[]);
4851 }
4852 self.emit(Opcode::GetArrayEl, &[]);
4853 }
4854 PropName::Private(_) => {
4855 return Err(SyntaxError::new(
4856 "private fields are not supported by the compiler yet",
4857 value.span,
4858 ));
4859 }
4860 }
4861 self.destructure(value, decl)?;
4862 }
4863 match rest {
4864 Some(rest) => {
4865 // `target src exclude`: the exclusion list is an array of the keys the
4866 // literal part already took, so the rest object gets only the others.
4867 self.emit(Opcode::Object, &[]);
4868 self.emit(Opcode::Swap, &[]);
4869 match &key_log {
4870 // Built while walking the pattern; see `needs_key_log`.
4871 Some(log) => {
4872 self.emit_var(VarAction::Get, log);
4873 }
4874 None => {
4875 for name in &taken {
4876 self.emit(Opcode::PushAtomValue, &[Op::Atom(Atom::from_wtf8(name))]);
4877 }
4878 self.emit(Opcode::ArrayFrom, &[Op::Int(taken.len() as i32)]);
4879 }
4880 }
4881 self.emit(Opcode::CopyDataProperties, &[Op::Int(COPY_ALL_PROPERTIES)]);
4882 self.emit(Opcode::Drop, &[]);
4883 self.emit(Opcode::Drop, &[]);
4884 self.destructure_rest(rest, decl)?;
4885 }
4886 // The source was only kept for a rest element.
4887 None => self.emit(Opcode::Drop, &[]),
4888 }
4889 Ok(())
4890 }
4891
4892 /// The pattern a rest element binds, as a target [`Self::destructure`] takes.
4893 fn destructure_rest(
4894 &mut self,
4895 rest: &RestElement,
4896 decl: Option<VarDeclKind>,
4897 ) -> Result<(), SyntaxError> {
4898 match rest {
4899 RestElement::Pattern(pattern) => self.destructure(pattern, decl),
4900 // `[...a.b] = c` stores into a property.
4901 RestElement::Member(member) => {
4902 let pattern = Pattern {
4903 kind: PatternKind::Member(member.clone()),
4904 span: member.span,
4905 };
4906 self.destructure(&pattern, decl)
4907 }
4908 }
4909 }
4910
4911 /// Compile a function declaration and queue it for instantiation at scope
4912 /// entry.
4913 ///
4914 /// A declaration is visible before the statement that declares it, so the
4915 /// code that creates the function object belongs at the top of the enclosing
4916 /// scope, not at the declaration.
4917 fn func_decl(&mut self, func: &ast::Function) -> Result<(), SyntaxError> {
4918 let name = func.name.as_ref().expect("a declaration has a name");
4919 let function = self.compile_function(func)?;
4920 let pool_index = self.push_constant(Constant::Function(Box::new(function)));
4921 let target = self.hoist_target(&name.name);
4922 let block = self.cur().current_block;
4923 self.state().hoisted.push((block, target, pool_index));
4924 Ok(())
4925 }
4926
4927 /// Where a name lives, for a hoisted declaration.
4928 fn hoist_target(&self, name: &str) -> HoistTarget {
4929 let state = self.cur();
4930 if let Some(index) = state.args.iter().position(|a| a.name == name) {
4931 return HoistTarget::Arg(index as u32);
4932 }
4933 if let Some(index) = state.vars.iter().position(|v| v.name == name) {
4934 return HoistTarget::Loc(index as u32);
4935 }
4936 // A global function declaration is not a slot at all.
4937 HoistTarget::Global(name.to_string())
4938 }
4939
4940 // -- expressions -------------------------------------------------------
4941
4942 /// Compile one expression, recording where its instructions sit.
4943 ///
4944 /// The position is the node's operator when it has one and its first token
4945 /// otherwise, and it is restored on the way out so a parent's own instructions —
4946 /// which are emitted *after* its children — are blamed on the parent. Without the
4947 /// restore the `add` in `a + b` would inherit `b`'s position instead of the `+`.
4948 fn expr(&mut self, expr: &Expr) -> Result<(), SyntaxError> {
4949 // `discard_value` belongs to the *statement* that is about to be compiled, so it
4950 // may only be honoured by that statement's own top-level expression. Taking it here
4951 // is what enforces that: `f(x = 1)` sets it for the call, and the assignment inside
4952 // the argument list is a different expression — it must still leave its value on the
4953 // stack. Without this the argument vanished, and `call` then consumed the callee as
4954 // its argument (`TypeError: undefined is not a function` from `f(x = 1)` inside any
4955 // function).
4956 self.discard_root = std::mem::take(&mut self.state().discard_value);
4957 let saved = self.cur().cur_pos;
4958 // Only the node kinds the reference calls `emit_source_pos` for record a position:
4959 // the operator a node exists for, and a variable *read*, which the reference
4960 // positions at the identifier itself (`case TOK_IDENT: … do_get_var:
4961 // emit_source_pos(s, source_ptr)`). Everything else — a literal, an object or array
4962 // start, a parenthesised group, an anonymous function expression — leaves the
4963 // previous position in place, because a table entry the reference never writes is
4964 // one we must not write either: the instruction that inherits a position (the
4965 // `using` epilogue, a template's `to_propkey`, a `super()` call) would otherwise
4966 // report a more recent token than the reference does.
4967 let pos = expr.op_pos.or(match &expr.kind {
4968 ExprKind::Ident(ident) => Some(ident.span.start),
4969 _ => None,
4970 });
4971 match pos {
4972 Some(pos) => self.state().cur_pos = Some(pos),
4973 // A node the reference records nothing for: its own instructions stay
4974 // unpositioned, so they inherit whatever was written last — which is what an
4975 // `emit_source_pos`-less stretch of the reference's bytecode does. Keeping the
4976 // enclosing position instead would blame them on a token the reference has not
4977 // reached yet: a spread's `iterator_open` reports the expression it follows, and
4978 // a template's `to_propkey` the interpolation.
4979 None => self.state().cur_pos = None,
4980 }
4981 // Note a direct `eval` call before compiling it, because the *whole* function
4982 // is affected: an eval can name any binding the function declares, so every one
4983 // of them has to live in a cell for a closure it creates to capture it.
4984 self.note_direct_eval(expr);
4985 let result = self.expr_inner(expr);
4986 self.discard_root = false;
4987 self.state().cur_pos = saved;
4988 result
4989 }
4990
4991 /// Record which bindings are in scope at a direct `eval` call.
4992 ///
4993 /// Ordinary name lookup happens at compile time; a direct `eval` bypasses that and
4994 /// resolves names from a string at run time, so the only chance to pin down *which*
4995 /// slot a name means is here. Visibility is the lexical rule: a binding counts when
4996 /// its block is the current block, an enclosing one, or the function scope.
4997 fn materialize_eval_sites(&mut self) {
4998 let pending = std::mem::take(&mut self.state().pending_eval_sites);
4999 for (span, site_block, in_params, private, arguments_allowed) in pending {
5000 self.resolve_eval_site(span, site_block, in_params, private, arguments_allowed);
5001 }
5002 }
5003
5004 /// Resolve the bindings visible at one `eval` call.
5005 fn resolve_eval_site(
5006 &mut self,
5007 span: Span,
5008 site_block: u64,
5009 site_in_params: bool,
5010 private_names: Vec<EvalPrivate>,
5011 arguments_allowed: bool,
5012 ) {
5013 /// How near a binding is: function distance first, then block depth, then the
5014 /// later declaration (which shadows the earlier one in the same block).
5015 type ScopePriority = (usize, usize, std::cmp::Reverse<u32>);
5016
5017 // `(sort key, binding)`, where a smaller key wins. The whole scope chain is
5018 // walked, innermost function first: a direct `eval` sees every enclosing
5019 // function's bindings, and none of them can be resolved at run time because the
5020 // runtime only has names to go on.
5021 let mut bindings: Vec<(ScopePriority, EvalVisible)> = Vec::new();
5022 let deepest = self.stack.len() - 1;
5023 for (level, state) in self.stack.iter().enumerate().rev() {
5024 let owner = (deepest - level) as u32;
5025 // The innermost function's block is the one the call sat in, which is not
5026 // the block the compiler is in now; the enclosing functions are still at
5027 // the point where this one was created.
5028 let here = if level == deepest {
5029 site_block
5030 } else {
5031 state.current_block
5032 };
5033 // The chain of live blocks, innermost first, with a depth for each. The walk
5034 // stops at `NO_PARENT`, which is a sentinel rather than `0` because a real
5035 // block can start at source offset zero.
5036 let mut live: Vec<(u64, usize)> = vec![(here, 0)];
5037 let mut block = here;
5038 while let Some(parent) = state
5039 .blocks
5040 .iter()
5041 .find(|candidate| candidate.key == block)
5042 .map(|candidate| candidate.parent)
5043 .filter(|parent| *parent != NO_PARENT)
5044 .filter(|parent| parent != &block)
5045 {
5046 live.push((parent, live.len()));
5047 block = parent;
5048 }
5049 let depth_of = |key: u64| {
5050 live.iter()
5051 .find(|(candidate, _)| *candidate == key)
5052 .map(|(_, depth)| *depth)
5053 // The function scope is the outermost depth there is. A binding of a
5054 // block this site is not inside lands here too, which pushes it
5055 // behind every live one — the right answer: it is out of scope.
5056 .unwrap_or(live.len())
5057 };
5058 for (index, arg) in state.args.iter().enumerate() {
5059 bindings.push((
5060 (owner as usize, live.len(), std::cmp::Reverse(index as u32)),
5061 EvalVisible {
5062 name: arg.name.clone(),
5063 is_arg: true,
5064 index: index as u32,
5065 owner,
5066 },
5067 ));
5068 }
5069 // A parameter list cannot see the body, so a body `var` is not a binding the
5070 // eval can name: `(a = eval("var c = 1"), p = () => c) => { var c = 2 }` must
5071 // not let that eval write the body's `c`.
5072 let hides_body = if level == deepest {
5073 site_in_params
5074 } else {
5075 state.created_in_params
5076 };
5077 for (index, var) in state.vars.iter().enumerate() {
5078 let block = state
5079 .var_block
5080 .get(index)
5081 .copied()
5082 .unwrap_or(FUNCTION_SCOPE);
5083 if hides_body && block == FUNCTION_SCOPE && !visible_in_params(var) {
5084 continue;
5085 }
5086 bindings.push((
5087 (
5088 owner as usize,
5089 depth_of(block),
5090 std::cmp::Reverse(index as u32),
5091 ),
5092 EvalVisible {
5093 name: var.name.clone(),
5094 is_arg: false,
5095 index: index as u32,
5096 owner,
5097 },
5098 ));
5099 }
5100 }
5101 // Innermost function first, then innermost block, then the later declaration
5102 // (which shadows the earlier one within a block).
5103 bindings.sort_by_key(|(priority, _)| *priority);
5104 let bindings = bindings.into_iter().map(|(_, visible)| visible).collect();
5105 self.state().eval_sites.push(EvalSite {
5106 line: span.start.line,
5107 column: span.start.column,
5108 bindings,
5109 private_names,
5110 arguments_allowed,
5111 });
5112 }
5113
5114 /// The private names visible from the compiler's current position, innermost last.
5115 ///
5116 /// A direct `eval` inherits these because private names are lexically scoped
5117 /// (§15.10.2). Flattened with the **first** occurrence winning as the scopes are walked
5118 /// outermost-first, so a nested class's `#x` shadows an outer class's — the same
5119 /// shadowing `ClassPlan::find` gives a use site inside the body.
5120 fn visible_private_names(&self) -> Vec<EvalPrivate> {
5121 let mut out: Vec<EvalPrivate> = Vec::new();
5122 for scope in &self.private_scopes {
5123 for (name, use_) in scope {
5124 if out.iter().any(|entry| &entry.name == name) {
5125 continue;
5126 }
5127 out.push(EvalPrivate {
5128 name: name.clone(),
5129 kind: match use_.kind {
5130 PrivateKind::Field => EvalPrivateKind::Field,
5131 PrivateKind::Method => EvalPrivateKind::Method,
5132 PrivateKind::Getter => EvalPrivateKind::Getter,
5133 PrivateKind::Setter => EvalPrivateKind::Setter,
5134 },
5135 setter: use_.setter.clone(),
5136 });
5137 }
5138 }
5139 out
5140 }
5141
5142 /// Whether `expr` is `eval(...)` — the direct form, which sees the caller's scope.
5143 ///
5144 /// `(0, eval)(…)` and `f.call(null, …)` are *indirect* and get no caller scope; only
5145 /// a bare identifier callee counts.
5146 /// Record everything a direct `eval` call site has to tell the runtime.
5147 ///
5148 /// Called from both places a call can be compiled: [`Compiler::expr`] for an ordinary
5149 /// one, and [`Compiler::expr_if_tail_call`] for a `return eval(…)`, which skips `expr`
5150 /// entirely. Missing the tail-call path is not hypothetical — it is why
5151 /// `class C { #m; f() { return eval("this.#m") } }` still failed after the private
5152 /// names were otherwise wired through.
5153 fn note_direct_eval(&mut self, expr: &Expr) {
5154 if !Self::is_direct_eval(expr) {
5155 return;
5156 }
5157 // Every enclosing function is affected too: the eval sees the whole scope chain,
5158 // and a closure it creates can capture a binding of any of them.
5159 // `for (let i …) { f() }` where `f` contains the eval still needs `i` in a cell,
5160 // because the closure the eval builds outlives the loop iteration.
5161 for state in &mut self.stack {
5162 state.has_direct_eval = true;
5163 }
5164 let block = self.cur().current_block;
5165 let in_params = self.cur().in_params;
5166 // The private names are snapshotted **here**, at the call site, not when the sites
5167 // are materialised: materialisation happens once the whole function is compiled, by
5168 // which point every class scope has been popped and the answer would always be
5169 // empty.
5170 let private = self.visible_private_names();
5171 // An arrow has no `arguments` of its own and inherits the restriction from the
5172 // nearest real function: `x = () => { () => eval('arguments') }` is still a
5173 // class field initializer's arrow, and still has no `arguments` to see.
5174 let arguments_allowed = !self
5175 .stack
5176 .iter()
5177 .rev()
5178 .find(|state| !state.is_arrow)
5179 .is_some_and(|state| state.no_arguments_binding);
5180 self.state().pending_eval_sites.push((
5181 expr.span,
5182 block,
5183 in_params,
5184 private,
5185 arguments_allowed,
5186 ));
5187 }
5188
5189 fn is_direct_eval(expr: &Expr) -> bool {
5190 matches!(
5191 &expr.kind,
5192 ExprKind::Call { callee, .. }
5193 if matches!(&callee.unparen().kind, ExprKind::Ident(name) if name.name == "eval")
5194 )
5195 }
5196
5197 fn expr_inner(&mut self, expr: &Expr) -> Result<(), SyntaxError> {
5198 match &expr.kind {
5199 ExprKind::Number(value) => self.push_number(*value),
5200 ExprKind::Bool(true) => self.emit(Opcode::PushTrue, &[]),
5201 ExprKind::Bool(false) => self.emit(Opcode::PushFalse, &[]),
5202 ExprKind::Null => self.emit(Opcode::Null, &[]),
5203 ExprKind::String(text) => self.push_string(text),
5204 ExprKind::BigInt { digits, radix } => self.push_bigint(digits, *radix),
5205 ExprKind::Ident(name) => self.emit_var(VarAction::Get, &name.name),
5206 ExprKind::This => self.this_expression(),
5207 ExprKind::NewTarget => self.new_target_expression(),
5208 ExprKind::Paren(inner) => self.expr(inner)?,
5209 ExprKind::Binary { op, left, right } => {
5210 self.expr(left)?;
5211 self.expr(right)?;
5212 self.emit(binary_opcode(*op), &[]);
5213 }
5214 ExprKind::Logical { op, left, right } => self.logical(*op, left, right)?,
5215 ExprKind::Unary {
5216 op: UnaryOp::Minus,
5217 argument,
5218 } if matches!(argument.unparen().kind, ExprKind::Number(_)) => {
5219 let ExprKind::Number(value) = argument.unparen().kind else {
5220 unreachable!("matched above")
5221 };
5222 // The reference folds a negative literal only when the negation is
5223 // exact in the integer range: `-1` becomes `push_minus1` and
5224 // `-1.5e3` becomes `push_i16 -1500`, but `-0` and `-2.5` keep a
5225 // runtime `neg`. Folding `-0` would lose the sign — `1/-0` is
5226 // `-Infinity`, not `Infinity` — and folding a fraction would change
5227 // which instruction the reference emits.
5228 let negated = -value;
5229 // `-2147483648` is deliberately excluded: its magnitude is one past
5230 // `i32::MAX`, so the reference sends it through the constant pool and
5231 // negates at run time instead.
5232 if value > 0.0
5233 && negated == negated.trunc()
5234 && negated >= -(i32::MAX as f64)
5235 && negated < 0.0
5236 {
5237 self.push_number(negated);
5238 } else {
5239 self.push_number(value);
5240 self.emit(Opcode::Neg, &[]);
5241 }
5242 }
5243 ExprKind::Unary { op, argument } => self.unary(*op, argument)?,
5244 ExprKind::Conditional { test, cons, alt } => {
5245 let else_label = self.new_label();
5246 let end_label = self.new_label();
5247 self.expr(test)?;
5248 self.emit_jump(Opcode::IfFalse, else_label, &[]);
5249 self.expr(cons)?;
5250 self.emit_jump(Opcode::Goto, end_label, &[]);
5251 self.place_label(else_label);
5252 self.expr(alt)?;
5253 self.place_label(end_label);
5254 }
5255 ExprKind::Assign { op, target, value } => {
5256 let discard = std::mem::take(&mut self.discard_root);
5257 self.assign(*op, target, value, discard)?
5258 }
5259 ExprKind::Update {
5260 op,
5261 argument,
5262 prefix,
5263 } => self.update(*op, argument, *prefix)?,
5264 ExprKind::Sequence(items) => {
5265 for (index, item) in items.iter().enumerate() {
5266 self.expr(item)?;
5267 if index + 1 != items.len() {
5268 self.emit(Opcode::Drop, &[]);
5269 }
5270 }
5271 }
5272 ExprKind::Call { .. } => self.chain_link_top(expr)?,
5273 ExprKind::Member { .. } => self.chain_link_top(expr)?,
5274 ExprKind::OptionalChain(inner) => self.optional_chain(inner)?,
5275 ExprKind::Array { elements } => self.array_literal(elements, expr.span)?,
5276 ExprKind::Object(properties) => self.object_literal(properties, expr.span)?,
5277 ExprKind::Template(template) => self.template_literal(template)?,
5278 ExprKind::TaggedTemplate { tag, quasi } => self.tagged_template(tag, quasi)?,
5279 ExprKind::New { callee, arguments } => {
5280 // `new C(args)` compiles to `C; dup; args…; call_constructor n`.
5281 // The `dup` is not redundant: `call_constructor` takes the
5282 // constructor twice, once as the target and once as `new.target`,
5283 // which is what makes `new.target === C` inside the body.
5284 self.expr(callee)?;
5285 self.emit(Opcode::Dup, &[]);
5286 let args = arguments.as_deref().unwrap_or(&[]);
5287 if Self::has_spread(args) {
5288 // `C C array`: the duplicated callee is already both the target
5289 // and `new.target`, so no reordering is needed before `apply 1`.
5290 self.argument_array(args)?;
5291 self.emit(Opcode::Apply, &[Op::Int(1)]);
5292 return Ok(());
5293 }
5294 for argument in args {
5295 self.expr(argument)?;
5296 }
5297 self.emit(Opcode::CallConstructor, &[Op::Int(args.len() as i32)]);
5298 }
5299 ExprKind::Class(class) => self.class_definition(class, true)?,
5300 ExprKind::SuperCall(arguments) => self.super_call(arguments)?,
5301 ExprKind::Yield { argument, delegate } => {
5302 self.yield_expression(argument.as_deref(), *delegate)?
5303 }
5304 ExprKind::Await(argument) => self.await_expression(argument)?,
5305 ExprKind::RegExp { pattern, flags } => {
5306 // A literal is compiled *here*, at parse time, not when the line runs. The
5307 // spec is explicit that an invalid pattern is an early error (§12.9.4:
5308 // "/ RegularExpressionLiteral /u — it is a Syntax Error if … the pattern does
5309 // not conform"), so `print(1); /\p{Nope}/u;` must not print anything. This
5310 // also validates `\p{…}` names: 163 conformance cases are patterns that have
5311 // to be rejected before any code runs.
5312 //
5313 // This is the whole reason the engine lives in its own crate rather than
5314 // inside `quickjs-pure`: the compiler could not depend on the interpreter
5315 // (`pure` depends on `compile`), but both need this.
5316 // The lexer already rejected an unknown or repeated flag, so an unparsable
5317 // flag string here would be a bug in the lexer rather than in the script;
5318 // fall back to the default flags instead of inventing a second message.
5319 let flags_parsed = quickjs_regexp::Flags::parse(flags).unwrap_or_default();
5320 let parsed = quickjs_regexp::parse(pattern, flags_parsed).map_err(|error| {
5321 SyntaxError::new(
5322 format!("invalid regular expression: {}", error.message),
5323 expr.span,
5324 )
5325 })?;
5326 // The tree is thrown away and rebuilt when the literal first runs: keeping it
5327 // would mean serialising the syntax tree into the function's constant pool,
5328 // and a literal is created once per evaluation of its expression anyway.
5329 let _ = parsed;
5330 // The pattern and its flags travel as two string constants; `regexp` builds
5331 // the object. A dedicated opcode (rather than a call to the constructor) is
5332 // what the reference does too, so that a literal never goes through the
5333 // public `RegExp` function and its string-coercion rules.
5334 self.push_string(&Wtf8::new(pattern));
5335 self.push_string(&Wtf8::new(flags));
5336 self.emit(Opcode::Regexp, &[]);
5337 }
5338 ExprKind::Arrow(func) => {
5339 let function = self.compile_function(func)?;
5340 let index = self.push_constant(Constant::Function(Box::new(function)));
5341 self.emit(Opcode::Fclosure, &[Op::Const(index)]);
5342 }
5343 ExprKind::Function(func) => {
5344 let function = self.compile_function_with_name(func, true)?;
5345 let index = self.push_constant(Constant::Function(Box::new(function)));
5346 self.emit(Opcode::Fclosure, &[Op::Const(index)]);
5347 }
5348 // `import.meta`: the host fills a per-module object at link time.
5349 ExprKind::ImportMeta => {
5350 self.emit(Opcode::SpecialObject, &[Op::Int(6)]);
5351 }
5352 // `import("x")` compiles to a two-slot push followed by one opcode: the
5353 // specifier, then the options object. Both are evaluated, in that order, because
5354 // §13.3.10.1 numbers them that way and their side effects are observable — the
5355 // absent second argument is a literal `undefined`, which evaluates to nothing.
5356 ExprKind::ImportCall(specifier, options) => {
5357 self.expr(specifier)?;
5358 match options {
5359 Some(options) => self.expr(options)?,
5360 None => {
5361 self.emit(Opcode::Undefined, &[]);
5362 }
5363 }
5364 self.emit(Opcode::Import, &[]);
5365 }
5366 ExprKind::PrivateIn { name, object } => {
5367 // `#x in o`: the object, then the binding, then one opcode which decides what
5368 // to do with the second operand. A field's binding holds a symbol and the
5369 // answer is an own-property test; a method's holds a function and the answer
5370 // is a brand check — both live in `private_in`, so the compiler emits the
5371 // same instruction for either.
5372 self.expr(object)?;
5373 self.emit_var(VarAction::Get, &format!("#{}", name.name));
5374 self.emit(Opcode::PrivateIn, &[]);
5375 }
5376 _ => {
5377 return Err(SyntaxError::new(
5378 "this expression form is not supported by the compiler yet",
5379 expr.span,
5380 ));
5381 }
5382 }
5383 Ok(())
5384 }
5385
5386 /// Build one array holding the evaluated call arguments, which is how a call
5387 /// containing a spread is compiled: the reference does the same, building the
5388 /// list on the stack and handing it to `apply`.
5389 fn argument_array(&mut self, arguments: &[Expr]) -> Result<(), SyntaxError> {
5390 let elements: Vec<Option<ArrayElement>> = arguments
5391 .iter()
5392 .map(|argument| match &argument.unparen().kind {
5393 ExprKind::Spread(inner) => Some(ArrayElement::Spread(inner.clone())),
5394 _ => Some(ArrayElement::Expr(Box::new(argument.clone()))),
5395 })
5396 .collect();
5397 self.array_literal(&elements, Span::default())
5398 }
5399
5400 /// Whether any argument is a spread, which is what selects the `apply` form.
5401 fn has_spread(arguments: &[Expr]) -> bool {
5402 arguments
5403 .iter()
5404 .any(|argument| matches!(argument.unparen().kind, ExprKind::Spread(_)))
5405 }
5406
5407 /// Compile `a${x}b`.
5408 ///
5409 /// A template is a `+` chain built left to right: the leading chunk (or an empty
5410 /// string when the template starts with a substitution), then for each
5411 /// substitution its value, `to_propkey` and `add`, then the following chunk when
5412 /// it is not empty. `to_propkey` is what makes a number or object substitute the
5413 /// way `ToString` would while leaving the result a string for `add` to
5414 /// concatenate.
5415 ///
5416 /// The chunk is an atom rather than a constant-pool string, because a non-empty
5417 /// chunk always lands where a value is pushed and `push_atom_value` is the
5418 /// instruction the reference uses for it; the empty first chunk has its own
5419 /// zero-byte form.
5420 fn template_literal(&mut self, template: &TemplateLiteral) -> Result<(), SyntaxError> {
5421 let first = template.quasis.first();
5422 match first.and_then(|quasi| quasi.cooked.clone()) {
5423 Some(text) if !text.is_empty() => {
5424 self.emit(Opcode::PushAtomValue, &[Op::Atom(Atom::from_wtf8(&text))]);
5425 }
5426 // Either the template begins with a substitution, or the chunk is
5427 // empty — in both cases the chain needs a string to start from.
5428 _ => self.emit(Opcode::PushEmptyString, &[]),
5429 }
5430 for (index, expression) in template.expressions.iter().enumerate() {
5431 self.expr(expression)?;
5432 self.emit(Opcode::ToPropkey, &[]);
5433 self.emit(Opcode::Add, &[]);
5434 if let Some(text) = template
5435 .quasis
5436 .get(index + 1)
5437 .and_then(|quasi| quasi.cooked.clone())
5438 && !text.is_empty()
5439 {
5440 self.emit(Opcode::PushAtomValue, &[Op::Atom(Atom::from_wtf8(&text))]);
5441 self.emit(Opcode::Add, &[]);
5442 }
5443 }
5444 Ok(())
5445 }
5446
5447 /// Compile an object literal.
5448 ///
5449 /// The object is built in place: `object` pushes it, and each property leaves it
5450 /// on the stack with one field more, so no temporary is needed and later
5451 /// properties can overwrite earlier ones.
5452 ///
5453 /// The instruction depends on *how* the property was written, not on what kind
5454 /// of value it holds:
5455 ///
5456 /// | source | instruction |
5457 /// |---|---|
5458 /// | `{ a: v }` | `define_field a` |
5459 /// | `{ __proto__: v }` | `set_proto` |
5460 /// | `{ [k]: v }` | `to_propkey` … `define_array_el` + `drop` |
5461 /// | `{ m() {} }` | `define_method m,4` |
5462 /// | `{ get m() {} }` / `{ set m(v) {} }` | `define_method m,5` / `,6` |
5463 /// | `{ [k]() {} }` | `define_method_computed 4` |
5464 /// | `{ ...v }` | `null` … `copy_data_properties 6` + two `drop`s |
5465 ///
5466 /// A computed *method* skips `to_propkey`: `define_method_computed` converts the
5467 /// key itself, which is why the trailing `drop` is absent there too.
5468 /// `tag`…``: a call whose first argument is the call site's template object.
5469 ///
5470 /// The template object is a frozen array of the cooked chunks with a frozen `raw`
5471 /// array beside it, so `String.raw` can read the source text back. It is a constant
5472 /// because its contents never change; the reference builds one per call site and
5473 /// reuses it, while this builds one per evaluation, which only `tag` code that
5474 /// compares template objects across calls could tell apart.
5475 /// A fresh template site id. See [`Constant::Template`].
5476 fn tagged_template(&mut self, tag: &Expr, quasi: &TemplateLiteral) -> Result<(), SyntaxError> {
5477 let cooked = quasi
5478 .quasis
5479 .iter()
5480 .map(|chunk| chunk.cooked.clone())
5481 .collect();
5482 let raw = quasi.quasis.iter().map(|chunk| chunk.raw.clone()).collect();
5483 let index = self.push_constant(Constant::Template {
5484 site: next_template_site(),
5485 cooked,
5486 raw,
5487 });
5488 let count = quasi.expressions.len() + 1;
5489 // `o.m`…`` passes `o` as `this`, exactly as `o.m(…)` does.
5490 if let ExprKind::Member {
5491 object, property, ..
5492 } = &tag.unparen().kind
5493 {
5494 self.expr(object)?;
5495 match property {
5496 MemberProp::Ident(name) => {
5497 self.emit(Opcode::GetField2, &[Op::Atom(Atom::from_text(&name.name))]);
5498 }
5499 MemberProp::Computed(key) => {
5500 self.expr(key)?;
5501 self.emit(Opcode::GetArrayEl2, &[]);
5502 }
5503 MemberProp::Private(name) => {
5504 let binding = format!("#{}", name.name);
5505 let (kind, _) = self.private_use(&binding, tag.span)?;
5506 self.private_callee(&binding, kind)?;
5507 }
5508 }
5509 self.emit(Opcode::PushConst, &[Op::Const(index)]);
5510 for expression in &quasi.expressions {
5511 self.expr(expression)?;
5512 }
5513 self.emit(Opcode::CallMethod, &[Op::Int(count as i32)]);
5514 return Ok(());
5515 }
5516 self.expr(tag)?;
5517 self.emit(Opcode::PushConst, &[Op::Const(index)]);
5518 for expression in &quasi.expressions {
5519 self.expr(expression)?;
5520 }
5521 self.emit(Opcode::Call, &[Op::Int(count as i32)]);
5522 Ok(())
5523 }
5524
5525 fn object_literal(
5526 &mut self,
5527 properties: &[ObjectProperty],
5528 span: Span,
5529 ) -> Result<(), SyntaxError> {
5530 self.emit(Opcode::Object, &[]);
5531 for property in properties {
5532 match property {
5533 ObjectProperty::Spread(value) => {
5534 // `copy_data_properties` takes the target, the source and an
5535 // exclusion list; a literal `null` means "exclude nothing".
5536 // Flag bit 1 copies symbols, bits 2/5 pick the source and the
5537 // exclusion list by stack offset.
5538 self.expr(spread_argument(value))?;
5539 self.emit(Opcode::Null, &[]);
5540 self.emit(Opcode::CopyDataProperties, &[Op::Int(COPY_ALL_PROPERTIES)]);
5541 self.emit(Opcode::Drop, &[]);
5542 self.emit(Opcode::Drop, &[]);
5543 }
5544 ObjectProperty::Property {
5545 key,
5546 value,
5547 kind,
5548 shorthand,
5549 span: property_span,
5550 } => match key {
5551 PropName::Computed(key_expr) => {
5552 self.expr(key_expr)?;
5553 match kind {
5554 PropertyKind::Value => {
5555 self.emit(Opcode::ToPropkey, &[]);
5556 self.expr(value)?;
5557 self.set_name_if_anonymous_computed(value);
5558 self.emit(Opcode::DefineArrayEl, &[]);
5559 // `define_array_el` leaves the object and the key;
5560 // the key is no longer needed.
5561 self.emit(Opcode::Drop, &[]);
5562 }
5563 PropertyKind::Method | PropertyKind::Get | PropertyKind::Set => {
5564 self.emit_method_function(value)?;
5565 self.emit(
5566 Opcode::DefineMethodComputed,
5567 &[Op::Int(define_method_flags(*kind))],
5568 );
5569 }
5570 }
5571 }
5572 PropName::Literal(key) => {
5573 let name = self.property_key_text(key, *property_span)?;
5574 match kind {
5575 PropertyKind::Method | PropertyKind::Get | PropertyKind::Set => {
5576 self.emit_method_function(value)?;
5577 self.emit(
5578 Opcode::DefineMethod,
5579 &[
5580 Op::Atom(Atom::from_wtf8(&name)),
5581 Op::Int(define_method_flags(*kind)),
5582 ],
5583 );
5584 }
5585 PropertyKind::Value => {
5586 self.expr(value)?;
5587 // `{__proto__: x}` sets the prototype instead of
5588 // creating a property; the shorthand `{__proto__}`
5589 // is an ordinary property and does not.
5590 if name == "__proto__" && !shorthand {
5591 self.emit(Opcode::SetProto, &[]);
5592 } else {
5593 self.set_name_if_anonymous(value, &name);
5594 self.emit(
5595 Opcode::DefineField,
5596 &[Op::Atom(Atom::from_wtf8(&name))],
5597 );
5598 }
5599 }
5600 }
5601 }
5602 PropName::Private(_) => {
5603 return Err(SyntaxError::new(
5604 "private names are not valid in object literals",
5605 *property_span,
5606 ));
5607 }
5608 },
5609 }
5610 }
5611 let _ = span;
5612 Ok(())
5613 }
5614
5615 /// Emit the function a method/accessor property defines.
5616 fn emit_method_function(&mut self, value: &Expr) -> Result<(), SyntaxError> {
5617 self.expr(value)
5618 }
5619
5620 /// The name a literal property key contributes.
5621 ///
5622 /// String keys are used as written. A numeric key is converted the way
5623 /// `ToString` would convert it, because the atom is made from that spelling:
5624 /// `{ 1e2: x }` and `{ 0x10: x }` both become `define_field 100` / `16`.
5625 fn property_key_text(&self, key: &PropKey, span: Span) -> Result<Wtf8, SyntaxError> {
5626 match key {
5627 PropKey::Str(text) => Ok(text.clone()),
5628 PropKey::Num(value) => numeric_key_text(*value, span).map(Wtf8::new),
5629 }
5630 }
5631
5632 /// Compile an optional chain.
5633 ///
5634 /// `?.` short-circuits the *whole remaining spine*, not just its own link:
5635 /// `a?.b.c` yields `undefined` when `a` is null, it does not read `.c` of
5636 /// `undefined`. So the chain is compiled with one end label and every guard
5637 /// jumps to it. The parser hands us the extent of that spine as an
5638 /// [`ExprKind::OptionalChain`] wrapper around the outermost link, which is
5639 /// exactly the scope the label has to cover.
5640 fn optional_chain(&mut self, inner: &Expr) -> Result<(), SyntaxError> {
5641 let end = self.new_label();
5642 self.chain_link(inner, end)?;
5643 self.place_label(end);
5644 Ok(())
5645 }
5646
5647 /// A member access or call reached from outside any optional chain.
5648 ///
5649 /// Such a link cannot contain a `?.` — if it did, the parser would have wrapped
5650 /// it in [`ExprKind::OptionalChain`] — so there is no guard and no label; one is
5651 /// still created because [`Self::chain_link`] takes it, and placing it at the
5652 /// end is a no-op that keeps a single code path.
5653 fn chain_link_top(&mut self, expr: &Expr) -> Result<(), SyntaxError> {
5654 let end = self.new_label();
5655 self.chain_link(expr, end)?;
5656 self.place_label(end);
5657 Ok(())
5658 }
5659
5660 /// One link of a chain, where `end` is the label a `?.` guard jumps to.
5661 fn chain_link(&mut self, expr: &Expr, end: Label) -> Result<(), SyntaxError> {
5662 match &expr.kind {
5663 ExprKind::Member {
5664 object,
5665 property,
5666 optional,
5667 } => {
5668 // `super.x` is not a lookup on a value: it starts at the home object's
5669 // prototype and keeps `this` as the receiver, so it cannot go through
5670 // `chain_link` and the ordinary field read.
5671 if matches!(object.unparen().kind, ExprKind::SuperProp) {
5672 self.super_base();
5673 match property {
5674 MemberProp::Ident(name) => self.emit(
5675 Opcode::PushAtomValue,
5676 &[Op::Atom(Atom::from_text(&name.name))],
5677 ),
5678 MemberProp::Computed(index) => self.expr(index)?,
5679 MemberProp::Private(_) => {
5680 return Err(SyntaxError::new(
5681 "private fields are not supported by the compiler yet",
5682 expr.span,
5683 ));
5684 }
5685 }
5686 self.emit(Opcode::GetSuperValue, &[]);
5687 return Ok(());
5688 }
5689 self.chain_link(object, end)?;
5690 if *optional {
5691 self.optional_guard(end);
5692 }
5693 match property {
5694 // `.length` has its own opcode. The reference emits it for every
5695 // object, not just arrays, so a name-based rule is right and
5696 // cheaper than the generic field read.
5697 MemberProp::Ident(name) if name.name == "length" => {
5698 self.emit(Opcode::GetLength, &[]);
5699 }
5700 MemberProp::Ident(name) => {
5701 self.emit(Opcode::GetField, &[Op::Atom(Atom::from_text(&name.name))]);
5702 }
5703 MemberProp::Computed(index) => {
5704 self.expr(index)?;
5705 self.emit(Opcode::GetArrayEl, &[]);
5706 }
5707 MemberProp::Private(name) => {
5708 // The binding comes from the class scope, so a read from outside the
5709 // class cannot name it at all. `?.` checks the object, not the field:
5710 // `o?.#x` guards on `o` being nullish.
5711 let binding = format!("#{}", name.name);
5712 let (kind, _) = self.private_use(&binding, expr.span)?;
5713 self.private_load(&binding, kind, expr.span)?;
5714 }
5715 }
5716 Ok(())
5717 }
5718 ExprKind::Call {
5719 callee,
5720 arguments,
5721 optional,
5722 } => {
5723 // `o.m(args)` has to pass `o` as `this`, which a plain `call`
5724 // cannot: it reads the function and then calls it with no
5725 // receiver at all. The reference's answer is to keep the object
5726 // under the function value — `get_field2` reads a field and leaves
5727 // its base in place — and to use `call_method`, which takes the
5728 // receiver from the stack. Missing this does not just cost an
5729 // instruction, it loses the `this` binding.
5730 if let ExprKind::Member {
5731 object,
5732 property,
5733 optional: member_optional,
5734 } = &callee.unparen().kind
5735 {
5736 // `super.m()` reads the method off the home object's prototype but
5737 // calls it with `this`, so the receiver goes under the read instead of
5738 // being replaced by it.
5739 if matches!(object.unparen().kind, ExprKind::SuperProp) {
5740 self.super_base();
5741 match property {
5742 MemberProp::Ident(name) => self.emit(
5743 Opcode::PushAtomValue,
5744 &[Op::Atom(Atom::from_text(&name.name))],
5745 ),
5746 MemberProp::Computed(index) => self.expr(index)?,
5747 MemberProp::Private(_) => {
5748 return Err(SyntaxError::new(
5749 "private fields are not supported by the compiler yet",
5750 expr.span,
5751 ));
5752 }
5753 }
5754 // The two-output form would drop the receiver; this one replaces
5755 // the prototype and the key, leaving `this` underneath.
5756 self.emit(Opcode::GetArrayEl, &[]);
5757 if Self::has_spread(arguments) {
5758 self.argument_array(arguments)?;
5759 self.emit(Opcode::Perm3, &[]);
5760 self.emit(Opcode::Apply, &[Op::Int(0)]);
5761 return Ok(());
5762 }
5763 for argument in arguments {
5764 self.expr(argument)?;
5765 }
5766 self.emit(Opcode::CallMethod, &[Op::Int(arguments.len() as i32)]);
5767 return Ok(());
5768 }
5769 self.chain_link(object, end)?;
5770 if *member_optional {
5771 self.optional_guard(end);
5772 }
5773 match property {
5774 MemberProp::Ident(name) => {
5775 self.emit(Opcode::GetField2, &[Op::Atom(Atom::from_text(&name.name))])
5776 }
5777 MemberProp::Computed(index) => {
5778 self.expr(index)?;
5779 // The key is not needed after the read, so this is the
5780 // two-output form: object, value.
5781 self.emit(Opcode::GetArrayEl2, &[]);
5782 }
5783 MemberProp::Private(name) => {
5784 // The receiver is already under the callee, which is exactly the
5785 // shape `call_method` and `apply` want — so nothing is dropped.
5786 let binding = format!("#{}", name.name);
5787 let (kind, _) = self.private_use(&binding, expr.span)?;
5788 self.private_callee(&binding, kind)?;
5789 }
5790 }
5791 if Self::has_spread(arguments) {
5792 // Stack is `obj func`; the array goes on top, then `perm3`
5793 // reorders to the `func this array` that `apply` wants.
5794 self.argument_array(arguments)?;
5795 self.emit(Opcode::Perm3, &[]);
5796 self.emit(Opcode::Apply, &[Op::Int(0)]);
5797 return Ok(());
5798 }
5799 for argument in arguments {
5800 self.expr(argument)?;
5801 }
5802 self.emit(Opcode::CallMethod, &[Op::Int(arguments.len() as i32)]);
5803 return Ok(());
5804 }
5805 // `(a?.b)()` keeps `a` as the receiver: the reference reads the method
5806 // with `get_field2` so the base stays under it, and on the short-circuit
5807 // path pushes an extra `undefined` as a placeholder receiver — the call
5808 // then throws, which is what calling a missing optional chain should do.
5809 if let ExprKind::OptionalChain(inner) = &callee.unparen().kind
5810 && let ExprKind::Member {
5811 object,
5812 property,
5813 optional: member_optional,
5814 } = &inner.unparen().kind
5815 {
5816 let call = self.new_label();
5817 // A guard target of its own: the outer `end` skips the whole
5818 // expression, and a short-circuited receiver still has to reach the
5819 // call so that calling it throws.
5820 let short = self.new_label();
5821 self.chain_link(object, end)?;
5822 if *member_optional {
5823 self.optional_guard(short);
5824 }
5825 match property {
5826 MemberProp::Ident(name) => {
5827 self.emit(Opcode::GetField2, &[Op::Atom(Atom::from_text(&name.name))])
5828 }
5829 MemberProp::Computed(index) => {
5830 self.expr(index)?;
5831 self.emit(Opcode::GetArrayEl2, &[]);
5832 }
5833 MemberProp::Private(name) => {
5834 let binding = format!("#{}", name.name);
5835 let (kind, _) = self.private_use(&binding, expr.span)?;
5836 self.private_callee(&binding, kind)?;
5837 }
5838 }
5839 self.emit_jump(Opcode::Goto, call, &[]);
5840 self.place_label(short);
5841 self.emit(Opcode::Undefined, &[]);
5842 self.place_label(call);
5843 if Self::has_spread(arguments) {
5844 self.argument_array(arguments)?;
5845 self.emit(Opcode::Perm3, &[]);
5846 self.emit(Opcode::Apply, &[Op::Int(0)]);
5847 return Ok(());
5848 }
5849 for argument in arguments {
5850 self.expr(argument)?;
5851 }
5852 self.emit(Opcode::CallMethod, &[Op::Int(arguments.len() as i32)]);
5853 return Ok(());
5854 }
5855 self.chain_link(callee, end)?;
5856 if *optional {
5857 self.optional_guard(end);
5858 }
5859 if Self::has_spread(arguments) {
5860 // `func array -> func undefined array`, which is the plain-call
5861 // form of `apply`: the receiver is `undefined`.
5862 self.argument_array(arguments)?;
5863 self.emit(Opcode::Undefined, &[]);
5864 self.emit(Opcode::Swap, &[]);
5865 self.emit(Opcode::Apply, &[Op::Int(0)]);
5866 return Ok(());
5867 }
5868 for argument in arguments {
5869 self.expr(argument)?;
5870 }
5871 self.emit(Opcode::Call, &[Op::Int(arguments.len() as i32)]);
5872 Ok(())
5873 }
5874 _ => self.expr(expr),
5875 }
5876 }
5877
5878 /// Compile `expr` as a tail call when it is one, reporting whether it was.
5879 ///
5880 /// `tail_call` reuses the current frame instead of pushing a new one, so a
5881 /// tail-recursive function runs in constant stack space. It also has to be the
5882 /// *last* thing the function does, which is why only a `return` reaches here.
5883 fn expr_if_tail_call(&mut self, expr: &Expr) -> Result<bool, SyntaxError> {
5884 let ExprKind::Call {
5885 callee,
5886 arguments,
5887 optional: false,
5888 } = &expr.unparen().kind
5889 else {
5890 return Ok(false);
5891 };
5892 // A spread call has no tail form: `tail_call` takes its arguments one at a time off
5893 // the stack, while `f(...xs)` builds an array and goes through `apply`. Compiling it
5894 // as an ordinary call costs the one frame the optimisation was saving and keeps the
5895 // semantics — the alternative was reaching the spread expression below and failing
5896 // with "this expression form is not supported", which is how `return super.m(...a)`
5897 // stopped compiling. Checked before anything is emitted, because the decision cannot
5898 // be taken back once `super_base` or a `get_field2` is on the stack.
5899 if Self::has_spread(arguments) {
5900 return Ok(false);
5901 }
5902 let end = self.new_label();
5903 if let ExprKind::Member {
5904 object,
5905 property,
5906 optional: false,
5907 } = &callee.unparen().kind
5908 {
5909 // `super.m()` in tail position is still an ordinary method call with `this`
5910 // as the receiver; only the read of the method differs.
5911 if matches!(object.unparen().kind, ExprKind::SuperProp) {
5912 self.super_base();
5913 match property {
5914 MemberProp::Ident(name) => self.emit(
5915 Opcode::PushAtomValue,
5916 &[Op::Atom(Atom::from_text(&name.name))],
5917 ),
5918 MemberProp::Computed(index) => self.expr(index)?,
5919 MemberProp::Private(_) => return Ok(false),
5920 }
5921 self.emit(Opcode::GetArrayEl, &[]);
5922 for argument in arguments {
5923 self.expr(argument)?;
5924 }
5925 self.emit(Opcode::TailCallMethod, &[Op::Int(arguments.len() as i32)]);
5926 self.place_label(end);
5927 return Ok(true);
5928 }
5929 self.chain_link(object, end)?;
5930 match property {
5931 MemberProp::Ident(name) => {
5932 self.emit(Opcode::GetField2, &[Op::Atom(Atom::from_text(&name.name))])
5933 }
5934 MemberProp::Computed(index) => {
5935 self.expr(index)?;
5936 self.emit(Opcode::GetArrayEl2, &[]);
5937 }
5938 MemberProp::Private(_) => return Ok(false),
5939 }
5940 for argument in arguments {
5941 self.expr(argument)?;
5942 }
5943 self.emit(Opcode::TailCallMethod, &[Op::Int(arguments.len() as i32)]);
5944 self.place_label(end);
5945 return Ok(true);
5946 }
5947 self.chain_link(callee, end)?;
5948 for argument in arguments {
5949 self.expr(argument)?;
5950 }
5951 self.emit(Opcode::TailCall, &[Op::Int(arguments.len() as i32)]);
5952 self.place_label(end);
5953 Ok(true)
5954 }
5955
5956 /// The `?.` guard: keep the value if it is neither null nor undefined,
5957 /// otherwise replace it with `undefined` and leave the whole chain.
5958 fn optional_guard(&mut self, end: Label) {
5959 let cont = self.new_label();
5960 self.emit(Opcode::Dup, &[]);
5961 self.emit(Opcode::IsUndefinedOrNull, &[]);
5962 self.emit_jump(Opcode::IfFalse, cont, &[]);
5963 self.emit(Opcode::Drop, &[]);
5964 self.emit(Opcode::Undefined, &[]);
5965 self.emit_jump(Opcode::Goto, end, &[]);
5966 self.place_label(cont);
5967 }
5968
5969 fn push_number(&mut self, value: f64) {
5970 // `push_N` / `push_i8` / `push_i32` cover small integers; everything else
5971 // goes into the constant pool.
5972 if value == value.trunc() && value.abs() <= i32::MAX as f64 {
5973 let int = value as i32;
5974 if (-1..=7).contains(&int) {
5975 self.emit(Opcode::PushI32, &[Op::Int(int)]);
5976 return;
5977 }
5978 if (-128..=127).contains(&int) {
5979 self.emit(Opcode::PushI8, &[Op::Int(int)]);
5980 return;
5981 }
5982 if (-32768..=32767).contains(&int) {
5983 self.emit(Opcode::PushI16, &[Op::Int(int)]);
5984 return;
5985 }
5986 self.emit(Opcode::PushI32, &[Op::Int(int)]);
5987 return;
5988 }
5989 let index = self.push_constant(Constant::Number(value));
5990 self.emit(Opcode::PushConst, &[Op::Const(index)]);
5991 }
5992
5993 /// Push a `BigInt` literal.
5994 ///
5995 /// A value that fits an `i32` uses the immediate form, which is what the reference
5996 /// emits too; anything larger goes into the constant pool, because the operand of
5997 /// `push_bigint` is only four bytes wide.
5998 fn push_bigint(&mut self, digits: &str, radix: u32) {
5999 if radix == 10
6000 && let Ok(value) = digits.parse::<i64>()
6001 && (i32::MIN as i64..=i32::MAX as i64).contains(&value)
6002 {
6003 self.emit(Opcode::PushBigintI32, &[Op::Int(value as i32)]);
6004 return;
6005 }
6006 let index = self.push_constant(Constant::BigInt {
6007 digits: digits.to_string(),
6008 radix,
6009 });
6010 self.emit(Opcode::PushConst, &[Op::Const(index)]);
6011 }
6012
6013 fn push_string(&mut self, text: &Wtf8) {
6014 if text.is_empty() {
6015 self.emit(Opcode::PushEmptyString, &[]);
6016 return;
6017 }
6018 self.emit(Opcode::PushAtomValue, &[Op::Atom(Atom::from_wtf8(text))]);
6019 }
6020
6021 /// Name an anonymous function from the binding it is assigned to.
6022 ///
6023 /// `var f = function(){}` produces a function whose `name` is `f`, which the
6024 /// runtime cannot know without being told: the function object is created
6025 /// before the store. `set_name` carries the name across.
6026 fn set_name_if_anonymous(&mut self, value: &Expr, name: &Wtf8) {
6027 if !value.is_anonymous_function_definition() {
6028 return;
6029 }
6030 // A class cannot use `set_name`, because its static field initialisers have already
6031 // run by the time the store happens and they can see `this.name`:
6032 // `var E = class { static f = this.name }` has to answer `"E"`. The reference patches
6033 // the `define_class` instruction's name operand instead, which is why
6034 // `set_class_name` is a compile-time marker with no runtime effect
6035 // (`class-name-static-initializer-anonymous`).
6036 if matches!(value.unparen().kind, ExprKind::Class(_)) {
6037 if let Some(index) = self.last_define_class() {
6038 let atom = Atom::from_wtf8(name);
6039 if let Some(Insn::Fixed { operands, .. }) = self.state().insns.get_mut(index) {
6040 // `define_class <atom> <flags>`: the name is operand 0.
6041 operands[0] = Op::Atom(atom);
6042 }
6043 }
6044 return;
6045 }
6046 self.emit(Opcode::SetName, &[Op::Atom(Atom::from_wtf8(name))]);
6047 }
6048
6049 /// The index of the most recent `define_class` in this function's instruction stream.
6050 ///
6051 /// A backwards scan, because everything the class body emitted for the *enclosing*
6052 /// function is still there after it — the static initialiser's call, the class
6053 /// binding's store, `leave_scope` — and only the `define_class` carries the name.
6054 fn last_define_class(&self) -> Option<usize> {
6055 self.cur().insns.iter().rposition(|insn| {
6056 matches!(
6057 insn,
6058 Insn::Fixed {
6059 op: Opcode::DefineClass,
6060 ..
6061 }
6062 )
6063 })
6064 }
6065
6066 /// The same, for a computed key: the name comes from the value on the stack
6067 /// rather than from an atom, so a different instruction carries it.
6068 fn set_name_if_anonymous_computed(&mut self, value: &Expr) {
6069 if value.is_anonymous_function_definition() {
6070 self.emit(Opcode::SetNameComputed, &[]);
6071 }
6072 }
6073
6074 /// Compile a function body that exists only in the compiler's head — a class's
6075 /// implicit constructor or its field initialiser.
6076 ///
6077 /// Everything structural is the same as a written function: a fresh `FnState`, its
6078 /// own body block, and resolution while the frame is still on the stack. Only the
6079 /// statements differ.
6080 fn compile_synthetic_function(
6081 &mut self,
6082 name: &str,
6083 strict: bool,
6084 span: Span,
6085 body: impl FnOnce(&mut Self) -> Result<(), SyntaxError>,
6086 ) -> Result<CompiledFunction, SyntaxError> {
6087 let mut state = FnState::new(name.to_string(), FunctionKind::Normal);
6088 state.span = Some((span.start.offset as usize, span.end.offset as usize));
6089 state.strict = strict;
6090 state.created_in_block = self.cur().current_block;
6091 state.with_names = self.cur().with_names.clone();
6092 state.line = span.start.line;
6093 state.column = span.start.column;
6094 let depth = self.stack.len();
6095 self.stack.push(state);
6096 let body_key = span.start.offset as u64;
6097 self.push_block(body_key, NO_PARENT);
6098 self.state().body_block = body_key;
6099 let result = (|| {
6100 self.emit_scope_enter(body_key);
6101 body(self)?;
6102 if self.end_is_reachable() {
6103 self.emit(Opcode::ReturnUndef, &[]);
6104 }
6105 Ok(())
6106 })();
6107 if result.is_err() {
6108 self.stack.truncate(depth);
6109 return result.map(|()| unreachable!());
6110 }
6111 Ok(self.finish_current())
6112 }
6113
6114 /// The implicit return of a class constructor.
6115 ///
6116 /// A constructor that falls off the end initialises its instance fields first, and a
6117 /// derived one returns `this` — which is what makes `new D()` the object `super()`
6118 /// built rather than `undefined`.
6119 fn emit_class_constructor_tail(&mut self) {
6120 match self.cur().ctor_kind {
6121 CtorKind::None => self.emit(Opcode::ReturnUndef, &[]),
6122 // Nothing to install: a base constructor did it in its prologue and a derived
6123 // one at each `super()` site, which is where `this` first exists.
6124 CtorKind::Base => self.emit(Opcode::ReturnUndef, &[]),
6125 CtorKind::Derived => {
6126 // `get_loc_check` rather than `get_loc`: reaching the end without ever
6127 // running `super()` is a ReferenceError, not `undefined`.
6128 self.emit_var(VarAction::Get, "this");
6129 self.emit(Opcode::Return, &[]);
6130 }
6131 }
6132 }
6133
6134 /// `yield expr` / `yield* expr`.
6135 ///
6136 /// The suspension itself is one instruction: the value is on the stack, `yield` hands
6137 /// it to the caller and parks the frame. On resume the stack holds the value the
6138 /// caller passed *and* a "magic" number saying which method resumed it — `next`
6139 /// passes `0`, `return` passes `1`, `throw` passes `2` — so the emitted
6140 /// `if_false <continue>` asks whether this was an ordinary `next`:
6141 ///
6142 /// * `next(v)` → the magic is falsy, jump over the `return_async` and `drop` `v`.
6143 /// * `return(v)`/`throw(e)` → fall into `return_async`, which finishes the generator
6144 /// and uses the value sitting under the magic number.
6145 ///
6146 /// A `throw` never reaches here: the interpreter unwinds instead (see
6147 /// `Interp::resume_generator`), so the `return_async` arm only ever carries `return`.
6148 fn yield_expression(
6149 &mut self,
6150 argument: Option<&Expr>,
6151 delegate: bool,
6152 ) -> Result<(), SyntaxError> {
6153 if delegate {
6154 return self.yield_star(argument);
6155 }
6156 // `AsyncGeneratorYield` settles the value *before* suspending, and `AsyncGenerator`
6157 // does the same for the `return(v)` that can resume it — which is why an async
6158 // generator's `yield` is `await; yield; (…); await; return_async` and a synchronous
6159 // generator's is just `yield`.
6160 let is_async = self.cur().kind == FunctionKind::AsyncGenerator;
6161 match argument {
6162 Some(value) => self.expr(value)?,
6163 None => self.emit(Opcode::Undefined, &[]),
6164 }
6165 if is_async {
6166 self.emit(Opcode::Await, &[]);
6167 self.state().has_await = true;
6168 }
6169 self.emit(Opcode::Yield, &[]);
6170 let resume = self.new_label();
6171 self.emit_jump(Opcode::IfFalse, resume, &[]);
6172 // `return(v)` resumed us. It is a `return` from the *body's* point of view, so it
6173 // runs the same cleanup chain: without it, `it.return()` inside `try { yield }`
6174 // finished the generator and never ran the `finally`.
6175 if is_async {
6176 self.emit(Opcode::Await, &[]);
6177 }
6178 self.emit_unwind_for_return(true);
6179 self.emit(Opcode::ReturnAsync, &[]);
6180 self.place_label(resume);
6181 // Nothing is emitted here: the value the caller passed to `next` *is* the value
6182 // of the `yield` expression, so `var x = yield 1` stores it and `yield 1;` drops
6183 // it through the ordinary expression-statement discard.
6184 Ok(())
6185 }
6186
6187 /// `yield* iterable`.
6188 ///
6189 /// The shape is the reference's, and it is a fall-through chain rather than a
6190 /// decision tree: drive the inner iterator, forward each value with `yield_star`, and
6191 /// on resume decide what the caller asked for — `next` keeps looping, `return` closes
6192 /// the inner iterator and finishes, `throw` forwards the exception into it and
6193 /// continues only if it has a `throw` method.
6194 ///
6195 /// The stack is `iter next catch value` throughout, `catch` being the offset
6196 /// `for_of_start` pushed; the `nip`s at the end uncover the value that is returned.
6197 fn yield_star(&mut self, argument: Option<&Expr>) -> Result<(), SyntaxError> {
6198 match argument {
6199 Some(value) => self.expr(value)?,
6200 // The parser rejects a bare `yield*`, so this is unreachable in practice.
6201 None => return Err(SyntaxError::new("yield* needs an operand", Span::default())),
6202 }
6203 // `for await of` is the same protocol as `for of` with two differences that matter
6204 // here: the iterator comes from `@@asyncIterator` with a `@@iterator` fallback, and
6205 // every `next()` result is a promise the delegate has to await.
6206 let is_async = self.cur().kind.is_async();
6207 self.emit(
6208 if is_async {
6209 Opcode::ForAwaitOfStart
6210 } else {
6211 Opcode::ForOfStart
6212 },
6213 &[],
6214 );
6215 self.emit(Opcode::Drop, &[]);
6216 self.emit(Opcode::Undefined, &[]);
6217 self.emit(Opcode::Undefined, &[]);
6218 let next = self.new_label();
6219 let resume = self.new_label();
6220 let finished = self.new_label();
6221 let rethrow = self.new_label();
6222 let throw_no_method = self.new_label();
6223 let done = self.new_label();
6224 self.place_label(next);
6225 self.emit(Opcode::IteratorNext, &[]);
6226 if is_async {
6227 self.emit(Opcode::Await, &[]);
6228 self.state().has_await = true;
6229 }
6230 self.emit(Opcode::IteratorCheckObject, &[]);
6231 self.emit(Opcode::GetField2, &[Op::Atom(Atom::from_text("done"))]);
6232 self.emit_jump(Opcode::IfTrue, done, &[]);
6233 // The suspension. `resume` is both the label the return path jumps back to in order
6234 // to yield one more value and where the caller's answer arrives, as the value
6235 // followed by the magic number.
6236 //
6237 // The two forms differ in what they hand the suspension: `yield_star` takes the
6238 // result object itself, `async_yield_star` takes `.value`, because an async
6239 // generator awaits and re-wraps whatever it yields.
6240 self.place_label(resume);
6241 if is_async {
6242 self.emit(Opcode::GetField, &[Op::Atom(Atom::from_text("value"))]);
6243 self.emit(Opcode::AsyncYieldStar, &[]);
6244 } else {
6245 self.emit(Opcode::YieldStar, &[]);
6246 }
6247 self.emit(Opcode::Dup, &[]);
6248 self.emit_jump(Opcode::IfTrue, rethrow, &[]);
6249 self.emit(Opcode::Drop, &[]);
6250 self.emit_jump(Opcode::Goto, next, &[]);
6251
6252 // `return(v)` / `throw(e)`: `2 === magic` tells them apart.
6253 self.place_label(rethrow);
6254 self.emit(Opcode::PushI32, &[Op::Int(2)]);
6255 self.emit(Opcode::StrictEq, &[]);
6256 self.emit_jump(Opcode::IfTrue, throw_no_method, &[]);
6257 // A `return` closes the inner iterator; if it had none, the delegate simply
6258 // finishes with the requested value. In an async generator both the call and its
6259 // result are awaited, because the inner `return` may itself be async.
6260 if is_async {
6261 self.emit(Opcode::Await, &[]);
6262 }
6263 self.emit(Opcode::IteratorCall, &[Op::Int(0)]);
6264 self.emit_jump(Opcode::IfTrue, finished, &[]);
6265 if is_async {
6266 self.emit(Opcode::Await, &[]);
6267 }
6268 self.emit(Opcode::IteratorCheckObject, &[]);
6269 self.emit(Opcode::GetField2, &[Op::Atom(Atom::from_text("done"))]);
6270 self.emit_jump(Opcode::IfFalse, resume, &[]);
6271 self.emit(Opcode::GetField, &[Op::Atom(Atom::from_text("value"))]);
6272 self.place_label(finished);
6273 self.emit(Opcode::Nip, &[]);
6274 self.emit(Opcode::Nip, &[]);
6275 self.emit(Opcode::Nip, &[]);
6276 // This is the delegate finishing on the caller's `return(v)`, so it is a `return`
6277 // from the body's point of view: `emit_return(s, TRUE)` in the reference, which
6278 // awaits the value in an async generator and then runs the same `finally`/iterator
6279 // unwinding a written `return` would. Skipping the unwinding made
6280 // `try { yield* xs } finally { … }` return early and leave the `finally` unrun.
6281 if is_async {
6282 self.emit(Opcode::Await, &[]);
6283 }
6284 self.emit_unwind_for_return(true);
6285 self.emit(Opcode::ReturnAsync, &[]);
6286
6287 // `throw(e)`: forward it into the inner iterator.
6288 self.place_label(throw_no_method);
6289 self.emit(Opcode::IteratorCall, &[Op::Int(1)]);
6290 let no_throw = self.new_label();
6291 self.emit_jump(Opcode::IfTrue, no_throw, &[]);
6292 if is_async {
6293 self.emit(Opcode::Await, &[]);
6294 }
6295 self.emit(Opcode::IteratorCheckObject, &[]);
6296 self.emit(Opcode::GetField2, &[Op::Atom(Atom::from_text("done"))]);
6297 self.emit_jump(Opcode::IfFalse, resume, &[]);
6298 self.emit_jump(Opcode::Goto, done, &[]);
6299 // No `throw` method: close the iterator, then report the spec's TypeError. The
6300 // `if_true` before the `await` is the reference's shape — the flag it consumes is
6301 // what `iterator_call` leaves behind, and a close that *did* find no `return`
6302 // method has nothing to await.
6303 self.place_label(no_throw);
6304 self.emit(Opcode::IteratorCall, &[Op::Int(2)]);
6305 let no_close = self.new_label();
6306 self.emit_jump(Opcode::IfTrue, no_close, &[]);
6307 if is_async {
6308 self.emit(Opcode::Await, &[]);
6309 }
6310 self.place_label(no_close);
6311 self.emit(Opcode::ThrowError, &[Op::Atom(Atom::Null), Op::Int(4)]);
6312
6313 // The inner iterator finished: the delegate's value is the `yield*` expression's
6314 // value, so it is left on the stack for whatever consumes it.
6315 self.place_label(done);
6316 self.emit(Opcode::GetField, &[Op::Atom(Atom::from_text("value"))]);
6317 self.emit(Opcode::Nip, &[]);
6318 self.emit(Opcode::Nip, &[]);
6319 self.emit(Opcode::Nip, &[]);
6320 Ok(())
6321 }
6322
6323 /// `await expr`: exactly one instruction.
6324 ///
6325 /// No resume-magic branch follows it. The reference's `await` leaves a single value
6326 /// on the stack and completion is signalled by the `return_async` at the end of the
6327 /// body; an `if_false`/`return_async` pair here would be an instruction sequence the
6328 /// reference never emits, and a `for await` loop — which reaches `await` through the
6329 /// same opcode — would then spill a value the loop's unpacking does not expect.
6330 fn await_expression(&mut self, argument: &Expr) -> Result<(), SyntaxError> {
6331 self.expr(argument)?;
6332 self.emit(Opcode::Await, &[]);
6333 self.state().has_await = true;
6334 Ok(())
6335 }
6336
6337 /// The `super` base: the receiver followed by the home object's prototype.
6338 ///
6339 /// Everything `super` does needs both. A *read* starts at the prototype but reports
6340 /// to the receiver (so a getter sees `this`), and a *call* reads the method off the
6341 /// prototype but calls it with the receiver.
6342 fn super_base(&mut self) {
6343 self.this_expression();
6344 self.home_object();
6345 self.emit(Opcode::GetSuper, &[]);
6346 }
6347
6348 /// `[[HomeObject]]` as `super` sees it.
6349 ///
6350 /// A method, a constructor and a field initialiser each carry one — `set_home_object`
6351 /// put it there — so for them the special object *is* the answer. An arrow and a
6352 /// static block have none: they read the enclosing function's, which has to be
6353 /// materialised into a local, exactly as `this` is for an arrow.
6354 ///
6355 /// The name matches what the reference stores, so the disassembly agrees; it is not a
6356 /// name any program can write.
6357 fn home_object(&mut self) {
6358 if !self.cur().is_arrow {
6359 self.emit(Opcode::SpecialObject, &[Op::Int(4)]);
6360 return;
6361 }
6362 if let Some(target) = self.enclosing_function() {
6363 self.state_at(target).needs_home_object_local = true;
6364 self.declare_at(target, HOME_OBJECT);
6365 }
6366 self.emit_var(VarAction::Get, HOME_OBJECT);
6367 }
6368
6369 /// `super(args)`: construct the parent class and adopt the result as `this`.
6370 ///
6371 /// The parent is the prototype of the constructor that is running, which is exactly
6372 /// what `extends` set up. `new.target` is passed through unchanged so that
6373 /// `new.target` inside the parent is the class actually being constructed.
6374 fn super_call(&mut self, arguments: &[Expr]) -> Result<(), SyntaxError> {
6375 self.active_func_expression();
6376 self.emit(Opcode::GetSuper, &[]);
6377 self.new_target_expression();
6378 if Self::has_spread(arguments) {
6379 self.argument_array(arguments)?;
6380 self.emit(Opcode::Apply, &[Op::Int(1)]);
6381 } else {
6382 for argument in arguments {
6383 self.expr(argument)?;
6384 }
6385 self.emit(Opcode::CallConstructor, &[Op::Int(arguments.len() as i32)]);
6386 }
6387 // The value stays on the stack: `super()` is an expression, and a derived
6388 // constructor's `this` may only be initialised once.
6389 self.emit(Opcode::Dup, &[]);
6390 self.emit_var(VarAction::PutInitChecked, "this");
6391 // Instance fields are installed here, not at the top of the body: a derived
6392 // constructor has no `this` to install them on until `super()` returns. The
6393 // reference emits the same call at every `super()` site.
6394 self.call_field_initialiser();
6395 Ok(())
6396 }
6397
6398 /// `this` as a local, which every class constructor and field initialiser needs.
6399 ///
6400 /// The reference materialises the receiver into a local rather than reading
6401 /// `push_this` inline, because `super()` in a derived constructor *replaces* `this`
6402 /// and a field initialiser has to see the final value.
6403 fn begin_this_local(&mut self) {
6404 self.declare_hidden_local("this", VarKind::Normal);
6405 self.emit(Opcode::PushThis, &[]);
6406 self.emit_var(VarAction::Put, "this");
6407 // The store is already at the top of the body, so `provide_this_local` has
6408 // nothing left to prepend. Without this the initialiser ended up with
6409 // `push_this; put_loc0 this` twice whenever the class also held a field
6410 // initialiser whose body read `this` through an arrow.
6411 self.state().has_this_prologue = true;
6412 }
6413
6414 /// Compile a constructor the class wrote.
6415 ///
6416 /// The flags have to be in place before the body is compiled, but
6417 /// `compile_function_with_name` creates its own state — so the caller's state is
6418 /// marked instead and the new one inherits it. That is the same trick the parameter
6419 /// prologue uses, and it keeps one code path for both.
6420 fn compile_class_constructor(
6421 &mut self,
6422 func: &ast::Function,
6423 has_heritage: bool,
6424 ) -> Result<CompiledFunction, SyntaxError> {
6425 let saved = self.cur().ctor_kind;
6426 self.state().class_ctor_pending = Some(if has_heritage {
6427 CtorKind::Derived
6428 } else {
6429 CtorKind::Base
6430 });
6431 let result = self.compile_function_with_name(func, false);
6432 self.state().ctor_kind = saved;
6433 self.state().class_ctor_pending = None;
6434 result
6435 }
6436
6437 /// The constructor a class gets when it does not declare one.
6438 ///
6439 /// A base class's is empty; a derived class's forwards every argument to the parent
6440 /// and is expressed by `init_ctor`, which also keeps `new.target`. Both run the
6441 /// instance field initialiser afterwards when the class has fields, which is why the
6442 /// initialiser is captured rather than inlined.
6443 fn compile_implicit_constructor(
6444 &mut self,
6445 class: &Class,
6446 has_heritage: bool,
6447 ) -> Result<CompiledFunction, SyntaxError> {
6448 self.compile_synthetic_function(
6449 "",
6450 true,
6451 Span::new(class.body_end, class.body_end),
6452 |compiler| {
6453 if has_heritage {
6454 // A derived constructor's `this` does not exist until `super()` returns,
6455 // so it starts in the dead zone and `init_ctor` fills it.
6456 compiler.declare("this", VarDef::lexical("this"));
6457 compiler.emit(
6458 Opcode::SetLocUninitialized,
6459 &[Op::Slot(Slot::Loc(compiler.cur().vars.len() as u32 - 1))],
6460 );
6461 compiler.emit(Opcode::InitCtor, &[]);
6462 compiler.emit(
6463 Opcode::PutLocCheckInit,
6464 &[Op::Slot(Slot::Loc(compiler.cur().vars.len() as u32 - 1))],
6465 );
6466 } else {
6467 compiler.begin_this_local();
6468 compiler.emit(Opcode::CheckCtor, &[]);
6469 }
6470 compiler.call_field_initialiser();
6471 // A derived constructor returns `this`, the object `super()` built. Without
6472 // this the implicit constructor fell through to `return_undef`, and `new B()`
6473 // handed back the empty object `construct` had made instead of the one the
6474 // parent constructor initialised.
6475 if has_heritage {
6476 compiler.emit_var(VarAction::Get, "this");
6477 compiler.emit(Opcode::Return, &[]);
6478 }
6479 Ok(())
6480 },
6481 )
6482 }
6483
6484 /// Emit the call to `<class_fields_init>`, guarded by an `undefined` test.
6485 ///
6486 /// A class with no instance fields leaves the binding `undefined`, and calling it
6487 /// would throw; the reference emits the same guard rather than branching at compile
6488 /// time because a class can be extended by a subclass whose fields still have to run.
6489 fn call_field_initialiser(&mut self) {
6490 let skip = self.new_label();
6491 self.emit_var(VarAction::Get, "<class_fields_init>");
6492 self.emit(Opcode::Dup, &[]);
6493 self.emit_jump(Opcode::IfFalse, skip, &[]);
6494 self.emit_var(VarAction::Get, "this");
6495 self.emit(Opcode::Swap, &[]);
6496 self.emit(Opcode::CallMethod, &[Op::Int(0)]);
6497 self.place_label(skip);
6498 self.emit(Opcode::Drop, &[]);
6499 }
6500
6501 /// The function that defines one class's fields on `this`, and runs its static blocks.
6502 ///
6503 /// `define_field` rather than `put_field`: a field is an own property created
6504 /// without consulting a setter on the prototype, so `class C { set x(v){} }` with an
6505 /// `x = 1` field must not call the setter.
6506 ///
6507 /// One function serves the whole class: it is called once per instance (or once, for
6508 /// the static half) and walks the members in source order. Static blocks are compiled
6509 /// into the same function because they *are* part of the same sequence — `static a =
6510 /// 1; static { }` and `static { this.a = 1 }; static a = 2` leave `a` holding
6511 /// different values, so the two kinds cannot be split apart.
6512 fn compile_field_initialiser(
6513 &mut self,
6514 items: &[StaticInitItem<'_>],
6515 span: Span,
6516 instance: bool,
6517 add_brand: bool,
6518 ) -> Result<CompiledFunction, SyntaxError> {
6519 self.compile_synthetic_function("", true, span, |compiler| {
6520 // A field initialiser and a static block are not functions, so neither has an
6521 // `arguments` of its own; see `FnState::no_arguments_binding`.
6522 let current = compiler.stack.len() - 1;
6523 compiler.stack[current].no_arguments_binding = true;
6524 if instance {
6525 // An instance initialiser always carries a `<home_object>` local, because the
6526 // brand block below reads it — even when that block turns out to be dead. The
6527 // reference has the same artefact, and the store is visible in its dump.
6528 let current = compiler.stack.len() - 1;
6529 compiler.stack[current].needs_home_object_local = true;
6530 }
6531 compiler.begin_this_local();
6532 if instance {
6533 // `this` gets the brand the prototype created, before any field is defined —
6534 // which is what makes `#m()` usable from inside a field initialiser.
6535 //
6536 // The reference always emits `push_false; if_false L; this; home; add_brand;
6537 // L:` and patches the `push_false` to `push_true` from the class parse when
6538 // the class has private methods; either way the branch folds, but the *mark*
6539 // it leaves (a `goto`) is what keeps the `put_loc`/`get_loc` pair around the
6540 // `this` local from being fused into a `set_loc`.
6541 let skip = compiler.new_label();
6542 if add_brand {
6543 compiler.emit(Opcode::PushTrue, &[]);
6544 } else {
6545 compiler.emit(Opcode::PushFalse, &[]);
6546 }
6547 compiler.emit_jump(Opcode::IfFalse, skip, &[]);
6548 compiler.emit_var(VarAction::Get, "this");
6549 compiler.emit_var(VarAction::Get, HOME_OBJECT);
6550 compiler.emit(Opcode::AddBrand, &[]);
6551 compiler.place_label(skip);
6552 }
6553 for item in items {
6554 match item {
6555 StaticInitItem::Field(key, value) => {
6556 // A private field is *defined*, not assigned: `define_private_field`
6557 // reads `obj symbol value`, and its point is that it fails on a
6558 // receiver that is not this class's — which `put_field` would not.
6559 //
6560 // The three shapes are the reference's: `define_field <atom>` for a
6561 // static name, `define_array_el` for a key that is only known at run
6562 // time (`obj key value`), `define_private_field` for `#x`, and a
6563 // computed key is read from its binding rather than recomputed.
6564 compiler.emit_var(VarAction::Get, "this");
6565 match key {
6566 FieldKey::Private(binding) | FieldKey::Computed(binding) => {
6567 compiler.emit_var(VarAction::Get, binding);
6568 }
6569 FieldKey::Literal(_) => {}
6570 }
6571 match value {
6572 Some(value) => {
6573 compiler.expr(value)?;
6574 // A field initialiser is a `NamedEvaluation` target:
6575 // `x = function(){}` names the function `"x"`, and a private
6576 // field keeps its `#` (`static #f = () => 1` is named
6577 // `"#f"` (elements/static-field-anonymous-function-name).
6578 match key {
6579 FieldKey::Literal(literal) => {
6580 let text = compiler.property_key_text(literal, span)?;
6581 compiler.set_name_if_anonymous(value, &text);
6582 }
6583 FieldKey::Private(binding) => {
6584 compiler.set_name_if_anonymous(value, &Wtf8::new(binding));
6585 }
6586 // The key is a value on the stack, and `set_name_computed`
6587 // is exactly the instruction for that.
6588 FieldKey::Computed(_) => {
6589 compiler.set_name_if_anonymous_computed(value);
6590 }
6591 }
6592 }
6593 None => compiler.emit(Opcode::Undefined, &[]),
6594 }
6595 match key {
6596 FieldKey::Literal(literal) => {
6597 let text = compiler.property_key_text(literal, span)?;
6598 compiler
6599 .emit(Opcode::DefineField, &[Op::Atom(Atom::from_wtf8(&text))]);
6600 }
6601 FieldKey::Computed(_) => {
6602 compiler.emit(Opcode::DefineArrayEl, &[]);
6603 // `define_array_el` leaves `obj key`; the key is consumed by
6604 // the copy the pattern machinery wants, so both go.
6605 compiler.emit(Opcode::Drop, &[]);
6606 }
6607 FieldKey::Private(_) => {
6608 compiler.emit(Opcode::DefinePrivateField, &[]);
6609 }
6610 }
6611 compiler.emit(Opcode::Drop, &[]);
6612 }
6613 StaticInitItem::Block { body, body_start } => {
6614 let block = compiler.compile_static_block(body, *body_start)?;
6615 let index = compiler.push_constant(Constant::Function(Box::new(block)));
6616 // `this fclosure`, so `call_method` finds the receiver below the
6617 // callee: the block runs with `this` bound to the class.
6618 compiler.emit(Opcode::Fclosure, &[Op::Const(index)]);
6619 compiler.emit_var(VarAction::Get, "this");
6620 compiler.emit(Opcode::Swap, &[]);
6621 compiler.emit(Opcode::CallMethod, &[Op::Int(0)]);
6622 // Nothing the block evaluates is wanted; its effects are the point.
6623 compiler.emit(Opcode::Drop, &[]);
6624 }
6625 }
6626 }
6627 Ok(())
6628 })
6629 }
6630
6631 /// Compile a `static { … }` body into the function the class calls for it.
6632 ///
6633 /// Shaped like an arrow, because that is the one function form with no `this`,
6634 /// `new.target` or `arguments` of its own: all three reach the enclosing static
6635 /// initialiser, and through it the class. `arguments` never gets that far — the parser
6636 /// rejects the reference — but `this` and `super` both depend on it.
6637 ///
6638 /// The body is hoisted like a function body's, because the reference parses it as one:
6639 /// `var` inside a block is a local of the block's function, not of whatever encloses
6640 /// the class.
6641 fn compile_static_block(
6642 &mut self,
6643 body: &[Stmt],
6644 body_start: Position,
6645 ) -> Result<CompiledFunction, SyntaxError> {
6646 let mut state = FnState::new(String::new(), FunctionKind::Normal);
6647 // Class bodies are strict, so a static block is too.
6648 state.strict = true;
6649 // The one property that makes this an arrow: nothing of its own to bind `this` to,
6650 // so `this` and `super` come from the initialiser that calls it.
6651 state.is_arrow = true;
6652 state.created_in_block = self.cur().current_block;
6653 state.with_names = self.cur().with_names.clone();
6654 state.line = body_start.line;
6655 state.column = body_start.column;
6656 let depth = self.stack.len();
6657 self.stack.push(state);
6658 let body_key = body_start.offset as u64;
6659 self.push_block(body_key, NO_PARENT);
6660 self.state().body_block = body_key;
6661 let result = (|| {
6662 self.hoist(body, body_key)?;
6663 self.emit_scope_enter(body_key);
6664 for statement in body {
6665 self.stmt(statement)?;
6666 }
6667 if self.end_is_reachable() {
6668 self.emit(Opcode::ReturnUndef, &[]);
6669 }
6670 Ok(())
6671 })();
6672 if result.is_err() {
6673 self.stack.truncate(depth);
6674 return result.map(|()| unreachable!());
6675 }
6676 Ok(self.finish_current())
6677 }
6678
6679 /// Compile a class, leaving the constructor on the stack when `keep`.
6680 ///
6681 /// The shape follows the reference: the class body is its own scope holding the
6682 /// class's *inner* name as a `const` — which is what lets a method refer to the
6683 /// class by name — plus a `<class_fields_init>` binding for the initialiser function.
6684 /// `define_class` turns `parent ctor` into `ctor proto`, then the members are defined
6685 /// on the top of the stack: the prototype for instance members, the constructor
6686 /// itself for `static` ones, which is why a static member costs an extra `swap`.
6687 fn class_definition(&mut self, class: &Class, keep: bool) -> Result<(), SyntaxError> {
6688 let parent_block = self.cur().current_block;
6689 let key = class.span.start.offset as u64;
6690 self.push_block(key, parent_block);
6691 let name = class.name.as_ref().map(|ident| ident.name.clone());
6692 // The class's own name is bound inside the body, so `class E { static F(){ return E } }`
6693 // resolves `E` without a global lookup. An *unnamed* class expression has no such
6694 // binding, and `define_class` is handed the empty name.
6695 if let Some(name) = &name {
6696 self.declare(name, VarDef::constant(name.clone()));
6697 }
6698 self.emit_scope_enter(key);
6699
6700 // The heritage clause is evaluated outside the class's own scope: it cannot see
6701 // the class binding it is about to initialise.
6702 let saved_block = self.cur().current_block;
6703 self.state().current_block = parent_block;
6704 match &class.super_class {
6705 Some(parent) => self.expr(parent)?,
6706 None => self.emit(Opcode::Undefined, &[]),
6707 }
6708 self.state().current_block = saved_block;
6709 let has_heritage = class.super_class.is_some();
6710
6711 // `<class_fields_init>` is declared *after* the heritage, so its dead-zone mark
6712 // lands after the heritage's code — which is where the reference puts it, because it
6713 // calls `define_var(..., JS_VAR_DEF_CONST)` at that point rather than at class entry.
6714 // Declaring it before `emit_scope_enter` instead put both marks at the class entry,
6715 // and `block_vars_reversed` prints a block's bindings backwards, so the two lines
6716 // came out in the opposite order from the reference's.
6717 //
6718 // `const`, as in `define_var(..., JS_VAR_DEF_CONST)`: the binding is filled exactly
6719 // once, through `put_var_init`/`scope_put_var_init` — the *initialising* store, which
6720 // a const accepts — so the old comment's worry ("a const would refuse the second
6721 // store") did not apply: there is no second store.
6722 // Every `#name` the class declares gets a `const` binding in the class scope, and so
6723 // does every computed field key. That is how the reference does it
6724 // (`add_private_class_field` → `add_scope_var` with `is_lexical`/`is_const`), and it is
6725 // what makes a private name resolve like any other class-scope variable — including
6726 // through a nested function's closure — while remaining invisible outside.
6727 //
6728 // All of them are declared *before* `<class_fields_init>`, in member order, because
6729 // that is when the reference's parser creates them.
6730 let plan = ClassPlan::build(class);
6731 // The body's private names are visible from here to the end of the class, and shadow
6732 // any outer class's of the same spelling. Pushed *before* the constructor is compiled
6733 // — it is compiled first because `define_class` consumes it, but its body can name
6734 // `#x` like any other member's.
6735 self.private_scopes.push(plan.uses.clone());
6736 let mut class_slots: Vec<u32> = Vec::with_capacity(plan.bindings.len());
6737 for binding in &plan.bindings {
6738 class_slots.push(self.declare(binding, VarDef::constant(binding.clone())));
6739 }
6740 let fci = self.declare(
6741 "<class_fields_init>",
6742 VarDef::constant("<class_fields_init>"),
6743 );
6744 // Dead-zone marks in reverse slot order, which is how `enter_scope` emits a scope's
6745 // lexical bindings — so `<class_fields_init>` (the highest) is marked first and the
6746 // members' bindings follow in reverse.
6747 self.emit(Opcode::SetLocUninitialized, &[Op::Slot(Slot::Loc(fci))]);
6748 for slot in class_slots.iter().rev() {
6749 self.emit(Opcode::SetLocUninitialized, &[Op::Slot(Slot::Loc(*slot))]);
6750 }
6751
6752 // The constructor is compiled before `define_class` because that instruction
6753 // consumes it; a class without one gets the implicit version.
6754 let constructor = class.elements.iter().find_map(|element| match element {
6755 ClassElement::Method {
6756 kind: MethodKind::Constructor,
6757 func,
6758 ..
6759 } => Some(&**func),
6760 _ => None,
6761 });
6762 // A constructor is compiled differently from a method: it owns `this`. The flags
6763 // go on the *enclosing* state because a constructor is a nested function and
6764 // `compile_function_with_name` starts a fresh one.
6765 let ctor = match constructor {
6766 Some(func) => self.compile_class_constructor(func, has_heritage)?,
6767 None => self.compile_implicit_constructor(class, has_heritage)?,
6768 };
6769 // A closure, not the bare constant: the constructor captures
6770 // `<class_fields_init>`, which is only filled after `define_class` has run, so it
6771 // has to hold the cell rather than a copy of its value.
6772 //
6773 // The pool slot is left unassigned for now, because the reference gives the
6774 // constructor the *last* index of the members' range: `js_parse_class` emits a
6775 // `push_const` whose operand is patched at the end of the class parse, after every
6776 // method has taken a slot. Emitting the members first and the constant second is how
6777 // the numbering comes out the same; the instruction itself stays where it is.
6778 let ctor_insn = self.cur().insns.len();
6779 self.emit(Opcode::Fclosure, &[Op::Const(CTOR_INDEX_PLACEHOLDER)]);
6780 let flags = if has_heritage { 1 } else { 0 };
6781 self.emit(
6782 Opcode::DefineClass,
6783 &[
6784 Op::Atom(Atom::from_text(name.as_deref().unwrap_or(""))),
6785 Op::Int(flags),
6786 ],
6787 );
6788
6789 // Instance fields and static fields are two different functions: the first runs
6790 // per instance from the constructor, the second runs once, here.
6791 let mut instance_fields: Vec<StaticInitItem<'_>> = Vec::new();
6792 let mut static_items: Vec<StaticInitItem<'_>> = Vec::new();
6793 for (index, element) in class.elements.iter().enumerate() {
6794 match element {
6795 ClassElement::Method {
6796 key: member_key,
6797 is_static,
6798 kind,
6799 func,
6800 span,
6801 } => {
6802 if *kind == MethodKind::Constructor {
6803 continue;
6804 }
6805 // `static(x)` is a *method* named `static`, not a static method; the
6806 // parser already decided which by putting it in `kind`.
6807 if *is_static {
6808 self.emit(Opcode::Swap, &[]);
6809 }
6810 // A computed key is evaluated *here*, before the method's closure
6811 // exists, and stays under it: `define_method_computed` pops
6812 // `function, key, object`, so the stack has to read
6813 // `[class, prototype, key, function]`. Evaluating the key after the
6814 // `fclosure` and swapping the two put the prototype *below* the
6815 // closure, which defined the method on the function and lost the
6816 // prototype: `class C { [k]() {} }` left `C` undefined. The order is
6817 // also the spec's — a class body evaluates every element's name before
6818 // that element's function.
6819 if let PropName::Computed(key) = member_key {
6820 self.expr(key)?;
6821 }
6822 let function = self.compile_function_with_name(func, true)?;
6823 let index = self.push_constant(Constant::Function(Box::new(function)));
6824 self.emit(Opcode::Fclosure, &[Op::Const(index)]);
6825 match member_key {
6826 // A private method is not a property of the prototype: it is a
6827 // closure in the class scope, which is why nothing outside can reach
6828 // it and why a use site has to brand-check. `set_name` gives the
6829 // function its `name` (`#m`), which an accessor does not get — the
6830 // reference leaves that commented out.
6831 PropName::Private(ident) => {
6832 let name = format!("#{}", ident.name);
6833 // `set_home_object` first: the brand check reads the function's
6834 // home object, and for a method that is the prototype.
6835 self.emit(Opcode::SetHomeObject, &[]);
6836 let binding = if *kind == MethodKind::Set {
6837 format!("{name}<set>")
6838 } else {
6839 name.clone()
6840 };
6841 if *kind == MethodKind::Method {
6842 self.emit(Opcode::SetName, &[Op::Atom(Atom::from_text(&name))]);
6843 }
6844 self.emit_var(VarAction::PutInit, &binding);
6845 }
6846 PropName::Computed(_) => {
6847 self.emit(
6848 Opcode::DefineMethodComputed,
6849 &[Op::Int(class_method_flags(*kind))],
6850 );
6851 }
6852 PropName::Literal(literal) => {
6853 let text = self.property_key_text(literal, *span)?;
6854 self.emit(
6855 Opcode::DefineMethod,
6856 &[
6857 Op::Atom(Atom::from_wtf8(&text)),
6858 Op::Int(class_method_flags(*kind)),
6859 ],
6860 );
6861 }
6862 }
6863 if *is_static {
6864 self.emit(Opcode::Swap, &[]);
6865 }
6866 }
6867 ClassElement::Field {
6868 key: field_key,
6869 is_static,
6870 value,
6871 ..
6872 } => {
6873 // A private field's *symbol* is created here, at the member, and stored
6874 // in its binding: the field's property is keyed by it, so it has to exist
6875 // before any initialiser runs, and a fresh one per class body is what
6876 // makes two classes that both write `#x` independent.
6877 //
6878 // A computed key is evaluated once, here, and `to_propkey`'d once — a key
6879 // whose `toString` has a side effect must not run again per instance.
6880 let key = match field_key {
6881 PropName::Private(ident) => {
6882 let binding = format!("#{}", ident.name);
6883 if *is_static {
6884 self.emit(Opcode::Swap, &[]);
6885 }
6886 self.emit(
6887 Opcode::PrivateSymbol,
6888 &[Op::Atom(Atom::from_text(&binding))],
6889 );
6890 self.emit_var(VarAction::PutInit, &binding);
6891 if *is_static {
6892 self.emit(Opcode::Swap, &[]);
6893 }
6894 FieldKey::Private(binding)
6895 }
6896 PropName::Computed(expression) => {
6897 let binding = plan
6898 .computed
6899 .get(&index)
6900 .cloned()
6901 .expect("every computed key got a binding");
6902 if *is_static {
6903 self.emit(Opcode::Swap, &[]);
6904 }
6905 self.expr(expression)?;
6906 self.emit(Opcode::ToPropkey, &[]);
6907 self.emit_var(VarAction::PutInit, &binding);
6908 if *is_static {
6909 self.emit(Opcode::Swap, &[]);
6910 }
6911 FieldKey::Computed(binding)
6912 }
6913 PropName::Literal(literal) => FieldKey::Literal(literal),
6914 };
6915 if *is_static {
6916 static_items.push(StaticInitItem::Field(key, value.as_deref()));
6917 } else {
6918 instance_fields.push(StaticInitItem::Field(key, value.as_deref()));
6919 }
6920 }
6921 ClassElement::StaticBlock {
6922 body, body_start, ..
6923 } => static_items.push(StaticInitItem::Block {
6924 body,
6925 body_start: *body_start,
6926 }),
6927 }
6928 }
6929
6930 // Now that every member has its slot, the constructor can have the next one and the
6931 // `fclosure` above can name it.
6932 let ctor_index = self.push_constant(Constant::Function(Box::new(ctor)));
6933 match self.state().insns.get_mut(ctor_insn) {
6934 Some(Insn::Fixed { operands, .. }) => {
6935 operands[0] = Op::Const(ctor_index);
6936 }
6937 // `emit` always pushes exactly one `Insn::Fixed`, so this cannot happen; failing
6938 // loudly beats emitting a `fclosure` of slot 4294967295.
6939 _ => {
6940 return Err(SyntaxError::new(
6941 "the class constructor's fclosure went missing",
6942 class.span,
6943 ));
6944 }
6945 }
6946
6947 // The instance brand: a symbol created once on the prototype, which every instance
6948 // then carries. `add_brand(obj, home)` reads `home` for the symbol (creating it the
6949 // first time) and adds it to `obj` — here `obj` is `null`, so only the prototype's
6950 // copy is created. The prototype is on top of the stack at this point.
6951 if plan.instance_brand {
6952 self.emit(Opcode::Dup, &[]);
6953 self.emit(Opcode::Null, &[]);
6954 self.emit(Opcode::Swap, &[]);
6955 self.emit(Opcode::AddBrand, &[]);
6956 }
6957
6958 // `<class_fields_init>` holds the instance initialiser, or `undefined` when the
6959 // class has no instance fields. The constructor calls it only when it is defined.
6960 //
6961 // A class with private *methods* but no fields still needs one, because adding the
6962 // brand to each new instance is the initialiser's job.
6963 if instance_fields.is_empty() && !plan.instance_brand {
6964 self.emit(Opcode::Undefined, &[]);
6965 } else {
6966 let initialiser = self.compile_field_initialiser(
6967 &instance_fields,
6968 class.span,
6969 true,
6970 plan.instance_brand,
6971 )?;
6972 let index = self.push_constant(Constant::Function(Box::new(initialiser)));
6973 self.emit(Opcode::Fclosure, &[Op::Const(index)]);
6974 // `set_home_object` reads `obj func`, so the prototype stays where it is.
6975 self.emit(Opcode::SetHomeObject, &[]);
6976 }
6977 self.emit_var(VarAction::PutInit, "<class_fields_init>");
6978 // The prototype has done its job: every instance member is defined on it. What
6979 // is left under it is the constructor.
6980 self.emit(Opcode::Drop, &[]);
6981
6982 // The static brand, for `static #m() {}`: same opcode, but the home object is the
6983 // constructor itself, so the symbol lands on the class and the class carries it.
6984 if plan.static_brand {
6985 self.emit(Opcode::Dup, &[]);
6986 self.emit(Opcode::Dup, &[]);
6987 self.emit(Opcode::AddBrand, &[]);
6988 }
6989
6990 // The class binding is initialised *before* static fields run, so a static field
6991 // can refer to the class by name (`static y = S.x`).
6992 // `set_loc` leaves the constructor on the stack, which is what the static field
6993 // call and the outer store both consume.
6994 //
6995 // Only when there *is* such a binding: an anonymous class expression declares no
6996 // class-scope name, and asking for one by the empty string resolved to nothing —
6997 // which made `var x = class {}` assign `undefined` and put a bogus global store in
6998 // the instruction stream.
6999 if let Some(name) = &name {
7000 self.emit_var(VarAction::SetInit, name);
7001 }
7002 if !static_items.is_empty() {
7003 // The static half has no brand prologue of its own: the constructor got its
7004 // brand above, before this runs.
7005 let initialiser =
7006 self.compile_field_initialiser(&static_items, class.span, false, false)?;
7007 let index = self.push_constant(Constant::Function(Box::new(initialiser)));
7008 self.emit(Opcode::Dup, &[]);
7009 self.emit(Opcode::Fclosure, &[Op::Const(index)]);
7010 self.emit(Opcode::SetHomeObject, &[]);
7011 self.emit(Opcode::CallMethod, &[Op::Int(0)]);
7012 self.emit(Opcode::Drop, &[]);
7013 }
7014 // The body is over, and with it this class's private names.
7015 let _ = self.private_scopes.pop();
7016 self.emit_scope_leave(key);
7017 self.state().current_block = parent_block;
7018 if keep {
7019 // A class *expression* is its own value; the class-scope binding was only
7020 // ever an alias for it.
7021 return Ok(());
7022 }
7023 // A declaration stores into the binding the enclosing statement declared.
7024 self.emit_var(VarAction::PutInit, &name.unwrap_or_default());
7025 Ok(())
7026 }
7027
7028 fn push_this(&mut self) {
7029 self.emit(Opcode::PushThis, &[]);
7030 }
7031
7032 /// `this`, which an arrow does not have of its own.
7033 ///
7034 /// The reference gives the enclosing function a local named `this`, initialised from
7035 /// `push_this` at the top of its body, and the arrow then reads it as a captured
7036 /// variable. That is why `(() => this)()` inside `f` yields `f`'s receiver even when
7037 /// the arrow is called with none.
7038 fn this_expression(&mut self) {
7039 // In a class constructor `this` is a local: a derived constructor only gets one
7040 // when `super()` returns, and reading the raw receiver would give the *outer*
7041 // one instead.
7042 if self.cur().ctor_kind != CtorKind::None {
7043 self.emit_var(VarAction::Get, "this");
7044 return;
7045 }
7046 if !self.cur().is_arrow {
7047 self.push_this();
7048 return;
7049 }
7050 // An arrow at the **top level** of a script or module has no enclosing function,
7051 // but it still inherits `this` — the script's or module's own. Falling through to
7052 // `emit_var(Get, "this")` without a target made that a *global* lookup, so
7053 // `var f = () => typeof this` at top level reported
7054 // `ReferenceError: 'this' is not defined` instead of `"object"`
7055 // (`Set/prototype/forEach/this-arg-explicit-cannot-override-lexical-this-arrow`
7056 // is the test262 case that reaches it, through a native `forEach`).
7057 //
7058 // The script state is the bottom of the stack, so it is the fallback target. Its
7059 // own `provide_this_local` then prepends the `push_this` the arrow reads.
7060 let target = self.enclosing_function().unwrap_or(0);
7061 self.state_at(target).needs_this_local = true;
7062 self.declare_at(target, "this");
7063 self.emit_var(VarAction::Get, "this");
7064 }
7065
7066 /// `new.target`, which an arrow likewise does not own.
7067 fn new_target_expression(&mut self) {
7068 if !self.cur().is_arrow {
7069 self.emit(Opcode::SpecialObject, &[Op::Int(3)]);
7070 return;
7071 }
7072 if let Some(target) = self.enclosing_function() {
7073 self.state_at(target).needs_new_target_local = true;
7074 self.declare_at(target, NEW_TARGET);
7075 }
7076 self.emit_var(VarAction::Get, NEW_TARGET);
7077 }
7078
7079 /// `this.active_func`: the function `super()` resolves against.
7080 ///
7081 /// In a constructor or a method that is the function being run, so the special object
7082 /// answers directly. In an arrow it is whatever the enclosing function saw, read out of
7083 /// a closure variable — see [`FnState::needs_active_func_local`].
7084 fn active_func_expression(&mut self) {
7085 if !self.cur().is_arrow {
7086 self.emit(Opcode::SpecialObject, &[Op::Int(2)]);
7087 return;
7088 }
7089 if let Some(target) = self.enclosing_function() {
7090 self.state_at(target).needs_active_func_local = true;
7091 self.declare_at(target, ACTIVE_FUNC);
7092 }
7093 self.emit_var(VarAction::Get, ACTIVE_FUNC);
7094 }
7095
7096 /// Give the function a local `<active_func>`, for an arrow inside it to capture.
7097 fn provide_active_func_local(&mut self) {
7098 let current = self.stack.len() - 1;
7099 if !self.stack[current].needs_active_func_local {
7100 return;
7101 }
7102 if !self.stack[current]
7103 .vars
7104 .iter()
7105 .any(|var| var.name == ACTIVE_FUNC)
7106 {
7107 self.declare_hidden_local(ACTIVE_FUNC, VarKind::Normal);
7108 }
7109 self.prepend_initialiser(
7110 ACTIVE_FUNC,
7111 Insn::Fixed {
7112 op: Opcode::SpecialObject,
7113 operands: vec![Op::Int(2)],
7114 },
7115 );
7116 }
7117
7118 /// Give the function a local `new.target`, for an arrow inside it to capture.
7119 fn provide_new_target_local(&mut self) {
7120 let current = self.stack.len() - 1;
7121 if !self.stack[current].needs_new_target_local {
7122 return;
7123 }
7124 if !self.stack[current]
7125 .vars
7126 .iter()
7127 .any(|var| var.name == NEW_TARGET)
7128 {
7129 self.declare_hidden_local(NEW_TARGET, VarKind::Normal);
7130 }
7131 self.prepend_initialiser(
7132 NEW_TARGET,
7133 Insn::Fixed {
7134 op: Opcode::SpecialObject,
7135 operands: vec![Op::Int(3)],
7136 },
7137 );
7138 }
7139
7140 /// `arguments` reached from an arrow, which likewise belongs to the enclosing
7141 /// function.
7142 fn ensure_enclosing_arguments(&mut self) {
7143 // An arrow created in a parameter list needs the *parameter* scope's
7144 // `arguments`, not the body's: the two are separate bindings and the arrow was
7145 // born before the body existed.
7146 let from_params = self.cur().created_in_params;
7147 if let Some(target) = self.enclosing_function() {
7148 self.state_at(target).needs_arguments_local = true;
7149 if from_params {
7150 self.state_at(target).needs_param_arguments = true;
7151 // Declare it now, not at the enclosing function's `finish_current`: the
7152 // arrow resolves its own `arguments` before that runs, and a binding that
7153 // does not exist yet resolves as a global.
7154 declare_param_var_at(&mut self.stack[target], "arguments");
7155 }
7156 self.declare_at(target, "arguments");
7157 }
7158 }
7159
7160 /// The innermost enclosing frame that is a real function — an arrow inherits from it
7161 /// rather than starting a scope of its own.
7162 /// The innermost enclosing frame that can own a lexical binding an arrow reads —
7163 /// a real function, or a **script** top level.
7164 ///
7165 /// A script is in the list because an `eval` body is compiled as one and an arrow
7166 /// written in eval'd code still has to find the caller's `new.target`, `this.active_func`
7167 /// and `[[HomeObject]]`. Excluding it made `eval("() => new.target")` compile the read as
7168 /// a *global* lookup of `new.target`, which no frame provides — so it raised
7169 /// `ReferenceError` instead of answering the caller's value
7170 /// (`arrow-body-direct-eval-err-contains-newtarget`).
7171 fn enclosing_function(&self) -> Option<usize> {
7172 (0..self.stack.len())
7173 .rev()
7174 .find(|index| !self.stack[*index].is_arrow)
7175 }
7176
7177 fn state_at(&mut self, index: usize) -> &mut FnState {
7178 &mut self.stack[index]
7179 }
7180
7181 /// Declare a `var` binding directly in a specific frame.
7182 fn declare_at(&mut self, index: usize, name: &str) {
7183 let state = &mut self.stack[index];
7184 if state.vars.iter().any(|var| var.name == name) {
7185 return;
7186 }
7187 state.var_block.push(FUNCTION_SCOPE);
7188 state.vars.push(VarDef::var(name));
7189 }
7190
7191 /// Prepend `<value-producing insn>; put <name>` to the body, which is how a binding
7192 /// the reference calls a `special_object` gets initialised on entry.
7193 fn prepend_initialiser(&mut self, name: &str, producer: Insn) {
7194 let current = self.stack.len() - 1;
7195 let init = [
7196 producer,
7197 Insn::Var {
7198 action: VarAction::Put,
7199 name: name.to_string(),
7200 block: 0,
7201 // A prologue initialiser runs before the body proper, but it is body
7202 // code: `this` and `arguments` are provided for it, not by it.
7203 in_params: false,
7204 },
7205 ];
7206 let inserted = init.len();
7207 for (index, instruction) in init.into_iter().enumerate() {
7208 self.stack[current].insns.insert(index, instruction);
7209 }
7210 for placed in self.stack[current].labels.iter_mut().flatten() {
7211 *placed += inserted;
7212 }
7213 self.stack[current].label_since_insn = true;
7214 }
7215
7216 fn push_constant(&mut self, constant: Constant) -> u32 {
7217 let state = self.state();
7218 let index = state.cpool.len() as u32;
7219 state.cpool.push(constant);
7220 index
7221 }
7222
7223 /// Compile `a && b`, `a || b`, `a ?? b`.
7224 ///
7225 /// A run of the *same* operator shares one end label, so `a || b || c` tests
7226 /// `a` once and jumps past everything when it is truthy, instead of falling
7227 /// into `b`'s test. The parser builds such a run left-associated —
7228 /// `((a || b) || c)` — so the operands are collected off the left spine.
7229 ///
7230 /// A *different* operator starts its own chain: `(a || b) && c` keeps the inner
7231 /// `||`'s label, because the inner chain really does end before `&&` begins.
7232 fn logical(&mut self, op: LogicalOp, left: &Expr, right: &Expr) -> Result<(), SyntaxError> {
7233 let mut operands = Vec::new();
7234 collect_same_operator(op, left, &mut operands);
7235 operands.push(right);
7236
7237 let end = self.new_label();
7238 // Every operand but the last decides whether the chain stops here.
7239 let last = operands.pop().expect("the right operand is always present");
7240 for operand in operands {
7241 self.expr(operand)?;
7242 self.emit(Opcode::Dup, &[]);
7243 match op {
7244 LogicalOp::And => self.emit_jump(Opcode::IfFalse, end, &[]),
7245 LogicalOp::Or => self.emit_jump(Opcode::IfTrue, end, &[]),
7246 // `??` cannot reuse the truthiness jumps: `0 ?? b` is `0` while
7247 // `0 || b` is `b`. The dedicated test keeps the value unless it is
7248 // null-ish, so the jump is taken on `false`.
7249 LogicalOp::Coalesce => {
7250 self.emit(Opcode::IsUndefinedOrNull, &[]);
7251 self.emit_jump(Opcode::IfFalse, end, &[]);
7252 }
7253 }
7254 self.emit(Opcode::Drop, &[]);
7255 }
7256 self.expr(last)?;
7257 self.place_label(end);
7258 Ok(())
7259 }
7260
7261 fn unary(&mut self, op: UnaryOp, argument: &Expr) -> Result<(), SyntaxError> {
7262 match op {
7263 UnaryOp::Typeof => {
7264 // `typeof x` must not throw on an undeclared name.
7265 if let ExprKind::Ident(name) = &argument.kind {
7266 self.emit_var(VarAction::GetUndef, &name.name);
7267 } else {
7268 self.expr(argument)?;
7269 }
7270 self.emit(Opcode::Typeof, &[]);
7271 }
7272 UnaryOp::Delete => {
7273 // `delete obj.prop` really deletes, and answers whether it could.
7274 // Deleting a *binding* is always `false`: a local, an argument and a
7275 // declared global are all non-configurable, which the reference encodes
7276 // as a constant `push_false` rather than a runtime check. Only a
7277 // property access has anything to do at run time.
7278 // `delete super.x` is not a delete at all: the spec refuses it, and the
7279 // reference encodes the refusal as a `throw_error`. The receiver and the
7280 // key are still evaluated first, which is what keeps the evaluation order
7281 // of the operand intact.
7282 // `delete z?.b.c` answers `true` when the chain short-circuits: there is
7283 // nothing to delete, and a failed delete is not the same as a skipped
7284 // one. The reference emits the guards so they land on a `drop; push_true`
7285 // tail, which is what this reproduces.
7286 if let ExprKind::OptionalChain(inner) = &argument.unparen().kind
7287 && let ExprKind::Member {
7288 object, property, ..
7289 } = &inner.unparen().kind
7290 {
7291 let end = self.new_label();
7292 let done = self.new_label();
7293 self.chain_link(object, end)?;
7294 match property {
7295 MemberProp::Ident(name) => self.emit(
7296 Opcode::PushAtomValue,
7297 &[Op::Atom(Atom::from_text(&name.name))],
7298 ),
7299 MemberProp::Computed(index) => self.expr(index)?,
7300 MemberProp::Private(_) => {
7301 return Err(SyntaxError::new(
7302 "deleting a private field is not allowed",
7303 argument.span,
7304 ));
7305 }
7306 }
7307 self.emit(Opcode::Delete, &[]);
7308 self.emit_jump(Opcode::Goto, done, &[]);
7309 self.place_label(end);
7310 self.emit(Opcode::Drop, &[]);
7311 self.emit(Opcode::PushTrue, &[]);
7312 self.place_label(done);
7313 return Ok(());
7314 }
7315 if let ExprKind::Member { object, .. } = &argument.unparen().kind
7316 && matches!(object.unparen().kind, ExprKind::SuperProp)
7317 {
7318 self.super_base();
7319 self.emit(Opcode::ThrowError, &[Op::Atom(Atom::Null), Op::Int(3)]);
7320 return Ok(());
7321 }
7322 // Parentheses are transparent to `delete`: `(x)` is still a Reference to
7323 // the binding `x`, so `delete (x)` answers `false` exactly as `delete x`
7324 // does, and `delete (a().b)` still evaluates `a()`. Matching on the
7325 // unparenthesised operand is what keeps both — matching on `argument.kind`
7326 // sent every parenthesised form to the "not a Reference" arm, which cost
7327 // `delete(__variable) === false` in test262's `S12.2_A2`.
7328 match &argument.unparen().kind {
7329 ExprKind::Member {
7330 object, property, ..
7331 } => {
7332 self.expr(object)?;
7333 match property {
7334 MemberProp::Ident(name) => {
7335 self.emit(
7336 Opcode::PushAtomValue,
7337 &[Op::Atom(Atom::from_text(&name.name))],
7338 );
7339 }
7340 MemberProp::Computed(index) => self.expr(index)?,
7341 MemberProp::Private(_) => {
7342 return Err(SyntaxError::new(
7343 "deleting a private field is not allowed",
7344 argument.span,
7345 ));
7346 }
7347 }
7348 self.emit(Opcode::Delete, &[]);
7349 }
7350 ExprKind::Ident(name) => {
7351 self.delete_ident(&name.name);
7352 }
7353 // §13.5.1.2 step 2: an operand that is **not** a Reference Record
7354 // answers `true` — there is nothing to delete, and "nothing needed
7355 // deleting" is success. `delete !0`, `delete (1 + 2)` and
7356 // `delete typeof 0` are all `true`, and the operand is still evaluated
7357 // (which is why it is `Drop`ed rather than skipped:
7358 // `delete f()` must call `f`).
7359 //
7360 // Answering `false` here is the C reference's old behaviour and was
7361 // wrong in an observable way: test262's
7362 // `dynamic-import/assignment-expression/logical-and-expr` builds a
7363 // specifier out of `delete void typeof +-~! 0 && b`, and a `false` left
7364 // half turned the whole `&&` into `false`, so the import asked for a
7365 // module named "false".
7366 _ => {
7367 self.expr(argument)?;
7368 self.emit(Opcode::Drop, &[]);
7369 self.emit(Opcode::PushTrue, &[]);
7370 }
7371 }
7372 }
7373 UnaryOp::Void => {
7374 self.expr(argument)?;
7375 self.emit(Opcode::Drop, &[]);
7376 self.emit(Opcode::Undefined, &[]);
7377 }
7378 UnaryOp::Minus => {
7379 self.expr(argument)?;
7380 self.emit(Opcode::Neg, &[]);
7381 }
7382 UnaryOp::Plus => {
7383 self.expr(argument)?;
7384 self.emit(Opcode::Plus, &[]);
7385 }
7386 UnaryOp::Not => {
7387 self.expr(argument)?;
7388 self.emit(Opcode::Lnot, &[]);
7389 }
7390 UnaryOp::BitNot => {
7391 self.expr(argument)?;
7392 self.emit(Opcode::Not, &[]);
7393 }
7394 }
7395 Ok(())
7396 }
7397
7398 /// A store to `name` while a `with` may capture it.
7399 ///
7400 /// The reference is resolved **first**, before the right-hand side runs. That order is
7401 /// the whole point: in `x = (delete env.x, 0)` the resolution has already decided that
7402 /// `x` is `env`'s property, so `PutValue` then finds it gone and strict code throws
7403 /// `ReferenceError` (`set-mutable-binding-binding-deleted-with-typed-array-in-
7404 /// proto-chain-strict-mode`). The ordinary path evaluates the right-hand side before
7405 /// the guard runs, which put the guard *after* the mutation.
7406 ///
7407 /// Shapes mirror [`Compiler::assign_ident_plain`] and the member arms of
7408 /// [`Compiler::assign`], with `dup; with_get_var` in place of `get_field2` and
7409 /// `with_put_var` in place of `put_field` — the same stack effects, but each half also
7410 /// asks the `HasProperty` that `GetBindingValue`/`SetMutableBinding` require.
7411 fn with_assign(
7412 &mut self,
7413 with_local: &str,
7414 name: &Ident,
7415 op: AssignOp,
7416 value: &Expr,
7417 keep: bool,
7418 ) -> Result<(), SyntaxError> {
7419 let atom = Atom::from_text(&name.name);
7420 self.state().cur_pos = Some(name.span.start);
7421 match op {
7422 AssignOp::Assign => {
7423 self.expr(value)?;
7424 self.set_name_if_anonymous(value, &Wtf8::new(&name.name));
7425 if keep {
7426 self.emit(Opcode::Dup, &[]);
7427 }
7428 self.state().no_value = !keep;
7429 self.emit_var(VarAction::Get, with_local);
7430 self.emit(Opcode::Swap, &[]);
7431 self.emit(Opcode::WithPutVar, &[Op::Atom(atom)]);
7432 }
7433 AssignOp::And | AssignOp::Or | AssignOp::Coalesce => {
7434 let (keep_label, end) = (self.new_label(), self.new_label());
7435 self.emit_var(VarAction::Get, with_local);
7436 self.emit(Opcode::Dup, &[]);
7437 self.emit(Opcode::WithGetVar, &[Op::Atom(atom.clone())]);
7438 // `obj value` — the object stays underneath for the store.
7439 self.emit(Opcode::Dup, &[]);
7440 self.emit_logical_test(op);
7441 self.emit_jump(logical_jump(op), keep_label, &[]);
7442 self.emit(Opcode::Drop, &[]);
7443 self.expr(value)?;
7444 self.emit(Opcode::Insert2, &[]);
7445 self.emit(Opcode::WithPutVar, &[Op::Atom(atom)]);
7446 self.emit_jump(Opcode::Goto, end, &[]);
7447 self.place_label(keep_label);
7448 self.emit(Opcode::Nip, &[]);
7449 self.place_label(end);
7450 }
7451 _ => {
7452 self.emit_var(VarAction::Get, with_local);
7453 self.emit(Opcode::Dup, &[]);
7454 self.emit(Opcode::WithGetVar, &[Op::Atom(atom.clone())]);
7455 self.expr(value)?;
7456 self.state().cur_pos = Some(name.span.start);
7457 self.emit(compound_opcode(op), &[]);
7458 self.state().no_value = !keep;
7459 if keep {
7460 self.emit(Opcode::Insert2, &[]);
7461 }
7462 self.emit(Opcode::WithPutVar, &[Op::Atom(atom)]);
7463 }
7464 }
7465 Ok(())
7466 }
7467
7468 /// `x++` / `++x` while a `with` may capture `x`, with one resolution for both halves.
7469 fn with_update(
7470 &mut self,
7471 with_local: &str,
7472 name: &Ident,
7473 op: UpdateOp,
7474 prefix: bool,
7475 ) -> Result<(), SyntaxError> {
7476 let instruction = match (op, prefix) {
7477 (UpdateOp::Increment, true) => Opcode::Inc,
7478 (UpdateOp::Increment, false) => Opcode::PostInc,
7479 (UpdateOp::Decrement, true) => Opcode::Dec,
7480 (UpdateOp::Decrement, false) => Opcode::PostDec,
7481 };
7482 let atom = Atom::from_text(&name.name);
7483 self.state().cur_pos = Some(name.span.start);
7484 self.emit_var(VarAction::Get, with_local);
7485 self.emit(Opcode::Dup, &[]);
7486 self.emit(Opcode::WithGetVar, &[Op::Atom(atom.clone())]);
7487 self.emit(instruction, &[]);
7488 self.emit(
7489 if prefix {
7490 Opcode::Insert2
7491 } else {
7492 Opcode::Perm3
7493 },
7494 &[],
7495 );
7496 self.emit(Opcode::WithPutVar, &[Op::Atom(atom)]);
7497 Ok(())
7498 }
7499
7500 /// A store to a plain identifier, with no `with` in the way.
7501 fn assign_ident_plain(
7502 &mut self,
7503 op: AssignOp,
7504 name: &Ident,
7505 value: &Expr,
7506 discard: bool,
7507 ) -> Result<(), SyntaxError> {
7508 // `discard` was taken by [`Compiler::expr`] for the expression the statement asked
7509 // about, so it is set only when this assignment *is* that expression.
7510 let keep = !discard;
7511 // A *simple* store is blamed on the identifier, not on the `=`: a
7512 // strict-mode `not_def = 1` raises when the name is written, which the
7513 // reference reports at the name's column. A compound store is blamed on
7514 // the operator instead (`a += poisoned` raises inside `ToPrimitive`,
7515 // which the reference reports at the `+=`), so only the simple case
7516 // moves the position.
7517 let saved = self.cur().cur_pos;
7518 let name_pos = Some(name.span.start);
7519 if matches!(op, AssignOp::Assign) {
7520 self.state().cur_pos = name_pos;
7521 }
7522 // A *compound* store reads the binding before it combines, and that read
7523 // is blamed on the identifier: `not_def += 2` fails while reading
7524 // `not_def`, so the position is the name's, not the `+=`'s. The
7525 // combination that follows is blamed on the operator, which is why
7526 // `cur_pos` is put back to the operator position before it is emitted.
7527 self.state().cur_pos = name_pos;
7528 // A direct `eval` in the right-hand side can declare a `var` with this name in the
7529 // *caller's* variable environment, and from then on the name means that binding.
7530 // §13.15.3 resolves the lvalue once, at step 1, and stores through it at step 7 —
7531 // so the binding has to be pinned before the right-hand side runs.
7532 // `compound-assignment/S11.13.2_A6.*` and `assignment/S11.13.1_A6_*` are entirely
7533 // about this. One `__proto__`-shaped corner costs a reference object; every other
7534 // assignment is byte-for-byte what it was.
7535 let pinned = self.cur().eval_can_declare;
7536 if pinned {
7537 self.emit_var(VarAction::MakeRef, &name.name);
7538 }
7539 match op {
7540 AssignOp::Assign => {
7541 self.expr(value)?;
7542 self.set_name_if_anonymous(value, &Wtf8::new(&name.name));
7543 if pinned {
7544 // `[ref, v] -> [v, ref, v] -> [v]`, the same `insert2` fold the
7545 // member stores use.
7546 if keep {
7547 self.emit(Opcode::Insert2, &[]);
7548 }
7549 self.emit(Opcode::PutRefValue, &[]);
7550 self.state().no_value = !keep;
7551 self.state().cur_pos = saved;
7552 return Ok(());
7553 }
7554 // A discarded store to a *slot* consumes its value, so no copy
7555 // is needed. A global store goes through `put_var`, which the
7556 // reference always pairs with a `dup` — matching it keeps the
7557 // bytecode identical. Getting this wrong is not only an extra
7558 // instruction: a stray copy gives the peephole a chance to fold
7559 // the store into an unrelated later read.
7560 let slot = self.is_slot(&name.name);
7561 if keep || !slot {
7562 self.emit(Opcode::Dup, &[]);
7563 }
7564 self.state().no_value = !keep && slot;
7565 self.emit_var(VarAction::Put, &name.name);
7566 }
7567 AssignOp::And | AssignOp::Or | AssignOp::Coalesce => {
7568 let end = self.new_label();
7569 // The pinned read leaves `[ref, v]`, so the branch that skips the store has
7570 // to `nip` the reference away; the branch that stores consumes it.
7571 self.emit_var(
7572 if pinned {
7573 VarAction::GetRef
7574 } else {
7575 VarAction::Get
7576 },
7577 &name.name,
7578 );
7579 self.state().cur_pos = saved;
7580 self.emit(Opcode::Dup, &[]);
7581 self.emit_logical_test(op);
7582 self.emit_jump(logical_jump(op), end, &[]);
7583 self.emit(Opcode::Drop, &[]);
7584 self.expr(value)?;
7585 // `x ||= function(){}` is a `NamedEvaluation` of the right-hand side, so the
7586 // function is named `x` — the same rule plain assignment follows
7587 // (`lgcl-*-namedevaluation-function`).
7588 self.set_name_if_anonymous(value, &Wtf8::new(&name.name));
7589 if pinned {
7590 self.emit(Opcode::Insert2, &[]);
7591 self.emit(Opcode::PutRefValue, &[]);
7592 } else {
7593 self.emit(Opcode::Dup, &[]);
7594 self.emit_var(VarAction::Put, &name.name);
7595 }
7596 self.place_label(end);
7597 if pinned {
7598 self.emit(Opcode::Nip, &[]);
7599 }
7600 }
7601 _ => {
7602 self.emit_var(
7603 if pinned {
7604 VarAction::GetRef
7605 } else {
7606 VarAction::Get
7607 },
7608 &name.name,
7609 );
7610 self.expr(value)?;
7611 self.state().cur_pos = saved;
7612 self.emit(compound_opcode(op), &[]);
7613 if pinned {
7614 self.emit(Opcode::Insert2, &[]);
7615 self.emit(Opcode::PutRefValue, &[]);
7616 } else {
7617 self.emit(Opcode::Dup, &[]);
7618 self.emit_var(VarAction::Put, &name.name);
7619 }
7620 }
7621 }
7622 self.state().cur_pos = saved;
7623 Ok(())
7624 }
7625
7626 /// Compile an assignment.
7627 ///
7628 /// Three operator families, three shapes:
7629 ///
7630 /// * **plain** `=` — evaluate, store. A member needs `insert2`/`insert3` when
7631 /// the value is kept, because `put_field`/`put_array_el` consume both the
7632 /// object and the value: `insert2` is `obj a -> a obj a`, so the store sees
7633 /// the pair it wants and leaves a copy on top.
7634 /// * **compound** `+=` … — read the place, apply the operator, store. A member
7635 /// reads through `get_field2`/`get_array_el3`, which leave the object (and
7636 /// index) underneath the value precisely so the store can follow.
7637 /// * **logical** `||=`, `&&=`, `??=` — read, test, and only then evaluate the
7638 /// right-hand side. The test *keeps* the current value and skips the store
7639 /// entirely, which is the whole point: `a ||= b` must not evaluate `b` when
7640 /// `a` is already truthy.
7641 fn assign(
7642 &mut self,
7643 op: AssignOp,
7644 target: &Pattern,
7645 value: &Expr,
7646 discard: bool,
7647 ) -> Result<(), SyntaxError> {
7648 // `discard` was taken by [`Compiler::expr`] for the expression the statement asked
7649 // about, so it is set only when this assignment *is* that expression.
7650 let keep = !discard;
7651 match &target.kind {
7652 PatternKind::Ident(name) => {
7653 // Any store to a name a `with` may capture resolves the reference first and
7654 // keeps that resolution for both halves — see [`Compiler::with_assign`].
7655 // Plain `=` needs it just as much as `+=`: `x = (delete env.x, 0)` must
7656 // resolve `x` before the right-hand side deletes it.
7657 let plain_name = name.name.clone();
7658 if !self.visible_with_names(&plain_name).is_empty() {
7659 return self.with_reference(
7660 &plain_name,
7661 &mut |compiler, with_local| {
7662 compiler.with_assign(with_local, name, op, value, !discard)
7663 },
7664 &mut |compiler| compiler.assign_ident_plain(op, name, value, discard),
7665 );
7666 }
7667 self.assign_ident_plain(op, name, value, discard)
7668 }
7669 PatternKind::Member(member) => {
7670 // `super.x = v` is not a store through a value: it starts at the home
7671 // object's prototype but writes to `this`, so it goes through
7672 // `put_super_value` rather than `put_field`. The receiver, prototype, key
7673 // and value are handed over together.
7674 if matches!(member.object.unparen().kind, ExprKind::SuperProp) {
7675 return self.assign_super(member, op, value);
7676 }
7677 // A store is blamed on the selector punctuator (`.` or `[`), the same
7678 // token a load is blamed on — the reference records `put_field obj.a`
7679 // at the `.`, so a setter that throws reports that column and not the
7680 // `=` of the assignment it sits in. The inner expressions restore their
7681 // own positions, so the selector's sticks for the store instructions.
7682 let saved = self.cur().cur_pos;
7683 self.state().cur_pos = member.op_pos.or(Some(member.span.start));
7684 self.expr(&member.object)?;
7685 match &member.property {
7686 MemberProp::Ident(property) => {
7687 let atom = Atom::from_text(&property.name);
7688 match op {
7689 AssignOp::Assign => {
7690 self.expr(value)?;
7691 // `put_field` consumes the object and the value, so
7692 // without `insert2` nothing is left over for the
7693 // statement to drop.
7694 self.state().no_value = !keep;
7695 if keep {
7696 self.emit(Opcode::Insert2, &[]);
7697 }
7698 self.emit(Opcode::PutField, &[Op::Atom(atom.clone())]);
7699 }
7700 AssignOp::And | AssignOp::Or | AssignOp::Coalesce => {
7701 // `get_field2` leaves the object under the value, so
7702 // the keep path has an object to dispose of. The store
7703 // path must jump *over* that cleanup: falling into it
7704 // would `nip` a stack that only holds the value.
7705 let (keep_label, end) = (self.new_label(), self.new_label());
7706 self.emit(Opcode::GetField2, &[Op::Atom(atom.clone())]);
7707 self.emit(Opcode::Dup, &[]);
7708 self.emit_logical_test(op);
7709 self.emit_jump(logical_jump(op), keep_label, &[]);
7710 self.emit(Opcode::Drop, &[]);
7711 self.expr(value)?;
7712 self.emit(Opcode::Insert2, &[]);
7713 self.emit(Opcode::PutField, &[Op::Atom(atom.clone())]);
7714 self.emit_jump(Opcode::Goto, end, &[]);
7715 self.place_label(keep_label);
7716 self.emit(Opcode::Nip, &[]);
7717 self.place_label(end);
7718 }
7719 _ => {
7720 self.emit(Opcode::GetField2, &[Op::Atom(atom.clone())]);
7721 self.expr(value)?;
7722 self.emit(compound_opcode(op), &[]);
7723 self.state().no_value = !keep;
7724 if keep {
7725 self.emit(Opcode::Insert2, &[]);
7726 }
7727 self.emit(Opcode::PutField, &[Op::Atom(atom.clone())]);
7728 }
7729 }
7730 }
7731 MemberProp::Computed(index) => {
7732 self.expr(index)?;
7733 match op {
7734 AssignOp::Assign => {
7735 self.expr(value)?;
7736 self.state().no_value = !keep;
7737 if keep {
7738 self.emit(Opcode::Insert3, &[]);
7739 }
7740 self.emit(Opcode::PutArrayEl, &[]);
7741 }
7742 AssignOp::And | AssignOp::Or | AssignOp::Coalesce => {
7743 let (keep_label, end) = (self.new_label(), self.new_label());
7744 self.emit(Opcode::GetArrayEl3, &[]);
7745 self.emit(Opcode::Dup, &[]);
7746 self.emit_logical_test(op);
7747 self.emit_jump(logical_jump(op), keep_label, &[]);
7748 self.emit(Opcode::Drop, &[]);
7749 self.expr(value)?;
7750 self.emit(Opcode::Insert3, &[]);
7751 self.emit(Opcode::PutArrayEl, &[]);
7752 self.emit_jump(Opcode::Goto, end, &[]);
7753 self.place_label(keep_label);
7754 // Both the object and the index are left over.
7755 self.emit(Opcode::Nip, &[]);
7756 self.emit(Opcode::Nip, &[]);
7757 self.place_label(end);
7758 }
7759 _ => {
7760 self.emit(Opcode::GetArrayEl3, &[]);
7761 self.expr(value)?;
7762 self.emit(compound_opcode(op), &[]);
7763 self.state().no_value = !keep;
7764 if keep {
7765 self.emit(Opcode::Insert3, &[]);
7766 }
7767 self.emit(Opcode::PutArrayEl, &[]);
7768 }
7769 }
7770 }
7771 MemberProp::Private(name) => {
7772 // `obj value` is on the stack, and every private store wants exactly
7773 // that. A top-level private name cannot be assigned (the parser rejects
7774 // `#x = 1`), so the only way here is `this.#x = …` inside the class.
7775 //
7776 // The reference emits `insert2` whether or not the value is wanted,
7777 // so this does too: the copy left behind is the assignment expression's
7778 // value, and a discarded one is simply never read.
7779 let binding = format!("#{}", name.name);
7780 let (kind, setter) = self.private_use(&binding, member.span)?;
7781 match op {
7782 AssignOp::Assign => {
7783 self.expr(value)?;
7784 if keep {
7785 self.emit(Opcode::Insert2, &[]);
7786 }
7787 self.private_store(&binding, kind, setter.as_deref())?;
7788 self.state().no_value = !keep;
7789 }
7790 AssignOp::And | AssignOp::Or | AssignOp::Coalesce => {
7791 let (keep_label, end) = (self.new_label(), self.new_label());
7792 self.emit(Opcode::Dup, &[]);
7793 self.private_load(&binding, kind, member.span)?;
7794 self.emit(Opcode::Dup, &[]);
7795 self.emit_logical_test(op);
7796 self.emit_jump(logical_jump(op), keep_label, &[]);
7797 self.emit(Opcode::Drop, &[]);
7798 self.expr(value)?;
7799 self.emit(Opcode::Insert2, &[]);
7800 self.private_store(&binding, kind, setter.as_deref())?;
7801 self.emit_jump(Opcode::Goto, end, &[]);
7802 self.place_label(keep_label);
7803 self.emit(Opcode::Nip, &[]);
7804 self.place_label(end);
7805 }
7806 _ => {
7807 self.emit(Opcode::Dup, &[]);
7808 self.private_load(&binding, kind, member.span)?;
7809 self.expr(value)?;
7810 self.emit(compound_opcode(op), &[]);
7811 self.emit(Opcode::Insert2, &[]);
7812 self.private_store(&binding, kind, setter.as_deref())?;
7813 }
7814 }
7815 }
7816 }
7817 self.state().cur_pos = saved;
7818 Ok(())
7819 }
7820 // A destructuring assignment: the right-hand side is the expression's own
7821 // value, so it is evaluated once and kept under the pattern's stores.
7822 PatternKind::Array { .. } | PatternKind::Object { .. } => {
7823 self.expr(value)?;
7824 if keep {
7825 self.emit(Opcode::Dup, &[]);
7826 }
7827 self.destructure(target, None)?;
7828 self.state().no_value = !keep;
7829 Ok(())
7830 }
7831 _ => Err(SyntaxError::new(
7832 "this assignment target is not supported by the compiler yet",
7833 target.span,
7834 )),
7835 }
7836 }
7837
7838 /// `super.x = v`, `super[k] = v`, and their compound and logical forms.
7839 ///
7840 /// The stack has to carry four values — receiver, prototype, key, value — because
7841 /// `put_super_value` takes them together; the receiver is what makes a setter found on
7842 /// the prototype run with `this`, and the key has to survive until the store, which is
7843 /// why a compound form converts it to a property key once and `dup3`s rather than
7844 /// evaluating it twice.
7845 fn assign_super(
7846 &mut self,
7847 member: &MemberPattern,
7848 op: AssignOp,
7849 value: &Expr,
7850 ) -> Result<(), SyntaxError> {
7851 let saved = self.cur().cur_pos;
7852 self.state().cur_pos = member.op_pos.or(Some(member.span.start));
7853 self.super_base();
7854 match &member.property {
7855 MemberProp::Ident(property) => self.emit(
7856 Opcode::PushAtomValue,
7857 &[Op::Atom(Atom::from_text(&property.name))],
7858 ),
7859 MemberProp::Computed(index) => self.expr(index)?,
7860 MemberProp::Private(_) => {
7861 return Err(SyntaxError::new(
7862 "private fields are not supported by the compiler yet",
7863 member.span,
7864 ));
7865 }
7866 }
7867 match op {
7868 AssignOp::Assign => {
7869 // The key is only converted once, by `put_super_value` itself, so a
7870 // computed key's `toString` runs exactly once.
7871 self.expr(value)?;
7872 self.emit(Opcode::Insert4, &[]);
7873 self.emit(Opcode::PutSuperValue, &[]);
7874 }
7875 AssignOp::And | AssignOp::Or | AssignOp::Coalesce => {
7876 let (keep_label, end) = (self.new_label(), self.new_label());
7877 self.emit(Opcode::ToPropkey, &[]);
7878 self.emit(Opcode::Dup3, &[]);
7879 self.emit(Opcode::GetSuperValue, &[]);
7880 self.emit(Opcode::Dup, &[]);
7881 self.emit_logical_test(op);
7882 self.emit_jump(logical_jump(op), keep_label, &[]);
7883 self.emit(Opcode::Drop, &[]);
7884 self.expr(value)?;
7885 self.emit(Opcode::Insert4, &[]);
7886 self.emit(Opcode::PutSuperValue, &[]);
7887 self.emit_jump(Opcode::Goto, end, &[]);
7888 self.place_label(keep_label);
7889 // The prototype and the key are still under the value that was read.
7890 self.emit(Opcode::Nip, &[]);
7891 self.emit(Opcode::Nip, &[]);
7892 self.emit(Opcode::Nip, &[]);
7893 self.place_label(end);
7894 }
7895 _ => {
7896 self.emit(Opcode::ToPropkey, &[]);
7897 self.emit(Opcode::Dup3, &[]);
7898 self.emit(Opcode::GetSuperValue, &[]);
7899 self.expr(value)?;
7900 self.emit(compound_opcode(op), &[]);
7901 self.emit(Opcode::Insert4, &[]);
7902 self.emit(Opcode::PutSuperValue, &[]);
7903 }
7904 }
7905 // No `drop` here for a discarded value. `insert4` keeps a copy of the value, so it
7906 // is still on the stack when the store finishes, and the expression statement is
7907 // what disposes of it — the same arrangement as `put_field`, reached from the other
7908 // side: there the store consumes the value (`no_value`), here it leaves it
7909 // (`keep` already false, so nothing tells the statement otherwise).
7910 self.state().cur_pos = saved;
7911 Ok(())
7912 }
7913
7914 /// The test a logical assignment applies to the current value.
7915 ///
7916 /// `??=` needs a real opcode rather than a truthiness jump: `0 ??= b` must
7917 /// assign, while `0 ||= b` must not.
7918 fn emit_logical_test(&mut self, op: AssignOp) {
7919 if op == AssignOp::Coalesce {
7920 self.emit(Opcode::IsUndefinedOrNull, &[]);
7921 }
7922 }
7923
7924 /// The private name `#name` this use site resolves against.
7925 ///
7926 /// The parser has already rejected a name no enclosing class declares, so a miss here
7927 /// means the compiler lost track of a class scope — which is worth a real error rather
7928 /// than an `unwrap`.
7929 fn private_use(
7930 &self,
7931 binding: &str,
7932 span: Span,
7933 ) -> Result<(PrivateKind, Option<String>), SyntaxError> {
7934 ClassPlan::find(self, binding)
7935 .map(|use_| (use_.kind, use_.setter.clone()))
7936 .ok_or_else(|| {
7937 SyntaxError::new(
7938 format!("the private name '{binding}' is out of scope here"),
7939 span,
7940 )
7941 })
7942 }
7943
7944 /// `obj.#name` as a value: `obj` is on the stack, the value replaces it.
7945 ///
7946 /// The three readable kinds take three different instructions, because a private name
7947 /// holds three different things — a symbol, a method function, a getter function — and
7948 /// only the first one is a property read at all.
7949 fn private_load(
7950 &mut self,
7951 binding: &str,
7952 kind: PrivateKind,
7953 span: Span,
7954 ) -> Result<(), SyntaxError> {
7955 match kind {
7956 PrivateKind::Field => {
7957 self.emit_var(VarAction::Get, binding);
7958 self.emit(Opcode::GetPrivateField, &[]);
7959 }
7960 PrivateKind::Method => {
7961 self.emit_var(VarAction::Get, binding);
7962 self.emit(Opcode::CheckBrand, &[]);
7963 // `check_brand` reads `obj func` and leaves both; the method itself is what
7964 // `this.#m` evaluates to.
7965 self.emit(Opcode::Nip, &[]);
7966 }
7967 PrivateKind::Getter => {
7968 self.emit_var(VarAction::Get, binding);
7969 self.emit(Opcode::CheckBrand, &[]);
7970 self.emit(Opcode::CallMethod, &[Op::Int(0)]);
7971 }
7972 // `#a` is declared but never filled when only a setter exists, so reading it is
7973 // the same refusal as assigning to a `const`. The reference reports it with the
7974 // generic read-only wording and leaves the better message as a `XXX`.
7975 PrivateKind::Setter => self.emit(
7976 Opcode::ThrowError,
7977 &[Op::Atom(Atom::from_text(binding)), Op::Int(0)],
7978 ),
7979 }
7980 let _ = span;
7981 Ok(())
7982 }
7983
7984 /// `obj.#name(...)`: like [`Self::private_load`], but the receiver stays under the callee.
7985 fn private_callee(&mut self, binding: &str, kind: PrivateKind) -> Result<(), SyntaxError> {
7986 match kind {
7987 // A method *is* the callee, so only the check goes in between.
7988 PrivateKind::Method => {
7989 self.emit_var(VarAction::Get, binding);
7990 self.emit(Opcode::CheckBrand, &[]);
7991 }
7992 _ => self.private_load(binding, kind, Span::default())?,
7993 }
7994 Ok(())
7995 }
7996
7997 /// The store half of `obj.#name = value`, with `obj value` on the stack and nothing
7998 /// wanted back.
7999 ///
8000 /// A getter/setter pair is a *method call*, not a property store: the reference reads
8001 /// the setter out of its own binding and calls it with the receiver, which is why the
8002 /// three `rot`/`swap` instructions below are needed. `insert2` at the call site is what
8003 /// keeps the assignment's value for an expression context.
8004 fn private_store(
8005 &mut self,
8006 binding: &str,
8007 kind: PrivateKind,
8008 setter: Option<&str>,
8009 ) -> Result<(), SyntaxError> {
8010 match kind {
8011 PrivateKind::Field => {
8012 self.emit_var(VarAction::Get, binding);
8013 self.emit(Opcode::PutPrivateField, &[]);
8014 }
8015 PrivateKind::Method | PrivateKind::Getter | PrivateKind::Setter => match setter {
8016 Some(setter) => {
8017 self.emit_var(VarAction::Get, setter);
8018 // `obj func value` -> `value obj func` for the check, and back again for
8019 // the call, which wants `obj func arg`.
8020 self.emit(Opcode::Swap, &[]);
8021 self.emit(Opcode::Rot3r, &[]);
8022 self.emit(Opcode::CheckBrand, &[]);
8023 self.emit(Opcode::Rot3l, &[]);
8024 self.emit(Opcode::CallMethod, &[Op::Int(1)]);
8025 // The setter's return value is discarded; the assignment's own value is
8026 // whatever the caller left underneath.
8027 self.emit(Opcode::Drop, &[]);
8028 }
8029 None => self.emit(
8030 Opcode::ThrowError,
8031 &[Op::Atom(Atom::from_text(binding)), Op::Int(0)],
8032 ),
8033 },
8034 }
8035 Ok(())
8036 }
8037
8038 fn update(&mut self, op: UpdateOp, argument: &Expr, prefix: bool) -> Result<(), SyntaxError> {
8039 // `x++` inside a `with` is a read-modify-write of a *property*, so the object is
8040 // resolved once for both halves. See [`Compiler::with_reference`].
8041 let unparened = argument.unparen();
8042 if let ExprKind::Ident(ident) = &unparened.kind {
8043 let name = ident.name.clone();
8044 if !self.visible_with_names(&name).is_empty() {
8045 return self.with_reference(
8046 &name,
8047 &mut |compiler, with_local| compiler.with_update(with_local, ident, op, prefix),
8048 &mut |compiler| compiler.update_plain(op, unparened, prefix),
8049 );
8050 }
8051 }
8052 self.update_plain(op, argument, prefix)
8053 }
8054
8055 fn update_plain(
8056 &mut self,
8057 op: UpdateOp,
8058 argument: &Expr,
8059 prefix: bool,
8060 ) -> Result<(), SyntaxError> {
8061 let instruction = match (op, prefix) {
8062 (UpdateOp::Increment, true) => Opcode::Inc,
8063 (UpdateOp::Increment, false) => Opcode::PostInc,
8064 (UpdateOp::Decrement, true) => Opcode::Dec,
8065 (UpdateOp::Decrement, false) => Opcode::PostDec,
8066 };
8067 // `(y)++` and `((o.x))++` are the same updates as the unparenthesised forms: §13.4
8068 // evaluates the operand as a `LeftHandSideExpression` and the parentheses around a
8069 // reference change nothing — they do not copy the value. Reading `argument.kind`
8070 // directly therefore rejected every parenthesised target with "increment of a
8071 // non-variable", which is not a thing the language has (`target-cover-id`).
8072 let argument = argument.unparen();
8073 if let ExprKind::Member {
8074 object,
8075 property,
8076 optional: _,
8077 } = &argument.kind
8078 {
8079 // `o.x++` needs the receiver twice, so the last link is read with the
8080 // `get_*2`/`get_*3` form that keeps it, and the update is written back
8081 // with `put_field`/`put_array_el`. The reordering in between is what puts
8082 // the old value below the receiver for a postfix update and the new one
8083 // above it for a prefix one:
8084 //
8085 // `obj val` → `post_inc` → `obj old new` → `perm3` → `old obj new`
8086 // `obj val` → `inc` → `obj new new` → `insert2` → `new obj new`
8087 //
8088 // This mirrors the reference instruction for instruction.
8089 self.expr(object)?;
8090 match property {
8091 MemberProp::Ident(name) => {
8092 self.emit(Opcode::GetField2, &[Op::Atom(Atom::from_text(&name.name))]);
8093 self.emit(instruction, &[]);
8094 self.emit(
8095 if prefix {
8096 Opcode::Insert2
8097 } else {
8098 Opcode::Perm3
8099 },
8100 &[],
8101 );
8102 self.emit(Opcode::PutField, &[Op::Atom(Atom::from_text(&name.name))]);
8103 }
8104 MemberProp::Computed(index) => {
8105 self.expr(index)?;
8106 self.emit(Opcode::GetArrayEl3, &[]);
8107 self.emit(instruction, &[]);
8108 self.emit(
8109 if prefix {
8110 Opcode::Insert3
8111 } else {
8112 Opcode::Perm4
8113 },
8114 &[],
8115 );
8116 self.emit(Opcode::PutArrayEl, &[]);
8117 }
8118 MemberProp::Private(name) => {
8119 // The receiver is duplicated and the read keeps it, exactly as `get_field2`
8120 // does for a public field: `obj val` -> `post_inc` -> `obj old new` ->
8121 // `perm3` -> `old obj new` -> store.
8122 let binding = format!("#{}", name.name);
8123 let (kind, setter) = self.private_use(&binding, argument.span)?;
8124 self.emit(Opcode::Dup, &[]);
8125 self.private_load(&binding, kind, argument.span)?;
8126 self.emit(instruction, &[]);
8127 self.emit(
8128 if prefix {
8129 Opcode::Insert2
8130 } else {
8131 Opcode::Perm3
8132 },
8133 &[],
8134 );
8135 self.private_store(&binding, kind, setter.as_deref())?;
8136 }
8137 }
8138 return Ok(());
8139 }
8140 let ExprKind::Ident(name) = &argument.kind else {
8141 return Err(SyntaxError::new(
8142 "increment of a non-variable is not supported by the compiler yet",
8143 argument.span,
8144 ));
8145 };
8146 // A discarded `i++` keeps the plain `get`/`post_inc`/`put` shape. The
8147 // reference's `inc_loc` folds those three into one, but it does so only in some
8148 // positions (a `for` update and not a bare statement, and never for a lexical
8149 // binding), so emitting it unconditionally would move *away* from its output.
8150 // The instruction is equivalent either way; matching the reference matters more
8151 // than saving two instructions.
8152 let _ = !std::mem::take(&mut self.state().discard_value);
8153 self.emit_var(VarAction::Get, &name.name);
8154 self.emit(instruction, &[]);
8155 if prefix {
8156 self.emit(Opcode::Dup, &[]);
8157 }
8158 self.emit_var(VarAction::Put, &name.name);
8159 Ok(())
8160 }
8161
8162 /// Compile an array literal.
8163 ///
8164 /// The reference splits this into three phases, and the split is load-bearing
8165 /// rather than an optimisation detail:
8166 ///
8167 /// 1. **A leading run of plain elements** becomes `array_from n`, which builds
8168 /// the array in one instruction.
8169 /// 2. **Everything up to the first spread** is appended with explicit indices
8170 /// (`define_field <index>`), because a hole has no element to pass to
8171 /// `array_from`. A hole here is what makes `length` need fixing up: an
8172 /// explicit index does not extend the array the way a pushed element does.
8173 /// 3. **From the first spread on** the index lives on the stack, so `append` and
8174 /// `define_array_el` can consume it and `inc` advances it.
8175 ///
8176 /// So `[1,,3]` and `[1,2,3]` are not two spellings of one program: the hole
8177 /// forces phase 2, and `[...a]` forces phase 3.
8178 fn array_literal(
8179 &mut self,
8180 elements: &[Option<ArrayElement>],
8181 span: Span,
8182 ) -> Result<(), SyntaxError> {
8183 let _ = span;
8184 let mut index: u32 = 0;
8185 let mut cursor = 0usize;
8186
8187 // Phase 1: a leading run of plain elements, at most 32 of them.
8188 while let Some(Some(ArrayElement::Expr(element))) = elements.get(cursor) {
8189 if index >= 32 {
8190 break;
8191 }
8192 self.expr(element)?;
8193 index += 1;
8194 cursor += 1;
8195 }
8196 self.emit(Opcode::ArrayFrom, &[Op::Int(index as i32)]);
8197
8198 // Phase 2: explicit indices, up to the first spread.
8199 let mut need_length = false;
8200 while let Some(element) = elements.get(cursor) {
8201 if matches!(element, Some(ArrayElement::Spread(_))) {
8202 break;
8203 }
8204 need_length = true;
8205 if let Some(ArrayElement::Expr(expression)) = element {
8206 self.expr(expression)?;
8207 self.emit_define_index(index);
8208 need_length = false;
8209 }
8210 index += 1;
8211 cursor += 1;
8212 }
8213
8214 if cursor >= elements.len() {
8215 if need_length {
8216 // `define_field` cannot set `length`, which is not configurable.
8217 self.emit(Opcode::Dup, &[]);
8218 self.push_number(index as f64);
8219 self.emit(Opcode::PutField, &[Op::Atom(Atom::from_text("length"))]);
8220 }
8221 return Ok(());
8222 }
8223
8224 // Phase 3: the index moves onto the stack for the spreading tail.
8225 //
8226 // `need_length` deliberately carries over from phase 2: a hole before the
8227 // first spread still has to be reflected in `length`, and only the final
8228 // check can do it because the array is not finished until the tail is
8229 // appended.
8230 self.push_number(index as f64);
8231 while let Some(element) = elements.get(cursor) {
8232 match element {
8233 Some(ArrayElement::Spread(expression)) => {
8234 // `append` copies an iterable and leaves the next index behind,
8235 // so no `inc` is needed here.
8236 self.expr(spread_argument(expression))?;
8237 self.emit(Opcode::Append, &[]);
8238 }
8239 None | Some(ArrayElement::Expr(_)) => {
8240 need_length = true;
8241 if let Some(ArrayElement::Expr(expression)) = element {
8242 self.expr(expression)?;
8243 self.emit(Opcode::DefineArrayEl, &[]);
8244 need_length = false;
8245 }
8246 self.emit(Opcode::Inc, &[]);
8247 }
8248 }
8249 cursor += 1;
8250 }
8251 if need_length {
8252 self.emit(Opcode::Dup1, &[]);
8253 self.emit(Opcode::PutField, &[Op::Atom(Atom::from_text("length"))]);
8254 } else {
8255 self.emit(Opcode::Drop, &[]);
8256 }
8257 Ok(())
8258 }
8259
8260 /// `define_field` with an array-index atom, which is how phase 2 stores elements.
8261 fn emit_define_index(&mut self, index: u32) {
8262 self.emit(
8263 Opcode::DefineField,
8264 &[Op::Atom(Atom::from_text(&index.to_string()))],
8265 );
8266 }
8267
8268 // -- functions ---------------------------------------------------------
8269
8270 fn compile_function(&mut self, func: &ast::Function) -> Result<CompiledFunction, SyntaxError> {
8271 self.compile_function_with_name(func, false)
8272 }
8273
8274 /// Compile a function, recording whether it is a *named function expression*.
8275 ///
8276 /// `var f = function g(){ return g }` has to see `g` inside its own body, but `g`
8277 /// must not leak outside. The reference does that by declaring `g` as a local of
8278 /// the function itself and initialising it with `special_object 2` (the current
8279 /// function), which is why this has to be known at compile time.
8280 fn compile_function_with_name(
8281 &mut self,
8282 func: &ast::Function,
8283 is_expression: bool,
8284 ) -> Result<CompiledFunction, SyntaxError> {
8285 let kind = match (func.is_generator, func.is_async) {
8286 (false, false) => FunctionKind::Normal,
8287 (true, false) => FunctionKind::Generator,
8288 (false, true) => FunctionKind::Async,
8289 (true, true) => FunctionKind::AsyncGenerator,
8290 };
8291 let mut state = FnState::new(
8292 func.name
8293 .as_ref()
8294 .map(|n| n.name.clone())
8295 .unwrap_or_default(),
8296 kind,
8297 );
8298 // The function's own mode, recorded by the parser. Inheriting the enclosing
8299 // function's instead let a nested `"use strict"` directive be ignored, so the
8300 // body ran with sloppy `this`, sloppy `arguments` and no const checks.
8301 state.strict = func.strict;
8302 // A function defined inside a `with` block keeps seeing that object: the guard
8303 // chain names the enclosing `<with>` locals, which resolve outward into closure
8304 // variables exactly like any other captured binding.
8305 state.inherited_with_names = self.cur().with_names.len();
8306 state.with_names = self.cur().with_names.clone();
8307 state.is_arrow = func.is_arrow;
8308 // Known before the body is compiled, so an lvalue can decide whether to pin its
8309 // reference before emitting the read. See [`FnState::eval_can_declare`].
8310 state.eval_can_declare = func.has_direct_eval;
8311 state.created_in_block = self.cur().current_block;
8312 // A default anywhere in the parameter list is what gives the function two
8313 // variable environments. The reference decides this the same way: it scans the
8314 // parenthesis for a top-level `=`, so a destructured name without a default
8315 // stays a plain function-scope binding.
8316 state.in_params = false;
8317 // The reference scans the parenthesis for *any* `=`, including one nested inside
8318 // a pattern, so `function f({a = 1})` has parameter expressions even though the
8319 // parameter itself carries no initialiser.
8320 state.has_parameter_expressions = func.params.iter().any(pattern_has_default);
8321 // `IsSimpleParameterList`: no default, no rest, no destructuring. Unlike the
8322 // flag above this looks at the *shape* of each parameter, not just for `=`.
8323 state.simple_parameter_list = func
8324 .params
8325 .iter()
8326 .all(|pattern| matches!(pattern.kind, PatternKind::Ident(_)));
8327 // A function born inside a parameter list inherits the prohibition: it must not
8328 // see the body bindings of the function it was created in.
8329 state.created_in_params = self.cur().in_params || self.cur().created_in_params;
8330 // A class constructor knows what it is only because the class told it.
8331 if let Some(kind) = self.cur().class_ctor_pending {
8332 state.ctor_kind = kind;
8333 }
8334 // A named *expression* binds its own name; a declaration's name is already
8335 // bound in the enclosing scope.
8336 state.self_name = if is_expression && !func.is_arrow {
8337 func.name.as_ref().map(|n| n.name.clone())
8338 } else {
8339 None
8340 };
8341 // Keep the written range so `Function.prototype.toString` can answer with the
8342 // original text rather than `[native code]`.
8343 //
8344 // It starts at the *parameter list*, not at the function: §20.2.3.5 removes the
8345 // accessor and generator prefixes, and for a method it must not include the name
8346 // or a leading `static`. `params_span` is exactly that boundary.
8347 // A *method* keeps the old `[native code]` answer: its reported text is defined
8348 // by the method-definition grammar (no name, no `static`, no `get`/`set`, but
8349 // the comments in between kept verbatim), and reconstructing that from a byte
8350 // span got it wrong in more cases than it got right. A plain function and an
8351 // arrow are the shapes libraries actually introspect, and those are exact.
8352 // A method's reported text starts at its **key** — `m(){}`, `[expr](){}`,
8353 // `#f /* a */ ( /* b */ ) {}` — which is exactly where the parser put `span.start`,
8354 // so the same slice works for every form. (`Params_span` is the boundary that
8355 // excludes `static`/`async`/`get`, which the spec's method grammar also omits.)
8356 // `source_span` is set only where the reported text is not the function's own
8357 // range — a class's constructor reports the whole class definition.
8358 let reported = func.source_span.unwrap_or(func.span);
8359 state.span = Some((reported.start.offset as usize, reported.end.offset as usize));
8360 state.line = func.span.start.line;
8361 state.column = func.span.start.column;
8362 // A function body has no hidden `<ret>` local; the value comes back on
8363 // the stack. Only a script keeps one.
8364 // Parameters are positional, so even a pattern occupies one argument slot. A
8365 // simple name is that slot itself; anything else (a pattern, a default, a rest
8366 // parameter) takes an anonymous slot and is unpicked into locals at the top of
8367 // the body, which is the only way one argument can bind several names.
8368 let mut prologue: Vec<(usize, Pattern)> = Vec::new();
8369 // `.length` stops at the first parameter that can be substituted: a default
8370 // fills a missing argument in, and a rest parameter absorbs the rest.
8371 let mut defined_args = func.params.len() as u32;
8372 for (index, param) in func.params.iter().enumerate() {
8373 match simple_parameter(param) {
8374 Some(name) => state.args.push(VarDef::var(name.name.clone())),
8375 None => {
8376 state.args.push(VarDef::var(ANONYMOUS_BINDING));
8377 prologue.push((index, param.clone()));
8378 }
8379 }
8380 }
8381 // A default anywhere before the end also ends the count, which the loop above
8382 // only catches for the parameter that carries it; `(a, b = 1, c)` is arity 1.
8383 for (position, param) in func.params.iter().enumerate() {
8384 if matches!(
8385 param.kind,
8386 PatternKind::Assign { .. } | PatternKind::Rest(_)
8387 ) {
8388 defined_args = position as u32;
8389 break;
8390 }
8391 }
8392 state.defined_args = defined_args;
8393 state.param_prologue = prologue;
8394 let depth = self.stack.len();
8395 self.stack.push(state);
8396 let result = self.compile_function_body(func);
8397 if result.is_err() {
8398 // A failed compile must not leave its `FnState` behind. Every caller
8399 // reads `self.state()` as "the function being compiled", so a leftover
8400 // frame silently retargets all later bookkeeping at a dead function.
8401 self.stack.truncate(depth);
8402 }
8403 result
8404 }
8405
8406 /// The body of a function, with its frame already pushed.
8407 fn compile_function_body(
8408 &mut self,
8409 func: &ast::Function,
8410 ) -> Result<CompiledFunction, SyntaxError> {
8411 let body_key = func.params_span.end.offset as u64;
8412 // Where the body begins, in source order. The runtime needs this to tell a
8413 // closure created by a default expression from one the body creates — the two see
8414 // different variable environments — and a bytecode offset would not survive the
8415 // instruction shuffling that building the frame does. Positions are in source
8416 // order, so a comparison answers it.
8417 self.state().body_start = (func.params_span.end.line, func.params_span.end.column);
8418 self.push_block(body_key, NO_PARENT);
8419 self.state().body_block = body_key;
8420 // An arrow with an expression body has no statements; the expression is
8421 // its `return`. Building the statement here keeps one code path below, and
8422 // matters for correctness beyond convenience: returning early with the new
8423 // `FnState` still on the stack would leave the compiler looking at the
8424 // wrong function, which surfaces as an unrelated underflow later.
8425 let concise = match &func.body {
8426 js_parse::ast::FunctionBody::Expr(value) => Some(Stmt::new(
8427 StmtKind::Return(Some(Box::new((**value).clone()))),
8428 value.span,
8429 )),
8430 js_parse::ast::FunctionBody::Block(_) => None,
8431 };
8432 let body: &[Stmt] = match &concise {
8433 Some(stmt) => std::slice::from_ref(stmt),
8434 None => func
8435 .body
8436 .statements()
8437 .ok_or_else(|| SyntaxError::new("unsupported function body", func.span))?,
8438 };
8439 let prologue = std::mem::take(&mut self.state().param_prologue);
8440 let has_param_scope = self.cur().has_parameter_expressions;
8441 // The parameter scope's own bindings, declared in source order.
8442 //
8443 // With parameter expressions the list gets a variable environment of its own, and
8444 // every name it binds is a `let` there. That is what puts the *list* in the
8445 // temporal dead zone: `function f(a = a){}` reads an uninitialised `a` and throws,
8446 // and `function f(x = y, y){}` does the same, where a single shared environment
8447 // would answer `undefined` to both.
8448 if has_param_scope {
8449 let mut declared: Vec<String> = Vec::new();
8450 for param in &func.params {
8451 let mut names = Vec::new();
8452 param.bound_names(&mut names);
8453 for name in names {
8454 if declared.contains(&name.name) {
8455 continue;
8456 }
8457 declared.push(name.name.clone());
8458 self.declare_param_binding(&name.name);
8459 }
8460 }
8461 }
8462 // A pattern parameter binds its names as function-scope locals, so they have to
8463 // exist — and be unpicked from the argument — before the body runs. With a
8464 // parameter scope these are the *second* environment: the pattern fills the
8465 // parameter's copy, and the body's binding is filled from it afterwards.
8466 for (_, pattern) in &prologue {
8467 let mut names = Vec::new();
8468 pattern.bound_names(&mut names);
8469 for name in names {
8470 self.declare_var(&name.name.clone(), VarDef::var(name.name.clone()));
8471 }
8472 }
8473 self.hoist(body, body_key)?;
8474 // A constructor's prologue is not a parameter unpacking but the `this` binding:
8475 // a base constructor takes the receiver, a derived one starts in the dead zone
8476 // because only `super()` may produce it.
8477 match self.cur().ctor_kind {
8478 CtorKind::None => {}
8479 CtorKind::Base => {
8480 self.begin_this_local();
8481 self.emit(Opcode::CheckCtor, &[]);
8482 // Instance fields are installed at the top of a base constructor's body,
8483 // before any statement — `class C { x = 1; constructor() { this.x } }` sees
8484 // `1`. This used to be emitted at the *tail*, which made every field read
8485 // `undefined` inside the constructor that declared it.
8486 self.call_field_initialiser();
8487 }
8488 CtorKind::Derived => {
8489 self.declare("this", VarDef::lexical("this"));
8490 let slot = self.cur().vars.len() as u32 - 1;
8491 self.emit(Opcode::SetLocUninitialized, &[Op::Slot(Slot::Loc(slot))]);
8492 self.emit(Opcode::CheckCtor, &[]);
8493 }
8494 }
8495 // Entering the parameter list: everything it binds starts in the dead zone.
8496 // The order is the reference's — it walks the scope chain, which is prepended, so
8497 // the bindings come out newest first.
8498 for name in self.param_binding_names().into_iter().rev() {
8499 if let Some(slot) = self.param_binding_slot(&name) {
8500 self.emit(Opcode::SetLocUninitialized, &[Op::Slot(Slot::Loc(slot))]);
8501 }
8502 }
8503 // The whole parameter list is one scope, and nothing in the body exists yet, so
8504 // every name it mentions resolves against the parameter bindings and outward.
8505 self.state().in_params = has_param_scope;
8506 for (index, param) in func.params.iter().enumerate() {
8507 if let Some(pattern) = prologue_pattern(&prologue, index) {
8508 // A destructuring parameter *initialises* its bindings: with a parameter
8509 // scope they are the list's own `let`s, which is why the stores skip the
8510 // dead-zone check, and why the reference reads their properties with
8511 // `get_field2` — a `let` needs no reference.
8512 let kind = if has_param_scope {
8513 VarDeclKind::Let
8514 } else {
8515 VarDeclKind::Var
8516 };
8517 match &pattern.kind {
8518 // `...rest` collects what is left rather than reading one slot.
8519 PatternKind::Rest(inner) => {
8520 self.emit(Opcode::Rest, &[Op::Int(index as i32)]);
8521 self.destructure(inner, Some(kind))?;
8522 }
8523 _ => {
8524 self.emit(Opcode::GetArg, &[Op::Slot(Slot::Arg(index as u32))]);
8525 self.destructure(pattern, Some(kind))?;
8526 }
8527 }
8528 continue;
8529 }
8530 // A plain name binds straight from its argument slot. With a parameter scope
8531 // the slot is also copied into the parameter binding, which is what a later
8532 // default (or a closure made among the defaults) reads.
8533 let Some(name) = simple_parameter(param) else {
8534 continue;
8535 };
8536 let target = self.param_binding_slot(&name.name);
8537 if matches!(param.kind, PatternKind::Rest(_)) {
8538 self.emit(Opcode::Rest, &[Op::Int(index as i32)]);
8539 if let Some(slot) = target {
8540 self.emit(Opcode::SetLoc, &[Op::Slot(Slot::Loc(slot))]);
8541 }
8542 // `put_arg` rather than `set_arg`: the array is the last thing on the
8543 // stack and nothing keeps it. Named by hand because a name in the
8544 // parameter list resolves to the parameter binding, and this store has to
8545 // reach the *argument* — that is what the body reads.
8546 self.emit(Opcode::PutArg, &[Op::Slot(Slot::Arg(index as u32))]);
8547 continue;
8548 }
8549 if let PatternKind::Assign { default, .. } = ¶m.kind {
8550 self.emit(Opcode::GetArg, &[Op::Slot(Slot::Arg(index as u32))]);
8551 let has_value = self.new_label();
8552 self.emit(Opcode::Dup, &[]);
8553 self.emit(Opcode::IsUndefined, &[]);
8554 self.emit_jump(Opcode::IfFalse, has_value, &[]);
8555 self.emit(Opcode::Drop, &[]);
8556 self.expr(default)?;
8557 self.set_name_if_anonymous(default, &Wtf8::new(&name.name));
8558 // The argument slot keeps the substituted value, because the *body* reads
8559 // the slot rather than the parameter binding — so this store is named
8560 // explicitly, like the rest parameter's.
8561 self.emit(Opcode::SetArg, &[Op::Slot(Slot::Arg(index as u32))]);
8562 self.place_label(has_value);
8563 if let Some(slot) = target {
8564 self.emit(Opcode::PutLoc, &[Op::Slot(Slot::Loc(slot))]);
8565 }
8566 continue;
8567 }
8568 if let Some(slot) = target {
8569 self.emit(Opcode::GetArg, &[Op::Slot(Slot::Arg(index as u32))]);
8570 self.emit(Opcode::PutLoc, &[Op::Slot(Slot::Loc(slot))]);
8571 }
8572 }
8573 // Copy the parameter scope into the body. A plain parameter needs nothing: the
8574 // body reads its argument slot, and the list kept the two in step. A name a
8575 // pattern bound has no argument slot of its own, so the body gets a `var` filled
8576 // from the parameter's copy — and *that* is why an assignment inside a default
8577 // does not reach the body.
8578 if has_param_scope {
8579 for (_, pattern) in &prologue {
8580 let mut names = Vec::new();
8581 pattern.bound_names(&mut names);
8582 for name in names {
8583 let Some(slot) = self.param_binding_slot(&name.name) else {
8584 continue;
8585 };
8586 let Some(body) = self.body_var_slot(&name.name) else {
8587 continue;
8588 };
8589 self.emit(Opcode::GetLocCheck, &[Op::Slot(Slot::Loc(slot))]);
8590 self.emit(Opcode::PutLoc, &[Op::Slot(Slot::Loc(body))]);
8591 }
8592 }
8593 }
8594 // The parameter list is over; from here on a direct `eval` belongs to the body.
8595 self.state().in_params = false;
8596 // Entering the body's own scope comes *after* the parameter list: the body's
8597 // `let`s are not in existence while the defaults run, and the reference emits
8598 // their `set_loc_uninitialized` only once the parameters are bound.
8599 self.emit_scope_enter(body_key);
8600 // A generator starts suspended: `initial_yield` parks the body so that creating one
8601 // runs no body code until the first `next()`.
8602 //
8603 // It comes *after* the parameter unpacking, not before, because a parameter
8604 // initialiser is not body code — `function* g(a = sideEffect())` must run
8605 // `sideEffect()` when `g` is *called*. Emitting `initial_yield` first parked the
8606 // defaults too, so `function* g(a = (() => { throw new Error })())` did not throw
8607 // until the first `next()` and 29 test262 cases that check for a synchronous throw
8608 // saw none at all.
8609 //
8610 // An async function does **not** get one. Its body runs synchronously up to the
8611 // first `await` — `async function f(){ log.push("a"); await 0 }` records `a`
8612 // before its caller's next statement — so an `initial_yield` here would park the
8613 // body before it started, which is not fixable at run time: the suspension looks
8614 // exactly like a real `await`.
8615 if self.cur().kind.is_generator() {
8616 self.emit(Opcode::InitialYield, &[]);
8617 }
8618 // Through `stmts`: the body is a block, and a `using` declaration in it is a
8619 // disposal region.
8620 self.stmts(body)?;
8621 // The implicit return only exists if control can actually get here: an
8622 // infinite loop never falls off the end.
8623 if self.end_is_reachable() {
8624 if self.cur().is_suspending() {
8625 // Falling off the end finishes the generator with `undefined`, and the
8626 // value is what tells the resume machinery "completed" rather than
8627 // "suspended".
8628 self.emit(Opcode::Undefined, &[]);
8629 self.emit(Opcode::ReturnAsync, &[]);
8630 } else {
8631 self.emit_class_constructor_tail();
8632 }
8633 }
8634 // Resolution runs while this function is still on the stack: capturing a
8635 // variable from an enclosing function means reaching into that
8636 // function's state, which requires the whole chain to be present.
8637 Ok(self.finish_current())
8638 }
8639
8640 /// Put every binding of a function that contains a direct `eval` into a cell.
8641 ///
8642 /// A direct eval can name any binding in scope, and any closure it creates has to
8643 /// keep sharing that binding after the function returns — `for (let i …)
8644 /// eval("push(() => i)")` collects one closure per iteration and each must read its
8645 /// own `i`. A copy in a side table would freeze the value, so the binding has to be
8646 /// a cell. Doing this unconditionally for such functions is the cheap, honest
8647 /// answer: the alternative is knowing at compile time which names a string will
8648 /// mention.
8649 fn capture_everything_for_eval(&mut self) {
8650 let current = self.stack.len() - 1;
8651 if !self.stack[current].has_direct_eval {
8652 return;
8653 }
8654 for arg in &mut self.stack[current].args {
8655 arg.is_captured = true;
8656 }
8657 for var in &mut self.stack[current].vars {
8658 var.is_captured = true;
8659 }
8660 }
8661
8662 /// Whether the current position in the instruction stream can be reached.
8663 ///
8664 /// A walk over the control-flow graph, using labels as instruction indices.
8665 /// The reference does the same thing to decide whether an implicit
8666 /// `return_undef` is needed.
8667 fn end_is_reachable(&self) -> bool {
8668 let state = self.cur();
8669 reachable_instructions(state, state.insns.len())[state.insns.len()]
8670 }
8671
8672 /// Resolve and assemble the function on top of the compiler stack, then pop
8673 /// it.
8674 fn finish_current(&mut self) -> CompiledFunction {
8675 self.provide_param_arguments();
8676 self.provide_arguments();
8677 self.provide_this_local();
8678 self.provide_new_target_local();
8679 self.provide_home_object_local();
8680 self.provide_active_func_local();
8681 self.provide_self_name();
8682 self.materialize_eval_sites();
8683 self.capture_everything_for_eval();
8684 let (mut resolved, resolved_pos) = resolve(&mut self.stack);
8685 // Captured bindings need a reference cell; the count goes in the header so
8686 // the runtime knows how many cells to allocate on entry.
8687 let current = self.stack.len() - 1;
8688 let captured = self.stack[current]
8689 .args
8690 .iter()
8691 .filter(|a| a.is_captured)
8692 .count()
8693 + self.stack[current]
8694 .vars
8695 .iter()
8696 .filter(|v| v.is_captured)
8697 .count();
8698 self.stack[current].var_ref_count = captured as u32;
8699 // The scope chain is only final now that every binding is known.
8700 rebuild_scope_chain(&mut self.stack[current]);
8701 let (code, stack_size, positions) =
8702 assemble(&mut resolved, &resolved_pos, &mut self.stack[current]);
8703 let _ = &mut resolved;
8704 let mut state = self.stack.pop().expect("a function is being compiled");
8705 CompiledFunction {
8706 name: state.name,
8707 kind: state.kind,
8708 strict: state.strict,
8709 is_derived_constructor: matches!(state.ctor_kind, CtorKind::Derived),
8710 // `is_script`/`is_module` are set only on the outermost function, which is
8711 // exactly the "script, eval or module body" the flag names.
8712 is_script_body: state.is_script || state.is_module,
8713 is_arrow: state.is_arrow,
8714 has_parameter_expressions: state.has_parameter_expressions,
8715 simple_parameter_list: state.simple_parameter_list,
8716 body_start: state.body_start,
8717 args: state.args,
8718 defined_args: state.defined_args,
8719 vars: state.vars,
8720 closure_vars: state.closure_vars,
8721 cpool: state.cpool,
8722 atoms: state.atoms,
8723 code,
8724 stack_size,
8725 var_ref_count: state.var_ref_count,
8726 positions,
8727 source: self.function_source(state.span, state.line, state.column),
8728 line: state.line,
8729 column: state.column,
8730 filename: None,
8731 eval_sites: state.eval_sites,
8732 module: state.module.take().map(Box::new),
8733 }
8734 }
8735}
8736
8737/// Assign each binding a scope level and rebuild the scope chains.
8738///
8739/// Levels are numbered in the order the blocks appear, with 0 reserved for the
8740/// function scope where `var` and hoisted functions live. Every binding outside
8741/// level 0 gets a `scope_next` link to the next binding visible from the same
8742/// point, so walking a block's chain enumerates exactly the bindings live there.
8743///
8744/// The links cannot be filled in while hoisting: `{ let a } let b` needs `a` to
8745/// point at `b`, which is declared later in the source but earlier in the chain.
8746fn rebuild_scope_chain(state: &mut FnState) {
8747 // Block key -> level. Level 0 is the function scope, keyed by the sentinel so a
8748 // real block that happens to start at offset zero keeps its own level instead of
8749 // being merged into the function scope.
8750 let mut levels: Vec<u64> = vec![FUNCTION_SCOPE];
8751 for block in &state.blocks {
8752 if !levels.contains(&block.key) {
8753 levels.push(block.key);
8754 }
8755 }
8756 let level_of = |key: u64| -> usize { levels.iter().position(|k| *k == key).unwrap_or(0) };
8757 let parent_level = |level: usize| -> usize {
8758 if level == 0 {
8759 return 0;
8760 }
8761 let key = levels[level];
8762 let parent = state
8763 .blocks
8764 .iter()
8765 .find(|b| b.key == key)
8766 .map(|b| b.parent)
8767 .unwrap_or(FUNCTION_SCOPE);
8768 level_of(parent)
8769 };
8770
8771 // Own bindings per level, in declaration order.
8772 let mut own: Vec<Vec<usize>> = vec![Vec::new(); levels.len()];
8773 let keys: Vec<u64> = (0..state.vars.len())
8774 .map(|index| {
8775 state
8776 .var_block
8777 .get(index)
8778 .copied()
8779 .unwrap_or(FUNCTION_SCOPE)
8780 })
8781 .collect();
8782 for (index, key) in keys.into_iter().enumerate() {
8783 // The parameter scope is not a block: it is a level of its own with no parent,
8784 // assigned below. Letting it land in level 0 would chain the body's bindings onto
8785 // it, which the reference does not do — the two environments are siblings.
8786 if key == PARAM_SCOPE {
8787 continue;
8788 }
8789 let level = level_of(key);
8790 state.vars[index].scope_level = level as u32;
8791 // A `catch` parameter is part of the runtime scope chain even though it is
8792 // not lexical: the handler's own bindings chain on to it, which is why the
8793 // reference prints `let y [next:1]` with `e` at 1.
8794 if state.vars[index].is_lexical || state.vars[index].kind == crate::bytecode::VarKind::Catch
8795 {
8796 own[level].push(index);
8797 }
8798 }
8799
8800 // A scope's chain is its own bindings in reverse declaration order followed
8801 // by the enclosing scope's chain.
8802 let mut head = vec![-1i32; levels.len()];
8803 for level in 0..levels.len() {
8804 let inherited = if level == 0 {
8805 -1
8806 } else {
8807 head[parent_level(level)]
8808 };
8809 let chain: Vec<usize> = own[level].iter().rev().copied().collect();
8810 head[level] = chain.first().map_or(inherited, |first| *first as i32);
8811 for (position, &index) in chain.iter().enumerate() {
8812 let next = chain
8813 .get(position + 1)
8814 .map_or(inherited, |next| *next as i32);
8815 state.vars[index].scope_next = if next < 0 { None } else { Some(next) };
8816 }
8817 }
8818 state.block_heads = head;
8819
8820 // The parameter list is a scope of its own, and it has no parent: the reference pops
8821 // it before the body exists, so its chain ends in `ARG_SCOPE_END` (`-2`) rather than
8822 // the `-1` a block uses. A level past every real block keeps it out of the walk above
8823 // — nothing but the dump reads it — and the links run newest-to-oldest through the
8824 // bindings themselves, which is the order `set_loc_uninitialized` walks.
8825 let param_level = levels.len() as u32;
8826 let mut previous: Option<usize> = None;
8827 for index in 0..state.vars.len() {
8828 if state.var_block.get(index).copied() != Some(PARAM_SCOPE) || !state.vars[index].is_lexical
8829 {
8830 continue;
8831 }
8832 state.vars[index].scope_level = param_level;
8833 state.vars[index].scope_next = Some(previous.map_or(-2, |previous| previous as i32));
8834 previous = Some(index);
8835 }
8836}
8837
8838/// This is where names become slots and where the temporal dead zone shows up in
8839/// the instruction stream: a read of a `let`/`const` binding compiles to
8840/// `get_loc_check`, which throws if the binding is still uninitialised.
8841///
8842/// The peephole pass from the reference implementation is applied at the end,
8843/// for the same reason it is applied to resolved bytecode there: the patterns are
8844/// stated in terms of `put_loc`/`set_loc` pairs, which only exist after
8845/// resolution. Deleted instructions stay in the list as `None` so that label
8846/// indices remain valid; [`Assembler`] maps them to byte offsets.
8847/// A resolved instruction and the source position it came from.
8848type ResolvedInsn = Option<(Opcode, Vec<Op>)>;
8849
8850/// A resolved instruction paired with its position, which is what `assemble` consumes.
8851type PositionedInsn = (Opcode, Vec<Op>);
8852
8853fn resolve(stack: &mut [FnState]) -> (Vec<ResolvedInsn>, Vec<Option<Position>>) {
8854 let current = stack.len() - 1;
8855 // Dead-code elimination, on the symbolic form where labels are still
8856 // instruction indices. A `break` inside a loop leaves the trailing `goto`
8857 // unreachable, and a `return` leaves everything after it unreachable; the
8858 // reference drops both. Doing it here means the emitter never has to think
8859 // about reachability.
8860 strip_empty_gosubs(stack, current);
8861 eliminate_dead_code(stack, current);
8862 let insns = std::mem::take(&mut stack[current].insns);
8863 // One entry per instruction, carried alongside: `insn_pos` is index-aligned with
8864 // `insns`, and every arm below pushes exactly one instruction, so the positions
8865 // stay aligned with `out`.
8866 let positions = std::mem::take(&mut stack[current].insn_pos);
8867 let mut out: Vec<Option<(Opcode, Vec<Op>)>> = Vec::with_capacity(insns.len());
8868 let mut out_pos: Vec<Option<Position>> = Vec::with_capacity(insns.len());
8869 for (index, insn) in insns.iter().enumerate() {
8870 let pos = positions.get(index).copied().flatten();
8871 out_pos.push(pos);
8872 match insn {
8873 Insn::Fixed { op, operands } => {
8874 let operands = operands
8875 .iter()
8876 .map(|operand| match operand {
8877 Op::Atom(atom) => {
8878 Op::AtomId(intern_atom_value(&mut stack[current], atom.clone()))
8879 }
8880 other => other.clone(),
8881 })
8882 .collect();
8883 out.push(Some((*op, operands)));
8884 }
8885 Insn::Var {
8886 action,
8887 name,
8888 block,
8889 in_params,
8890 } => {
8891 // Both reads and writes in the parameter list address the parameter
8892 // scope. That is what puts the list in the temporal dead zone — a read of
8893 // a later parameter is `get_loc_check` on an uninitialised slot — and it
8894 // is also what keeps an assignment made inside a default away from the
8895 // body, which sees a separate environment.
8896 let slot = resolve_slot(stack, current, name, *block, *in_params);
8897 // A store to the name of a named function expression is special: the
8898 // reference drops it in sloppy mode and throws in strict mode, because
8899 // the binding is immutable but only *checked* when the body is strict.
8900 // The same rule applies when the name is reached through a closure:
8901 // `var f = function myfunc() { (() => { myfunc = 1 })() }` has to drop
8902 // the store in the arrow too, not just in the function that owns the
8903 // binding. Reaching the owner means walking the chain of closure
8904 // entries, which is what `self_name_binding` does.
8905 let self_name = matches!(action, VarAction::Put | VarAction::Set)
8906 .then(|| {
8907 // A local of this function is the common case and needs no
8908 // chain walk; only an access that resolves elsewhere can be
8909 // pointing at an enclosing function's name binding.
8910 if let Slot::Loc(index) = slot {
8911 stack[current]
8912 .vars
8913 .get(index as usize)
8914 .filter(|var| var.kind == VarKind::FunctionName)
8915 .map(|var| var.is_const)
8916 } else {
8917 self_name_binding(stack, current, name, *block)
8918 }
8919 })
8920 .flatten();
8921 if let Some(is_const) = self_name {
8922 out.push(Some(if is_const {
8923 (
8924 Opcode::ThrowError,
8925 vec![
8926 Op::AtomId(intern_atom(&mut stack[current], name)),
8927 Op::Int(0),
8928 ],
8929 )
8930 } else {
8931 (Opcode::Drop, Vec::new())
8932 }));
8933 continue;
8934 }
8935 if *action == VarAction::MakeRef {
8936 // A reference to a *local* has to keep working after the enclosing
8937 // frame is gone, and `get_ref_value` reads a cell — so the binding is
8938 // forced into one, exactly as the reference implementation's
8939 // `capture_var` does. Only an access that a direct `eval` in the same
8940 // function can shadow ever asks for this, so the cost is confined to
8941 // functions that contain one.
8942 match slot {
8943 Slot::Loc(index) => {
8944 if let Some(var) = stack[current].vars.get_mut(index as usize) {
8945 var.is_captured = true;
8946 }
8947 }
8948 Slot::Arg(index) => {
8949 if let Some(arg) = stack[current].args.get_mut(index as usize) {
8950 arg.is_captured = true;
8951 }
8952 }
8953 _ => {}
8954 }
8955 }
8956 let (opcode, mut operands) = variable_instruction(stack, current, *action, slot);
8957 if *action == VarAction::MakeRef {
8958 // Operand 0 is the placeholder `variable_instruction` could not fill
8959 // in; the name is in hand here, and it has to be *interned* — this arm
8960 // bypasses `Insn::Fixed`, which is where `Op::Atom` normally becomes an
8961 // `Op::AtomId`.
8962 operands[0] = Op::AtomId(intern_atom(&mut stack[current], name));
8963 }
8964 out.push(Some((opcode, operands)));
8965 }
8966 Insn::CloseCaptured { name, block } => {
8967 // The block matters: a loop variable is scoped to the `for` head's own
8968 // block, so resolving it against block 0 would miss it entirely and
8969 // silently emit nothing.
8970 let slot = resolve_slot(stack, current, name, *block, false);
8971 // Only a local with a reference cell has anything to close. A global
8972 // or a never-captured local resolves to no instruction at all, which
8973 // keeps the bytecode identical to the reference's.
8974 if let Slot::Loc(index) = slot
8975 && stack[current]
8976 .vars
8977 .get(index as usize)
8978 .is_some_and(|v| v.is_captured)
8979 {
8980 out.push(Some((Opcode::CloseLoc, vec![Op::Slot(slot)])));
8981 } else {
8982 out.push(None);
8983 }
8984 }
8985 Insn::DeleteVar { name } => {
8986 // A binding — a local, an argument, or a declared global — cannot be
8987 // deleted, and the reference encodes that as a constant `push_false`.
8988 // Only an implicit global needs the runtime lookup.
8989 if matches!(
8990 resolve_slot(stack, current, name, 0, false),
8991 Slot::Global(_)
8992 ) {
8993 let atom = intern_atom(&mut stack[current], name);
8994 out.push(Some((Opcode::DeleteVar, vec![Op::AtomId(atom)])));
8995 } else {
8996 out.push(Some((Opcode::PushFalse, Vec::new())));
8997 }
8998 }
8999 Insn::Dead => out.push(None),
9000 }
9001 }
9002 // Which label (if any) sits on each instruction, so the jump patterns can
9003 // tell whether they would cross a jump target.
9004 let mut label_at: Vec<Option<u32>> = vec![None; out.len() + 1];
9005 for (id, placed) in stack[current].labels.iter().enumerate() {
9006 if let Some(index) = *placed
9007 && index < label_at.len()
9008 && label_at[index].is_none()
9009 {
9010 label_at[index] = Some(id as u32);
9011 }
9012 }
9013 if std::env::var_os("QJS_DEBUG").is_some() {
9014 eprintln!("--- peephole entry ---");
9015 for (i, e) in out.iter().enumerate() {
9016 eprintln!("{i}: {e:?}");
9017 }
9018 eprintln!("label_at: {label_at:?}");
9019 }
9020 peephole(&mut out, &label_at, &stack[current].labels);
9021 (out, out_pos)
9022}
9023
9024/// Find where `name` lives, capturing it in an enclosing function when needed.
9025///
9026/// The search runs outward through the enclosing functions' states, which are
9027/// still on the compiler stack while a nested function is resolved. Finding the
9028/// name in an enclosing function is what creates a closure reference, and every
9029/// function in between has to forward it — a function can only reach its own
9030/// parent's frame.
9031///
9032/// A name declared nowhere is a global. The reference does *not* look it up by
9033/// name from the inner function: the top-level function gets one `[global]`
9034/// entry and every nested function gets a `[global_ref<n>]` pointing at its
9035/// parent's entry, which is why `function f(){ g(); }` shows `[global_ref0]`
9036/// rather than `[global]`.
9037/// The lexical blocks enclosing `block`, innermost first.
9038fn block_chain(state: &FnState, block: u64) -> Vec<u64> {
9039 let mut chain = Vec::new();
9040 let mut current = Some(block);
9041 while let Some(key) = current {
9042 // `NO_PARENT` is not a block, so the walk ends here. Stopping on the sentinel
9043 // explicitly (rather than on "no block with this key") is what keeps a block
9044 // that happens to sit at offset zero from being mistaken for the terminator.
9045 if key == NO_PARENT || chain.contains(&key) {
9046 break;
9047 }
9048 chain.push(key);
9049 current = state.blocks.iter().find(|b| b.key == key).map(|b| b.parent);
9050 }
9051 chain
9052}
9053
9054/// The `const`-ness of a named function expression's own name, if `name` resolves to one.
9055///
9056/// The binding may be several functions away: an arrow nested in `function myfunc`
9057/// reaches `myfunc` through a chain of closure entries, so finding out *what* it names
9058/// means following `Ref` entries down and then reading the owning function's var table.
9059fn self_name_binding(stack: &[FnState], current: usize, name: &str, block: u64) -> Option<bool> {
9060 let state = stack.get(current)?;
9061 // A parameter shadows everything and is never a function-expression name.
9062 if state.args.iter().any(|arg| arg.name == name) {
9063 return None;
9064 }
9065 // A local of this very function: the answer is in its var table.
9066 if let Some(index) = local_slot_index(state, name, block) {
9067 let var = state.vars.get(index)?;
9068 return (var.kind == VarKind::FunctionName).then_some(var.is_const);
9069 }
9070 // Otherwise the name lives further out, and the closure entry says how to get
9071 // there. `Local` names the owner's slot directly; `Ref` names the next level's
9072 // closure entry, so the walk continues downwards.
9073 let mut level = current;
9074 let mut index = state
9075 .closure_vars
9076 .iter()
9077 .position(|closure| closure.name == name)?;
9078 loop {
9079 let state = stack.get(level)?;
9080 let closure = state.closure_vars.get(index)?;
9081 match closure.closure_type {
9082 ClosureType::Local => {
9083 let owner = stack.get(level.checked_sub(1)?)?;
9084 let var = owner.vars.get(closure.var_idx as usize)?;
9085 return (var.kind == VarKind::FunctionName).then_some(var.is_const);
9086 }
9087 ClosureType::Arg => return None,
9088 ClosureType::Ref => {
9089 level -= 1;
9090 index = closure.var_idx as usize;
9091 }
9092 // A global is never a function-expression name.
9093 ClosureType::Global
9094 | ClosureType::GlobalDecl
9095 | ClosureType::GlobalRef
9096 | ClosureType::ModuleDecl
9097 | ClosureType::ModuleImport => return None,
9098 }
9099 }
9100}
9101
9102/// The index of `name`'s binding in `state`, looked up the way [`resolve_slot`] does.
9103fn local_slot_index(state: &FnState, name: &str, block: u64) -> Option<usize> {
9104 block_chain(state, block).into_iter().find_map(|scope| {
9105 state.vars.iter().enumerate().find_map(|(index, var)| {
9106 (var.name == name && state.var_block.get(index).copied() == Some(scope))
9107 .then_some(index)
9108 })
9109 })
9110}
9111
9112/// Declare `name` as a binding of `state`'s parameter scope, returning its slot.
9113fn declare_param_var_at(state: &mut FnState, name: &str) -> u32 {
9114 if let Some(index) = state.vars.iter().enumerate().position(|(index, var)| {
9115 var.name == name && state.var_block.get(index).copied() == Some(PARAM_SCOPE)
9116 }) {
9117 return index as u32;
9118 }
9119 state.var_block.push(PARAM_SCOPE);
9120 state.vars.push(VarDef::var(name));
9121 state.vars.len() as u32 - 1
9122}
9123
9124/// The name a parameter binds straight from its argument slot, if it has one.
9125///
9126/// A plain name does — with or without a default, and with or without `...`. Everything
9127/// else is a pattern, which takes an anonymous slot for the parameter list to unpick; the
9128/// reference names the argument in the first case and leaves it `<null>` in the second,
9129/// so both the dump and the closures that capture the argument depend on this.
9130fn simple_parameter(param: &Pattern) -> Option<&Ident> {
9131 match ¶m.kind {
9132 PatternKind::Ident(name) => Some(name),
9133 PatternKind::Assign { target, .. } => match &target.kind {
9134 PatternKind::Ident(name) => Some(name),
9135 _ => None,
9136 },
9137 PatternKind::Rest(inner) => match &inner.kind {
9138 PatternKind::Ident(name) => Some(name),
9139 _ => None,
9140 },
9141 _ => None,
9142 }
9143}
9144
9145/// The pattern a parameter list has to unpick, if `index` is one of them.
9146fn prologue_pattern(prologue: &[(usize, Pattern)], index: usize) -> Option<&Pattern> {
9147 prologue
9148 .iter()
9149 .find(|(at, _)| *at == index)
9150 .map(|(_, pattern)| pattern)
9151}
9152
9153fn pattern_has_default(pattern: &Pattern) -> bool {
9154 match &pattern.kind {
9155 PatternKind::Assign { .. } => true,
9156 PatternKind::Rest(inner) => pattern_has_default(inner),
9157 PatternKind::Array { elements, rest } => {
9158 elements.iter().flatten().any(element_has_default)
9159 || rest.as_deref().is_some_and(rest_has_default)
9160 }
9161 PatternKind::Object { properties, rest } => {
9162 properties.iter().flatten().any(element_has_default)
9163 || rest.as_deref().is_some_and(rest_has_default)
9164 }
9165 _ => false,
9166 }
9167}
9168
9169fn element_has_default(element: &PatternElement) -> bool {
9170 match element {
9171 PatternElement::Pattern(pattern) => pattern_has_default(pattern),
9172 PatternElement::Property { value, .. } => pattern_has_default(value),
9173 }
9174}
9175
9176fn rest_has_default(rest: &RestElement) -> bool {
9177 match rest {
9178 RestElement::Pattern(pattern) => pattern_has_default(pattern),
9179 RestElement::Member(_) => false,
9180 }
9181}
9182
9183/// Whether a function-scope binding is visible to the parameter list.
9184///
9185/// The parameter list runs before the body, so the body's `var`s and function
9186/// declarations do not exist yet — a name that only the body declares has to resolve
9187/// outward instead. What *does* exist by then is the compiler's own prologue: the
9188/// self-name of a named function expression (bound by `special_object 2` before anything
9189/// else), `this` and `new.target`. Those stay visible, which is what makes
9190/// `function f(a = this)` and `var f = function f(a = f)` work.
9191///
9192/// `arguments` is handled separately, as a binding of the parameter scope itself: with
9193/// parameter expressions the reference creates two of them, and the one the parameter
9194/// list sees is not the one the body sees (`function f(a = eval("var arguments = 1"))`).
9195fn visible_in_params(var: &VarDef) -> bool {
9196 var.kind == VarKind::FunctionName || var.name == "this" || var.name == "new.target"
9197}
9198
9199fn resolve_slot(
9200 stack: &mut [FnState],
9201 current: usize,
9202 name: &str,
9203 block: u64,
9204 in_params: bool,
9205) -> Slot {
9206 // The parameter list's own bindings. They are consulted first because they shadow
9207 // the argument slots they were copied from: `function f(a = 1, p = () => a)` keeps
9208 // `a` in the parameter scope, so a closure made there reads the parameter even after
9209 // the body assigns to its own `a`.
9210 if in_params
9211 && let Some(index) = stack[current]
9212 .vars
9213 .iter()
9214 .enumerate()
9215 .position(|(index, var)| {
9216 var.name == name
9217 && stack[current].var_block.get(index).copied() == Some(PARAM_SCOPE)
9218 })
9219 {
9220 return Slot::Loc(index as u32);
9221 }
9222 // A name can be bound more than once: two `catch` parameters in nested
9223 // handlers are two slots. The binding that wins is the one whose scope encloses
9224 // the access, and among those the innermost — so the blocks are walked outward
9225 // and the first binding found on the way is the one that counts. A binding in
9226 // no block (`var`) is reachable from anywhere, which is why the function scope
9227 // is the end of the walk.
9228 //
9229 // The block walk comes *before* the argument slots, because a block may shadow a
9230 // parameter: `function f(a){ { let a = 2 } }` writes the inner `a`, and the argument
9231 // slot is only the answer once nothing nearer claims the name.
9232 let chain = block_chain(&stack[current], block);
9233 for scope in &chain {
9234 let found = stack[current]
9235 .vars
9236 .iter()
9237 .enumerate()
9238 .find(|(index, var)| {
9239 var.name == name && stack[current].var_block.get(*index).copied() == Some(*scope)
9240 })
9241 .map(|(index, _)| index);
9242 if let Some(index) = found {
9243 return Slot::Loc(index as u32);
9244 }
9245 }
9246 // A parameter, which is neither block-scoped nor a plain function-scope `var`: it has
9247 // its own slot, and `var` of the same name in the body is the same binding.
9248 if let Some(index) = stack[current].args.iter().position(|a| a.name == name) {
9249 return Slot::Arg(index as u32);
9250 }
9251 // Function-scope bindings — `var` and function declarations — are recorded with
9252 // the sentinel block `0`, which no real scope uses, so the walk above cannot see
9253 // them. They are reachable from anywhere in the function, which is exactly what
9254 // the sentinel means.
9255 //
9256 // This pass is *only* for those. A lexical binding has to be found through the
9257 // chain or not at all, and looking a name up without its block is precisely how
9258 // `var x = 1; { let x = 2; } x` used to see the inner `x`, and how a `let` in a
9259 // block leaked out of it.
9260 let function_scoped = stack[current]
9261 .vars
9262 .iter()
9263 .enumerate()
9264 .find(|(index, var)| {
9265 var.name == name
9266 && stack[current].var_block.get(*index).copied() == Some(FUNCTION_SCOPE)
9267 && (!in_params || visible_in_params(var))
9268 })
9269 .map(|(index, _)| index);
9270 if let Some(index) = function_scoped {
9271 return Slot::Loc(index as u32);
9272 }
9273 if let Some(index) = stack[current]
9274 .closure_vars
9275 .iter()
9276 .position(|c| c.name == name)
9277 {
9278 return slot_for_closure(&stack[current].closure_vars[index], index as u32);
9279 }
9280
9281 for owner in (0..current).rev() {
9282 // The nested function was created inside one of this frame's blocks, and the
9283 // outermost visible binding is the innermost block on that chain — not whatever
9284 // comes first in the variable table. `function f(){ class S{} }` has two `S`
9285 // bindings: the `let S` inside `f` and the `const S` inside the class body, and
9286 // the class body is the one a method may see.
9287 let entry = stack
9288 .get(owner + 1)
9289 .map(|s| s.created_in_block)
9290 .unwrap_or(0);
9291 let lexical = block_chain(&stack[owner], entry)
9292 .into_iter()
9293 .find_map(|scope| {
9294 stack[owner]
9295 .vars
9296 .iter()
9297 .enumerate()
9298 .find(|(index, var)| {
9299 var.name == name
9300 && stack[owner].var_block.get(*index).copied() == Some(scope)
9301 })
9302 .map(|(index, _)| index)
9303 });
9304 // A function born in a parameter list sees that list's bindings, not the body's:
9305 // the parameter scope is the environment it was created in.
9306 let in_param_scope = stack
9307 .get(owner + 1)
9308 .is_some_and(|child| child.created_in_params)
9309 .then(|| {
9310 stack[owner]
9311 .vars
9312 .iter()
9313 .enumerate()
9314 .position(|(index, var)| {
9315 var.name == name
9316 && stack[owner].var_block.get(index).copied() == Some(PARAM_SCOPE)
9317 })
9318 })
9319 .flatten();
9320 let found = if let Some(index) = in_param_scope {
9321 let var = &stack[owner].vars[index];
9322 Some(Found::Local(
9323 ClosureType::Local,
9324 index as u32,
9325 var.is_const,
9326 var.needs_check(),
9327 ))
9328 } else if let Some(index) = stack[owner].args.iter().position(|a| a.name == name) {
9329 Some(Found::Local(ClosureType::Arg, index as u32, false, false))
9330 } else if let Some(index) = lexical {
9331 let var = &stack[owner].vars[index];
9332 Some(Found::Local(
9333 ClosureType::Local,
9334 index as u32,
9335 var.is_const,
9336 var.needs_check(),
9337 ))
9338 } else if let Some(index) = stack[owner]
9339 .vars
9340 .iter()
9341 .enumerate()
9342 .find_map(|(index, var)| {
9343 // A function created inside a parameter list must not see the body of the
9344 // function it was born in; see [`FnState::created_in_params`].
9345 let hidden = stack
9346 .get(owner + 1)
9347 .is_some_and(|child| child.created_in_params);
9348 (var.name == name && (!hidden || visible_in_params(var))).then_some(index)
9349 })
9350 {
9351 let var = &stack[owner].vars[index];
9352 Some(Found::Local(
9353 ClosureType::Local,
9354 index as u32,
9355 var.is_const,
9356 var.needs_check(),
9357 ))
9358 } else if stack[owner].self_name.as_deref() == Some(name) {
9359 // A named function expression's own name. The reference declares it here,
9360 // on the first lookup that fails, rather than up front — and that is what
9361 // makes it reachable from a *nested* function: the nested lookup is what
9362 // walks out and creates the binding. A direct reference in the body is
9363 // caught the same way, which is why `provide_self_name` only has to add
9364 // the prologue.
9365 let strict = stack[owner].strict;
9366 stack[owner].var_block.push(FUNCTION_SCOPE);
9367 stack[owner].vars.push(VarDef {
9368 kind: VarKind::FunctionName,
9369 // In strict mode the name is immutable, so a store raises; sloppy
9370 // mode drops the store instead (see `variable_instruction`).
9371 is_const: strict,
9372 ..VarDef::var(name)
9373 });
9374 let index = stack[owner].vars.len() as u32 - 1;
9375 Some(Found::Local(ClosureType::Local, index, strict, false))
9376 } else if let Some(index) = stack[owner]
9377 .closure_vars
9378 .iter()
9379 .position(|c| c.name == name)
9380 {
9381 let closure = &stack[owner].closure_vars[index];
9382 Some(match closure.closure_type {
9383 // `GlobalRef` belongs here too: it is a *global* reached through this
9384 // frame's reference table, so treating it as a `Ref` to a local cell makes
9385 // the reader look for a cell no frame ever fills. That is how a second
9386 // function using `eval` in its parameter list read `undefined` after a
9387 // sibling had already made `eval` a closure entry.
9388 ClosureType::Global | ClosureType::GlobalDecl | ClosureType::GlobalRef => {
9389 Found::Global(index as u32)
9390 }
9391 // A module variable is a cell in the *module's* environment, which is
9392 // the module body's parent as far as a nested function is concerned — so
9393 // it is captured as a plain reference, not looked up as a global.
9394 ClosureType::ModuleDecl | ClosureType::ModuleImport => Found::Local(
9395 ClosureType::Ref,
9396 index as u32,
9397 closure.is_const,
9398 closure.is_lexical,
9399 ),
9400 _ => Found::Local(
9401 ClosureType::Ref,
9402 index as u32,
9403 closure.is_const,
9404 closure.is_lexical,
9405 ),
9406 })
9407 } else {
9408 None
9409 };
9410 let Some(found) = found else { continue };
9411
9412 let (is_const, is_lexical) = match found {
9413 Found::Local(_, _, is_const, is_lexical) => (is_const, is_lexical),
9414 Found::Global(_) => (false, false),
9415 };
9416 // Mark the owner's binding as captured so it moves into a reference cell.
9417 if let Found::Local(ClosureType::Arg | ClosureType::Local, index, _, _) = found {
9418 let slot = match found {
9419 Found::Local(ClosureType::Arg, _, _, _) => &mut stack[owner].args[index as usize],
9420 _ => &mut stack[owner].vars[index as usize],
9421 };
9422 slot.is_captured = true;
9423 }
9424 // Forward the reference through every function in between.
9425 let mut previous = match found {
9426 Found::Local(kind, index, _, _) => (kind, index),
9427 Found::Global(index) => (ClosureType::Global, index),
9428 };
9429 for level in owner + 1..=current {
9430 let kind = match (previous.0, level) {
9431 // A global stays a global at *every* level. Without `GlobalRef` in
9432 // this arm the second nested function over the same global got a
9433 // `Ref` to a cell no frame ever held, so the innermost closure read
9434 // `undefined` — which is how a two-deep getter lost its outer
9435 // variable.
9436 (ClosureType::Global | ClosureType::GlobalDecl | ClosureType::GlobalRef, _) => {
9437 ClosureType::GlobalRef
9438 }
9439 (ClosureType::Arg | ClosureType::Local, level) if level == owner + 1 => previous.0,
9440 _ => ClosureType::Ref,
9441 };
9442 let index = ensure_closure(stack, level, name, is_const, is_lexical, kind, previous.1);
9443 previous = (kind, index);
9444 }
9445 let index = previous.1;
9446 return slot_for_closure(&stack[current].closure_vars[index as usize], index);
9447 }
9448
9449 // Declared nowhere: a dynamic global lookup, which sloppy mode may satisfy by
9450 // creating a property. The top-level function holds the entry.
9451 let mut previous = (
9452 ClosureType::Global,
9453 ensure_closure(stack, 0, name, false, false, ClosureType::Global, 0),
9454 );
9455 for level in 1..=current {
9456 let index = ensure_closure(
9457 stack,
9458 level,
9459 name,
9460 false,
9461 false,
9462 ClosureType::GlobalRef,
9463 previous.1,
9464 );
9465 previous = (ClosureType::GlobalRef, index);
9466 }
9467 Slot::Global(previous.1)
9468}
9469
9470/// What an outward search turned up.
9471#[derive(Debug, Clone, Copy)]
9472enum Found {
9473 /// A binding in an enclosing function, reachable through a closure of this
9474 /// type, with its const/lexical flags.
9475 Local(ClosureType, u32, bool, bool),
9476 /// A global, reached through the enclosing function's closure entry.
9477 Global(u32),
9478}
9479
9480/// Add a closure entry to `level` if it is not there yet.
9481fn ensure_closure(
9482 stack: &mut [FnState],
9483 level: usize,
9484 name: &str,
9485 is_const: bool,
9486 is_lexical: bool,
9487 closure_type: ClosureType,
9488 var_idx: u32,
9489) -> u32 {
9490 if let Some(index) = stack[level]
9491 .closure_vars
9492 .iter()
9493 .position(|c| c.name == name)
9494 {
9495 return index as u32;
9496 }
9497 stack[level].closure_vars.push(ClosureVar {
9498 name: name.to_string(),
9499 is_const,
9500 is_lexical,
9501 // Only a declaration in the script's own scope can be one, and that path records
9502 // it directly (`declare_global`); a capture of it forwards the name, not the kind.
9503 is_function_decl: false,
9504 closure_type,
9505 var_idx: var_idx as u16,
9506 });
9507 stack[level].closure_vars.len() as u32 - 1
9508}
9509
9510fn slot_for_closure(closure: &ClosureVar, index: u32) -> Slot {
9511 match closure.closure_type {
9512 // A `global_ref` only says *how* the binding is found (through the
9513 // parent's closure table); the access itself is an ordinary global one.
9514 ClosureType::Global | ClosureType::GlobalRef => Slot::Global(index),
9515 ClosureType::GlobalDecl => Slot::GlobalDecl(index),
9516 // A module variable is a real cell in the module's environment, so it is reached
9517 // exactly like a captured local — the host, not the global object, is what fills
9518 // the slot.
9519 ClosureType::ModuleDecl | ClosureType::ModuleImport => Slot::VarRef(index),
9520 _ => Slot::VarRef(index),
9521 }
9522}
9523
9524/// Pick the opcode for one variable access.
9525///
9526/// The `_check` variants are what enforce the temporal dead zone. They are used
9527/// for every access to a `let`/`const` binding except its own initialisation —
9528/// which is exactly the operation that takes the binding out of the dead zone.
9529fn variable_instruction(
9530 stack: &[FnState],
9531 current: usize,
9532 action: VarAction,
9533 slot: Slot,
9534) -> (Opcode, Vec<Op>) {
9535 let lexical = match slot {
9536 Slot::Loc(index) => stack[current]
9537 .vars
9538 .get(index as usize)
9539 .is_some_and(|v| v.needs_check()),
9540 Slot::VarRef(index) => stack[current]
9541 .closure_vars
9542 .get(index as usize)
9543 .is_some_and(|c| c.is_lexical),
9544 _ => false,
9545 };
9546 let operand = vec![Op::Slot(slot)];
9547 // `make_*_ref` carries the name as well as the slot: the reference's runtime resolution
9548 // consults the names a direct `eval` has declared in this frame, which is a by-name
9549 // question, so the atom cannot be dropped. `variable_instruction` never sees the name, so
9550 // the caller patches operand 0 in (see `Compiler::emit_var`).
9551 //
9552 // Operand 1 is a *bare* slot index, not an `Op::Slot`: the opcode already says which
9553 // table it counts in, and `OpFormat::AtomU16`'s second operand is written by the plain
9554 // `u16` encoder, which an `Op::Slot` would silently skip — leaving the instruction two
9555 // bytes short and the whole stream desynchronised.
9556 let ref_slot = match slot {
9557 Slot::Arg(index)
9558 | Slot::Loc(index)
9559 | Slot::VarRef(index)
9560 | Slot::Global(index)
9561 | Slot::GlobalDecl(index) => index,
9562 };
9563 let ref_operand = vec![Op::AtomId(0), Op::Int(ref_slot as i32)];
9564 match (action, slot) {
9565 (VarAction::Get, Slot::Loc(index)) => (
9566 if lexical {
9567 Opcode::GetLocCheck
9568 } else {
9569 Opcode::GetLoc
9570 },
9571 vec![Op::Slot(Slot::Loc(index))],
9572 ),
9573 (VarAction::Get, Slot::Arg(index)) => (Opcode::GetArg, vec![Op::Slot(Slot::Arg(index))]),
9574 (VarAction::Get, Slot::VarRef(index)) => (
9575 if lexical {
9576 Opcode::GetVarRefCheck
9577 } else {
9578 Opcode::GetVarRef
9579 },
9580 vec![Op::Slot(Slot::VarRef(index))],
9581 ),
9582 (VarAction::Get, Slot::Global(_)) => (Opcode::GetVar, operand),
9583 (VarAction::Get, Slot::GlobalDecl(_)) => (Opcode::GetVar, operand),
9584 // `typeof x` is a *reading* of `x` (§13.5.3 evaluates the operand as a Reference and
9585 // then `GetValue`s it), so a lexical binding still has its dead zone checked. Only
9586 // the *unresolvable* case is different: `typeof undeclared` answers `"undefined"`
9587 // instead of throwing, and that is what `GetVarUndef` is for. Skipping the check for
9588 // every slot made `typeof x; let x;` print `"undefined"` where the spec requires a
9589 // `ReferenceError`.
9590 (VarAction::GetUndef, Slot::Loc(index)) => (
9591 if lexical {
9592 Opcode::GetLocCheck
9593 } else {
9594 Opcode::GetLoc
9595 },
9596 vec![Op::Slot(Slot::Loc(index))],
9597 ),
9598 (VarAction::GetUndef, Slot::Arg(_)) => (Opcode::GetArg, operand),
9599 (VarAction::GetUndef, Slot::VarRef(index)) => (
9600 if lexical {
9601 Opcode::GetVarRefCheck
9602 } else {
9603 Opcode::GetVarRef
9604 },
9605 vec![Op::Slot(Slot::VarRef(index))],
9606 ),
9607 (VarAction::GetUndef, Slot::Global(_) | Slot::GlobalDecl(_)) => {
9608 (Opcode::GetVarUndef, operand)
9609 }
9610
9611 (VarAction::Put, Slot::Loc(_)) => (
9612 if lexical {
9613 Opcode::PutLocCheck
9614 } else {
9615 Opcode::PutLoc
9616 },
9617 operand,
9618 ),
9619 (VarAction::Put, Slot::Arg(_)) => (Opcode::PutArg, operand),
9620 (VarAction::Put, Slot::VarRef(_)) => (
9621 if lexical {
9622 Opcode::PutVarRefCheck
9623 } else {
9624 Opcode::PutVarRef
9625 },
9626 operand,
9627 ),
9628 (VarAction::Put, Slot::Global(_)) => (Opcode::PutVar, operand),
9629 (VarAction::Put, Slot::GlobalDecl(_)) => (Opcode::PutVar, operand),
9630 // Initialisation is what ends the dead zone, so it never checks.
9631 (VarAction::PutInit, Slot::Loc(_)) => (Opcode::PutLoc, operand),
9632 (VarAction::PutInitChecked, Slot::Loc(_)) => (Opcode::PutLocCheckInit, operand),
9633 // `this` in a derived constructor is always a local, so these cannot happen;
9634 // routing them to the ordinary forms keeps the match total without inventing
9635 // opcodes the reference does not have.
9636 (VarAction::PutInitChecked, Slot::Arg(_)) => (Opcode::PutArg, operand),
9637 // The captured form of `PutLocCheckInit`: `super()` inside an arrow that closes over
9638 // the constructor's `this` still has to refuse a second initialisation, and the
9639 // plain store accepted it (`fields-run-once-on-double-super`).
9640 (VarAction::PutInitChecked, Slot::VarRef(_)) => (Opcode::PutVarRefCheckInit, operand),
9641 (VarAction::PutInitChecked, Slot::Global(_) | Slot::GlobalDecl(_)) => {
9642 (Opcode::PutVarInit, operand)
9643 }
9644 (VarAction::PutInit, Slot::Arg(_)) => (Opcode::PutArg, operand),
9645 (VarAction::PutInit, Slot::VarRef(_)) => (Opcode::PutVarRef, operand),
9646 (VarAction::PutInit, Slot::Global(_) | Slot::GlobalDecl(_)) => {
9647 (Opcode::PutVarInit, operand)
9648 }
9649 (VarAction::Set, Slot::Loc(_)) => (
9650 if lexical {
9651 Opcode::SetLocCheck
9652 } else {
9653 Opcode::SetLoc
9654 },
9655 operand,
9656 ),
9657 (VarAction::SetInit, Slot::Loc(_)) => (Opcode::SetLoc, operand),
9658 (VarAction::SetInit, Slot::Arg(_)) => (Opcode::SetArg, operand),
9659 (VarAction::SetInit, Slot::VarRef(_)) => (Opcode::SetVarRef, operand),
9660 (VarAction::SetInit, Slot::Global(_) | Slot::GlobalDecl(_)) => (Opcode::PutVar, operand),
9661 (VarAction::Set, Slot::Arg(_)) => (Opcode::SetArg, operand),
9662 (VarAction::Set, Slot::VarRef(_)) => (Opcode::SetVarRef, operand),
9663 (VarAction::Set, Slot::Global(_)) => (Opcode::PutVar, operand),
9664 (VarAction::Set, Slot::GlobalDecl(_)) => (Opcode::SetVarRef, operand),
9665 (VarAction::PutRef, Slot::Loc(_)) => (Opcode::PutLoc, operand),
9666 (VarAction::PutRef, Slot::Arg(_)) => (Opcode::PutArg, operand),
9667 (VarAction::PutRef, Slot::VarRef(_)) => (Opcode::PutVarRef, operand),
9668 (VarAction::PutRef, Slot::Global(_) | Slot::GlobalDecl(_)) => (Opcode::PutVarRef, operand),
9669 // A reference pins the binding so that one lvalue can be read and stored without
9670 // resolving the name in between. Which opcode builds it depends on where the
9671 // binding lives; the atom rides along because the *runtime* resolution can still
9672 // override the static answer — see `Interp::make_var_ref`.
9673 (VarAction::MakeRef, Slot::Loc(_)) => (Opcode::MakeLocRef, ref_operand),
9674 (VarAction::MakeRef, Slot::Arg(_)) => (Opcode::MakeArgRef, ref_operand),
9675 (VarAction::MakeRef, Slot::VarRef(_)) => (Opcode::MakeVarRefRef, ref_operand),
9676 (VarAction::MakeRef, Slot::Global(_) | Slot::GlobalDecl(_)) => {
9677 (Opcode::MakeVarRef, vec![ref_operand[0].clone()])
9678 }
9679 // Reading through a reference does not consult the binding at all — the reference
9680 // already points at it — so the slot plays no part.
9681 (VarAction::GetRef, _) => (Opcode::GetRefValue, Vec::new()),
9682 }
9683}
9684
9685/// The instruction-rewriting pass.
9686///
9687/// These are the reference implementation's patterns, restricted to the ones the
9688/// constructs this compiler supports can produce. Each entry is a comment on the
9689/// bytecode it removes, because the whole point is that the result is one
9690/// instruction shorter than the literal translation of the AST.
9691fn peephole(
9692 insns: &mut [Option<(Opcode, Vec<Op>)>],
9693 label_at: &[Option<u32>],
9694 placed: &[Option<usize>],
9695) {
9696 fold_dup_patterns(insns, label_at);
9697
9698 // `drop` before `return_undef` is dead: the return discards the whole frame
9699 // anyway. This runs *after* the `dup` folds, because a `dup; put; drop` there
9700 // consumes its own `drop`; removing the drop first would leave the `dup` and
9701 // produce a `set_` where the reference has a `put_`.
9702 for index in 0..insns.len() {
9703 if opcode_at(insns, index) != Some(Opcode::Drop) {
9704 continue;
9705 }
9706 // Skip over a run of drops, but stop at a jump target: removing code on
9707 // one side of a label would silently retarget the jump.
9708 let mut next = index + 1;
9709 while opcode_at(insns, next) == Some(Opcode::Drop) && !is_label_at(label_at, next) {
9710 next += 1;
9711 }
9712 if is_label_at(label_at, next) {
9713 continue;
9714 }
9715 if opcode_at(insns, next) == Some(Opcode::ReturnUndef) {
9716 for entry in &mut insns[index..next] {
9717 *entry = None;
9718 }
9719 }
9720 }
9721
9722 // The rewrites below all decide against one fixed snapshot, which is what the
9723 // reference sees: `code_match` reads the bytecode buffer as it was on entry to
9724 // the pass, so a rule never observes what an earlier rule removed. Gathering
9725 // every deletion first and applying them together reproduces that.
9726 let snapshot: Vec<Option<Opcode>> = insns
9727 .iter()
9728 .map(|entry| entry.as_ref().map(|(op, _)| *op))
9729 .collect();
9730 // The next instruction that is still there. Holes left by dead-code
9731 // elimination are not instructions, so a rule looks past them.
9732 let next_op = |index: usize| -> Option<usize> {
9733 (index + 1..snapshot.len()).find(|position| snapshot[*position].is_some())
9734 };
9735
9736 let mut doomed = vec![false; insns.len()];
9737 for index in 0..insns.len() {
9738 // A constant pushed only to be dropped does nothing at all. This is what a
9739 // comma expression with a literal left operand compiles to — `(0, f)()` — and
9740 // the reference removes the pair rather than making the reader step over it.
9741 let constant = matches!(
9742 snapshot[index],
9743 Some(
9744 Opcode::Undefined
9745 | Opcode::Null
9746 | Opcode::PushMinus1
9747 | Opcode::Push0
9748 | Opcode::Push1
9749 | Opcode::Push2
9750 | Opcode::Push3
9751 | Opcode::Push4
9752 | Opcode::Push5
9753 | Opcode::Push6
9754 | Opcode::Push7
9755 | Opcode::PushTrue
9756 | Opcode::PushFalse
9757 | Opcode::PushI32
9758 )
9759 );
9760 if constant
9761 && let Some(next) = next_op(index)
9762 && snapshot[next] == Some(Opcode::Drop)
9763 {
9764 doomed[index] = true;
9765 doomed[next] = true;
9766 }
9767 }
9768 for (index, entry) in insns.iter_mut().enumerate() {
9769 if doomed[index] {
9770 *entry = None;
9771 }
9772 }
9773
9774 // A conditional whose destination is the very next instruction just pops its
9775 // condition, so it becomes a plain `drop`. This is what an empty `case` clause
9776 // compiles to.
9777 //
9778 // Order matters, and it is the reference's order: this runs *before* the
9779 // folding below, on the instruction the conditional originally had. Folding
9780 // moves a conditional's destination, and the reference never re-examines it
9781 // afterwards — which is why `if (c) continue;` at the end of a `do` body stays
9782 // a conditional even though folding leaves it pointing at the next
9783 // instruction.
9784 for (index, entry) in insns.iter_mut().enumerate() {
9785 let Some((op, operands)) = entry.clone() else {
9786 continue;
9787 };
9788 if !matches!(op, Opcode::IfTrue | Opcode::IfFalse) {
9789 continue;
9790 }
9791 let Some(id) = label_id(&operands) else {
9792 continue;
9793 };
9794 if placed.get(id as usize).copied().flatten() == Some(index + 1) {
9795 *entry = Some((Opcode::Drop, Vec::new()));
9796 }
9797 }
9798
9799 // A constant condition is decided here rather than at run time.
9800 fold_constant_conditions(insns, label_at);
9801 // The conditional folding below is about pairs of *real* branches, so it runs
9802 // before a jump to the next instruction is dropped: `do { … if (c) continue }
9803 // while (t)` puts `continue` exactly on the condition, and the reference inverts
9804 // the branch first and only then notices the jump goes nowhere.
9805 fold_conditional_jumps(insns, label_at, placed);
9806
9807 // A jump whose destination is the very next instruction does nothing, which is
9808 // what constant folding leaves behind for `while (1) { … }`.
9809 remove_jump_to_next(insns, placed);
9810
9811 // `put_x(n) get_x(n)` -> `set_x(n)`, which is what a declaration followed by
9812 // a use of the same variable boils down to.
9813 for index in 0..insns.len() {
9814 let Some((put_op, _)) = insns[index].clone() else {
9815 continue;
9816 };
9817 if !is_foldable_put(put_op) {
9818 continue;
9819 }
9820 if is_label_at(label_at, index + 1) {
9821 continue;
9822 }
9823 let Some((get_op, get_operands)) = insns.get(index + 1).cloned().flatten() else {
9824 continue;
9825 };
9826 if get_op != get_form_of(put_op) {
9827 continue;
9828 }
9829 let put_slot = insns[index].as_ref().and_then(|(_, o)| o.first().cloned());
9830 if put_slot.is_none() || put_slot != get_operands.first().cloned() {
9831 continue;
9832 }
9833 insns[index] = Some((set_form_of(put_op), get_operands));
9834 insns[index + 1] = None;
9835 }
9836}
9837
9838/// Drop `gosub`s that call an empty subroutine.
9839///
9840/// A `gosub` whose target starts with `ret` returns immediately, so the reference
9841/// drops the call. This is how `try`/`catch` without a `finally` loses its
9842/// finalizer plumbing: the finalizer block is empty, its first instruction is
9843/// `ret`, and every `gosub` to it disappears — leaving the `ret` unreachable, which
9844/// [`eliminate_dead_code`] then removes.
9845fn strip_empty_gosubs(stack: &mut [FnState], current: usize) {
9846 let state = &stack[current];
9847 let mut targets = Vec::new();
9848 for insn in &state.insns {
9849 if let Insn::Fixed { op, operands } = insn
9850 && *op == Opcode::Gosub
9851 && let Some(id) = label_id(operands)
9852 && let Some(target) = state.labels.get(id as usize).copied().flatten()
9853 {
9854 targets.push(target);
9855 }
9856 }
9857 let empty: Vec<usize> = targets
9858 .into_iter()
9859 .filter(|target| {
9860 stack[current]
9861 .insns
9862 .get(*target)
9863 .map(|insn| {
9864 matches!(
9865 insn,
9866 Insn::Fixed {
9867 op: Opcode::Ret,
9868 ..
9869 }
9870 )
9871 })
9872 .unwrap_or(false)
9873 })
9874 .collect();
9875 if empty.is_empty() {
9876 return;
9877 }
9878 for insn in stack[current].insns.iter_mut() {
9879 if let Insn::Fixed { op, operands } = insn
9880 && *op == Opcode::Gosub
9881 && let Some(id) = label_id(operands)
9882 && let Some(target) = stack[current].labels.get(id as usize).copied().flatten()
9883 && empty.contains(&target)
9884 {
9885 *insn = Insn::Dead;
9886 }
9887 }
9888}
9889
9890/// Replace unreachable instructions with [`Insn::Dead`].
9891fn eliminate_dead_code(stack: &mut [FnState], current: usize) {
9892 let reachable = reachable_instructions(&stack[current], stack[current].insns.len());
9893 for (index, insn) in stack[current].insns.iter_mut().enumerate() {
9894 if !reachable[index] {
9895 *insn = Insn::Dead;
9896 }
9897 }
9898}
9899
9900/// Mark every instruction index reachable from the entry, plus the index one past
9901/// the last instruction.
9902///
9903/// `seen[len]` answers "can control reach the end of this function", and the
9904/// entries before it identify dead code. Both DCE and the implicit-return decision
9905/// read the same result, which keeps them from disagreeing.
9906fn reachable_instructions(state: &FnState, count: usize) -> Vec<bool> {
9907 let mut seen = vec![false; count + 1];
9908 let mut worklist = vec![0usize];
9909 while let Some(index) = worklist.pop() {
9910 if index > count || seen[index] {
9911 continue;
9912 }
9913 seen[index] = true;
9914 if index == count {
9915 continue;
9916 }
9917 let (op, operands) = match &state.insns[index] {
9918 Insn::Fixed { op, operands } => (*op, operands.as_slice()),
9919 // A variable access never transfers control, and a removed
9920 // instruction is only reachable if it is already marked.
9921 Insn::Var { .. } | Insn::CloseCaptured { .. } | Insn::DeleteVar { .. } | Insn::Dead => {
9922 worklist.push(index + 1);
9923 continue;
9924 }
9925 };
9926 match op {
9927 // A return, a throw and a `ret` all leave this instruction stream: the
9928 // first two give control to the caller or the handler, and `ret`
9929 // returns to a `gosub` elsewhere.
9930 // A tail call leaves the function too: the callee's result becomes this
9931 // function's result, so nothing after it runs.
9932 Opcode::Return
9933 | Opcode::ReturnUndef
9934 | Opcode::ReturnAsync
9935 | Opcode::TailCall
9936 | Opcode::TailCallMethod
9937 | Opcode::Throw
9938 | Opcode::ThrowError
9939 | Opcode::Ret => {}
9940 // A `catch` records where exceptions from the code that follows go.
9941 // That code is not reachable through normal control flow, but it is
9942 // reachable — through the exception edge — so the walk has to follow
9943 // it, or dead-code elimination would delete every handler.
9944 Opcode::Catch => {
9945 if let Some(target) = placed_label(state, operands) {
9946 worklist.push(target);
9947 }
9948 worklist.push(index + 1);
9949 }
9950 // A `gosub` calls a subroutine and then continues, so both edges count.
9951 Opcode::Gosub => {
9952 if let Some(target) = placed_label(state, operands) {
9953 worklist.push(target);
9954 }
9955 worklist.push(index + 1);
9956 }
9957 Opcode::Goto => {
9958 if let Some(target) = placed_label(state, operands) {
9959 worklist.push(target);
9960 }
9961 }
9962 Opcode::IfTrue | Opcode::IfFalse => {
9963 if let Some(target) = placed_label(state, operands) {
9964 worklist.push(target);
9965 }
9966 worklist.push(index + 1);
9967 }
9968 _ => worklist.push(index + 1),
9969 }
9970 }
9971 seen
9972}
9973
9974/// The instruction index a jump operand points at, resolved through the label
9975/// placement table.
9976fn placed_label(state: &FnState, operands: &[Op]) -> Option<usize> {
9977 let id = label_id(operands)?;
9978 state.labels.get(id as usize).copied().flatten()
9979}
9980
9981/// The label an instruction refers to.
9982fn label_id(operands: &[Op]) -> Option<u32> {
9983 operands.iter().find_map(|operand| match operand {
9984 Op::Label(label) => Some(label.0),
9985 _ => None,
9986 })
9987}
9988
9989/// Turn `if_false L; goto M; L:` into `if_true M`.
9990///
9991/// A conditional whose alternate branch is an unconditional jump needs one jump,
9992/// not two. This is the shape `if (c) break;` produces, so folding it removes an
9993/// instruction and a label from every conditional `break`.
9994/// The boolean a constant-push instruction produces, or `None` if it is not one.
9995///
9996/// Only the operators whose truthiness is decided by the opcode are covered; a
9997/// constant that needs the constant pool (a string) is left alone, because reading it
9998/// would mean threading the pool through the peephole for a case the reference also
9999/// skips.
10000fn constant_truth(op: Opcode, operands: &[Op]) -> Option<bool> {
10001 match op {
10002 // `push_0` returns -1 for zero, `push_1` 1, and so on.
10003 Opcode::PushMinus1 => Some(true),
10004 Opcode::Push0 => Some(false),
10005 Opcode::Push1
10006 | Opcode::Push2
10007 | Opcode::Push3
10008 | Opcode::Push4
10009 | Opcode::Push5
10010 | Opcode::Push6
10011 | Opcode::Push7 => Some(true),
10012 Opcode::PushTrue => Some(true),
10013 Opcode::PushFalse => Some(false),
10014 Opcode::Undefined | Opcode::Null => Some(false),
10015 Opcode::PushI32 => match operands.first() {
10016 Some(Op::Int(value)) => Some(*value != 0),
10017 _ => None,
10018 },
10019 _ => None,
10020 }
10021}
10022
10023/// Fold a branch on a constant condition.
10024///
10025/// `if (0) a() else b()` must not test anything at run time, and the reference
10026/// compiles it to a plain `goto`. Removing the test also removes the unreachable arm,
10027/// which is why the bytecode for a `while (1)` loop has no condition at all.
10028///
10029/// Two instructions become one, so the slot the test occupied is left empty rather
10030/// than shifting everything after it: labels have already been resolved to indices.
10031fn fold_constant_conditions(insns: &mut [Option<(Opcode, Vec<Op>)>], label_at: &[Option<u32>]) {
10032 for index in 0..insns.len() {
10033 let Some((push_op, push_operands)) = insns[index].clone() else {
10034 continue;
10035 };
10036 let Some(truth) = constant_truth(push_op, &push_operands) else {
10037 continue;
10038 };
10039 let Some((branch_op, branch_operands)) = insns.get(index + 1).cloned().flatten() else {
10040 continue;
10041 };
10042 // A label on the branch means something else jumps *here* — the value is on the
10043 // stack and the conditional is what pops it. Deleting the branch would leave that
10044 // jump with no instruction, and a label whose slot is empty resolves to the next
10045 // one that is not, i.e. to the far side of the branch. That is how
10046 // `if (a && false) then else` jumped to `then`: `&&` ends its chain on a label, and
10047 // the constant `false` sits directly in front of the statement's own conditional.
10048 if is_label_at(label_at, index + 1) {
10049 continue;
10050 }
10051 let (destination, taken) = match branch_op {
10052 Opcode::IfTrue => (branch_operands.first().cloned(), truth),
10053 Opcode::IfFalse => (branch_operands.first().cloned(), !truth),
10054 _ => continue,
10055 };
10056 let Some(destination) = destination else {
10057 continue;
10058 };
10059 insns[index] = if taken {
10060 // The branch is always taken, so it becomes an unconditional jump.
10061 Some((Opcode::Goto, vec![destination]))
10062 } else {
10063 // The branch never runs: both instructions disappear and control falls
10064 // through to what came after.
10065 None
10066 };
10067 insns[index + 1] = None;
10068 }
10069}
10070
10071/// Remove a jump whose destination is the instruction right after it.
10072///
10073/// Folding a constant condition leaves these behind often: `while (1) { ... }` turns
10074/// its test into nothing, and the loop-end jump then points at the following
10075/// instruction. The reference drops them, so `stack_size` and the listing agree.
10076fn remove_jump_to_next(insns: &mut [Option<(Opcode, Vec<Op>)>], placed: &[Option<usize>]) {
10077 for index in 0..insns.len() {
10078 let Some((op, operands)) = insns[index].clone() else {
10079 continue;
10080 };
10081 if !is_goto(op) {
10082 continue;
10083 }
10084 let Some(id) = label_id(&operands) else {
10085 continue;
10086 };
10087 // The next instruction that still exists, which is what "the instruction
10088 // after this jump" means once earlier folds have punched holes.
10089 let next = (index + 1..insns.len()).find(|position| insns[*position].is_some());
10090 if placed.get(id as usize).copied().flatten() == next {
10091 insns[index] = None;
10092 }
10093 }
10094}
10095
10096fn fold_conditional_jumps(
10097 insns: &mut [Option<(Opcode, Vec<Op>)>],
10098 label_at: &[Option<u32>],
10099 placed: &[Option<usize>],
10100) {
10101 for index in 0..insns.len() {
10102 let Some((op, operands)) = insns[index].clone() else {
10103 continue;
10104 };
10105 let inverted = match op {
10106 Opcode::IfFalse => Opcode::IfTrue,
10107 Opcode::IfTrue => Opcode::IfFalse,
10108 _ => continue,
10109 };
10110 // Next must be an unconditional jump that is not itself a target, and the
10111 // instruction after it must be exactly where the conditional goes.
10112 let Some((next_op, next_operands)) = insns.get(index + 1).cloned().flatten() else {
10113 continue;
10114 };
10115 if !is_goto(next_op) || is_label_at(label_at, index + 1) {
10116 continue;
10117 }
10118 // The conditional must land on the instruction *after* the jump. Several
10119 // labels can share a position, so this asks where *this* label was put
10120 // rather than what label happens to sit there.
10121 let Some(taken) = label_id(&operands) else {
10122 continue;
10123 };
10124 if placed.get(taken as usize).copied().flatten() != Some(index + 2) {
10125 continue;
10126 }
10127 let Some(destination) = next_operands.first().cloned() else {
10128 continue;
10129 };
10130 insns[index] = Some((inverted, vec![destination]));
10131 insns[index + 1] = None;
10132 }
10133}
10134
10135/// Whether a jump target is placed at this instruction index.
10136fn is_label_at(label_at: &[Option<u32>], index: usize) -> bool {
10137 label_at.get(index).copied().flatten().is_some()
10138}
10139
10140fn fold_dup_patterns(insns: &mut [Option<(Opcode, Vec<Op>)>], label_at: &[Option<u32>]) {
10141 // `dup put_x(n)` -> `set_x(n)`
10142 // `dup put_x(n) drop` -> `put_x(n)`
10143 // `dup put_x(n) drop get_x(n)` -> `set_x(n)`
10144 for index in 0..insns.len() {
10145 if opcode_at(insns, index) != Some(Opcode::Dup) {
10146 continue;
10147 }
10148 if is_label_at(label_at, index + 1) {
10149 continue;
10150 }
10151 let Some((put_op, put_operands)) = insns[index + 1].clone() else {
10152 continue;
10153 };
10154 if !is_foldable_put(put_op) {
10155 continue;
10156 }
10157 let Some(Op::Slot(slot)) = put_operands.first().cloned() else {
10158 continue;
10159 };
10160 let mut new_op = set_form_of(put_op);
10161 let mut end = index + 2;
10162 if is_label_at(label_at, end) {
10163 // The `put` has to stay as it is; only the `dup` can be folded.
10164 insns[index] = Some((set_form_of(put_op), vec![Op::Slot(slot)]));
10165 insns[index + 1] = None;
10166 continue;
10167 }
10168 // A `drop` or a `get` that is the target of a jump must stay exactly where it is.
10169 // Deleting it moves the label's target onto whatever follows, and the code that
10170 // jumps there arrives with a different stack than the fall-through path: that is
10171 // how `p = "x"; if (c) { p = "a"; } return p;` came to return `undefined` — the
10172 // `get_x` the `if` jumped to was folded away, so the jump landed on `return` with
10173 // an empty stack. The store had already consumed the value it was supposed to
10174 // leave behind.
10175 if opcode_at(insns, end) == Some(Opcode::Drop) && !is_label_at(label_at, end) {
10176 new_op = put_op;
10177 end += 1;
10178 if opcode_at(insns, end) == Some(get_form_of(put_op))
10179 && !is_label_at(label_at, end)
10180 && insns[end]
10181 .as_ref()
10182 .is_some_and(|(_, operands)| operands.first() == Some(&Op::Slot(slot)))
10183 {
10184 new_op = set_form_of(put_op);
10185 end += 1;
10186 }
10187 }
10188 insns[index] = Some((new_op, vec![Op::Slot(slot)]));
10189 for entry in &mut insns[index + 1..end] {
10190 *entry = None;
10191 }
10192 }
10193}
10194
10195fn opcode_at(insns: &[Option<(Opcode, Vec<Op>)>], index: usize) -> Option<Opcode> {
10196 insns
10197 .get(index)
10198 .and_then(|entry| entry.as_ref())
10199 .map(|(op, _)| *op)
10200}
10201
10202/// The four `put_` families that have a `set_` twin. Deliberately not including
10203/// the global forms or `put_var_ref_check`: the reference's peephole lists exactly
10204/// these, and folding the others would produce instructions that do not exist.
10205fn is_foldable_put(op: Opcode) -> bool {
10206 matches!(
10207 op,
10208 Opcode::PutLoc | Opcode::PutLocCheck | Opcode::PutArg | Opcode::PutVarRef
10209 )
10210}
10211
10212fn set_form_of(op: Opcode) -> Opcode {
10213 match op {
10214 Opcode::PutLoc => Opcode::SetLoc,
10215 Opcode::PutLocCheck => Opcode::SetLocCheck,
10216 Opcode::PutArg => Opcode::SetArg,
10217 Opcode::PutVarRef => Opcode::SetVarRef,
10218 other => other,
10219 }
10220}
10221
10222fn get_form_of(op: Opcode) -> Opcode {
10223 match op {
10224 Opcode::PutLoc => Opcode::GetLoc,
10225 Opcode::PutLocCheck => Opcode::GetLocCheck,
10226 Opcode::PutArg => Opcode::GetArg,
10227 Opcode::PutVarRef => Opcode::GetVarRef,
10228 other => other,
10229 }
10230}
10231
10232/// Atom interning, per function.
10233///
10234/// Everything the reference interns goes through `JS_NewAtomStr`, including plain
10235/// identifiers, so the array-index rule applies here rather than at the handful of
10236/// call sites that build property keys.
10237fn intern_atom(state: &mut FnState, name: &str) -> u32 {
10238 intern_atom_value(state, Atom::from_text(name))
10239}
10240
10241/// [`intern_atom`] for an operand that is already an [`Atom`].
10242///
10243/// Separate because `Atom::Null` has no text form: going through `Display` turned it into
10244/// the *string* `"null"`, which is what `throw_error` printed and what a `delete super.x`
10245/// would have looked up.
10246fn intern_atom_value(state: &mut FnState, atom: Atom) -> u32 {
10247 if let Some(index) = state.atoms.iter().position(|a| *a == atom) {
10248 return index as u32;
10249 }
10250 state.atoms.push(atom);
10251 state.atoms.len() as u32 - 1
10252}
10253
10254fn binary_opcode(op: BinaryOp) -> Opcode {
10255 match op {
10256 BinaryOp::Add => Opcode::Add,
10257 BinaryOp::Sub => Opcode::Sub,
10258 BinaryOp::Mul => Opcode::Mul,
10259 BinaryOp::Div => Opcode::Div,
10260 BinaryOp::Mod => Opcode::Mod,
10261 BinaryOp::Pow => Opcode::Pow,
10262 BinaryOp::BitOr => Opcode::Or,
10263 BinaryOp::BitXor => Opcode::Xor,
10264 BinaryOp::BitAnd => Opcode::And,
10265 BinaryOp::Shl => Opcode::Shl,
10266 BinaryOp::Shr => Opcode::Sar,
10267 BinaryOp::UShr => Opcode::Shr,
10268 BinaryOp::Lt => Opcode::Lt,
10269 BinaryOp::LtEq => Opcode::Lte,
10270 BinaryOp::Gt => Opcode::Gt,
10271 BinaryOp::GtEq => Opcode::Gte,
10272 BinaryOp::Eq => Opcode::Eq,
10273 BinaryOp::NotEq => Opcode::Neq,
10274 BinaryOp::StrictEq => Opcode::StrictEq,
10275 BinaryOp::StrictNotEq => Opcode::StrictNeq,
10276 BinaryOp::In => Opcode::In,
10277 BinaryOp::Instanceof => Opcode::Instanceof,
10278 }
10279}
10280
10281fn compound_opcode(op: AssignOp) -> Opcode {
10282 match op {
10283 AssignOp::Add => Opcode::Add,
10284 AssignOp::Sub => Opcode::Sub,
10285 AssignOp::Mul => Opcode::Mul,
10286 AssignOp::Div => Opcode::Div,
10287 AssignOp::Mod => Opcode::Mod,
10288 AssignOp::Pow => Opcode::Pow,
10289 AssignOp::Shl => Opcode::Shl,
10290 AssignOp::Shr => Opcode::Sar,
10291 AssignOp::UShr => Opcode::Shr,
10292 AssignOp::BitOr => Opcode::Or,
10293 AssignOp::BitXor => Opcode::Xor,
10294 AssignOp::BitAnd => Opcode::And,
10295 AssignOp::Assign | AssignOp::And | AssignOp::Or | AssignOp::Coalesce => Opcode::Nop,
10296 }
10297}
10298
10299/// Encode the resolved instruction stream, choosing short forms where possible.
10300///
10301/// The peephole pass leaves holes in the instruction list so that label indices
10302/// stay valid. A label names an *instruction index*, and an index that was
10303/// deleted has to resolve to the next surviving instruction, which is what
10304/// [`resolve_label`] does before the byte offsets are known.
10305fn assemble(
10306 insns: &mut [Option<(Opcode, Vec<Op>)>],
10307 insn_pos: &[Option<Position>],
10308 state: &mut FnState,
10309) -> (Vec<u8>, u32, Vec<LineCol>) {
10310 // Compaction: surviving instructions in order, plus the index mapping.
10311 //
10312 // `spans` runs parallel to `kept` and is compacted in lock step with it, at every
10313 // point below where instructions are removed — otherwise a stack trace would point
10314 // at the wrong source line as soon as dead-code elimination kicked in.
10315 let mut kept: Vec<(Opcode, Vec<Op>)> = Vec::with_capacity(insns.len());
10316 let mut spans: Vec<Option<Position>> = Vec::with_capacity(insns.len());
10317 let mut original_to_kept: Vec<Option<usize>> = vec![None; insns.len()];
10318 for (original, entry) in insns.iter_mut().enumerate() {
10319 if let Some((op, operands)) = entry.take() {
10320 original_to_kept[original] = Some(kept.len());
10321 kept.push((op, operands));
10322 spans.push(insn_pos.get(original).copied().flatten());
10323 }
10324 }
10325
10326 if std::env::var_os("QJS_DEBUG").is_some() {
10327 eprintln!("--- assemble entry --- {kept:?}");
10328 }
10329 // How many labels are real, as opposed to the per-instruction ones allocated
10330 // just below. Only a real label marks a spot in the source program.
10331 let real_labels = state.labels.len();
10332
10333 // Give every surviving instruction a label of its own. Jump cleanup below
10334 // redirects jumps to arbitrary instructions, and a jump target has to be a
10335 // label; pre-allocating one per index means a redirect never has to invent
10336 // anything.
10337 let existing = state.labels.len();
10338 let base = kept.len();
10339 let mut index_label: Vec<Label> = Vec::with_capacity(kept.len() + 1);
10340 for offset in 0..=kept.len() {
10341 state.labels.push(Some(0));
10342 index_label.push(Label((existing + offset) as u32));
10343 }
10344 // Point each pre-allocated label at its instruction, reusing the count from
10345 // `original_to_kept` so the mapping survives compaction.
10346 let place_index_labels = |state: &mut FnState,
10347 original_to_kept: &[Option<usize>],
10348 kept_len: usize,
10349 index_label: &[Label]| {
10350 for (original, mapped) in original_to_kept.iter().enumerate() {
10351 if let Some(kept_index) = mapped {
10352 let label = index_label[*kept_index].0 as usize;
10353 state.labels[label] = Some(original);
10354 }
10355 }
10356 state.labels[index_label[kept_len].0 as usize] = Some(usize::MAX);
10357 };
10358 place_index_labels(state, &original_to_kept, base, &index_label);
10359
10360 // Resolve every label to a kept index once; the placement table maps labels
10361 // to original indices, so a second hop lands in kept space.
10362 let mut label_kept: Vec<Option<usize>> = vec![None; state.labels.len()];
10363 for (id, placed) in state.labels.iter().enumerate() {
10364 let Some(original) = placed else { continue };
10365 label_kept[id] = if *original == usize::MAX {
10366 Some(base)
10367 } else {
10368 (*original..original_to_kept.len()).find_map(|i| original_to_kept[i])
10369 };
10370 }
10371
10372 // Code after an unconditional transfer is unreachable, and the reference drops it
10373 // as it walks past the transfer — the `skip_dead_code` in its first pass. It
10374 // scans forward until it finds a label something still jumps to, so a run of
10375 // dead instructions between a `throw` and the next live target disappears.
10376 //
10377 // The scan repeats because dropping a jump lowers the reference count of the
10378 // label it pointed at, which can strand what follows. Only a real label keeps an
10379 // instruction alive here; the per-instruction labels allocated above belong to
10380 // this pass, not to the program.
10381 loop {
10382 let mut references = vec![false; kept.len() + 1];
10383 for (_, operands) in &kept {
10384 if let Some(target) = target_kept_index(operands, &label_kept)
10385 && target < references.len()
10386 {
10387 references[target] = true;
10388 }
10389 }
10390 let mut doomed = vec![false; kept.len()];
10391 let mut any = false;
10392 for (index, (op, _)) in kept.iter().enumerate() {
10393 if !is_transfer(*op) {
10394 continue;
10395 }
10396 for next in index + 1..kept.len() {
10397 if references[next] {
10398 break;
10399 }
10400 doomed[next] = true;
10401 any = true;
10402 }
10403 }
10404 if !any {
10405 break;
10406 }
10407 (kept, spans) = drop_instructions(kept, spans, &mut label_kept, &doomed);
10408 }
10409
10410 // A label that lands on an unconditional jump stands for wherever that jump
10411 // goes, so retarget it once and every jump to the label follows for free.
10412 // This is what makes `continue` in a `for` head reach the loop top instead of
10413 // stopping at the update's trailing jump.
10414 let folded: Vec<Option<usize>> = label_kept
10415 .iter()
10416 .map(|slot| slot.map(|target| follow_jump_chain(&kept, &label_kept, target)))
10417 .collect();
10418 label_kept = folded;
10419
10420 // Jump cleanup, in compacted index space. Two rewrites the reference also
10421 // applies while it resolves labels:
10422 // * a jump whose destination is the very next instruction does nothing;
10423 // * a jump to a jump is redirected to its final destination.
10424 // The second can expose the first, so this repeats until it settles.
10425 loop {
10426 let mut delete = vec![false; kept.len()];
10427 let mut changed = false;
10428 for index in 0..kept.len() {
10429 let (op, operands) = &kept[index];
10430 if !is_goto(*op) {
10431 continue;
10432 }
10433 let Some(immediate) = target_kept_index(operands, &label_kept) else {
10434 continue;
10435 };
10436 let target = follow_jump_chain(&kept, &label_kept, immediate);
10437 if target == index + 1 {
10438 delete[index] = true;
10439 changed = true;
10440 } else if matches!(
10441 kept.get(target).map(|(op, _)| *op),
10442 Some(Opcode::Return | Opcode::ReturnUndef | Opcode::Throw)
10443 ) {
10444 // Jumping straight to a return or throw is the same as doing it
10445 // here, so the jump becomes that instruction.
10446 kept[index] = (kept[target].0, Vec::new());
10447 changed = true;
10448 } else if target != immediate {
10449 // Redirect to the end of the chain.
10450 let label = index_label[target];
10451 kept[index].1 = vec![Op::Label(label)];
10452 changed = true;
10453 }
10454 }
10455 if !changed {
10456 break;
10457 }
10458 if !delete.iter().any(|deleted| *deleted) {
10459 break;
10460 }
10461 // Drop the deleted instructions and renumber everything.
10462 let mut next: Vec<(Opcode, Vec<Op>)> = Vec::with_capacity(kept.len());
10463 let mut next_spans: Vec<Option<Position>> = Vec::with_capacity(kept.len());
10464 let mut moved: Vec<Option<usize>> = vec![None; kept.len()];
10465 for (old, entry) in kept.into_iter().enumerate() {
10466 if delete[old] {
10467 continue;
10468 }
10469 moved[old] = Some(next.len());
10470 next.push(entry);
10471 next_spans.push(spans[old]);
10472 }
10473 for (id, slot) in label_kept.iter_mut().enumerate() {
10474 let Some(old) = *slot else { continue };
10475 *slot = match moved.get(old).copied().flatten() {
10476 Some(new) => Some(new),
10477 // The target was deleted: the jump now lands on whatever follows.
10478 None => (old..moved.len())
10479 .find_map(|i| moved[i])
10480 .or(Some(next.len())),
10481 };
10482 let _ = id;
10483 }
10484 kept = next;
10485 spans = next_spans;
10486 }
10487
10488 // The same walk at the end of the function: `try`/`catch`'s `goto end` becomes a
10489 // jump to the next instruction and is deleted, leaving the label at the end with
10490 // nothing pointing at it. If that also strands the last instruction, it goes
10491 // too — which is how a `try` whose body always returns ends on its `ret` rather
10492 // than an implicit `return_undef`.
10493 // Which instructions something still jumps to. Reading the surviving jumps is
10494 // what the reference's reference counts amount to: once a jump has been folded
10495 // away the label it named is unreferenced, even though the program still has a
10496 // label there.
10497 let mut references = vec![false; kept.len() + 1];
10498 let _ = real_labels;
10499 for (_, operands) in &kept {
10500 if let Some(target) = target_kept_index(operands, &label_kept)
10501 && target < references.len()
10502 {
10503 references[target] = true;
10504 }
10505 }
10506 let mut end = kept.len();
10507 while end > 0 {
10508 let last = end - 1;
10509 let reachable = references[last] || end < kept.len();
10510 if reachable {
10511 break;
10512 }
10513 let after_transfer = last
10514 .checked_sub(1)
10515 .map(|previous| {
10516 matches!(
10517 kept[previous].0,
10518 Opcode::Goto | Opcode::Return | Opcode::ReturnUndef | Opcode::Throw
10519 )
10520 })
10521 .unwrap_or(false);
10522 if !after_transfer {
10523 break;
10524 }
10525 end = last;
10526 }
10527 kept.truncate(end);
10528 spans.truncate(end);
10529
10530 // Choose an opcode for each instruction and its size, so label offsets can be
10531 // computed.
10532 let chosen = choose_opcodes(&kept, &label_kept);
10533 let offsets = instruction_offsets(&chosen);
10534 let offset = *offsets.last().unwrap_or(&0);
10535
10536 let mut code = Vec::with_capacity(offset);
10537 for (position, (_, operands)) in kept.iter().enumerate() {
10538 let op = chosen[position];
10539 code.push(op as u8);
10540 let operands = retarget_labels(operands, &label_kept, kept.len());
10541 encode_operands(&mut code, op, &operands, offsets[position], &offsets);
10542 }
10543 let stack_size = compute_stack_size(&code);
10544 // Keep only the offsets where the position actually changes: a run of
10545 // instructions on one line is one table entry, and the runtime binary searches
10546 // the table for the frame's pc.
10547 //
10548 // The table always starts at pc 0 with the *function's own* position, because the
10549 // reference's `compute_pc2line_info` seeds it that way: `dbuf_put_leb128(&s->pc2line,
10550 // last_line_num)` from `fd->source_pos`, the token the function definition starts at
10551 // (`function`, `async`, a method's property name). An instruction before the first
10552 // recorded operator therefore reports the function's own start, which is what makes a
10553 // `using` epilogue with a plain initialiser report `1:2` rather than nothing at all.
10554 let mut positions: Vec<LineCol> = vec![LineCol {
10555 pc: 0,
10556 line: state.line,
10557 column: state.column,
10558 }];
10559 let mut last: Option<Position> = None;
10560 for (index, span) in spans.iter().enumerate() {
10561 let Some(pos) = *span else { continue };
10562 if last == Some(pos) {
10563 continue;
10564 }
10565 last = Some(pos);
10566 if pos.line == state.line && pos.column == state.column {
10567 // Already the seed entry above.
10568 continue;
10569 }
10570 positions.push(LineCol {
10571 pc: offsets[index] as u32,
10572 line: pos.line,
10573 column: pos.column,
10574 });
10575 }
10576 (code, stack_size, positions)
10577}
10578
10579/// Whether an instruction always transfers control away, so anything after it in the
10580/// same stream is unreachable.
10581fn is_transfer(op: Opcode) -> bool {
10582 matches!(
10583 op,
10584 Opcode::Goto
10585 | Opcode::Goto8
10586 | Opcode::Goto16
10587 | Opcode::Return
10588 | Opcode::ReturnUndef
10589 | Opcode::Throw
10590 | Opcode::ThrowError
10591 | Opcode::Ret
10592 )
10593}
10594
10595/// Remove the marked instructions and renumber the label table so it keeps pointing
10596/// at the same instructions. A label whose instruction went away moves to whatever
10597/// follows it, since a jump is never left with nowhere to land.
10598fn drop_instructions(
10599 kept: Vec<(Opcode, Vec<Op>)>,
10600 spans: Vec<Option<Position>>,
10601 label_kept: &mut [Option<usize>],
10602 doomed: &[bool],
10603) -> (Vec<PositionedInsn>, Vec<Option<Position>>) {
10604 let mut result: Vec<(Opcode, Vec<Op>)> = Vec::with_capacity(kept.len());
10605 let mut result_spans: Vec<Option<Position>> = Vec::with_capacity(kept.len());
10606 let mut moved: Vec<Option<usize>> = vec![None; kept.len()];
10607 for (old, entry) in kept.into_iter().enumerate() {
10608 if doomed.get(old).copied().unwrap_or(false) {
10609 continue;
10610 }
10611 moved[old] = Some(result.len());
10612 result.push(entry);
10613 result_spans.push(spans[old]);
10614 }
10615 for slot in label_kept.iter_mut() {
10616 let Some(old) = *slot else { continue };
10617 *slot = match moved.get(old).copied().flatten() {
10618 Some(new) => Some(new),
10619 None => (old..moved.len())
10620 .find_map(|i| moved[i])
10621 .or(Some(result.len())),
10622 };
10623 }
10624 (result, result_spans)
10625}
10626
10627fn is_goto(op: Opcode) -> bool {
10628 matches!(op, Opcode::Goto | Opcode::Goto8 | Opcode::Goto16)
10629}
10630
10631/// The kept index a jump operand points at.
10632fn target_kept_index(operands: &[Op], label_kept: &[Option<usize>]) -> Option<usize> {
10633 let id = label_id(operands)?;
10634 label_kept.get(id as usize).copied().flatten()
10635}
10636
10637/// Follow a chain of unconditional jumps to its first real destination.
10638fn follow_jump_chain(
10639 kept: &[(Opcode, Vec<Op>)],
10640 label_kept: &[Option<usize>],
10641 start: usize,
10642) -> usize {
10643 let mut current = start;
10644 // `for(;;)` jumps to itself, so the walk has to be bounded.
10645 for _ in 0..kept.len() {
10646 let Some((op, operands)) = kept.get(current) else {
10647 return current;
10648 };
10649 if !is_goto(*op) {
10650 return current;
10651 }
10652 let Some(next) = target_kept_index(operands, label_kept) else {
10653 return current;
10654 };
10655 if next == current {
10656 return current;
10657 }
10658 current = next;
10659 }
10660 current
10661}
10662
10663/// Rewrite label operands from label ids to kept instruction indices.
10664fn retarget_labels(operands: &[Op], label_kept: &[Option<usize>], kept_len: usize) -> Vec<Op> {
10665 operands
10666 .iter()
10667 .map(|operand| match operand {
10668 Op::Label(label) => {
10669 let target = label_kept
10670 .get(label.0 as usize)
10671 .copied()
10672 .flatten()
10673 .unwrap_or(kept_len);
10674 Op::Label(Label(target as u32))
10675 }
10676 other => other.clone(),
10677 })
10678 .collect()
10679}
10680
10681/// Encode the resolved instruction stream, choosing short forms where possible.
10682///
10683/// Compute the maximum value-stack depth by exploring the control-flow graph.
10684///
10685/// This is a breadth-first walk from the first instruction, tracking the stack
10686/// depth on entry to each instruction. Every instruction has at most two
10687/// successors (fall through, and a jump target), so a worklist over byte offsets
10688/// is enough. The reference does the same thing in `compute_stack_size`, which is
10689/// why the resulting numbers match exactly.
10690///
10691/// Instructions that pop a variable number of values (`call`, `array_from`, …)
10692/// encode that count in their operand, which is added to the static `n_pop`.
10693fn compute_stack_size(code: &[u8]) -> u32 {
10694 let mut depth_at = vec![u16::MAX; code.len()];
10695 // Each entry carries the enclosing `catch` levels, innermost last, because
10696 // `nip_catch` needs them: it rewinds the stack to just above the innermost catch
10697 // offset and forgets that level.
10698 let mut worklist: Vec<(usize, u32, Vec<u32>)> = vec![(0, 0, Vec::new())];
10699 let mut max_depth = 0u32;
10700
10701 while let Some((pc, depth, catch_levels)) = worklist.pop() {
10702 if pc >= code.len() {
10703 continue;
10704 }
10705 if depth_at[pc] != u16::MAX {
10706 continue;
10707 }
10708 force_depth(&mut depth_at, pc, depth);
10709
10710 let Some(op) = Opcode::from_u8(code[pc]) else {
10711 break;
10712 };
10713 let info = op.info();
10714 let next = pc + info.size as usize;
10715 if next > code.len() {
10716 break;
10717 }
10718 let mut n_pop = info.n_pop as u32;
10719 let mut n_push = info.n_push as u32;
10720 // Variable-length forms carry their count in the operand.
10721 match info.format {
10722 crate::opcode::OpFormat::Npop | crate::opcode::OpFormat::NpopU16 => {
10723 n_pop += read_u16(code, pc + 1) as u32;
10724 }
10725 crate::opcode::OpFormat::Npopx => {
10726 n_pop += op.specialised_index().unwrap_or(0).max(0) as u32;
10727 }
10728 _ => {}
10729 }
10730 // `put_loc`/`put_arg`/`put_var_ref` keep the value on the stack when they
10731 // are the `set_` variant; the table already records that, so nothing to
10732 // adjust here.
10733 let _ = &mut n_push;
10734
10735 // The depth before this instruction's own push, which is what a `catch`
10736 // records as its level.
10737 let depth_before = depth;
10738 let mut depth = depth.saturating_sub(n_pop) + n_push;
10739 let mut catch_levels = catch_levels;
10740 if op == Opcode::NipCatch {
10741 // Discard everything above the innermost catch offset, keeping the value
10742 // on top: the frame the code after this sees is the same shape it would
10743 // have had if the `try` were not there.
10744 if let Some(base) = catch_levels.pop() {
10745 depth = base + 1;
10746 }
10747 }
10748 max_depth = max_depth.max(depth);
10749
10750 // Successors.
10751 let target = jump_target_of(code, pc, op);
10752 match op {
10753 Opcode::Goto | Opcode::Goto8 | Opcode::Goto16 => {
10754 if let Some(target) = target {
10755 worklist.push((target, depth, catch_levels));
10756 }
10757 }
10758 Opcode::IfFalse | Opcode::IfFalse8 | Opcode::IfTrue | Opcode::IfTrue8 => {
10759 if let Some(target) = target {
10760 worklist.push((target, depth, catch_levels.clone()));
10761 }
10762 worklist.push((next, depth, catch_levels));
10763 }
10764 // A `catch` records an exception edge to the handler. The handler is
10765 // entered with the thrown value on top of the stack, in the slot the
10766 // catch offset occupies on the normal path — which is why the handler's
10767 // first instruction can `put_loc` the exception away, and why the depth
10768 // is the same on both paths.
10769 Opcode::Catch => {
10770 if let Some(target) = target {
10771 // The handler is protected by the *enclosing* catch, not by this
10772 // one: an error raised inside it is what the handler's own
10773 // `catch` catches.
10774 worklist.push((target, depth, catch_levels.clone()));
10775 }
10776 catch_levels.push(depth_before);
10777 worklist.push((next, depth, catch_levels));
10778 }
10779 // A `for`/`of` loop keeps its own catch offset, and `nip_catch` has to
10780 // rewind past it too. Its level sits one slot higher than a `catch`'s:
10781 // the iterator and next-method slots occupy the offset's place.
10782 Opcode::ForOfStart | Opcode::ForAwaitOfStart => {
10783 if let Some(target) = target {
10784 worklist.push((target, depth, catch_levels.clone()));
10785 }
10786 catch_levels.push(depth_before + 1);
10787 worklist.push((next, depth, catch_levels));
10788 }
10789 // `gosub` calls a subroutine with the return address on top. The opcode
10790 // table records no push for it — `ret` is what pops the slot — so the
10791 // extra one is added here, where the depth of the subroutine's first
10792 // instruction is being computed.
10793 Opcode::Gosub => {
10794 if let Some(target) = target {
10795 worklist.push((target, depth + 1, catch_levels.clone()));
10796 }
10797 worklist.push((next, depth, catch_levels));
10798 }
10799 // `ret` goes back to a `gosub`; nothing here follows it.
10800 Opcode::Ret
10801 | Opcode::Return
10802 | Opcode::ReturnUndef
10803 | Opcode::Throw
10804 | Opcode::ThrowError => {}
10805 _ => worklist.push((next, depth, catch_levels)),
10806 }
10807 }
10808 max_depth
10809}
10810
10811/// Record the stack depth on entry to `pc`, keeping the deeper value if the
10812/// instruction is reachable more than once.
10813fn force_depth(depth_at: &mut [u16], pc: usize, depth: u32) {
10814 let clamped = depth.min(u16::MAX as u32 - 1) as u16;
10815 if depth_at[pc] == u16::MAX || depth_at[pc] < clamped {
10816 depth_at[pc] = clamped;
10817 }
10818}
10819
10820fn read_u16(code: &[u8], at: usize) -> u16 {
10821 let mut value = 0u16;
10822 for i in 0..2 {
10823 value = (value << 8) | code.get(at + i).copied().unwrap_or(0) as u16;
10824 }
10825 value
10826}
10827
10828/// The absolute target of a jump instruction, if it has one.
10829fn jump_target_of(code: &[u8], pc: usize, op: Opcode) -> Option<usize> {
10830 let info = op.info();
10831 let position = pc + 1;
10832 match info.format {
10833 crate::opcode::OpFormat::Label8 => {
10834 let offset = *code.get(position)? as i8 as i64;
10835 Some((position as i64 + offset) as usize)
10836 }
10837 crate::opcode::OpFormat::Label16 => {
10838 let offset = read_u16(code, position) as i16 as i64;
10839 Some((position as i64 + offset) as usize)
10840 }
10841 crate::opcode::OpFormat::Label => {
10842 let mut offset = 0i32;
10843 for i in 0..4 {
10844 offset = (offset << 8) | *code.get(position + i).unwrap_or(&0) as i32;
10845 }
10846 Some((position as i64 + offset as i64) as usize)
10847 }
10848 _ => None,
10849 }
10850}
10851
10852fn choose_short_form(op: Opcode, operands: &[Op]) -> Opcode {
10853 use Opcode::*;
10854 match (op, operands.first()) {
10855 (PushI32, Some(Op::Int(value))) if (-1..=7).contains(value) => {
10856 op.short_form(*value as u32).unwrap_or(op)
10857 }
10858 (PushConst, Some(Op::Const(index))) if *index < 256 => Opcode::PushConst8,
10859 (Fclosure, Some(Op::Const(index))) if *index < 256 => Opcode::Fclosure8,
10860 (GetLoc | PutLoc | SetLoc, Some(Op::Slot(Slot::Loc(index))))
10861 | (GetArg | PutArg | SetArg, Some(Op::Slot(Slot::Arg(index))))
10862 | (GetVarRef | PutVarRef | SetVarRef, Some(Op::Slot(Slot::VarRef(index))))
10863 // A declared global is reached through its reference cell, so it shares
10864 // the `var_ref` encodings, short forms included.
10865 | (GetVarRef | PutVarRef | SetVarRef, Some(Op::Slot(Slot::GlobalDecl(index)))) => {
10866 op.short_form(*index).unwrap_or(op)
10867 }
10868 (Call, Some(Op::Int(count))) if (0..=3).contains(count) => {
10869 op.short_form(*count as u32).unwrap_or(op)
10870 }
10871 _ => op,
10872 }
10873}
10874
10875/// The byte offset each instruction will start at, plus the total code size.
10876fn instruction_offsets(chosen: &[Opcode]) -> Vec<usize> {
10877 let mut offsets = Vec::with_capacity(chosen.len() + 1);
10878 let mut offset = 0usize;
10879 for op in chosen {
10880 offsets.push(offset);
10881 offset += op.size() as usize;
10882 }
10883 offsets.push(offset);
10884 offsets
10885}
10886
10887/// Pick an encoding for every instruction, shrinking a jump to its 8-bit form only when
10888/// the offset actually fits.
10889///
10890/// The choice is circular: an instruction's size decides the offsets of everything after
10891/// it, and the offsets decide whether a jump may be short. So this starts with every jump
10892/// in its widest form and shrinks what fits, repeating until a pass changes nothing.
10893/// Shrinking only ever *shortens* distances, so the loop converges.
10894///
10895/// Doing it in one pass instead — which is what this used to do — silently truncated any
10896/// jump further than 127 bytes: `goto8` with a mangled offset lands in the middle of the
10897/// bytecode, and the VM treats running off the end as a return. That is how a nested loop
10898/// with four closures in its body simply stopped, with no error and no output past the
10899/// first iteration.
10900fn choose_opcodes(kept: &[(Opcode, Vec<Op>)], label_kept: &[Option<usize>]) -> Vec<Opcode> {
10901 let mut chosen: Vec<Opcode> = kept
10902 .iter()
10903 .map(|(op, operands)| choose_short_form(*op, operands))
10904 .collect();
10905 // A jump the compiler emitted in its widest form, and the forms it may shrink to.
10906 let candidates = |op: Opcode| match op {
10907 Opcode::Goto => Some((Opcode::Goto8, Opcode::Goto16, true)),
10908 Opcode::IfFalse => Some((Opcode::IfFalse8, Opcode::IfFalse, false)),
10909 Opcode::IfTrue => Some((Opcode::IfTrue8, Opcode::IfTrue, false)),
10910 _ => None,
10911 };
10912 loop {
10913 let offsets = instruction_offsets(&chosen);
10914 let mut changed = false;
10915 for index in 0..kept.len() {
10916 let (op, operands) = &kept[index];
10917 let Some((short, medium, has_medium)) = candidates(*op) else {
10918 continue;
10919 };
10920 if chosen[index] == short {
10921 continue;
10922 }
10923 let Some(target) = target_kept_index(operands, label_kept) else {
10924 continue;
10925 };
10926 let Some(&target_offset) = offsets.get(target) else {
10927 continue;
10928 };
10929 // A jump is relative to the byte after its opcode, which is the convention
10930 // `jump_target_of` decodes with.
10931 let relative = target_offset as i64 - (offsets[index] as i64 + 1);
10932 if (-128..=127).contains(&relative) {
10933 chosen[index] = short;
10934 changed = true;
10935 } else if has_medium
10936 && chosen[index] == Opcode::Goto
10937 && (-32_768..=32_767).contains(&relative)
10938 {
10939 // Too far for 8 bits and close enough for 16. Only `goto` has a medium
10940 // form: `if_false`/`if_true` jump straight from 8 to 32 bits, exactly as
10941 // the reference encodes them.
10942 chosen[index] = medium;
10943 changed = true;
10944 }
10945 }
10946 if !changed {
10947 return chosen;
10948 }
10949 }
10950}
10951
10952fn encode_operands(
10953 code: &mut Vec<u8>,
10954 op: Opcode,
10955 operands: &[Op],
10956 position: usize,
10957 offsets: &[usize],
10958) {
10959 use crate::opcode::OpFormat::*;
10960 let info = op.info();
10961 let write_slot = |code: &mut Vec<u8>, slot: Slot| {
10962 let index = match slot {
10963 Slot::Arg(i)
10964 | Slot::Loc(i)
10965 | Slot::VarRef(i)
10966 | Slot::Global(i)
10967 | Slot::GlobalDecl(i) => i,
10968 };
10969 code.extend_from_slice(&(index as u16).to_be_bytes());
10970 };
10971 match info.format {
10972 None | NoneInt | NoneLoc | NoneArg | NoneVarRef | Npopx => {}
10973 U8 | Const8 => {
10974 if let Some(value) = operands.first().and_then(operand_uint) {
10975 code.push(value as u8);
10976 }
10977 }
10978 // The narrow slot forms (`inc_loc8` and friends) take a slot operand just
10979 // like their wide counterparts, only one byte wide.
10980 Loc8 => {
10981 if let Some(Op::Slot(slot)) = operands.first() {
10982 let index = match slot {
10983 Slot::Arg(i)
10984 | Slot::Loc(i)
10985 | Slot::VarRef(i)
10986 | Slot::Global(i)
10987 | Slot::GlobalDecl(i) => *i,
10988 };
10989 code.push(index as u8);
10990 }
10991 }
10992 I8 => {
10993 if let Some(value) = operands.first().and_then(operand_int) {
10994 code.push(value as i8 as u8);
10995 }
10996 }
10997 U16 | Npop => {
10998 if let Some(value) = operands.first().and_then(operand_int) {
10999 code.extend_from_slice(&(value as u16).to_be_bytes());
11000 }
11001 }
11002 I16 => {
11003 if let Some(value) = operands.first().and_then(operand_int) {
11004 code.extend_from_slice(&(value as i16 as u16).to_be_bytes());
11005 }
11006 }
11007 I32 => {
11008 if let Some(value) = operands.first().and_then(operand_int) {
11009 code.extend_from_slice(&value.to_be_bytes());
11010 }
11011 }
11012 U32 | Const => {
11013 if let Some(value) = operands.first().and_then(operand_uint) {
11014 code.extend_from_slice(&value.to_be_bytes());
11015 }
11016 }
11017 Loc | Arg | VarRef => {
11018 if let Some(Op::Slot(slot)) = operands.first() {
11019 write_slot(code, *slot);
11020 }
11021 }
11022 Atom | AtomU8 | AtomU16 | AtomLabelU8 | AtomLabelU16 => {
11023 if let Some(Op::AtomId(index)) = operands.first() {
11024 code.extend_from_slice(&index.to_be_bytes());
11025 }
11026 // The trailing immediate means different things per format, and the
11027 // atom forms that carry a *label* have to resolve it like any other
11028 // jump, so they cannot share the `U8`/`U16` arms above.
11029 match info.format {
11030 AtomU8 | AtomLabelU8 => {
11031 if let Some(value) = operands.get(1).and_then(operand_uint) {
11032 code.push(value as u8);
11033 }
11034 }
11035 AtomU16 | AtomLabelU16 => {
11036 if let Some(value) = operands.get(1).and_then(operand_uint) {
11037 code.extend_from_slice(&(value as u16).to_be_bytes());
11038 }
11039 }
11040 _ => {}
11041 }
11042 }
11043 NpopU16 => {
11044 for operand in operands.iter().take(2) {
11045 if let Some(value) = operand_uint(operand) {
11046 code.extend_from_slice(&(value as u16).to_be_bytes());
11047 }
11048 }
11049 }
11050 Label | Label8 | Label16 | LabelU16 => {
11051 if let Some(Op::Label(label)) = operands.first() {
11052 // Labels were already remapped to kept-instruction indices.
11053 let Some(&target) = offsets.get(label.0 as usize) else {
11054 debug_assert!(false, "label {} is past the end", label.0);
11055 return;
11056 };
11057 let relative = target as i64 - (position as i64 + 1);
11058 match info.format {
11059 Label8 => code.push(relative as i8 as u8),
11060 Label16 => code.extend_from_slice(&(relative as i16 as u16).to_be_bytes()),
11061 // `label_u16` stores the target followed by an unrelated u16.
11062 LabelU16 => {
11063 code.extend_from_slice(&(relative as i32).to_be_bytes());
11064 if let Some(value) = operands.get(1).and_then(operand_uint) {
11065 code.extend_from_slice(&(value as u16).to_be_bytes());
11066 }
11067 }
11068 _ => code.extend_from_slice(&(relative as i32).to_be_bytes()),
11069 }
11070 }
11071 }
11072 }
11073}
11074
11075fn operand_int(op: &Op) -> Option<i32> {
11076 match op {
11077 Op::Int(value) => Some(*value),
11078 _ => None,
11079 }
11080}
11081
11082fn operand_uint(op: &Op) -> Option<u32> {
11083 match op {
11084 Op::Const(value) | Op::AtomId(value) => Some(*value),
11085 Op::Int(value) => Some(*value as u32),
11086 _ => None,
11087 }
11088}
11089
11090/// Disassemble a compiled function.
11091pub fn disassemble(function: &CompiledFunction) -> String {
11092 disasm::disassemble_program(function)
11093}
11094
11095/// How many of an object pattern's keys are computed.
11096///
11097/// Only the count matters: a rest element needs a run-time key log exactly when at least one
11098/// key is not a literal, and the log is sized by walking the pattern anyway.
11099fn computed_key_count(properties: &[Option<PatternElement>]) -> usize {
11100 properties
11101 .iter()
11102 .flatten()
11103 .filter(|element| {
11104 matches!(
11105 element,
11106 PatternElement::Property {
11107 key: PropName::Computed(_),
11108 ..
11109 }
11110 )
11111 })
11112 .count()
11113}