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 Atom, ClosureType, ClosureVar, Constant, EvalSite, EvalVisible, Function as CompiledFunction,
27 FunctionKind, VarDef, VarKind,
28};
29use crate::disasm;
30use crate::opcode::Opcode;
31use js_parse::Position;
32use js_parse::Span;
33use js_parse::SyntaxError;
34use js_parse::ast::{self, *};
35
36/// A label id, local to the function being compiled.
37#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
38pub struct Label(u32);
39
40/// The `var_block` sentinel for a binding that lives at function scope.
41///
42/// It has to be a value a *real* block key can never take. Block keys are source
43/// offsets, so `0` is a perfectly ordinary key — the first block statement of a file
44/// gets it — and using `0` as the sentinel made `{ let y = 2 }` at offset zero look
45/// like a function-scoped `var`, which is how a top-level block's `let` leaked out of
46/// its block. The body block already uses `u64::MAX` to stay clear of offsets, so the
47/// sentinel takes the slot below it.
48const FUNCTION_SCOPE: u64 = u64::MAX - 3;
49
50/// The `var_block` sentinel for a binding of the parameter list.
51///
52/// A function whose parameter list contains a default expression gets *two* variable
53/// environments: one for the parameters and one for the body, so a `var` in the body
54/// that shares a name with a parameter is a different binding. The parameter bindings
55/// therefore need a scope key of their own: reachable while the defaults are
56/// evaluated, invisible to the body, and never merged with a body `var` of the same
57/// name.
58///
59/// Without this, `function f(a = 1, p = () => a) { var a = 2 }` made `p()` return 2:
60/// the closure and the body shared one slot, when only the parameters were in scope
61/// when it was created.
62const PARAM_SCOPE: u64 = u64::MAX - 4;
63
64/// The name of the hidden local a `using` declaration caches its dispose method in.
65///
66/// It has to be a name no source can produce, because a script may declare anything: the
67/// angle brackets keep it out of the identifier grammar, exactly like `<ret>`.
68fn using_method_name(name: &str) -> String {
69 format!("<using.method {name}>")
70}
71
72/// The `blocks` parent sentinel for "this block has no enclosing block".
73///
74/// Same reasoning as [`FUNCTION_SCOPE`]: `0` is a legal block key, and when it was
75/// also the terminator the chain walk from the script body reached the file's
76/// offset-zero block and treated it as an *enclosing* block — so that block's `let`
77/// leaked into the body scope.
78const NO_PARENT: u64 = u64::MAX - 2;
79
80/// The block key for a script body. Distinct from both sentinels and unreachable from
81/// any source offset.
82const SCRIPT_BODY: u64 = u64::MAX - 1;
83
84/// An operand of a symbolic instruction.
85#[derive(Debug, Clone, PartialEq)]
86enum Op {
87 /// An immediate integer.
88 Int(i32),
89 /// A jump target.
90 Label(Label),
91 /// A constant pool index.
92 Const(u32),
93 /// An atom, before interning.
94 Atom(Atom),
95 /// An interned atom, as an index into [`Function::atoms`].
96 AtomId(u32),
97 /// A resolved slot.
98 Slot(Slot),
99}
100
101/// Where a resolved variable lives.
102#[derive(Debug, Clone, Copy, PartialEq, Eq)]
103enum Slot {
104 Arg(u32),
105 Loc(u32),
106 VarRef(u32),
107 /// A global, by closure-var index.
108 Global(u32),
109 /// A global *declared* in this script. The reference keeps these bindings in
110 /// reference cells so that the script and any closure share one variable, so
111 /// a store goes through `put_var_ref` while a read uses `get_var`.
112 GlobalDecl(u32),
113}
114
115/// What a symbolic variable access does, which decides the final opcode.
116#[derive(Debug, Clone, Copy, PartialEq, Eq)]
117enum VarAction {
118 /// Read the value.
119 Get,
120 /// Read the value, yielding `undefined` for an undeclared global.
121 GetUndef,
122 /// Write, leaving nothing on the stack.
123 Put,
124 /// Write and initialise, leaving the value on the stack.
125 PutInit,
126 /// Write, leaving the value on the stack.
127 Set,
128 /// Initialise a binding that may only be initialised once, such as a derived
129 /// constructor's `this`.
130 PutInitChecked,
131 /// Initialise, leaving the value on the stack and without the `const` check.
132 ///
133 /// A class's own scope binding is a `const` that has to be initialised in the middle
134 /// of the definition — after the constructor exists but before the static fields run
135 /// — and the value has to survive for the outer store to use.
136 SetInit,
137 /// Write a binding that lives in a reference cell.
138 PutRef,
139}
140
141#[derive(Debug, Clone)]
142enum Insn {
143 /// A fully determined instruction.
144 Fixed { op: Opcode, operands: Vec<Op> },
145 /// A variable access, resolved in the second pass.
146 ///
147 /// `block` is the lexical block the access appears in, which is what makes
148 /// shadowing work: two bindings can share a name, and the one that wins is
149 /// whichever scope encloses the access.
150 Var {
151 action: VarAction,
152 name: String,
153 block: u64,
154 /// Whether the access was written in the parameter list; see
155 /// [`FnState::in_params`].
156 in_params: bool,
157 },
158 /// Close a binding *if* it turned out to be captured.
159 ///
160 /// Whether a `for (let i ...)` loop variable needs a fresh per-iteration cell is
161 /// only known once the body has been compiled — a closure created there is the
162 /// thing that makes it necessary. The reference emits `close_loc` exactly in that
163 /// case and nothing otherwise, so the decision is deferred to [`resolve`] instead
164 /// of emitted blind.
165 CloseCaptured { name: String, block: u64 },
166 /// `delete name`, which can only answer `false` once the binding is known.
167 ///
168 /// It is not a `Var` action because `delete_var` carries an *atom*: the runtime
169 /// looks the name up on the global object, which is what distinguishes an implicit
170 /// global (configurable, deletable) from a declared one (a binding, always `false`).
171 DeleteVar { name: String },
172 /// An instruction that dead-code elimination removed. It keeps its slot so
173 /// that label indices stay valid, and resolves to no bytecode.
174 Dead,
175}
176
177/// Where `break` and `continue` jump to.
178///
179/// Targets are stacked as the compiler enters loops and labelled statements, so a
180/// bare `break` needs no analysis: it is simply the innermost target. A labelled
181/// one searches outward by name.
182#[derive(Debug, Clone)]
183struct JumpTarget {
184 /// The labels attached to this target. `l: for(;;)` gives one name; a bare
185 /// loop gives none; `a: b: for(;;)` gives two, because both labels name the
186 /// same statement and `break a` must reach the same place as `break b`.
187 names: Vec<String>,
188 /// Where `break` lands. `None` for a construct `break` may only leave, not
189 /// target — a `try`, whose entry exists purely to unwind.
190 break_label: Option<Label>,
191 /// Where `continue` lands. `None` for anything that is not a loop.
192 continue_label: Option<Label>,
193 /// Stack slots to discard when control leaves this construct by a jump.
194 ///
195 /// Both `switch` and `try` leave something on the value stack for the duration
196 /// of the construct — the discriminant, or the `catch` offset — and a jump out
197 /// has to take it with it. A loop leaves nothing.
198 drop_count: u32,
199 /// The finalizer to run when control leaves this construct.
200 ///
201 /// Set on a `try` even when it has no `finally`: the label is always emitted and
202 /// the empty-subroutine removal cleans up afterwards, so the code that unwinds
203 /// does not have to know whether a finalizer exists.
204 finally_label: Option<Label>,
205 /// Whether this is a labelled non-loop statement, which an unlabelled `break`
206 /// does not reach.
207 is_regular_stmt: bool,
208 /// Whether leaving this construct has to close an iterator.
209 ///
210 /// A `for`/`of` loop keeps an iterator on the value stack, and leaving early has
211 /// to run its `return` method. `for`/`in` keeps only an enumeration object, which
212 /// is dropped rather than closed.
213 has_iterator: bool,
214}
215
216/// `copy_data_properties` flags for an object-literal spread.
217///
218/// The byte packs three fields: the low bits are the stack offset of the source,
219/// the next three the offset of the exclusion list, and bit 2 asks for symbol keys
220/// as well as string keys. A spread passes a literal `null` exclusion list right
221/// below the source, so that field stays zero and only the source offset and the
222/// symbol bit are set — hence `{...v}` copies symbols, which the flag name says.
223const COPY_ALL_PROPERTIES: i32 = 2 | (1 << 2);
224
225/// The expression a `...` introduces.
226///
227/// The parser marks the spread in two places — the element/property variant and an
228/// [`ExprKind::Spread`] wrapper around the argument — so the wrapper has to be
229/// stepped through before the argument can be compiled.
230fn spread_argument(spread: &Expr) -> &Expr {
231 match &spread.kind {
232 ExprKind::Spread(inner) => inner,
233 _ => spread,
234 }
235}
236
237/// The flag byte `define_method` takes.
238///
239/// The low two bits pick value/getter/setter; bit 2 marks the property
240/// enumerable, which every object-literal method is.
241/// What kind of class constructor a function is being compiled as.
242///
243/// A constructor is not an ordinary method: a base one materialises `this` and refuses
244/// to run without `new`, and a derived one starts with `this` in the dead zone until
245/// `super()` produces it.
246#[derive(Debug, Clone, Copy, PartialEq, Eq)]
247enum CtorKind {
248 /// Not a class constructor.
249 None,
250 /// A constructor of a class without `extends`.
251 Base,
252 /// A constructor of a class with `extends`.
253 Derived,
254}
255
256/// The flag byte `define_method` takes for a class member.
257///
258/// The low two bits pick value/getter/setter; bit 2 marks the property enumerable, which
259/// a class method is *not* — that is the whole difference from an object-literal method,
260/// and the reason `Object.keys(C.prototype)` stays empty.
261fn class_method_flags(kind: MethodKind) -> i32 {
262 match kind {
263 MethodKind::Constructor | MethodKind::Method => 0,
264 MethodKind::Get => 1,
265 MethodKind::Set => 2,
266 }
267}
268
269fn define_method_flags(kind: PropertyKind) -> i32 {
270 let base = match kind {
271 PropertyKind::Value | PropertyKind::Method => 0,
272 PropertyKind::Get => 1,
273 PropertyKind::Set => 2,
274 };
275 base | 4
276}
277
278/// Convert a numeric property key to the text an atom would be made from.
279///
280/// Only the range where Rust and JavaScript agree on the spelling is accepted.
281/// Both print the shortest representation that round-trips, so plain decimal
282/// digits match; they diverge at the extremes, where JavaScript switches to an
283/// exponent (`1e-7`, `1e+21`) and Rust does not. Rather than emit an atom that
284/// differs from the reference, those keys are rejected.
285fn numeric_key_text(value: f64, span: Span) -> Result<String, SyntaxError> {
286 if !value.is_finite() {
287 return Err(SyntaxError::new(
288 "a non-finite numeric property key is not supported by the compiler yet",
289 span,
290 ));
291 }
292 if value == value.trunc() && value.abs() < 1e21 {
293 return Ok(format!("{}", value as i64));
294 }
295 if value.abs() >= 1e-6 && value.abs() < 1e21 {
296 return Ok(format!("{value}"));
297 }
298 Err(SyntaxError::new(
299 "a numeric property key outside [1e-6, 1e21) is not supported by the compiler yet",
300 span,
301 ))
302}
303
304/// Collect the operands of a same-operator logical run, in source order.
305///
306/// Recurses down the left spine only: `((a || b) || c)` contributes `a`, `b`, then
307/// the caller appends `c`. A node with a different operator is one operand.
308fn collect_same_operator<'a>(op: LogicalOp, expr: &'a Expr, out: &mut Vec<&'a Expr>) {
309 if let ExprKind::Logical {
310 op: inner_op,
311 left,
312 right,
313 } = &expr.kind
314 && *inner_op == op
315 {
316 collect_same_operator(op, left, out);
317 out.push(right);
318 return;
319 }
320 out.push(expr);
321}
322
323/// The jump a logical assignment or `??` takes when the value is kept.
324///
325/// `||` and `&&` branch on truthiness, so the same opcode serves both the operator
326/// and `??` once [`Compiler::emit_logical_test`] has pushed a boolean. `??` keeps
327/// the value when it is *not* null-ish, so it is the `if_false` side.
328fn logical_jump(op: AssignOp) -> Opcode {
329 match op {
330 AssignOp::Or => Opcode::IfTrue,
331 AssignOp::And | AssignOp::Coalesce => Opcode::IfFalse,
332 _ => Opcode::IfFalse,
333 }
334}
335
336/// Whether a loop enumerates keys or values.
337#[derive(Debug, Clone, Copy, PartialEq, Eq)]
338enum ForLoopKind {
339 /// `for (x in o)` — the keys of an object.
340 In,
341 /// `for (x of o)` — the values of an iterable.
342 Of,
343 /// `for await (x of o)` — the values of an async iterable, or of a sync one.
344 AwaitOf,
345}
346
347/// Which part of a `try` statement a block key refers to.
348#[derive(Debug, Clone, Copy)]
349enum TryPart {
350 /// The guarded block.
351 Block = 0,
352 /// The handler body, excluding the catch parameter.
353 Catch = 1,
354 /// The finalizer block.
355 Finally = 2,
356 /// The catch parameter's own scope.
357 Param = 3,
358}
359
360/// A lexical scope, identified while hoisting and numbered at the end.
361///
362/// Scope identity is needed in two passes that must agree: declarations are
363/// hoisted in source order (so slots come out in source order, as in the
364/// reference), but a binding belongs to the block it was written in, which is only
365/// entered later. Blocks are therefore keyed by the source position of their
366/// opening brace, which is stable across both walks.
367#[derive(Debug, Clone, Copy)]
368struct Block {
369 /// Source position of the block.
370 key: u64,
371 /// The block this one is nested in; `0` for the function scope.
372 parent: u64,
373}
374
375/// One function under construction.
376struct FnState {
377 name: String,
378 kind: FunctionKind,
379 strict: bool,
380 args: Vec<VarDef>,
381 vars: Vec<VarDef>,
382 closure_vars: Vec<ClosureVar>,
383 cpool: Vec<Constant>,
384 atoms: Vec<Atom>,
385 /// Every lexical scope, in creation order.
386 blocks: Vec<Block>,
387 /// The block currently being parsed or compiled.
388 current_block: u64,
389 /// The block a *nested* function was created in, so a capture made from here can be
390 /// resolved against the enclosing function's lexical scopes rather than against a
391 /// flat name table. Without it, `function f(){ class S{} }` capturing `S` found the
392 /// function's own `let S` instead of the class body's `const S`.
393 created_in_block: u64,
394 /// The block each local was declared in, parallel to `vars`. `0` means the
395 /// function scope, where `var` bindings live.
396 var_block: Vec<u64>,
397 /// Set when the expression just compiled left no value on the stack.
398 ///
399 /// Only a store can do that: `put_field` consumes the object and the value, so
400 /// an assignment whose result is unused emits nothing extra. The expression
401 /// statement then has nothing to drop.
402 no_value: bool,
403 /// Whether a label was placed since the last instruction was emitted.
404 ///
405 /// The `put`/`get` fold is only valid when the two are adjacent in the final
406 /// stream; a label in between means a jump can land on the read, so the store has
407 /// to keep consuming its value. A flag is enough and avoids having to reason about
408 /// which index a label recorded.
409 label_since_insn: bool,
410 /// Whether the value of the expression being compiled is thrown away.
411 ///
412 /// Only an expression *statement* discards its value, and only the outermost
413 /// assignment in it may act on that: in `x = (o.a = 1)` the inner assignment
414 /// still has to produce a value. Consumed by [`Compiler::assign`], which is
415 /// the one construct whose bytecode depends on it.
416 discard_value: bool,
417 /// The block that holds the function body.
418 body_block: u64,
419 /// Head of each scope's binding chain, indexed by level. Filled in by
420 /// [`rebuild_scope_chain`]; the scope chain is only needed at run time.
421 block_heads: Vec<i32>,
422 /// Enclosing `break`/`continue` targets, innermost last.
423 jump_targets: Vec<JumpTarget>,
424 insns: Vec<Insn>,
425 labels: Vec<Option<usize>>,
426 /// Captured locals, which need a reference cell.
427 var_ref_count: u32,
428 line: u32,
429 column: u32,
430 /// Whether this is a script body. A script's top-level declarations create
431 /// global properties rather than locals, which is why they show up as
432 /// closure variables with `[global_decl]`.
433 is_script: bool,
434 /// Whether the function is an arrow, which never gets its own `arguments`.
435 is_arrow: bool,
436 /// The name a *named function expression* binds inside its own body.
437 /// How many parameters count towards `.length`.
438 defined_args: u32,
439 /// Parameters that are not a plain name, with the argument slot each came from.
440 param_prologue: Vec<(usize, Pattern)>,
441 /// What kind of class constructor this function is, if any.
442 ctor_kind: CtorKind,
443 /// Whether the class has instance fields, so the constructor has to run their
444 /// initialiser before it returns.
445 has_instance_fields: bool,
446 /// What the nested function about to be compiled should be told about its class.
447 class_ctor_pending: Option<(CtorKind, bool)>,
448 /// Whether this function needs the hidden `this` local, because an arrow inside it
449 /// refers to `this`.
450 ///
451 /// An arrow has no `this` of its own, so the reference materialises the enclosing
452 /// function's receiver into a local and lets the arrow capture it as an ordinary
453 /// closure variable. Declaring the local is not enough on its own: the store that
454 /// fills it has to be prepended to the body, which is what this flag arranges.
455 needs_this_local: bool,
456 /// The same, for `arguments`.
457 needs_arguments_local: bool,
458 /// The same, for `new.target`.
459 needs_new_target_local: bool,
460 /// Hidden locals of the `with` blocks currently open, innermost last.
461 with_names: Vec<String>,
462 /// Set while a with-guard is being emitted, so the guard's own accesses are not
463 /// wrapped in another guard.
464 emitting_with_guard: bool,
465 self_name: Option<String>,
466 /// Where the function body starts, in source order; see [`Function::body_start`].
467 body_start: (u32, u32),
468 /// Whether the body contains a *direct* `eval(...)` call.
469 ///
470 /// A direct eval sees every binding of the function that called it, including ones
471 /// no other code mentions. It also hands those bindings to any closure it creates,
472 /// which can outlive the function. Both need the bindings to live in cells, so this
473 /// flag makes the function treat all of them as captured.
474 has_direct_eval: bool,
475 /// Whether the parameter list contains a default expression, which is what gives
476 /// the function a second variable environment (see [`PARAM_SCOPE`]).
477 has_parameter_expressions: bool,
478 /// Whether the instructions being emitted belong to the parameter list.
479 ///
480 /// References made here must not see the body's `var`s: the body has not run yet,
481 /// and the reference's own model keeps the two scopes apart.
482 in_params: bool,
483 /// Whether an arrow created in this function's parameter list needs the parameter
484 /// scope's `arguments` binding.
485 needs_param_arguments: bool,
486 /// Whether this function was *created* inside a parameter list.
487 ///
488 /// Inherited, so `f(a = () => () => c)` hides `f`'s body bindings from the inner
489 /// arrow too. The name reference is the arrow's, but the scope it must not see
490 /// belongs to the function the arrow was born in.
491 created_in_params: bool,
492 /// What each direct `eval(...)` in this function can see; see [`EvalSite`].
493 ///
494 /// Only filled in by [`Compiler::materialize_eval_sites`], because the answer is not
495 /// final while the body is still being compiled: a named function expression declares
496 /// its own name binding *after* the body, and that binding is exactly what
497 /// `eval("myfunc = 1")` has to find.
498 eval_sites: Vec<EvalSite>,
499 /// Direct `eval` call sites seen so far: where, and the block that was current.
500 pending_eval_sites: Vec<(Span, u64, bool)>,
501 /// Whether the self-name prologue (`special_object 2` then the store) has been
502 /// emitted for this function.
503 ///
504 /// A *nested* function's lookup declares the binding early (see
505 /// [`resolve_slot`]), so `provide_self_name` cannot decide on its own whether the
506 /// prologue is still needed — the binding existing is not the same as it being
507 /// initialised.
508 self_name_initialized: bool,
509 /// Whether the code emitted so far leaves the program's result on the stack.
510 /// The reference tracks this for the hidden `<ret>` local of an eval script.
511 leaves_value: bool,
512 /// Statement nesting depth, used to tell top-level statements apart.
513 stmt_depth: u32,
514 /// Function declarations waiting to be instantiated at scope entry, as
515 /// (target slot, constant pool index). The reference emits these from
516 /// `instantiate_hoisted_definitions` rather than at the statement, because a
517 /// declaration is visible before it is reached.
518 hoisted: Vec<(u64, HoistTarget, u32)>,
519 /// Function declarations whose bodies are compiled only once the enclosing scope
520 /// has finished hoisting, as (owning block, declaration).
521 ///
522 /// Compiling a body at the declaration makes the result depend on source order: in
523 /// `function f(){ return t } var t`, `t` is not declared yet when `f` is compiled,
524 /// so the read resolved to a *global* instead of the enclosing `var`. Hoisting the
525 /// names first and the bodies second is what removes that dependence.
526 deferred_funcs: Vec<(u64, Box<ast::Function>)>,
527 /// The source position of the node being compiled. Every instruction emitted
528 /// takes it, which is how the position table that feeds stack traces is built.
529 cur_pos: Option<Position>,
530 /// One position per entry in `insns`, index-aligned.
531 insn_pos: Vec<Option<Position>>,
532}
533
534/// Where a hoisted function declaration is stored.
535#[derive(Debug, Clone)]
536enum HoistTarget {
537 Arg(u32),
538 Loc(u32),
539 /// A global, which the resolver looks up by name.
540 Global(String),
541}
542
543impl FnState {
544 /// Whether this function suspends: a generator or an async function.
545 ///
546 /// A suspending function's `return` is a `return_async` and its body starts with an
547 /// `initial_yield`, so almost every statement that touches control flow asks this.
548 fn is_suspending(&self) -> bool {
549 self.kind.is_generator() || self.kind.is_async()
550 }
551
552 fn new(name: impl Into<String>, kind: FunctionKind) -> FnState {
553 FnState {
554 name: name.into(),
555 kind,
556 strict: false,
557 args: Vec::new(),
558 vars: Vec::new(),
559 closure_vars: Vec::new(),
560 cpool: Vec::new(),
561 atoms: Vec::new(),
562 blocks: Vec::new(),
563 current_block: 0,
564 created_in_block: NO_PARENT,
565 var_block: Vec::new(),
566 no_value: false,
567 label_since_insn: false,
568 discard_value: false,
569 body_block: 0,
570 block_heads: Vec::new(),
571 jump_targets: Vec::new(),
572 insns: Vec::new(),
573 labels: Vec::new(),
574 var_ref_count: 0,
575 line: 1,
576 column: 1,
577 is_script: false,
578 is_arrow: false,
579 defined_args: 0,
580 param_prologue: Vec::new(),
581 ctor_kind: CtorKind::None,
582 has_instance_fields: false,
583 class_ctor_pending: None,
584 needs_this_local: false,
585 needs_arguments_local: false,
586 needs_new_target_local: false,
587 with_names: Vec::new(),
588 emitting_with_guard: false,
589 self_name: None,
590 has_direct_eval: false,
591 body_start: (0, 0),
592 has_parameter_expressions: false,
593 in_params: false,
594 needs_param_arguments: false,
595 created_in_params: false,
596 eval_sites: Vec::new(),
597 pending_eval_sites: Vec::new(),
598 self_name_initialized: false,
599 leaves_value: false,
600 stmt_depth: 0,
601 hoisted: Vec::new(),
602 deferred_funcs: Vec::new(),
603 cur_pos: None,
604 insn_pos: Vec::new(),
605 }
606 }
607
608 /// The scope a declaration lands in: a script's top-level declarations are
609 /// globals, everything else gets a slot.
610 /// Whether a binding declared *now* becomes a property of the global object.
611 ///
612 /// For a script, a top-level `var` and the top-level `let`/`const` are globals.
613 /// The `var` case is decided by the keyword rather than by the cursor position:
614 /// `var` is function-scoped, so a `var i` in a `for` head is still the same
615 /// binding as a `var i` in the body, even though the head has its own block.
616 fn declares_globally(&self, def: &VarDef) -> bool {
617 self.is_script && (!def.is_lexical || self.current_block == self.body_block)
618 }
619}
620
621/// The compiler's entry point.
622pub struct Compiler {
623 module: bool,
624 /// Enclosing functions, outermost first. The last entry is the current one.
625 stack: Vec<FnState>,
626}
627
628/// Compile a script.
629pub fn compile_script(program: &Program) -> Result<CompiledFunction, SyntaxError> {
630 Compiler::new(false).compile(program)
631}
632
633/// Compile a module.
634pub fn compile_module(program: &Program) -> Result<CompiledFunction, SyntaxError> {
635 Compiler::new(true).compile(program)
636}
637
638impl Compiler {
639 /// Create a compiler.
640 pub fn new(module: bool) -> Compiler {
641 Compiler {
642 module,
643 stack: Vec::new(),
644 }
645 }
646
647 /// Compile a whole program into its top-level function.
648 pub fn compile(mut self, program: &Program) -> Result<CompiledFunction, SyntaxError> {
649 let mut state = FnState::new("<eval>", FunctionKind::Normal);
650 state.is_script = true;
651 state.strict = program.strict || self.module;
652 state.line = program.span.start.line;
653 state.column = program.span.start.column;
654 // Locals are numbered in declaration order; `<ret>` is always slot 0.
655 //
656 // `var_block` has to grow in step with `vars`: it is indexed by slot, so a
657 // slot that only appears in one of the two arrays shifts every later
658 // binding's block and silently loses the temporal-dead-zone marking for
659 // the script's own blocks. A function frame has no `<ret>`, which is why
660 // the misalignment only showed up at the top level.
661 state.vars.push(VarDef::var("<ret>"));
662 state.var_block.push(FUNCTION_SCOPE);
663 self.stack.push(state);
664 // The body is its own scope, keyed by the position of the program.
665 // The script body needs a key no statement can produce. Statement keys are
666 // source offsets, and the program's own start offset is `0` — which is also
667 // the offset of the first statement, so a top-level `{ let x }` or
668 // `for (let i …)` used to share the body's block and lose its scope.
669 let body_key = SCRIPT_BODY;
670 self.push_block(body_key, NO_PARENT);
671 self.state().body_block = body_key;
672 self.hoist(&program.body, body_key)?;
673 self.emit_scope_enter(body_key);
674 // Through `stmts` rather than the loop, so a `using` region at the top level of an
675 // eval'd body or a module gets its disposal epilogue like any other block.
676 self.stmts(&program.body)?;
677 // The program's value is whatever the last expression statement stored in
678 // the hidden `<ret>` local; `put_loc0`/`get_loc0` folding turns the common
679 // case into a single `set_loc0`.
680 self.emit(Opcode::GetLoc, &[Op::Slot(Slot::Loc(0))]);
681 self.emit(Opcode::Return, &[]);
682 Ok(self.finish_current())
683 }
684
685 // -- emitting ----------------------------------------------------------
686
687 fn state(&mut self) -> &mut FnState {
688 self.stack.last_mut().expect("a function is being compiled")
689 }
690
691 fn cur(&self) -> &FnState {
692 self.stack.last().expect("a function is being compiled")
693 }
694
695 fn emit(&mut self, op: Opcode, operands: &[Op]) {
696 self.state().label_since_insn = false;
697 let pos = self.cur().cur_pos;
698 self.state().insns.push(Insn::Fixed {
699 op,
700 operands: operands.to_vec(),
701 });
702 self.state().insn_pos.push(pos);
703 }
704
705 /// Reset the script's hidden return value to `undefined`.
706 ///
707 /// Called at the start of every statement that does not itself produce the
708 /// program's value, which is how the reference keeps `if`/loop results from
709 /// leaking into an eval result.
710 fn reset_value(&mut self) {
711 if !self.cur().is_script {
712 return;
713 }
714 self.emit(Opcode::Undefined, &[]);
715 self.emit(Opcode::PutLoc, &[Op::Slot(Slot::Loc(0))]);
716 self.state().leaves_value = false;
717 }
718
719 /// Whether `name` is a local or argument slot rather than a global.
720 fn is_slot(&self, name: &str) -> bool {
721 self.cur().vars.iter().any(|v| v.name == name)
722 || self.cur().args.iter().any(|a| a.name == name)
723 }
724
725 /// `with (object) body`
726 ///
727 /// The boxed object lives in a hidden local marked [`VarKind::With`]. A local is
728 /// what makes the object reachable from a closure created inside the block, and it
729 /// is also what lets an `eval` find it: the runtime collects the active `With`
730 /// locals of every frame and resolves names against them before the realm.
731 ///
732 /// Inside the block every name reference is spelled as "look in the with objects
733 /// first", innermost outwards, and falls through to the ordinary access. The test is
734 /// `in`, which is `HasProperty` — the same question the spec's Object Environment
735 /// Record asks.
736 fn with_stmt(&mut self, object: &Expr, body: &Stmt) -> Result<(), SyntaxError> {
737 let name = self.next_with_name();
738 // The object expression is evaluated *outside* the scope it introduces, so no
739 // wrapper may be emitted for the names it mentions.
740 let saved = std::mem::take(&mut self.state().with_names);
741 self.expr(object)?;
742 self.state().with_names = saved;
743 self.emit(Opcode::ToObject, &[]);
744 self.declare_hidden_local(&name, VarKind::With);
745 // Pushed before the store so the store itself is not guarded by an *outer*
746 // `with` — the object being stored is the new one, not something to look up.
747 self.state().with_names.push(name.clone());
748 self.emit_var(VarAction::Put, &name);
749 let result = self.stmt(body);
750 self.state().with_names.pop();
751 result
752 }
753
754 /// A hidden-local name for one `with` block, distinct from every enclosing one.
755 fn next_with_name(&self) -> String {
756 let depth = self.cur().with_names.len();
757 if depth == 0 {
758 "<with>".to_string()
759 } else {
760 format!("<with{depth}>")
761 }
762 }
763
764 /// Declare a hidden local that must stay a *local* even in a script.
765 ///
766 /// A script's `var` is a property of the global object, but the `with` object is not
767 /// part of the source program's name space at all — it only exists for the compiler
768 /// and the runtime — so it goes straight into the frame's slot list.
769 fn declare_hidden_local(&mut self, name: &str, kind: VarKind) {
770 let state = self.state();
771 if state.vars.iter().any(|v| v.name == name) {
772 return;
773 }
774 state.var_block.push(FUNCTION_SCOPE);
775 state.vars.push(VarDef {
776 kind,
777 ..VarDef::var(name)
778 });
779 }
780
781 /// Emit a name access, guarded by every active `with` object.
782 ///
783 /// Each guard is `get_loc <with>; push_atom_value name; in; if_false <next>` and then
784 /// the read itself; the outer guards and the plain access are what the `if_false`
785 /// jumps to, so the innermost object wins.
786 fn emit_with_guarded(&mut self, action: VarAction, name: &str) {
787 let names = self.cur().with_names.clone();
788 let done = self.new_label();
789 let mut starts = Vec::new();
790 // Innermost object first: the last `with` opened is the one that shadows the
791 // others, so its guard has to be the first chance to satisfy the name.
792 for with_name in names.iter().rev() {
793 let next = self.new_label();
794 // `in` takes the key then the object.
795 self.emit(Opcode::PushAtomValue, &[Op::Atom(Atom::from_text(name))]);
796 self.emit_var(VarAction::Get, with_name);
797 self.emit(Opcode::In, &[]);
798 self.emit_jump(Opcode::IfFalse, next, &[]);
799 starts.push(next);
800 match action {
801 // A store keeps the value under the receiver, which is where
802 // `put_field` expects it.
803 VarAction::Put | VarAction::PutInit => {
804 self.emit_var(VarAction::Get, with_name);
805 self.emit(Opcode::Swap, &[]);
806 self.emit(Opcode::PutField, &[Op::Atom(Atom::from_text(name))]);
807 }
808 _ => {
809 self.emit_var(VarAction::Get, with_name);
810 self.emit(Opcode::PushAtomValue, &[Op::Atom(Atom::from_text(name))]);
811 self.emit(Opcode::GetArrayEl, &[]);
812 }
813 }
814 self.emit_jump(Opcode::Goto, done, &[]);
815 self.place_label(next);
816 }
817 self.emit_var(action, name);
818 self.place_label(done);
819 }
820
821 fn emit_var(&mut self, action: VarAction, name: &str) {
822 // Peephole: `put_x v` followed by `get_x v` becomes `set_x v`, which
823 // stores and keeps the value in one instruction. The reference does this
824 // in a post-pass; folding it at emit time keeps instruction indices
825 // stable, which matters because labels are recorded as indices.
826 //
827 // Only slots have a `set_` form: a global is stored with `put_var` and
828 // read with `get_var`, and the reference does not fold those.
829 //
830 // A label between the two cancels the fold. `set_x v` leaves the value on
831 // the stack, which is only equivalent when the read immediately follows the
832 // store; when a jump target sits in between, the store must *consume* the
833 // value and the read must fetch it afresh. A loop head is exactly that
834 // case — `for (var i = 0; i < 3; i++)` stores the initialiser, then the
835 // condition re-reads it — and folding across the label would make the
836 // condition compare whatever the previous iteration left on the stack.
837 if action == VarAction::Get {
838 let is_slot = self.is_slot(name);
839 let at_label = std::mem::take(&mut self.state().label_since_insn);
840 //
841 // `arguments` is excluded because the reference treats it as a special
842 // binding: it is initialised once and read many times, and folding its
843 // initialisation into a `set_` would leave the object on the stack where
844 // the reference leaves nothing.
845 if is_slot
846 && name != "arguments"
847 && !at_label
848 && let Some(Insn::Var {
849 action: previous,
850 name: previous_name,
851 ..
852 }) = self.state().insns.last_mut()
853 && *previous == VarAction::Put
854 && previous_name == name
855 {
856 *previous = VarAction::Set;
857 return;
858 }
859 }
860 // Inside a `with`, every name lookup consults the with objects first. The
861 // hidden `<with…>` locals themselves are exempt, or the guard would recurse.
862 let guarded = !self.cur().with_names.is_empty()
863 && !self.cur().with_names.iter().any(|hidden| hidden == name)
864 && matches!(action, VarAction::Get | VarAction::Put | VarAction::PutInit)
865 && !self.state().emitting_with_guard;
866 if guarded {
867 self.state().emitting_with_guard = true;
868 self.emit_with_guarded(action, name);
869 self.state().emitting_with_guard = false;
870 return;
871 }
872 let block = self.cur().current_block;
873 self.state().label_since_insn = false;
874 let pos = self.cur().cur_pos;
875 let in_params = self.cur().in_params;
876 self.state().insns.push(Insn::Var {
877 action,
878 name: name.to_string(),
879 block,
880 in_params,
881 });
882 self.state().insn_pos.push(pos);
883 }
884
885 fn new_label(&mut self) -> Label {
886 let state = self.state();
887 state.labels.push(None);
888 Label(state.labels.len() as u32 - 1)
889 }
890
891 fn place_label(&mut self, label: Label) {
892 let index = self.cur().insns.len();
893 self.state().label_since_insn = true;
894 self.state().labels[label.0 as usize] = Some(index);
895 }
896
897 fn emit_jump(&mut self, op: Opcode, label: Label, extra: &[Op]) {
898 let mut operands = vec![Op::Label(label)];
899 operands.extend_from_slice(extra);
900 self.emit(op, &operands);
901 }
902
903 // -- scopes ------------------------------------------------------------
904
905 /// Start a new lexical scope inside `parent`.
906 fn push_block(&mut self, key: u64, parent: u64) {
907 let state = self.state();
908 if !state.blocks.iter().any(|b| b.key == key) {
909 state.blocks.push(Block { key, parent });
910 }
911 state.current_block = key;
912 }
913
914 /// Emit the code that runs when a lexical scope is entered.
915 ///
916 /// Every `let`/`const`/`class` binding starts out in the temporal dead zone,
917 /// so entering its block marks it uninitialised. Hoisted function
918 /// declarations are created here instead, which is why a call before the
919 /// declaration still works.
920 ///
921 /// The order is not obvious: bindings are emitted in *reverse* declaration
922 /// order, because the reference walks its scope chain, which is built by
923 /// prepending.
924 fn emit_scope_enter(&mut self, block: u64) {
925 let hoisted = std::mem::take(&mut self.state().hoisted);
926 let mut mine: Vec<(HoistTarget, u32)> = hoisted
927 .into_iter()
928 .filter(|(owner, _, _)| *owner == block)
929 .map(|(_, target, pool_index)| (target, pool_index))
930 .collect();
931 mine.sort_by_key(|(target, _)| match target {
932 HoistTarget::Arg(index) | HoistTarget::Loc(index) => *index,
933 HoistTarget::Global(_) => u32::MAX,
934 });
935 for (target, pool_index) in mine {
936 self.emit(Opcode::Fclosure, &[Op::Const(pool_index)]);
937 match target {
938 HoistTarget::Arg(index) => self.emit(Opcode::PutArg, &[Op::Slot(Slot::Arg(index))]),
939 HoistTarget::Loc(index) => self.emit(Opcode::PutLoc, &[Op::Slot(Slot::Loc(index))]),
940 HoistTarget::Global(name) => {
941 // A global binding lives in a reference cell, so the store
942 // goes through `put_var_ref` while reads use `get_var`.
943 let block = self.cur().current_block;
944 let pos = self.cur().cur_pos;
945 let in_params = self.cur().in_params;
946 self.state().insns.push(Insn::Var {
947 action: VarAction::PutRef,
948 name,
949 block,
950 in_params,
951 });
952 self.state().insn_pos.push(pos);
953 }
954 }
955 }
956 for index in self.block_vars_reversed(block) {
957 self.emit(
958 Opcode::SetLocUninitialized,
959 &[Op::Slot(Slot::Loc(index as u32))],
960 );
961 }
962 }
963
964 /// Emit the code that runs when a lexical scope is exited.
965 ///
966 /// A captured binding has to be closed: detaching its reference cell freezes
967 /// the value the binding had when the block ended, which is what a closure
968 /// created inside the block must keep seeing.
969 fn emit_scope_leave(&mut self, block: u64) {
970 for index in self.block_vars_reversed(block) {
971 if self.cur().vars[index].is_captured {
972 self.emit(Opcode::CloseLoc, &[Op::Slot(Slot::Loc(index as u32))]);
973 }
974 }
975 }
976
977 /// Locals declared in `block`, in reverse declaration order.
978 fn block_vars_reversed(&self, block: u64) -> Vec<usize> {
979 let state = self.cur();
980 let mut out: Vec<usize> = (0..state.vars.len())
981 .filter(|index| {
982 state.var_block.get(*index).copied() == Some(block) && state.vars[*index].is_lexical
983 })
984 .collect();
985 out.reverse();
986 out
987 }
988
989 /// Declare a local, even at the top level of a script.
990 ///
991 /// A `catch` parameter is always a local: the reference puts it in the
992 /// function's own variable list (`1: catch e`), never in the global object,
993 /// because it only exists while the handler runs.
994 fn declare_local(&mut self, _name: &str, def: VarDef) -> u32 {
995 let state = self.state();
996 let index = state.vars.len() as u32;
997 // A `catch` parameter belongs to a scope even though it is not lexical: the
998 // runtime instantiates it per handler entry, but it never sits in the
999 // temporal dead zone.
1000 let block = if def.is_lexical || def.kind == crate::bytecode::VarKind::Catch {
1001 state.current_block
1002 } else {
1003 0
1004 };
1005 state.var_block.push(block);
1006 state.vars.push(def);
1007 index
1008 }
1009
1010 fn declare(&mut self, name: &str, def: VarDef) -> u32 {
1011 if self.cur().declares_globally(&def) {
1012 self.declare_global(name, &def);
1013 return 0;
1014 }
1015 let state = self.state();
1016 let index = state.vars.len() as u32;
1017 let block = if def.is_lexical {
1018 state.current_block
1019 } else {
1020 0
1021 };
1022 state.var_block.push(block);
1023 state.vars.push(def);
1024 index
1025 }
1026
1027 /// Declare a `using` binding and its cached dispose method, returning both slots.
1028 ///
1029 /// The two are adjacent by construction, because `using_dispose` addresses the pair as
1030 /// `(value, value + 1)` — the reference does the same and documents the constraint.
1031 fn declare_using(&mut self, name: &str) -> (u32, u32) {
1032 let mut def = VarDef::lexical(name);
1033 def.kind = VarKind::Using;
1034 let value = self.declare(name, def);
1035 let mut method = VarDef::lexical(using_method_name(name));
1036 method.kind = VarKind::UsingMethod;
1037 let method_slot = self.declare(&using_method_name(name), method);
1038 (value, method_slot)
1039 }
1040
1041 /// The slot a `using` binding's dispose method lives in.
1042 fn using_method_slot(&self, name: &str) -> Option<u32> {
1043 let hidden = using_method_name(name);
1044 self.cur()
1045 .vars
1046 .iter()
1047 .position(|var| var.name == hidden)
1048 .map(|index| index as u32)
1049 }
1050
1051 // -- statements --------------------------------------------------------
1052
1053 fn stmt(&mut self, stmt: &Stmt) -> Result<(), SyntaxError> {
1054 self.stmt_labelled(stmt, &[])
1055 }
1056
1057 /// Compile a statement that a chain of labels names.
1058 ///
1059 /// Only a loop consumes `labels`; every other statement ignores them (the
1060 /// parser has already rejected a label on a statement that cannot use it).
1061 fn stmt_labelled(&mut self, stmt: &Stmt, labels: &[String]) -> Result<(), SyntaxError> {
1062 // Only a *top-level* expression statement supplies the program's value.
1063 let saved = self.cur().leaves_value;
1064 self.state().leaves_value =
1065 matches!(stmt.kind, StmtKind::Expr(_)) && self.cur().stmt_depth == 0;
1066 self.state().stmt_depth += 1;
1067 let result = self.stmt_inner(stmt, labels);
1068 self.state().stmt_depth -= 1;
1069 // A nested statement never contributes the program's value, so the flag
1070 // the wrapper set above is what survives.
1071 let produced = self.cur().leaves_value && self.cur().stmt_depth == 0;
1072 self.state().leaves_value = produced;
1073 let _ = saved;
1074 result
1075 }
1076
1077 fn stmt_inner(&mut self, stmt: &Stmt, labels: &[String]) -> Result<(), SyntaxError> {
1078 match &stmt.kind {
1079 StmtKind::Empty | StmtKind::Debugger => {}
1080 StmtKind::Expr(expr) => {
1081 // An expression statement's value is thrown away — except in a
1082 // script, where it becomes the program's result. `assign` reads this
1083 // and clears it, so a nested assignment still produces a value.
1084 self.state().discard_value = !self.cur().is_script;
1085 let result = self.expr(expr);
1086 self.state().discard_value = false;
1087 result?;
1088 if std::mem::take(&mut self.state().no_value) {
1089 // A store whose value was discarded left nothing to drop.
1090 } else if self.cur().is_script {
1091 // The program's value lands in the hidden `<ret>` local.
1092 self.emit(Opcode::PutLoc, &[Op::Slot(Slot::Loc(0))]);
1093 } else {
1094 self.emit(Opcode::Drop, &[]);
1095 }
1096 }
1097 StmtKind::Block(body) => {
1098 // The block's declarations were hoisted with its enclosing
1099 // statement list, so there is nothing left to declare here.
1100 let key = stmt.span.start.offset as u64;
1101 let parent = self.cur().current_block;
1102 self.push_block(key, parent);
1103 self.emit_scope_enter(key);
1104 // A block is where a `using` region lives, so its statements have to go
1105 // through `stmts`: that is what emits the disposal epilogue.
1106 self.stmts(body)?;
1107 self.emit_scope_leave(key);
1108 self.state().current_block = parent;
1109 }
1110 StmtKind::VarDecl(decl) => self.var_decl(decl)?,
1111 // A function declaration was already instantiated when its scope was
1112 // entered, so the statement itself emits nothing.
1113 StmtKind::FuncDecl(_) => {}
1114 StmtKind::If { test, cons, alt } => {
1115 self.reset_value();
1116 let else_label = self.new_label();
1117 let end_label = self.new_label();
1118 self.expr(test)?;
1119 self.emit_jump(Opcode::IfFalse, else_label, &[]);
1120 self.stmt(cons)?;
1121 if alt.is_some() {
1122 self.emit_jump(Opcode::Goto, end_label, &[]);
1123 }
1124 self.place_label(else_label);
1125 if let Some(alt) = alt {
1126 self.stmt(alt)?;
1127 self.place_label(end_label);
1128 }
1129 }
1130 StmtKind::While { test, body } => {
1131 self.reset_value();
1132 let top = self.new_label();
1133 let end = self.new_label();
1134 self.place_label(top);
1135 self.expr(test)?;
1136 // The condition's false branch and `break` share one target,
1137 // which is why a `while` loop needs only one end label.
1138 self.emit_jump(Opcode::IfFalse, end, &[]);
1139 self.loop_body(body, labels, top, end)?;
1140 self.emit_jump(Opcode::Goto, top, &[]);
1141 self.place_label(end);
1142 }
1143 StmtKind::DoWhile { body, test } => {
1144 self.reset_value();
1145 let top = self.new_label();
1146 let cont = self.new_label();
1147 let end = self.new_label();
1148 self.place_label(top);
1149 // `continue` in a `do…while` runs the test, so it lands on `cont`
1150 // rather than on the loop head.
1151 self.loop_body(body, labels, cont, end)?;
1152 self.place_label(cont);
1153 self.expr(test)?;
1154 self.emit_jump(Opcode::IfTrue, top, &[]);
1155 self.place_label(end);
1156 }
1157 StmtKind::For {
1158 init,
1159 test,
1160 update,
1161 body,
1162 } => {
1163 self.reset_value();
1164 let for_key = stmt.span.start.offset as u64;
1165 let for_parent = self.cur().current_block;
1166 self.push_block(for_key, for_parent);
1167 self.emit_scope_enter(for_key);
1168 if let Some(init) = init {
1169 match init {
1170 ForInit::VarDecl(decl) => {
1171 self.var_decl(decl)?;
1172 }
1173 ForInit::Expr(expr) => {
1174 // The head's value is discarded. Saying so lets an
1175 // assignment store with `put` instead of `dup`+`put`, which
1176 // is what the reference emits — and the difference matters:
1177 // a `dup`/`drop` pair around the store gives the peephole a
1178 // chance to fold the store into the *condition's* read.
1179 self.state().discard_value = true;
1180 let result = self.expr(expr);
1181 self.state().discard_value = false;
1182 result?;
1183 if !std::mem::take(&mut self.state().no_value) {
1184 self.emit(Opcode::Drop, &[]);
1185 }
1186 }
1187 }
1188 }
1189 // A `let`/`const` in the head gets a *fresh binding per iteration*,
1190 // so a closure made in the body captures that iteration's value
1191 // instead of sharing one. The reference expresses this with
1192 // `close_loc`, which swaps in a new reference cell holding the
1193 // current value; the three points below are the ones it uses — after
1194 // the initialiser, before the update, and after the loop.
1195 let loop_bindings = match init {
1196 Some(ForInit::VarDecl(decl)) if decl.kind != VarDeclKind::Var => {
1197 let mut names: Vec<String> = Vec::new();
1198 for declarator in &decl.declarators {
1199 let mut idents = Vec::new();
1200 declarator.target.bound_names(&mut idents);
1201 names.extend(idents.into_iter().map(|ident| ident.name));
1202 }
1203 names
1204 }
1205 _ => Vec::new(),
1206 };
1207 // The reference also closes right after the initialiser, so the first
1208 // iteration's closures get their own cell rather than sharing the one
1209 // the initialiser wrote into.
1210 for name in &loop_bindings {
1211 let pos = self.cur().cur_pos;
1212 self.state().insns.push(Insn::CloseCaptured {
1213 name: name.clone(),
1214 block: for_key,
1215 });
1216 self.state().insn_pos.push(pos);
1217 }
1218 let top = self.new_label();
1219 let cont = self.new_label();
1220 let end = self.new_label();
1221 self.place_label(top);
1222 if let Some(test) = test {
1223 self.expr(test)?;
1224 self.emit_jump(Opcode::IfFalse, end, &[]);
1225 }
1226 // `continue` runs the update expression first, so it lands on
1227 // `cont`, which sits just before the update.
1228 self.loop_body(body, labels, cont, end)?;
1229 self.place_label(cont);
1230 // Each iteration ends with a fresh cell, so the closures the body just
1231 // created keep the cell they captured and the update writes to a new
1232 // one. Without this every closure in the loop shares one binding.
1233 let binding_block = for_key;
1234 for name in &loop_bindings {
1235 let pos = self.cur().cur_pos;
1236 self.state().insns.push(Insn::CloseCaptured {
1237 name: name.clone(),
1238 block: binding_block,
1239 });
1240 self.state().insn_pos.push(pos);
1241 }
1242 if let Some(update) = update {
1243 self.state().discard_value = true;
1244 let result = self.expr(update);
1245 self.state().discard_value = false;
1246 result?;
1247 if !std::mem::take(&mut self.state().no_value) {
1248 self.emit(Opcode::Drop, &[]);
1249 }
1250 }
1251 self.emit_jump(Opcode::Goto, top, &[]);
1252 self.place_label(end);
1253 self.emit_scope_leave(for_key);
1254 self.state().current_block = for_parent;
1255 }
1256 StmtKind::Return(value) => self.return_stmt(value.as_deref())?,
1257 StmtKind::Throw(expr) => {
1258 self.expr(expr)?;
1259 self.emit(Opcode::Throw, &[]);
1260 }
1261 StmtKind::Break(_) | StmtKind::Continue(_) => {
1262 // Labels and loops are wired up in a later milestone; a bare
1263 // break/continue jumps to the innermost enclosing target, which
1264 // the loop helpers register.
1265 self.control_transfer(stmt)?;
1266 }
1267 StmtKind::Labeled { label, body } => {
1268 self.labeled(label, body, stmt)?;
1269 }
1270 StmtKind::Switch {
1271 discriminant,
1272 cases,
1273 } => {
1274 self.switch(discriminant, cases, stmt)?;
1275 }
1276 StmtKind::Try {
1277 block,
1278 handler,
1279 finalizer,
1280 } => {
1281 self.try_stmt(stmt, block, handler, finalizer.as_deref())?;
1282 }
1283 StmtKind::ForIn { left, right, body } => {
1284 self.for_in_of(stmt, left, right, body, ForLoopKind::In)?;
1285 }
1286 StmtKind::ForOf {
1287 left,
1288 right,
1289 body,
1290 is_await,
1291 } => {
1292 let kind = if *is_await {
1293 ForLoopKind::AwaitOf
1294 } else {
1295 ForLoopKind::Of
1296 };
1297 self.for_in_of(stmt, left, right, body, kind)?;
1298 }
1299 StmtKind::With { object, body } => self.with_stmt(object, body)?,
1300 StmtKind::ClassDecl(class) => self.class_definition(class, false)?,
1301 StmtKind::Import(_) | StmtKind::Export(_) => {
1302 return Err(SyntaxError::new(
1303 "modules are not supported by the compiler yet",
1304 stmt.span,
1305 ));
1306 }
1307 }
1308 Ok(())
1309 }
1310
1311 /// Compile `return`, running every enclosing finalizer on the way out.
1312 ///
1313 /// `nip_catch` is what makes this possible: it discards everything on the stack
1314 /// down to and including the `catch` offset while keeping the return value on
1315 /// top, so the frame the finalizer sees has the same shape as on the normal
1316 /// path.
1317 fn return_stmt(&mut self, value: Option<&Expr>) -> Result<(), SyntaxError> {
1318 let mut has_value = value.is_some();
1319 if let Some(expr) = value {
1320 // `return f(x)` is a tail call *only* when nothing has to happen to the
1321 // value afterwards. A `finally` or an open iterator in scope forces the
1322 // normal path, because the cleanup has to run after the call returns —
1323 // which is exactly what a tail call refuses to do.
1324 let plain = self
1325 .cur()
1326 .jump_targets
1327 .iter()
1328 .all(|target| target.finally_label.is_none() && !target.has_iterator);
1329 if plain && self.expr_if_tail_call(expr)? {
1330 return Ok(());
1331 }
1332 self.expr(expr)?;
1333 }
1334 let targets = self.cur().jump_targets.clone();
1335 for target in targets.iter().rev() {
1336 if target.finally_label.is_none() && !target.has_iterator {
1337 continue;
1338 }
1339 if !has_value {
1340 // The cleanup expects a value to pass through; with nothing to
1341 // return, `undefined` stands in.
1342 self.emit(Opcode::Undefined, &[]);
1343 has_value = true;
1344 }
1345 self.emit(Opcode::NipCatch, &[]);
1346 if target.has_iterator {
1347 // Rewind to the loop's own slots, then rotate the return value out
1348 // of the way and hand `iterator_close` a dummy catch offset: the
1349 // loop is being abandoned, so there is nothing left to catch.
1350 self.emit(Opcode::Rot3r, &[]);
1351 self.emit(Opcode::Undefined, &[]);
1352 self.emit(Opcode::IteratorClose, &[]);
1353 } else if let Some(finally) = target.finally_label {
1354 self.emit_jump(Opcode::Gosub, finally, &[]);
1355 }
1356 }
1357 // A generator or async function does not return to its caller: it either
1358 // finishes, and the value becomes `{value, done: true}`, or it suspends.
1359 // `return_async` is the "finished" half, and it reads the value off the stack
1360 // rather than carrying it, which is what the resume machinery expects.
1361 if self.cur().is_suspending() {
1362 if !has_value {
1363 self.emit(Opcode::Undefined, &[]);
1364 }
1365 self.emit(Opcode::ReturnAsync, &[]);
1366 return Ok(());
1367 }
1368 if has_value {
1369 self.emit(Opcode::Return, &[]);
1370 } else {
1371 self.emit(Opcode::ReturnUndef, &[]);
1372 }
1373 Ok(())
1374 }
1375
1376 /// Compile a statement list, stopping at the first statement that cannot
1377 /// fall through.
1378 fn stmts(&mut self, body: &[Stmt]) -> Result<(), SyntaxError> {
1379 for (index, stmt) in body.iter().enumerate() {
1380 // A `using` declaration is not just a binding: everything after it, to the end
1381 // of the list, runs inside its disposal region. Compiling the rest of the list
1382 // recursively is what gives nested regions their innermost-first order.
1383 if Self::using_declaration(stmt).is_some() {
1384 return self.using_region(stmt, &body[index + 1..]);
1385 }
1386 self.stmt(stmt)?;
1387 if Self::terminates(stmt) {
1388 break;
1389 }
1390 }
1391 Ok(())
1392 }
1393
1394 /// The declaration a `using` statement carries, if it is one.
1395 fn using_declaration(stmt: &Stmt) -> Option<&VarDecl> {
1396 match &stmt.kind {
1397 StmtKind::VarDecl(decl) if decl.kind.is_using() => Some(decl),
1398 _ => None,
1399 }
1400 }
1401
1402 /// Compile `decl` and then the rest of its block, disposing when the block ends.
1403 ///
1404 /// The shape mirrors a `try`/`finally`, and deliberately so: the disposal has to run on
1405 /// every way out of the block — reaching its end, `return`, `break`, `continue`, and an
1406 /// exception — and this engine already funnels all of those through `catch` plus
1407 /// `gosub`. Registering the region as a jump target with a `finally_label` is what makes
1408 /// `return` and `break` dispose without knowing anything about `using`.
1409 ///
1410 /// ```text
1411 /// <declaration> value -> x, method -> x+1
1412 /// catch CATCH <- an exception in the rest lands here
1413 /// REST:
1414 /// <the rest of the block>
1415 /// drop <- the catch offset, on the fall-through path
1416 /// undefined; gosub DISPOSE; drop
1417 /// goto END
1418 /// CATCH:
1419 /// using_dispose x <- merges the failure into the pending exception
1420 /// throw
1421 /// DISPOSE:
1422 /// using_dispose_init
1423 /// using_dispose x
1424 /// using_dispose_end <- rethrows if a dispose failed
1425 /// ret
1426 /// END:
1427 /// ```
1428 fn using_region(&mut self, stmt: &Stmt, rest: &[Stmt]) -> Result<(), SyntaxError> {
1429 let Some(decl) = Self::using_declaration(stmt) else {
1430 unreachable!("using_region is only called for a using declaration");
1431 };
1432 // `using` binds exactly one name and has no pattern form, which the parser
1433 // enforces; the region still has to know *which* slot to dispose.
1434 let name = decl
1435 .declarators
1436 .first()
1437 .and_then(|declarator| match &declarator.target.kind {
1438 PatternKind::Ident(ident) => Some(ident.name.clone()),
1439 _ => None,
1440 });
1441 self.stmt(stmt)?;
1442 let Some(name) = name else {
1443 // Unreachable for a well-formed `using`, but a bare `using` with no declarator
1444 // must not make the compiler panic.
1445 return self.stmts(rest);
1446 };
1447 let Some(value_slot) = self.using_value_slot(&name) else {
1448 // Declared globally, which the parser rules out for a script; a module's
1449 // top level is a scope, and there the disposal stays a known gap.
1450 return self.stmts(rest);
1451 };
1452 // A block that ends in a `return` or a `throw` never reaches its own epilogue; the
1453 // exit path already disposed.
1454 let live = !rest.last().is_some_and(Self::terminates);
1455 self.using_region_around(value_slot, live, |compiler| compiler.stmts(rest))
1456 }
1457
1458 /// The slot a `using` binding's value lives in.
1459 fn using_value_slot(&self, name: &str) -> Option<u32> {
1460 self.cur()
1461 .vars
1462 .iter()
1463 .position(|var| var.name == name && var.kind == VarKind::Using)
1464 .map(|index| index as u32)
1465 }
1466
1467 /// Wrap `inside` in a disposal region for the resource in `value_slot`.
1468 ///
1469 /// Shared between a `using` statement — which owns the rest of its block — and a
1470 /// `for (using x of …)` body, which owns only one iteration. The shape mirrors a
1471 /// `try`/`finally`, deliberately: the disposal has to run on every way out — reaching
1472 /// the end, `return`, `break`, `continue`, and an exception — and this engine already
1473 /// funnels all of those through `catch` plus `gosub`. Registering the region as a jump
1474 /// target with a `finally_label` is what makes `return` and `break` dispose without
1475 /// knowing anything about `using`.
1476 ///
1477 /// ```text
1478 /// catch CATCH <- an exception inside lands here
1479 /// <inside>
1480 /// drop <- the catch offset, on the fall-through path
1481 /// undefined; gosub DISPOSE; drop
1482 /// goto END
1483 /// CATCH:
1484 /// using_dispose slot <- merges the failure into the pending exception
1485 /// throw
1486 /// DISPOSE:
1487 /// using_dispose_init
1488 /// using_dispose slot
1489 /// using_dispose_end <- rethrows if a dispose failed
1490 /// ret
1491 /// END:
1492 /// ```
1493 fn using_region_around(
1494 &mut self,
1495 value_slot: u32,
1496 live: bool,
1497 inside: impl FnOnce(&mut Self) -> Result<(), SyntaxError>,
1498 ) -> Result<(), SyntaxError> {
1499 let catch_label = self.new_label();
1500 let end_label = self.new_label();
1501 let dispose_label = self.new_label();
1502
1503 self.emit_jump(Opcode::Catch, catch_label, &[]);
1504 self.push_jump_target(JumpTarget {
1505 names: Vec::new(),
1506 break_label: None,
1507 continue_label: None,
1508 // The catch offset is the one thing on the stack that leaving has to remove.
1509 drop_count: 1,
1510 finally_label: Some(dispose_label),
1511 is_regular_stmt: false,
1512 has_iterator: false,
1513 });
1514 inside(self)?;
1515 self.pop_jump_target();
1516
1517 if live {
1518 self.emit(Opcode::Drop, &[]);
1519 self.emit(Opcode::Undefined, &[]);
1520 self.emit_jump(Opcode::Gosub, dispose_label, &[]);
1521 self.emit(Opcode::Drop, &[]);
1522 self.emit_jump(Opcode::Goto, end_label, &[]);
1523 }
1524
1525 // An exception unwinds to here with the thrown value on the stack, which is exactly
1526 // the shape `using_dispose` expects as its error state.
1527 self.place_label(catch_label);
1528 self.emit(Opcode::UsingDispose, &[Op::Slot(Slot::Loc(value_slot))]);
1529 self.emit(Opcode::Throw, &[]);
1530
1531 self.place_label(dispose_label);
1532 // Inside the subroutine the return value and the `gosub` return address are both
1533 // live, and neither an outer finalizer nor another region may run before this one
1534 // has finished.
1535 self.push_jump_target(JumpTarget {
1536 names: Vec::new(),
1537 break_label: None,
1538 continue_label: None,
1539 drop_count: 2,
1540 finally_label: None,
1541 is_regular_stmt: false,
1542 has_iterator: false,
1543 });
1544 self.emit(Opcode::UsingDisposeInit, &[]);
1545 self.emit(Opcode::UsingDispose, &[Op::Slot(Slot::Loc(value_slot))]);
1546 self.emit(Opcode::UsingDisposeEnd, &[]);
1547 self.pop_jump_target();
1548 self.emit(Opcode::Ret, &[]);
1549 self.place_label(end_label);
1550 Ok(())
1551 }
1552
1553 /// Declare every name a statement list introduces, before compiling any of
1554 /// it, so a reference that appears textually before a declaration still
1555 /// resolves.
1556 ///
1557 /// Declarations are walked in source order because that is the order the
1558 /// reference numbers its slots in: `let a; var b;` gives `a` slot 0 and `b`
1559 /// slot 1, while `var b; let a;` gives the opposite. `var` and function
1560 /// declarations hoist out to the function scope; lexical names belong to the
1561 /// block they were written in, which `block` records.
1562 fn hoist(&mut self, body: &[Stmt], block: u64) -> Result<(), SyntaxError> {
1563 let saved = self.cur().current_block;
1564 self.state().current_block = block;
1565 let result = self.hoist_list(body);
1566 // Only now is every binding of this scope known, so the deferred function
1567 // bodies can be compiled against the finished list. Compiled at its own
1568 // declaration instead, a body that names a `var` written further down would
1569 // have resolved that name as a global.
1570 if result.is_ok() {
1571 let deferred = std::mem::take(&mut self.state().deferred_funcs);
1572 let mut outcome = Ok(());
1573 for (owner, func) in deferred {
1574 let previous = self.cur().current_block;
1575 self.state().current_block = owner;
1576 outcome = self.func_decl(&func);
1577 self.state().current_block = previous;
1578 if outcome.is_err() {
1579 break;
1580 }
1581 }
1582 self.state().current_block = saved;
1583 return outcome;
1584 }
1585 // `current_block` is restored by the caller for a block statement, since
1586 // it needs it set while compiling; only clean up on the hoist path.
1587 self.state().current_block = saved;
1588 result
1589 }
1590
1591 fn hoist_list(&mut self, body: &[Stmt]) -> Result<(), SyntaxError> {
1592 for stmt in body {
1593 self.hoist_stmt(stmt)?;
1594 }
1595 Ok(())
1596 }
1597
1598 /// Whether a statement always transfers control away, making everything after
1599 /// it in the same list unreachable.
1600 ///
1601 /// The reference drops such statements in `skip_dead_code`, so `return 1;
1602 /// let x = 2;` compiles to the same bytecode as `return 1;`.
1603 fn terminates(stmt: &Stmt) -> bool {
1604 matches!(
1605 stmt.kind,
1606 StmtKind::Return(_) | StmtKind::Throw(_) | StmtKind::Break(_) | StmtKind::Continue(_)
1607 )
1608 }
1609
1610 fn hoist_stmt(&mut self, stmt: &Stmt) -> Result<(), SyntaxError> {
1611 match &stmt.kind {
1612 StmtKind::VarDecl(decl) => {
1613 for declarator in &decl.declarators {
1614 let mut names = Vec::new();
1615 declarator.target.bound_names(&mut names);
1616 for name in names {
1617 let text = name.name.clone();
1618 if decl.kind == VarDeclKind::Var {
1619 let def = VarDef::var(text.clone());
1620 self.declare_var(&text, def);
1621 } else if decl.kind.is_using() {
1622 // Two adjacent slots: the resource, then the dispose method
1623 // snapshotted at declaration. `using_dispose` reads them as a
1624 // pair `(slot, slot + 1)`, so nothing may be declared between
1625 // them — which is why both are declared here, in one step,
1626 // rather than the method being added at emission time.
1627 self.declare_using(&text);
1628 } else {
1629 let def = if decl.kind == VarDeclKind::Const {
1630 VarDef::constant(text.clone())
1631 } else {
1632 VarDef::lexical(text.clone())
1633 };
1634 self.declare(&text, def);
1635 }
1636 }
1637 }
1638 }
1639 StmtKind::FuncDecl(func) => {
1640 if let Some(name) = &func.name {
1641 // A function declaration is a `var` binding that happens to
1642 // hold a function, not a lexical one.
1643 let def = VarDef::var(name.name.clone());
1644 self.declare_var(&name.name.clone(), def);
1645 }
1646 // The function object is created when the scope is entered, so it
1647 // exists before the declaration is reached. Its body is compiled
1648 // *after* this scope's hoisting finishes, so a name it uses resolves
1649 // even when the `var` that declares it comes later in the source.
1650 let owner = self.cur().current_block;
1651 self.state().deferred_funcs.push((owner, func.clone()));
1652 }
1653 StmtKind::ClassDecl(class) => {
1654 if let Some(name) = &class.name {
1655 self.declare(&name.name.clone(), VarDef::lexical(name.name.clone()));
1656 }
1657 }
1658 StmtKind::Block(inner) => self.hoist_block(stmt.span.start.offset as u64, inner)?,
1659 StmtKind::If { cons, alt, .. } => {
1660 self.hoist_stmt(cons)?;
1661 if let Some(alt) = alt {
1662 self.hoist_stmt(alt)?;
1663 }
1664 }
1665 StmtKind::While { body, .. }
1666 | StmtKind::DoWhile { body, .. }
1667 | StmtKind::Labeled { body, .. }
1668 | StmtKind::With { body, .. } => self.hoist_stmt(body)?,
1669 StmtKind::For { init, body, .. } => {
1670 // A `for` head gets its own scope even when it declares nothing,
1671 // because `let` in the head is scoped to the loop.
1672 let key = stmt.span.start.offset as u64;
1673 let parent = self.cur().current_block;
1674 self.push_block(key, parent);
1675 if let Some(init) = init
1676 && let ForInit::VarDecl(decl) = init
1677 {
1678 self.hoist_stmt(&Stmt::new(StmtKind::VarDecl(decl.clone()), stmt.span))?;
1679 }
1680 self.hoist_stmt(body)?;
1681 self.state().current_block = parent;
1682 }
1683 StmtKind::ForIn { left, body, .. } | StmtKind::ForOf { left, body, .. } => {
1684 let key = stmt.span.start.offset as u64;
1685 let parent = self.cur().current_block;
1686 self.push_block(key, parent);
1687 if let ForHead::VarDecl(decl) = left {
1688 self.hoist_stmt(&Stmt::new(StmtKind::VarDecl(decl.clone()), stmt.span))?;
1689 }
1690 self.hoist_stmt(body)?;
1691 self.state().current_block = parent;
1692 }
1693 StmtKind::Try {
1694 block,
1695 handler,
1696 finalizer,
1697 } => {
1698 self.hoist_block(Self::try_block_key(stmt, TryPart::Block), block)?;
1699 let try_parent = self.cur().current_block;
1700 if let Some(handler) = handler {
1701 // The catch parameter belongs to the function scope, not to a
1702 // block: it is a `catch` binding rather than a `let`, so it is
1703 // never in the temporal dead zone and `emit_scope_enter` must
1704 // not mark it uninitialised. It still has to be declared before
1705 // the handler body is hoisted, so it takes the slot the
1706 // reference gives it (bindings are numbered in source order).
1707 if let Some(Pattern {
1708 kind: PatternKind::Ident(name),
1709 ..
1710 }) = &handler.param
1711 {
1712 // The parameter gets its own scope, so entering the handler
1713 // does not have to re-declare it. It is not lexical, so it
1714 // is never marked uninitialised.
1715 let key = Self::try_block_key(stmt, TryPart::Param);
1716 let parent = self.cur().current_block;
1717 self.push_block(key, parent);
1718 let def = VarDef {
1719 name: name.name.clone(),
1720 is_const: false,
1721 is_lexical: false,
1722 kind: crate::bytecode::VarKind::Catch,
1723 is_captured: false,
1724 scope_level: 0,
1725 scope_next: None,
1726 };
1727 self.declare_local(&name.name.clone(), def);
1728 // The handler body nests inside the parameter's scope, so the
1729 // body's bindings chain on to the parameter (the reference
1730 // prints `let y [next:1]`, pointing at `e`).
1731 self.state().current_block = key;
1732 }
1733 self.hoist_block(Self::try_block_key(stmt, TryPart::Catch), &handler.body)?;
1734 // Back to the block the `try` itself lives in, so the finalizer
1735 // is a sibling of the handler rather than nested in it.
1736 self.state().current_block = try_parent;
1737 }
1738 if let Some(finalizer) = finalizer {
1739 self.hoist_block(Self::try_block_key(stmt, TryPart::Finally), finalizer)?;
1740 }
1741 }
1742 StmtKind::Switch { cases, .. } => {
1743 let key = stmt.span.start.offset as u64;
1744 let parent = self.cur().current_block;
1745 self.push_block(key, parent);
1746 for case in cases {
1747 self.hoist_list(&case.body)?;
1748 }
1749 self.state().current_block = parent;
1750 }
1751 _ => {}
1752 }
1753 Ok(())
1754 }
1755
1756 /// Hoist a nested statement list, which is its own lexical scope.
1757 fn hoist_block(&mut self, key: u64, body: &[Stmt]) -> Result<(), SyntaxError> {
1758 let parent = self.cur().current_block;
1759 self.push_block(key, parent);
1760 self.hoist_list(body)?;
1761 self.state().current_block = parent;
1762 Ok(())
1763 }
1764
1765 /// A block key for one part of a `try` statement.
1766 ///
1767 /// The three parts are three separate scopes, so they cannot share the key a
1768 /// statement's own offset would give them: the try block, the handler body and
1769 /// the finalizer would then look like one scope, and their `let` bindings would
1770 /// be marked uninitialised only on entering the first of them.
1771 fn try_block_key(stmt: &Stmt, part: TryPart) -> u64 {
1772 (stmt.span.start.offset as u64) * 4 + part as u64
1773 }
1774
1775 /// Declare a `var`: it lives in the function's own scope, not the block's.
1776 fn declare_var(&mut self, name: &str, def: VarDef) {
1777 if self.cur().declares_globally(&def) {
1778 self.declare_global(name, &def);
1779 return;
1780 }
1781 let state = self.state();
1782 // A binding of the *parameter* scope does not count: the body's `var` of the
1783 // same name is a different binding and needs a slot of its own.
1784 if state.vars.iter().enumerate().any(|(index, v)| {
1785 v.name == name && state.var_block.get(index).copied() != Some(PARAM_SCOPE)
1786 }) {
1787 return;
1788 }
1789 // A `var` belongs to the function scope, never to the enclosing block.
1790 state.var_block.push(FUNCTION_SCOPE);
1791 state.vars.push(def);
1792 }
1793
1794 /// Declare `name` as a binding of the parameter scope, returning its slot.
1795 fn declare_param_var(&mut self, name: &str) -> u32 {
1796 declare_param_var_at(self.state(), name)
1797 }
1798
1799 /// Give the *parameter* scope an `arguments` binding if the parameter list mentions
1800 /// one.
1801 ///
1802 /// With parameter expressions the reference creates two: an unmapped one in the
1803 /// argument scope, for the defaults and anything they close over, and the body's own.
1804 /// They are separate bindings, which is what makes
1805 /// `(a = eval("var arguments = 1"), p = () => arguments) => { var arguments = 2 }`
1806 /// report 1 from `p` and 2 from the body.
1807 fn provide_param_arguments(&mut self) {
1808 if !self.cur().has_parameter_expressions {
1809 return;
1810 }
1811 let mentioned = self.cur().needs_param_arguments
1812 || self
1813 .cur()
1814 .insns
1815 .iter()
1816 .any(|insn| matches!(insn, Insn::Var { name, in_params: true, .. } if name == "arguments"));
1817 if !mentioned {
1818 return;
1819 }
1820 let slot = self.declare_param_var("arguments");
1821 let magic = if self.cur().strict { 0 } else { 1 };
1822 self.prepend_initialiser_to(
1823 slot,
1824 Insn::Fixed {
1825 op: Opcode::SpecialObject,
1826 operands: vec![Op::Int(magic)],
1827 },
1828 );
1829 }
1830
1831 /// [`Compiler::prepend_initialiser`] for a slot rather than a name.
1832 fn prepend_initialiser_to(&mut self, slot: u32, producer: Insn) {
1833 let current = self.stack.len() - 1;
1834 let init = [
1835 producer,
1836 Insn::Fixed {
1837 op: Opcode::PutLoc,
1838 operands: vec![Op::Slot(Slot::Loc(slot))],
1839 },
1840 ];
1841 let inserted = init.len();
1842 for (index, instruction) in init.into_iter().enumerate() {
1843 self.stack[current].insns.insert(index, instruction);
1844 }
1845 for placed in self.stack[current].labels.iter_mut().flatten() {
1846 *placed += inserted;
1847 }
1848 self.state().label_since_insn = false;
1849 }
1850
1851 /// Give the function an `arguments` binding if its body mentions one.
1852 ///
1853 /// The check runs on the *instruction* stream rather than the AST: by this point
1854 /// every reference has become an `Insn::Var`, so scanning is exact and needs no
1855 /// AST walker. Declaring lazily matters for more than tidiness — always declaring
1856 /// would renumber every later local slot and stop the bytecode matching the
1857 /// reference, which only adds the binding when the body uses it.
1858 ///
1859 /// `arguments` is a local, initialised at the top of the body by
1860 /// `special_object`; that is the reference's shape, so the disassembly agrees.
1861 fn provide_arguments(&mut self) {
1862 let current = self.stack.len() - 1;
1863 if self.stack[current].is_script {
1864 return;
1865 }
1866 // An arrow has no `arguments` of its own: the binding belongs to the enclosing
1867 // function, which is why `() => arguments` sees the caller's arguments.
1868 if self.stack[current].is_arrow {
1869 if self.mentions("arguments") {
1870 self.ensure_enclosing_arguments();
1871 }
1872 return;
1873 }
1874 // Only a *body* mention needs the body's binding: the parameter list has one of
1875 // its own (see [`Compiler::provide_param_arguments`]).
1876 let mentioned = self.cur().insns.iter().any(|insn| {
1877 matches!(insn, Insn::Var { name, in_params, .. } if name == "arguments" && !*in_params)
1878 });
1879 if !mentioned && !self.cur().needs_arguments_local {
1880 return;
1881 }
1882 // The request may have come only from a parameter-list arrow, in which case the
1883 // parameter scope's binding already answers for it and the body needs none.
1884 if !mentioned && self.cur().has_parameter_expressions && !self.body_mentions_arguments() {
1885 return;
1886 }
1887 // 0 is strict `arguments`, 1 is sloppy (mapped) `arguments`. The mapping
1888 // itself is not implemented, so the two behave alike for now.
1889 let magic = if self.stack[current].strict { 0 } else { 1 };
1890 self.prepend_binding("arguments", magic);
1891 }
1892
1893 /// Whether a *body* instruction refers to `arguments`.
1894 fn body_mentions_arguments(&self) -> bool {
1895 self.cur()
1896 .insns
1897 .iter()
1898 .any(|insn| matches!(insn, Insn::Var { name, in_params, .. } if name == "arguments" && !*in_params))
1899 }
1900
1901 /// Whether the function body's instruction stream refers to `name`.
1902 fn mentions(&self, name: &str) -> bool {
1903 let current = self.stack.len() - 1;
1904 // A binding of the parameter scope does not answer for the body: the body's own
1905 // `arguments` (or self-name) still has to be provided for it.
1906 if self.stack[current]
1907 .vars
1908 .iter()
1909 .enumerate()
1910 .any(|(index, v)| {
1911 v.name == name
1912 && self.stack[current].var_block.get(index).copied() != Some(PARAM_SCOPE)
1913 })
1914 {
1915 return false;
1916 }
1917 self.stack[current]
1918 .insns
1919 .iter()
1920 .any(|insn| matches!(insn, Insn::Var { name: used, .. } if used == name))
1921 }
1922
1923 /// Bind the name a named function expression uses to refer to itself.
1924 ///
1925 /// The value is `special_object 2`, the function currently running, so the binding
1926 /// is the closure itself and not a copy. It is a local of this function, which is
1927 /// what keeps `g` out of the enclosing scope.
1928 /// Give the function a local `this`, for an arrow inside it to capture.
1929 fn provide_this_local(&mut self) {
1930 let current = self.stack.len() - 1;
1931 if !self.stack[current].needs_this_local {
1932 return;
1933 }
1934 if !self.stack[current]
1935 .vars
1936 .iter()
1937 .any(|var| var.name == "this")
1938 {
1939 self.declare_hidden_local("this", VarKind::Normal);
1940 }
1941 self.prepend_initialiser(
1942 "this",
1943 Insn::Fixed {
1944 op: Opcode::PushThis,
1945 operands: vec![],
1946 },
1947 );
1948 }
1949
1950 fn provide_self_name(&mut self) {
1951 let current = self.stack.len() - 1;
1952 let Some(name) = self.stack[current].self_name.clone() else {
1953 return;
1954 };
1955 if self.stack[current].self_name_initialized {
1956 return;
1957 }
1958 // Either the body refers to the name, or a nested function already forced the
1959 // binding into existence while being resolved. A direct `eval` can name it
1960 // without mentioning it, so its presence is a third reason: in strict mode
1961 // `eval("f = 1")` has to raise a `TypeError` rather than a `ReferenceError`, and
1962 // that only happens if the binding exists.
1963 let declared = self.stack[current].vars.iter().any(|v| v.name == name);
1964 if !declared && !self.mentions(&name) && !self.stack[current].has_direct_eval {
1965 return;
1966 }
1967 self.stack[current].self_name_initialized = true;
1968 self.prepend_binding_with(&name, 2, VarKind::FunctionName);
1969 }
1970
1971 /// Insert `special_object magic` plus the store to `name` at the top of the body.
1972 ///
1973 /// Prepending shifts every label that has been placed, so they are all moved by
1974 /// the number of instructions inserted.
1975 fn prepend_binding(&mut self, name: &str, magic: i32) {
1976 self.prepend_binding_with(name, magic, VarKind::Normal);
1977 }
1978
1979 /// [`Compiler::prepend_binding`] for a binding that is more than a plain local.
1980 fn prepend_binding_with(&mut self, name: &str, magic: i32, kind: VarKind) {
1981 let current = self.stack.len() - 1;
1982 // A function-expression's own name is immutable in strict mode, which is what
1983 // makes `f = 1` inside a strict body throw instead of being dropped.
1984 let is_const = kind == VarKind::FunctionName && self.stack[current].strict;
1985 self.declare_var(
1986 name,
1987 VarDef {
1988 kind,
1989 is_const,
1990 ..VarDef::var(name)
1991 },
1992 );
1993 let init = [
1994 Insn::Fixed {
1995 op: Opcode::SpecialObject,
1996 operands: vec![Op::Int(magic)],
1997 },
1998 Insn::Var {
1999 // An initialisation, not an assignment: sloppy mode drops stores to a
2000 // function-expression's own name, and the prologue is what puts the
2001 // value there in the first place.
2002 action: if kind == VarKind::FunctionName {
2003 VarAction::PutInit
2004 } else {
2005 VarAction::Put
2006 },
2007 name: name.to_string(),
2008 block: 0,
2009 in_params: false,
2010 },
2011 ];
2012 let inserted = init.len();
2013 for (index, instruction) in init.into_iter().enumerate() {
2014 self.stack[current].insns.insert(index, instruction);
2015 }
2016 for placed in self.stack[current].labels.iter_mut().flatten() {
2017 *placed += inserted;
2018 }
2019 // A store sits at the insertion point now, so the `put`/`get` fold must not
2020 // reach across it.
2021 self.stack[current].label_since_insn = true;
2022 }
2023
2024 /// Record a top-level script declaration as a global.
2025 ///
2026 /// A script's top-level `var`/`let`/`function` create properties of the
2027 /// global object, not slots in the script's frame, so they show up as closure
2028 /// variables instead.
2029 fn declare_global(&mut self, name: &str, def: &VarDef) {
2030 let state = self.state();
2031 if let Some(existing) = state.closure_vars.iter_mut().find(|c| c.name == name) {
2032 // The name was already referenced, from a function compiled before this
2033 // declaration was reached — `function a(){ b() } function b(){}` resolves
2034 // `b` while `b` is still unknown, and that guess has to be corrected here.
2035 // Leaving it as a plain global meant the declaration was never registered,
2036 // so the binding did not exist at run time and `a()` threw
2037 // `b is not defined`.
2038 if matches!(existing.closure_type, ClosureType::Global) {
2039 existing.closure_type = ClosureType::GlobalDecl;
2040 existing.is_const = def.is_const;
2041 existing.is_lexical = def.is_lexical;
2042 }
2043 return;
2044 }
2045 state.closure_vars.push(ClosureVar {
2046 name: name.to_string(),
2047 is_const: def.is_const,
2048 is_lexical: def.is_lexical,
2049 closure_type: ClosureType::GlobalDecl,
2050 var_idx: 0,
2051 });
2052 }
2053
2054 /// Compile a loop body with a `break`/`continue` target pushed for it.
2055 fn loop_body(
2056 &mut self,
2057 body: &Stmt,
2058 labels: &[String],
2059 continue_label: Label,
2060 break_label: Label,
2061 ) -> Result<(), SyntaxError> {
2062 self.push_jump_target(JumpTarget {
2063 names: labels.to_vec(),
2064 break_label: Some(break_label),
2065 continue_label: Some(continue_label),
2066 // A loop leaves nothing of its own on the value stack.
2067 drop_count: 0,
2068 finally_label: None,
2069 is_regular_stmt: false,
2070 has_iterator: false,
2071 });
2072 let result = self.stmt(body);
2073 self.pop_jump_target();
2074 result
2075 }
2076
2077 fn push_jump_target(&mut self, target: JumpTarget) {
2078 self.state().jump_targets.push(target);
2079 }
2080
2081 fn pop_jump_target(&mut self) {
2082 self.state().jump_targets.pop();
2083 }
2084
2085 fn control_transfer(&mut self, stmt: &Stmt) -> Result<(), SyntaxError> {
2086 let (label, is_break) = match &stmt.kind {
2087 StmtKind::Break(label) => (label.as_ref(), true),
2088 StmtKind::Continue(label) => (label.as_ref(), false),
2089 _ => unreachable!("control_transfer is only called for break and continue"),
2090 };
2091
2092 // Walk outward from the innermost construct. Everything considered before
2093 // the match is a construct control is leaving, and leaving it has a cost:
2094 // its stack slots go, and its finalizer runs.
2095 let targets = self.cur().jump_targets.clone();
2096 for target in targets.iter().rev() {
2097 let destination = match (label, is_break) {
2098 // An unlabelled `break` skips a labelled non-loop statement: `break`
2099 // may name one, but the bare form only means "leave the loop".
2100 (None, true) => target.break_label.filter(|_| !target.is_regular_stmt),
2101 (None, false) => target.continue_label,
2102 (Some(name), true) => target
2103 .break_label
2104 .filter(|_| target.names.contains(&name.name)),
2105 (Some(name), false) => target
2106 .continue_label
2107 .filter(|_| target.names.contains(&name.name)),
2108 };
2109
2110 if let Some(destination) = destination {
2111 self.emit_jump(Opcode::Goto, destination, &[]);
2112 return Ok(());
2113 }
2114
2115 // Closing the iterator consumes the three slots the loop keeps on the
2116 // stack (iterator, next method, catch offset), so those are not dropped
2117 // again below.
2118 let mut remaining = target.drop_count;
2119 if target.has_iterator {
2120 self.emit(Opcode::IteratorClose, &[]);
2121 remaining = remaining.saturating_sub(3);
2122 }
2123 for _ in 0..remaining {
2124 self.emit(Opcode::Drop, &[]);
2125 }
2126 if let Some(finally) = target.finally_label {
2127 // The finalizer runs as a subroutine and is handed a dummy return
2128 // value, which is dropped afterwards to keep the stack the depth it
2129 // had before.
2130 self.emit(Opcode::Undefined, &[]);
2131 self.emit_jump(Opcode::Gosub, finally, &[]);
2132 self.emit(Opcode::Drop, &[]);
2133 }
2134 }
2135
2136 // The parser rejects a break/continue with no target, so reaching here
2137 // means the compiler's own bookkeeping is wrong.
2138 Err(SyntaxError::new(
2139 if is_break {
2140 "break has no enclosing loop or switch"
2141 } else {
2142 "continue has no enclosing loop"
2143 },
2144 stmt.span,
2145 ))
2146 }
2147
2148 /// Compile a labelled statement.
2149 ///
2150 /// `a: b: for(…)` is a chain of labels on one loop; every name has to reach
2151 /// that loop's targets, so the chain is collected and handed to the loop. A
2152 /// label on a non-loop statement only provides a `break` target, because
2153 /// `continue` may not target it.
2154 fn labeled(&mut self, label: &Ident, body: &Stmt, stmt: &Stmt) -> Result<(), SyntaxError> {
2155 let mut names = vec![label.name.clone()];
2156 let mut inner = body;
2157 while let StmtKind::Labeled {
2158 label: next,
2159 body: deeper,
2160 } = &inner.kind
2161 {
2162 names.push(next.name.clone());
2163 inner = deeper;
2164 }
2165 if Self::is_loop(inner) {
2166 return self.stmt_labelled(inner, &names);
2167 }
2168 let end = self.new_label();
2169 self.push_jump_target(JumpTarget {
2170 names,
2171 break_label: Some(end),
2172 continue_label: None,
2173 drop_count: 0,
2174 finally_label: None,
2175 is_regular_stmt: true,
2176 has_iterator: false,
2177 });
2178 let result = self.stmt(inner);
2179 self.pop_jump_target();
2180 result?;
2181 self.place_label(end);
2182 let _ = stmt;
2183 Ok(())
2184 }
2185
2186 /// Whether a statement is a loop, i.e. a valid target for `continue`.
2187 fn is_loop(stmt: &Stmt) -> bool {
2188 matches!(
2189 stmt.kind,
2190 StmtKind::While { .. }
2191 | StmtKind::DoWhile { .. }
2192 | StmtKind::For { .. }
2193 | StmtKind::ForIn { .. }
2194 | StmtKind::ForOf { .. }
2195 )
2196 }
2197
2198 /// Compile `switch`.
2199 ///
2200 /// The discriminant is evaluated once and stays on the value stack while the
2201 /// clauses compare against copies of it, so it is dropped at the end — which is
2202 /// why `switch (x) { }` still leaves `x` behind. Fallthrough is real: a
2203 /// clause's body jumps over the *next* clause's tests straight into its body.
2204 ///
2205 /// The tests form a chain: each `case` run compares and, on a miss, hands over to
2206 /// the next run's tests. Only the last run's miss reaches the `default` body, or
2207 /// the end of the switch when there is no `default`. That failure path can point
2208 /// backwards (`default` written first), so the runs and their labels are worked
2209 /// out before any code is emitted.
2210 fn switch(
2211 &mut self,
2212 discriminant: &Expr,
2213 cases: &[SwitchCase],
2214 stmt: &Stmt,
2215 ) -> Result<(), SyntaxError> {
2216 self.reset_value();
2217 // The discriminant is evaluated outside the switch's block scope, before
2218 // any `case` clause exists.
2219 self.expr(discriminant)?;
2220
2221 let switch_key = stmt.span.start.offset as u64;
2222 let switch_parent = self.cur().current_block;
2223 self.push_block(switch_key, switch_parent);
2224 self.emit_scope_enter(switch_key);
2225
2226 let break_label = self.new_label();
2227 self.push_jump_target(JumpTarget {
2228 names: Vec::new(),
2229 break_label: Some(break_label),
2230 // `switch` is a valid `break` target but not a `continue` target.
2231 continue_label: None,
2232 // The discriminant stays on the value stack for the whole statement, so
2233 // a `break` aimed further out has to discard it.
2234 drop_count: 1,
2235 finally_label: None,
2236 is_regular_stmt: false,
2237 has_iterator: false,
2238 });
2239
2240 // Runs of tests. `case 1: case 2: body` is one run: the empty clause hands
2241 // its label to the clause after it, so both tests reach the same body.
2242 let mut runs: Vec<(usize, usize)> = Vec::new();
2243 let mut scan = 0;
2244 while scan < cases.len() {
2245 if cases[scan].test.is_some() {
2246 let mut last = scan;
2247 while last + 1 < cases.len()
2248 && cases[last].test.is_some()
2249 && cases[last].body.is_empty()
2250 && cases[last + 1].test.is_some()
2251 {
2252 last += 1;
2253 }
2254 runs.push((scan, last));
2255 scan = last + 1;
2256 } else {
2257 scan += 1;
2258 }
2259 }
2260
2261 let body_labels: Vec<Label> = cases.iter().map(|_| self.new_label()).collect();
2262 let run_labels: Vec<Label> = runs.iter().map(|_| self.new_label()).collect();
2263 let default_at = cases.iter().position(|case| case.test.is_none());
2264 // Where the last run sends control when nothing matched.
2265 let miss_target = match default_at {
2266 Some(index) => body_labels[index],
2267 None => break_label,
2268 };
2269
2270 // When `default` comes first, control has to jump over it to reach the
2271 // tests. It only needs to when some clause actually has a test; otherwise
2272 // the default body is the entry point.
2273 let mut entry = None;
2274 if default_at == Some(0) && !runs.is_empty() {
2275 self.emit_jump(Opcode::Goto, run_labels[0], &[]);
2276 entry = Some(run_labels[0]);
2277 }
2278
2279 let mut index = 0;
2280 let mut run = 0;
2281 let result = (|| -> Result<(), SyntaxError> {
2282 while index < cases.len() {
2283 if cases[index].test.is_some() {
2284 let (first, last) = runs[run];
2285 // Reaching these tests from the preceding body is a
2286 // fallthrough, which continues inside the body and skips them.
2287 if index > 0 {
2288 self.emit_jump(Opcode::Goto, body_labels[index], &[]);
2289 }
2290 if let Some(label) = entry.take() {
2291 self.place_label(label);
2292 }
2293 self.place_label(run_labels[run]);
2294
2295 for (offset, case) in cases[first..=last].iter().enumerate() {
2296 let test = case.test.as_ref().unwrap();
2297 self.emit(Opcode::Dup, &[]);
2298 self.expr(test)?;
2299 self.emit(Opcode::StrictEq, &[]);
2300 if first + offset < last {
2301 self.emit_jump(Opcode::IfTrue, body_labels[index], &[]);
2302 } else {
2303 // Hand over to the next run's tests, or give up.
2304 let next = match runs.get(run + 1) {
2305 Some(_) => run_labels[run + 1],
2306 None => miss_target,
2307 };
2308 self.emit_jump(Opcode::IfFalse, next, &[]);
2309 }
2310 }
2311
2312 self.place_label(body_labels[index]);
2313 for case in &cases[first..=last] {
2314 self.stmts(&case.body)?;
2315 }
2316 index = last + 1;
2317 run += 1;
2318 } else {
2319 // `default`: control arrives here either by falling through or
2320 // because every test missed.
2321 self.place_label(body_labels[index]);
2322 self.stmts(&cases[index].body)?;
2323 index += 1;
2324 }
2325 }
2326 Ok(())
2327 })();
2328
2329 if result.is_ok() {
2330 self.place_label(break_label);
2331 // Discard the discriminant now that no test needs it.
2332 self.emit(Opcode::Drop, &[]);
2333 }
2334
2335 self.pop_jump_target();
2336 self.emit_scope_leave(switch_key);
2337 self.state().current_block = switch_parent;
2338 result
2339 }
2340
2341 /// Compile `try`/`catch`/`finally`.
2342 ///
2343 /// The shape is an exception table built out of `catch` instructions, each of
2344 /// which records where control goes if the instructions that follow raise:
2345 ///
2346 /// ```text
2347 /// catch HANDLER <- if the guarded block throws, jump to HANDLER
2348 /// <guarded block>
2349 /// drop <- discard the catch offset
2350 /// undefined; gosub FINALLY; drop
2351 /// goto END
2352 /// HANDLER:
2353 /// <bind the catch parameter>
2354 /// catch CATCH2 <- if the handler itself throws, go to CATCH2
2355 /// <handler body>
2356 /// drop; undefined; gosub FINALLY; drop; goto END
2357 /// CATCH2:
2358 /// gosub FINALLY; throw <- run the finalizer, then let the error out
2359 /// FINALLY:
2360 /// <finalizer>
2361 /// ret <- return to the `gosub`
2362 /// END:
2363 /// ```
2364 ///
2365 /// `gosub` is a subroutine call and `ret` returns to it, which is how one copy
2366 /// of the finalizer serves the normal path, the handler path and the
2367 /// propagating-exception path.
2368 ///
2369 /// The `undefined` before each `gosub` is a dummy return value: the finalizer
2370 /// runs with `ret_value` on the stack, and the normal path has no value to
2371 /// keep, so it pushes one to keep the stack depth identical on every path.
2372 fn try_stmt(
2373 &mut self,
2374 stmt: &Stmt,
2375 block: &[Stmt],
2376 handler: &Option<CatchClause>,
2377 finalizer: Option<&[Stmt]>,
2378 ) -> Result<(), SyntaxError> {
2379 self.reset_value();
2380
2381 let catch_label = self.new_label();
2382 let catch2_label = self.new_label();
2383 let finally_label = self.new_label();
2384 let end_label = self.new_label();
2385
2386 self.emit_jump(Opcode::Catch, catch_label, &[]);
2387
2388 // The guarded block. `break` may not target it, so its entry exists purely
2389 // to unwind: a jump out has to discard the catch offset and run the
2390 // finalizer.
2391 self.push_jump_target(JumpTarget {
2392 names: Vec::new(),
2393 break_label: None,
2394 continue_label: None,
2395 drop_count: 1,
2396 finally_label: Some(finally_label),
2397 is_regular_stmt: false,
2398 has_iterator: false,
2399 });
2400
2401 let block_key = Self::try_block_key(stmt, TryPart::Block);
2402 let block_parent = self.cur().current_block;
2403 self.push_block(block_key, block_parent);
2404 self.emit_scope_enter(block_key);
2405 self.stmts(block)?;
2406 self.emit_scope_leave(block_key);
2407 self.state().current_block = block_parent;
2408 // A guarded block that ends in a `return`/`throw` never reaches the
2409 // epilogue, so the reference does not emit one.
2410 self.pop_jump_target();
2411 let block_live = !block.last().is_some_and(Self::terminates);
2412
2413 if block_live {
2414 self.emit(Opcode::Drop, &[]);
2415 self.emit(Opcode::Undefined, &[]);
2416 self.emit_jump(Opcode::Gosub, finally_label, &[]);
2417 self.emit(Opcode::Drop, &[]);
2418 self.emit_jump(Opcode::Goto, end_label, &[]);
2419 }
2420
2421 if let Some(handler) = handler {
2422 self.place_label(catch_label);
2423 // The thrown value is on top of the stack: bind it, or discard it for
2424 // `catch { }`.
2425 match &handler.param {
2426 Some(Pattern {
2427 kind: PatternKind::Ident(name),
2428 ..
2429 }) => {
2430 // The store resolves the name, so it has to run inside the
2431 // parameter's own scope; otherwise a same-named `catch` further
2432 // out could win.
2433 let param_key = Self::try_block_key(stmt, TryPart::Param);
2434 let param_parent = self.cur().current_block;
2435 self.push_block(param_key, param_parent);
2436 self.emit_var(VarAction::Put, &name.name);
2437 self.state().current_block = param_parent;
2438 }
2439 Some(other) => {
2440 return Err(SyntaxError::new(
2441 "destructuring catch parameters are not supported by the compiler yet",
2442 other.span,
2443 ));
2444 }
2445 None => self.emit(Opcode::Drop, &[]),
2446 }
2447 self.emit_jump(Opcode::Catch, catch2_label, &[]);
2448
2449 self.push_jump_target(JumpTarget {
2450 names: Vec::new(),
2451 break_label: None,
2452 continue_label: None,
2453 drop_count: 1,
2454 finally_label: Some(finally_label),
2455 is_regular_stmt: false,
2456 has_iterator: false,
2457 });
2458 let catch_key = Self::try_block_key(stmt, TryPart::Catch);
2459 let catch_parent = self.cur().current_block;
2460 self.push_block(catch_key, catch_parent);
2461 self.emit_scope_enter(catch_key);
2462 self.stmts(&handler.body)?;
2463 self.emit_scope_leave(catch_key);
2464 self.state().current_block = catch_parent;
2465 self.pop_jump_target();
2466 let handler_live = !handler.body.last().is_some_and(Self::terminates);
2467
2468 if handler_live {
2469 self.emit(Opcode::Drop, &[]);
2470 self.emit(Opcode::Undefined, &[]);
2471 self.emit_jump(Opcode::Gosub, finally_label, &[]);
2472 self.emit(Opcode::Drop, &[]);
2473 self.emit_jump(Opcode::Goto, end_label, &[]);
2474 }
2475
2476 // An error raised inside the handler still has to run the finalizer.
2477 self.place_label(catch2_label);
2478 self.emit_jump(Opcode::Gosub, finally_label, &[]);
2479 self.emit(Opcode::Throw, &[]);
2480 } else {
2481 // `try`/`finally` with no handler: the finalizer runs, then the error
2482 // keeps propagating.
2483 self.place_label(catch_label);
2484 self.emit_jump(Opcode::Gosub, finally_label, &[]);
2485 self.emit(Opcode::Throw, &[]);
2486 }
2487
2488 self.place_label(finally_label);
2489 // Inside the finalizer, leaving has a different cost: the return value and
2490 // the `gosub` return address are both on the stack, and neither finalizer nor
2491 // any outer one may run before the block has finished.
2492 self.push_jump_target(JumpTarget {
2493 names: Vec::new(),
2494 break_label: None,
2495 continue_label: None,
2496 drop_count: 2,
2497 finally_label: None,
2498 is_regular_stmt: false,
2499 has_iterator: false,
2500 });
2501 if let Some(finalizer) = finalizer {
2502 let finally_key = Self::try_block_key(stmt, TryPart::Finally);
2503 let finally_parent = self.cur().current_block;
2504 self.push_block(finally_key, finally_parent);
2505 self.emit_scope_enter(finally_key);
2506 self.stmts(finalizer)?;
2507 self.emit_scope_leave(finally_key);
2508 self.state().current_block = finally_parent;
2509 }
2510 self.pop_jump_target();
2511 self.emit(Opcode::Ret, &[]);
2512 self.place_label(end_label);
2513 Ok(())
2514 }
2515
2516 /// Compile `for`/`in` and `for`/`of`.
2517 ///
2518 /// Both keep an enumeration record on the value stack for the whole loop, which
2519 /// is what makes leaving early expensive: the record has to be dropped, or the
2520 /// iterator closed. The layout is
2521 ///
2522 /// ```text
2523 /// <iterated expression>
2524 /// for_in_start | for_of_start <- pushes the record
2525 /// goto TEST
2526 /// NEXT:
2527 /// <bind the loop variable>
2528 /// <body>
2529 /// TEST:
2530 /// for_in_next | for_of_next 0
2531 /// if_false NEXT <- not finished: next iteration
2532 /// drop <- finished: discard the leftover value
2533 /// BREAK:
2534 /// drop | iterator_close <- the one cleanup `break` also uses
2535 /// ```
2536 ///
2537 /// `BREAK` sits *on* the cleanup rather than after it, so an early exit and the
2538 /// normal exit share one copy — which is why `break` inside the loop emits nothing
2539 /// of its own, and only a jump that passes *through* the loop pays for its record.
2540 fn for_in_of(
2541 &mut self,
2542 stmt: &Stmt,
2543 left: &ForHead,
2544 right: &Expr,
2545 body: &Stmt,
2546 kind: ForLoopKind,
2547 ) -> Result<(), SyntaxError> {
2548 self.reset_value();
2549
2550 let loop_key = stmt.span.start.offset as u64;
2551 let loop_parent = self.cur().current_block;
2552 self.push_block(loop_key, loop_parent);
2553 self.emit_scope_enter(loop_key);
2554
2555 // The iterated expression is evaluated inside the loop's scope, after the
2556 // bindings exist in the temporal dead zone.
2557 self.expr(right)?;
2558
2559 let next = self.new_label();
2560 let test = self.new_label();
2561 let break_target = self.new_label();
2562
2563 let has_iterator = matches!(kind, ForLoopKind::Of | ForLoopKind::AwaitOf);
2564 match kind {
2565 ForLoopKind::In => self.emit(Opcode::ForInStart, &[]),
2566 ForLoopKind::Of => self.emit(Opcode::ForOfStart, &[]),
2567 ForLoopKind::AwaitOf => self.emit(Opcode::ForAwaitOfStart, &[]),
2568 }
2569 self.emit_jump(Opcode::Goto, test, &[]);
2570
2571 self.push_jump_target(JumpTarget {
2572 names: Vec::new(),
2573 break_label: Some(break_target),
2574 continue_label: Some(test),
2575 // Passing through the loop has to dispose of its record. A `for`/`of`
2576 // record is three slots, and closing the iterator consumes all of them.
2577 drop_count: if has_iterator { 3 } else { 1 },
2578 finally_label: None,
2579 is_regular_stmt: false,
2580 has_iterator,
2581 });
2582
2583 self.place_label(next);
2584 self.bind_loop_variable(left)?;
2585 // The reference marks the body with its own label here. Nothing jumps to it
2586 // once the loop is laid out, but it is not decoration: a label between the
2587 // store and the body is why `put_loc v; get_loc v` does *not* fold into
2588 // `set_loc v` when the body starts by reading the loop variable.
2589 let body_label = self.new_label();
2590 self.place_label(body_label);
2591 // `for (using x of …)` disposes once per iteration, so the body is a disposal
2592 // region rather than the whole loop: the resource is the element that this
2593 // iteration produced.
2594 let using_slot = match left {
2595 ForHead::VarDecl(decl) if decl.kind.is_using() => {
2596 decl.declarators
2597 .first()
2598 .and_then(|declarator| match &declarator.target.kind {
2599 PatternKind::Ident(ident) => self.using_value_slot(&ident.name),
2600 _ => None,
2601 })
2602 }
2603 _ => None,
2604 };
2605 match using_slot {
2606 Some(slot) => {
2607 let live = !Self::terminates(body);
2608 self.using_region_around(slot, live, |compiler| compiler.stmt(body))?;
2609 }
2610 None => self.stmt(body)?,
2611 }
2612
2613 self.place_label(test);
2614 match kind {
2615 ForLoopKind::In => self.emit(Opcode::ForInNext, &[]),
2616 ForLoopKind::Of => self.emit(Opcode::ForOfNext, &[Op::Int(0)]),
2617 ForLoopKind::AwaitOf => {
2618 // The reference's shape: step, `await` the result, then unpack it.
2619 self.emit(Opcode::ForAwaitOfNext, &[Op::Int(0)]);
2620 self.emit(Opcode::Await, &[]);
2621 self.emit(Opcode::IteratorGetValueDone, &[]);
2622 }
2623 }
2624 self.emit_jump(Opcode::IfFalse, next, &[]);
2625 // The loop is finished; `for_xx_next` left an `undefined` behind.
2626 self.emit(Opcode::Drop, &[]);
2627
2628 self.pop_jump_target();
2629 self.place_label(break_target);
2630 if has_iterator {
2631 self.emit(Opcode::IteratorClose, &[]);
2632 } else {
2633 self.emit(Opcode::Drop, &[]);
2634 }
2635
2636 self.emit_scope_leave(loop_key);
2637 self.state().current_block = loop_parent;
2638 Ok(())
2639 }
2640
2641 /// Store the value `for_xx_next` left on the stack into the loop variable.
2642 fn bind_loop_variable(&mut self, left: &ForHead) -> Result<(), SyntaxError> {
2643 // A declaration *initialises* the binding, which is what takes a `let` out of
2644 // the temporal dead zone, so the store is the unchecked form. Assigning to a
2645 // binding declared elsewhere is an ordinary write and keeps its check.
2646 let (pattern, action) = match left {
2647 ForHead::VarDecl(decl) => (&decl.declarators[0].target, VarAction::PutInit),
2648 ForHead::Assign(pattern) => (pattern.as_ref(), VarAction::Put),
2649 };
2650 match &pattern.kind {
2651 PatternKind::Ident(name) => {
2652 // `for (using x of …)` validates and snapshots each iteration's value
2653 // before the body runs, which is what makes a non-disposable element fail
2654 // on the iteration that produced it rather than at the end of the loop.
2655 if let ForHead::VarDecl(decl) = left
2656 && decl.kind.is_using()
2657 {
2658 let method_slot = self
2659 .using_method_slot(&name.name)
2660 .expect("a using binding was declared during hoisting");
2661 self.emit(
2662 Opcode::UsingCheck,
2663 &[Op::Int(if decl.kind.is_await_using() { 1 } else { 0 })],
2664 );
2665 self.emit(Opcode::PutLoc, &[Op::Slot(Slot::Loc(method_slot))]);
2666 }
2667 self.emit_var(action, &name.name);
2668 Ok(())
2669 }
2670 // Every other target stores through the same path an assignment pattern
2671 // uses, which is what makes `for (a[0] in obj)` write each key into the
2672 // property instead of refusing the loop outright.
2673 _ => self.destructure(
2674 pattern,
2675 match left {
2676 ForHead::VarDecl(decl) => Some(decl.kind),
2677 ForHead::Assign(_) => None,
2678 },
2679 ),
2680 }
2681 }
2682
2683 fn var_decl(&mut self, decl: &VarDecl) -> Result<(), SyntaxError> {
2684 for declarator in &decl.declarators {
2685 let Some(init) = &declarator.init else {
2686 // `var x;` stays `undefined`. A lexical binding is different: it
2687 // has to be *initialised* to leave the temporal dead zone, so the
2688 // compiler supplies an explicit `undefined`.
2689 if decl.kind.is_lexical() {
2690 // A lexical binding has to be *initialised* to leave the temporal
2691 // dead zone, and a destructuring one is no different — `let {a}`
2692 // with no initialiser is a syntax error, but `let [a] = []` still
2693 // needs `a` to be initialised from an empty source, which the
2694 // pattern does on its own.
2695 self.emit(Opcode::Undefined, &[]);
2696 self.destructure(&declarator.target, Some(decl.kind))?;
2697 }
2698 continue;
2699 };
2700 match &declarator.target.kind {
2701 PatternKind::Ident(name) => {
2702 self.expr(init)?;
2703 self.set_name_if_anonymous(init, &name.name);
2704 if decl.kind.is_using() {
2705 // `using_check` validates the value and snapshots its dispose
2706 // method: `value -> value, method`. The snapshot is what makes a
2707 // later change to `Symbol.dispose` irrelevant, and validating here
2708 // is what keeps the body from running at all when the value is not
2709 // disposable.
2710 let method_slot = self
2711 .using_method_slot(&name.name)
2712 .expect("a using binding was declared during hoisting");
2713 self.emit(
2714 Opcode::UsingCheck,
2715 &[Op::Int(if decl.kind.is_await_using() { 1 } else { 0 })],
2716 );
2717 self.emit(Opcode::PutLoc, &[Op::Slot(Slot::Loc(method_slot))]);
2718 self.emit_var(VarAction::PutInit, &name.name);
2719 continue;
2720 }
2721 // A declaration statement produces no value, so nothing is
2722 // duplicated onto the stack.
2723 match decl.kind {
2724 VarDeclKind::Var => self.emit_var(VarAction::Put, &name.name),
2725 _ => self.emit_var(VarAction::PutInit, &name.name),
2726 }
2727 }
2728 _ => {
2729 // A destructuring declaration keeps nothing on the stack: the
2730 // pattern consumes the initialiser.
2731 self.expr(init)?;
2732 self.destructure(&declarator.target, Some(decl.kind))?;
2733 }
2734 }
2735 }
2736 Ok(())
2737 }
2738
2739 /// Bind a destructuring pattern from the value on top of the stack.
2740 ///
2741 /// `decl` picks the mode. `Some(kind)` is a *declaration*: every target is an
2742 /// identifier and the store is a binding write, `put_*` for `var` and `put_*_init`
2743 /// for `let`/`const` so the binding leaves its dead zone. `None` is a destructuring
2744 /// *assignment*, where a member expression is a legal target and the store is an
2745 /// ordinary property write.
2746 ///
2747 /// The value is consumed. An assignment expression's own result is the right-hand
2748 /// side, which the caller keeps separately — the spec does not make the pattern's
2749 /// last store produce it.
2750 fn destructure(
2751 &mut self,
2752 pattern: &Pattern,
2753 decl: Option<VarDeclKind>,
2754 ) -> Result<(), SyntaxError> {
2755 match &pattern.kind {
2756 PatternKind::Ident(name) => {
2757 match decl {
2758 Some(VarDeclKind::Var) | None => {
2759 self.emit_var(VarAction::Put, &name.name);
2760 }
2761 Some(_) => self.emit_var(VarAction::PutInit, &name.name),
2762 }
2763 Ok(())
2764 }
2765 PatternKind::Assign { target, default } => {
2766 // A default only applies to `undefined`, not to `null`: `[a = 1] = [null]`
2767 // keeps `null`.
2768 let use_default = self.new_label();
2769 let done = self.new_label();
2770 self.emit(Opcode::Dup, &[]);
2771 self.emit(Opcode::IsUndefined, &[]);
2772 self.emit_jump(Opcode::IfTrue, use_default, &[]);
2773 self.destructure(target, decl)?;
2774 self.emit_jump(Opcode::Goto, done, &[]);
2775 self.place_label(use_default);
2776 self.emit(Opcode::Drop, &[]);
2777 self.expr(default)?;
2778 // `var {f = function(){}} = {}` names the function `f`, like a plain
2779 // `var f = function(){}` does.
2780 self.destructure(target, decl)?;
2781 self.place_label(done);
2782 Ok(())
2783 }
2784 PatternKind::Array { elements, rest } => self.destructure_array(elements, rest, decl),
2785 PatternKind::Object { properties, rest } => {
2786 self.destructure_object(properties, rest, decl, pattern)
2787 }
2788 PatternKind::Member(member) if decl.is_none() => {
2789 // An assignment pattern may store into a property. The value is on the
2790 // stack, so the receiver and the key go above it and `rot3l`/`swap2`
2791 // put the three in the order `put_array_el`/`put_field` expect.
2792 self.expr(&member.object)?;
2793 match &member.property {
2794 MemberProp::Ident(name) => {
2795 // `value obj` -> `obj value`, the order `put_field` takes.
2796 // Nothing needs to be left behind: a pattern element's value is
2797 // consumed by its own store.
2798 self.emit(Opcode::Swap, &[]);
2799 self.emit(Opcode::PutField, &[Op::Atom(Atom::from_text(&name.name))]);
2800 }
2801 MemberProp::Computed(index) => {
2802 self.expr(index)?;
2803 // `value obj key` -> `obj key value`.
2804 self.emit(Opcode::Rot3l, &[]);
2805 self.emit(Opcode::PutArrayEl, &[]);
2806 }
2807 MemberProp::Private(_) => {
2808 return Err(SyntaxError::new(
2809 "private fields are not supported by the compiler yet",
2810 member.span,
2811 ));
2812 }
2813 }
2814 Ok(())
2815 }
2816 PatternKind::Rest(inner) => self.destructure(inner, decl),
2817 PatternKind::Invalid(expr) => {
2818 Err(SyntaxError::new("invalid assignment target", expr.span))
2819 }
2820 _ => Err(SyntaxError::new(
2821 "this destructuring target is not supported by the compiler yet",
2822 pattern.span,
2823 )),
2824 }
2825 }
2826
2827 /// `[…]` on the left: drain an iterator, binding one target per element.
2828 fn destructure_array(
2829 &mut self,
2830 elements: &[Option<PatternElement>],
2831 rest: &Option<Box<RestElement>>,
2832 decl: Option<VarDeclKind>,
2833 ) -> Result<(), SyntaxError> {
2834 // The iterator protocol is the same one `for (… of …)` uses, so a destructuring
2835 // pattern accepts any iterable and closes the iterator when the pattern ends
2836 // early. `for_of_next` pushes the value and a `done` flag; the flag comes off
2837 // first because it is on top.
2838 self.emit(Opcode::ForOfStart, &[]);
2839 for element in elements {
2840 self.emit(Opcode::ForOfNext, &[Op::Int(0)]);
2841 self.emit(Opcode::Drop, &[]);
2842 match element {
2843 Some(PatternElement::Pattern(pattern)) => self.destructure(pattern, decl)?,
2844 Some(PatternElement::Property { span, .. }) => {
2845 return Err(SyntaxError::new(
2846 "a property pattern is not a valid array element",
2847 *span,
2848 ));
2849 }
2850 // An elision skips the value, which is already on the stack.
2851 None => self.emit(Opcode::Drop, &[]),
2852 }
2853 }
2854 if let Some(rest) = rest {
2855 // The remaining values go into a fresh array. The target and its running
2856 // index stay on the stack above the iterator, which is what the operand of
2857 // `for_of_next` accounts for: two values sit above the iterator triple.
2858 self.emit(Opcode::ArrayFrom, &[Op::Int(0)]);
2859 self.emit(Opcode::Push0, &[]);
2860 let top = self.new_label();
2861 self.place_label(top);
2862 self.emit(Opcode::ForOfNext, &[Op::Int(2)]);
2863 let done = self.new_label();
2864 self.emit_jump(Opcode::IfTrue, done, &[]);
2865 self.emit(Opcode::DefineArrayEl, &[]);
2866 self.emit(Opcode::Inc, &[]);
2867 self.emit_jump(Opcode::Goto, top, &[]);
2868 self.place_label(done);
2869 self.emit(Opcode::Drop, &[]);
2870 self.emit(Opcode::Drop, &[]);
2871 self.destructure_rest(rest, decl)?;
2872 }
2873 self.emit(Opcode::IteratorClose, &[]);
2874 Ok(())
2875 }
2876
2877 /// `{…}` on the left: read properties off one boxed source object.
2878 fn destructure_object(
2879 &mut self,
2880 properties: &[Option<PatternElement>],
2881 rest: &Option<Box<RestElement>>,
2882 decl: Option<VarDeclKind>,
2883 pattern: &Pattern,
2884 ) -> Result<(), SyntaxError> {
2885 // `ToObject` is what refuses `null`/`undefined`, and it also puts the source
2886 // aside for the rest element below.
2887 self.emit(Opcode::ToObject, &[]);
2888 let mut taken: Vec<String> = Vec::new();
2889 // Whether any key was computed, which a rest element cannot exclude.
2890 let mut computed = false;
2891 for property in properties {
2892 let Some(PatternElement::Property {
2893 key, value, span, ..
2894 }) = property
2895 else {
2896 return Err(SyntaxError::new(
2897 "a bare pattern is not a valid object property",
2898 properties
2899 .iter()
2900 .flatten()
2901 .map(|element| match element {
2902 PatternElement::Pattern(pattern) => pattern.span,
2903 PatternElement::Property { span, .. } => *span,
2904 })
2905 .next()
2906 .unwrap_or(pattern.span),
2907 ));
2908 };
2909 // Every read needs the source twice: once to read from, once to keep for
2910 // the next property. `get_field2` is not used here because the value has to
2911 // come off a stack that also holds the source.
2912 self.emit(Opcode::Dup, &[]);
2913 match key {
2914 PropName::Literal(literal) => {
2915 let name = self.property_key_text(literal, *span)?;
2916 taken.push(name.clone());
2917 self.emit(Opcode::GetField, &[Op::Atom(Atom::from_text(&name))]);
2918 }
2919 PropName::Computed(index) => {
2920 // A computed key has no name to exclude ahead of time, so a rest
2921 // element that has to skip it is refused below rather than silently
2922 // copying the property into the rest object.
2923 computed = true;
2924 self.expr(index)?;
2925 self.emit(Opcode::GetArrayEl, &[]);
2926 }
2927 PropName::Private(_) => {
2928 return Err(SyntaxError::new(
2929 "private fields are not supported by the compiler yet",
2930 value.span,
2931 ));
2932 }
2933 }
2934 self.destructure(value, decl)?;
2935 }
2936 match rest {
2937 Some(rest) => {
2938 if computed {
2939 return Err(SyntaxError::new(
2940 "a computed key with a rest element is not supported by the compiler yet",
2941 Self::rest_span(rest),
2942 ));
2943 }
2944 // `target src exclude`: the exclusion list is an array of the keys the
2945 // literal part already took, so the rest object gets only the others.
2946 self.emit(Opcode::Object, &[]);
2947 self.emit(Opcode::Swap, &[]);
2948 for name in &taken {
2949 self.emit(Opcode::PushAtomValue, &[Op::Atom(Atom::from_text(name))]);
2950 }
2951 self.emit(Opcode::ArrayFrom, &[Op::Int(taken.len() as i32)]);
2952 self.emit(Opcode::CopyDataProperties, &[Op::Int(COPY_ALL_PROPERTIES)]);
2953 self.emit(Opcode::Drop, &[]);
2954 self.emit(Opcode::Drop, &[]);
2955 self.destructure_rest(rest, decl)?;
2956 }
2957 // The source was only kept for a rest element.
2958 None => self.emit(Opcode::Drop, &[]),
2959 }
2960 Ok(())
2961 }
2962
2963 /// The pattern a rest element binds, as a target [`Self::destructure`] takes.
2964 fn destructure_rest(
2965 &mut self,
2966 rest: &RestElement,
2967 decl: Option<VarDeclKind>,
2968 ) -> Result<(), SyntaxError> {
2969 match rest {
2970 RestElement::Pattern(pattern) => self.destructure(pattern, decl),
2971 // `[...a.b] = c` stores into a property.
2972 RestElement::Member(member) => {
2973 let pattern = Pattern {
2974 kind: PatternKind::Member(member.clone()),
2975 span: member.span,
2976 };
2977 self.destructure(&pattern, decl)
2978 }
2979 }
2980 }
2981
2982 /// The source range of a rest element, for error messages.
2983 fn rest_span(rest: &RestElement) -> Span {
2984 match rest {
2985 RestElement::Pattern(pattern) => pattern.span,
2986 RestElement::Member(member) => member.span,
2987 }
2988 }
2989
2990 /// Compile a function declaration and queue it for instantiation at scope
2991 /// entry.
2992 ///
2993 /// A declaration is visible before the statement that declares it, so the
2994 /// code that creates the function object belongs at the top of the enclosing
2995 /// scope, not at the declaration.
2996 fn func_decl(&mut self, func: &ast::Function) -> Result<(), SyntaxError> {
2997 let name = func.name.as_ref().expect("a declaration has a name");
2998 let function = self.compile_function(func)?;
2999 let pool_index = self.push_constant(Constant::Function(Box::new(function)));
3000 let target = self.hoist_target(&name.name);
3001 let block = self.cur().current_block;
3002 self.state().hoisted.push((block, target, pool_index));
3003 Ok(())
3004 }
3005
3006 /// Where a name lives, for a hoisted declaration.
3007 fn hoist_target(&self, name: &str) -> HoistTarget {
3008 let state = self.cur();
3009 if let Some(index) = state.args.iter().position(|a| a.name == name) {
3010 return HoistTarget::Arg(index as u32);
3011 }
3012 if let Some(index) = state.vars.iter().position(|v| v.name == name) {
3013 return HoistTarget::Loc(index as u32);
3014 }
3015 // A global function declaration is not a slot at all.
3016 HoistTarget::Global(name.to_string())
3017 }
3018
3019 // -- expressions -------------------------------------------------------
3020
3021 /// Compile one expression, recording where its instructions sit.
3022 ///
3023 /// The position is the node's operator when it has one and its first token
3024 /// otherwise, and it is restored on the way out so a parent's own instructions —
3025 /// which are emitted *after* its children — are blamed on the parent. Without the
3026 /// restore the `add` in `a + b` would inherit `b`'s position instead of the `+`.
3027 fn expr(&mut self, expr: &Expr) -> Result<(), SyntaxError> {
3028 let saved = self.cur().cur_pos;
3029 self.state().cur_pos = Some(expr.op_pos.unwrap_or(expr.span.start));
3030 // Note a direct `eval` call before compiling it, because the *whole* function
3031 // is affected: an eval can name any binding the function declares, so every one
3032 // of them has to live in a cell for a closure it creates to capture it.
3033 if Self::is_direct_eval(expr) {
3034 // Every enclosing function is affected too: the eval sees the whole scope
3035 // chain, and a closure it creates can capture a binding of any of them.
3036 // `for (let i …) { f() }` where `f` contains the eval still needs `i` in a
3037 // cell, because the closure the eval builds outlives the loop iteration.
3038 for state in &mut self.stack {
3039 state.has_direct_eval = true;
3040 }
3041 let block = self.cur().current_block;
3042 let in_params = self.cur().in_params;
3043 self.state()
3044 .pending_eval_sites
3045 .push((expr.span, block, in_params));
3046 }
3047 let result = self.expr_inner(expr);
3048 self.state().cur_pos = saved;
3049 result
3050 }
3051
3052 /// Record which bindings are in scope at a direct `eval` call.
3053 ///
3054 /// Ordinary name lookup happens at compile time; a direct `eval` bypasses that and
3055 /// resolves names from a string at run time, so the only chance to pin down *which*
3056 /// slot a name means is here. Visibility is the lexical rule: a binding counts when
3057 /// its block is the current block, an enclosing one, or the function scope.
3058 fn materialize_eval_sites(&mut self) {
3059 let pending = std::mem::take(&mut self.state().pending_eval_sites);
3060 for (span, site_block, in_params) in pending {
3061 self.resolve_eval_site(span, site_block, in_params);
3062 }
3063 }
3064
3065 /// Resolve the bindings visible at one `eval` call.
3066 fn resolve_eval_site(&mut self, span: Span, site_block: u64, site_in_params: bool) {
3067 /// How near a binding is: function distance first, then block depth, then the
3068 /// later declaration (which shadows the earlier one in the same block).
3069 type ScopePriority = (usize, usize, std::cmp::Reverse<u32>);
3070
3071 // `(sort key, binding)`, where a smaller key wins. The whole scope chain is
3072 // walked, innermost function first: a direct `eval` sees every enclosing
3073 // function's bindings, and none of them can be resolved at run time because the
3074 // runtime only has names to go on.
3075 let mut bindings: Vec<(ScopePriority, EvalVisible)> = Vec::new();
3076 let deepest = self.stack.len() - 1;
3077 for (level, state) in self.stack.iter().enumerate().rev() {
3078 let owner = (deepest - level) as u32;
3079 // The innermost function's block is the one the call sat in, which is not
3080 // the block the compiler is in now; the enclosing functions are still at
3081 // the point where this one was created.
3082 let here = if level == deepest {
3083 site_block
3084 } else {
3085 state.current_block
3086 };
3087 // The chain of live blocks, innermost first, with a depth for each. The walk
3088 // stops at `NO_PARENT`, which is a sentinel rather than `0` because a real
3089 // block can start at source offset zero.
3090 let mut live: Vec<(u64, usize)> = vec![(here, 0)];
3091 let mut block = here;
3092 while let Some(parent) = state
3093 .blocks
3094 .iter()
3095 .find(|candidate| candidate.key == block)
3096 .map(|candidate| candidate.parent)
3097 .filter(|parent| *parent != NO_PARENT)
3098 .filter(|parent| parent != &block)
3099 {
3100 live.push((parent, live.len()));
3101 block = parent;
3102 }
3103 let depth_of = |key: u64| {
3104 live.iter()
3105 .find(|(candidate, _)| *candidate == key)
3106 .map(|(_, depth)| *depth)
3107 // The function scope is the outermost depth there is. A binding of a
3108 // block this site is not inside lands here too, which pushes it
3109 // behind every live one — the right answer: it is out of scope.
3110 .unwrap_or(live.len())
3111 };
3112 for (index, arg) in state.args.iter().enumerate() {
3113 bindings.push((
3114 (owner as usize, live.len(), std::cmp::Reverse(index as u32)),
3115 EvalVisible {
3116 name: arg.name.clone(),
3117 is_arg: true,
3118 index: index as u32,
3119 owner,
3120 },
3121 ));
3122 }
3123 // A parameter list cannot see the body, so a body `var` is not a binding the
3124 // eval can name: `(a = eval("var c = 1"), p = () => c) => { var c = 2 }` must
3125 // not let that eval write the body's `c`.
3126 let hides_body = if level == deepest {
3127 site_in_params
3128 } else {
3129 state.created_in_params
3130 };
3131 for (index, var) in state.vars.iter().enumerate() {
3132 let block = state
3133 .var_block
3134 .get(index)
3135 .copied()
3136 .unwrap_or(FUNCTION_SCOPE);
3137 if hides_body && block == FUNCTION_SCOPE && !visible_in_params(var) {
3138 continue;
3139 }
3140 bindings.push((
3141 (
3142 owner as usize,
3143 depth_of(block),
3144 std::cmp::Reverse(index as u32),
3145 ),
3146 EvalVisible {
3147 name: var.name.clone(),
3148 is_arg: false,
3149 index: index as u32,
3150 owner,
3151 },
3152 ));
3153 }
3154 }
3155 // Innermost function first, then innermost block, then the later declaration
3156 // (which shadows the earlier one within a block).
3157 bindings.sort_by_key(|(priority, _)| *priority);
3158 let bindings = bindings.into_iter().map(|(_, visible)| visible).collect();
3159 self.state().eval_sites.push(EvalSite {
3160 line: span.start.line,
3161 column: span.start.column,
3162 bindings,
3163 });
3164 }
3165
3166 /// Whether `expr` is `eval(...)` — the direct form, which sees the caller's scope.
3167 ///
3168 /// `(0, eval)(…)` and `f.call(null, …)` are *indirect* and get no caller scope; only
3169 /// a bare identifier callee counts.
3170 fn is_direct_eval(expr: &Expr) -> bool {
3171 matches!(
3172 &expr.kind,
3173 ExprKind::Call { callee, .. }
3174 if matches!(&callee.unparen().kind, ExprKind::Ident(name) if name.name == "eval")
3175 )
3176 }
3177
3178 fn expr_inner(&mut self, expr: &Expr) -> Result<(), SyntaxError> {
3179 match &expr.kind {
3180 ExprKind::Number(value) => self.push_number(*value),
3181 ExprKind::Bool(true) => self.emit(Opcode::PushTrue, &[]),
3182 ExprKind::Bool(false) => self.emit(Opcode::PushFalse, &[]),
3183 ExprKind::Null => self.emit(Opcode::Null, &[]),
3184 ExprKind::String(text) => self.push_string(text),
3185 ExprKind::BigInt { digits, radix } => self.push_bigint(digits, *radix),
3186 ExprKind::Ident(name) => self.emit_var(VarAction::Get, &name.name),
3187 ExprKind::This => self.this_expression(),
3188 ExprKind::NewTarget => self.new_target_expression(),
3189 ExprKind::Paren(inner) => self.expr(inner)?,
3190 ExprKind::Binary { op, left, right } => {
3191 self.expr(left)?;
3192 self.expr(right)?;
3193 self.emit(binary_opcode(*op), &[]);
3194 }
3195 ExprKind::Logical { op, left, right } => self.logical(*op, left, right)?,
3196 ExprKind::Unary {
3197 op: UnaryOp::Minus,
3198 argument,
3199 } if matches!(argument.unparen().kind, ExprKind::Number(_)) => {
3200 let ExprKind::Number(value) = argument.unparen().kind else {
3201 unreachable!("matched above")
3202 };
3203 // The reference folds a negative literal only when the negation is
3204 // exact in the integer range: `-1` becomes `push_minus1` and
3205 // `-1.5e3` becomes `push_i16 -1500`, but `-0` and `-2.5` keep a
3206 // runtime `neg`. Folding `-0` would lose the sign — `1/-0` is
3207 // `-Infinity`, not `Infinity` — and folding a fraction would change
3208 // which instruction the reference emits.
3209 let negated = -value;
3210 // `-2147483648` is deliberately excluded: its magnitude is one past
3211 // `i32::MAX`, so the reference sends it through the constant pool and
3212 // negates at run time instead.
3213 if value > 0.0
3214 && negated == negated.trunc()
3215 && negated >= -(i32::MAX as f64)
3216 && negated < 0.0
3217 {
3218 self.push_number(negated);
3219 } else {
3220 self.push_number(value);
3221 self.emit(Opcode::Neg, &[]);
3222 }
3223 }
3224 ExprKind::Unary { op, argument } => self.unary(*op, argument)?,
3225 ExprKind::Conditional { test, cons, alt } => {
3226 let else_label = self.new_label();
3227 let end_label = self.new_label();
3228 self.expr(test)?;
3229 self.emit_jump(Opcode::IfFalse, else_label, &[]);
3230 self.expr(cons)?;
3231 self.emit_jump(Opcode::Goto, end_label, &[]);
3232 self.place_label(else_label);
3233 self.expr(alt)?;
3234 self.place_label(end_label);
3235 }
3236 ExprKind::Assign { op, target, value } => self.assign(*op, target, value)?,
3237 ExprKind::Update {
3238 op,
3239 argument,
3240 prefix,
3241 } => self.update(*op, argument, *prefix)?,
3242 ExprKind::Sequence(items) => {
3243 for (index, item) in items.iter().enumerate() {
3244 self.expr(item)?;
3245 if index + 1 != items.len() {
3246 self.emit(Opcode::Drop, &[]);
3247 }
3248 }
3249 }
3250 ExprKind::Call { .. } => self.chain_link_top(expr)?,
3251 ExprKind::Member { .. } => self.chain_link_top(expr)?,
3252 ExprKind::OptionalChain(inner) => self.optional_chain(inner)?,
3253 ExprKind::Array { elements } => self.array_literal(elements, expr.span)?,
3254 ExprKind::Object(properties) => self.object_literal(properties, expr.span)?,
3255 ExprKind::Template(template) => self.template_literal(template)?,
3256 ExprKind::TaggedTemplate { tag, quasi } => self.tagged_template(tag, quasi)?,
3257 ExprKind::New { callee, arguments } => {
3258 // `new C(args)` compiles to `C; dup; args…; call_constructor n`.
3259 // The `dup` is not redundant: `call_constructor` takes the
3260 // constructor twice, once as the target and once as `new.target`,
3261 // which is what makes `new.target === C` inside the body.
3262 self.expr(callee)?;
3263 self.emit(Opcode::Dup, &[]);
3264 let args = arguments.as_deref().unwrap_or(&[]);
3265 if Self::has_spread(args) {
3266 // `C C array`: the duplicated callee is already both the target
3267 // and `new.target`, so no reordering is needed before `apply 1`.
3268 self.argument_array(args)?;
3269 self.emit(Opcode::Apply, &[Op::Int(1)]);
3270 return Ok(());
3271 }
3272 for argument in args {
3273 self.expr(argument)?;
3274 }
3275 self.emit(Opcode::CallConstructor, &[Op::Int(args.len() as i32)]);
3276 }
3277 ExprKind::Class(class) => self.class_definition(class, true)?,
3278 ExprKind::SuperCall(arguments) => self.super_call(arguments)?,
3279 ExprKind::Yield { argument, delegate } => {
3280 self.yield_expression(argument.as_deref(), *delegate)?
3281 }
3282 ExprKind::Await(argument) => self.await_expression(argument)?,
3283 ExprKind::RegExp { pattern, flags } => {
3284 // The pattern and its flags travel as two string constants; `regexp` builds
3285 // the object. A dedicated opcode (rather than a call to the constructor) is
3286 // what the reference does too, so that a literal never goes through the
3287 // public `RegExp` function and its string-coercion rules.
3288 self.push_string(pattern);
3289 self.push_string(flags);
3290 self.emit(Opcode::Regexp, &[]);
3291 }
3292 ExprKind::Arrow(func) => {
3293 let function = self.compile_function(func)?;
3294 let index = self.push_constant(Constant::Function(Box::new(function)));
3295 self.emit(Opcode::Fclosure, &[Op::Const(index)]);
3296 }
3297 ExprKind::Function(func) => {
3298 let function = self.compile_function_with_name(func, true)?;
3299 let index = self.push_constant(Constant::Function(Box::new(function)));
3300 self.emit(Opcode::Fclosure, &[Op::Const(index)]);
3301 }
3302 _ => {
3303 return Err(SyntaxError::new(
3304 "this expression form is not supported by the compiler yet",
3305 expr.span,
3306 ));
3307 }
3308 }
3309 Ok(())
3310 }
3311
3312 /// Build one array holding the evaluated call arguments, which is how a call
3313 /// containing a spread is compiled: the reference does the same, building the
3314 /// list on the stack and handing it to `apply`.
3315 fn argument_array(&mut self, arguments: &[Expr]) -> Result<(), SyntaxError> {
3316 let elements: Vec<Option<ArrayElement>> = arguments
3317 .iter()
3318 .map(|argument| match &argument.unparen().kind {
3319 ExprKind::Spread(inner) => Some(ArrayElement::Spread(inner.clone())),
3320 _ => Some(ArrayElement::Expr(Box::new(argument.clone()))),
3321 })
3322 .collect();
3323 self.array_literal(&elements, Span::default())
3324 }
3325
3326 /// Whether any argument is a spread, which is what selects the `apply` form.
3327 fn has_spread(arguments: &[Expr]) -> bool {
3328 arguments
3329 .iter()
3330 .any(|argument| matches!(argument.unparen().kind, ExprKind::Spread(_)))
3331 }
3332
3333 /// Compile `a${x}b`.
3334 ///
3335 /// A template is a `+` chain built left to right: the leading chunk (or an empty
3336 /// string when the template starts with a substitution), then for each
3337 /// substitution its value, `to_propkey` and `add`, then the following chunk when
3338 /// it is not empty. `to_propkey` is what makes a number or object substitute the
3339 /// way `ToString` would while leaving the result a string for `add` to
3340 /// concatenate.
3341 ///
3342 /// The chunk is an atom rather than a constant-pool string, because a non-empty
3343 /// chunk always lands where a value is pushed and `push_atom_value` is the
3344 /// instruction the reference uses for it; the empty first chunk has its own
3345 /// zero-byte form.
3346 fn template_literal(&mut self, template: &TemplateLiteral) -> Result<(), SyntaxError> {
3347 let first = template.quasis.first();
3348 match first.and_then(|quasi| quasi.cooked.clone()) {
3349 Some(text) if !text.is_empty() => {
3350 self.emit(Opcode::PushAtomValue, &[Op::Atom(Atom::from_text(&text))]);
3351 }
3352 // Either the template begins with a substitution, or the chunk is
3353 // empty — in both cases the chain needs a string to start from.
3354 _ => self.emit(Opcode::PushEmptyString, &[]),
3355 }
3356 for (index, expression) in template.expressions.iter().enumerate() {
3357 self.expr(expression)?;
3358 self.emit(Opcode::ToPropkey, &[]);
3359 self.emit(Opcode::Add, &[]);
3360 if let Some(text) = template
3361 .quasis
3362 .get(index + 1)
3363 .and_then(|quasi| quasi.cooked.clone())
3364 && !text.is_empty()
3365 {
3366 self.emit(Opcode::PushAtomValue, &[Op::Atom(Atom::from_text(&text))]);
3367 self.emit(Opcode::Add, &[]);
3368 }
3369 }
3370 Ok(())
3371 }
3372
3373 /// Compile an object literal.
3374 ///
3375 /// The object is built in place: `object` pushes it, and each property leaves it
3376 /// on the stack with one field more, so no temporary is needed and later
3377 /// properties can overwrite earlier ones.
3378 ///
3379 /// The instruction depends on *how* the property was written, not on what kind
3380 /// of value it holds:
3381 ///
3382 /// | source | instruction |
3383 /// |---|---|
3384 /// | `{ a: v }` | `define_field a` |
3385 /// | `{ __proto__: v }` | `set_proto` |
3386 /// | `{ [k]: v }` | `to_propkey` … `define_array_el` + `drop` |
3387 /// | `{ m() {} }` | `define_method m,4` |
3388 /// | `{ get m() {} }` / `{ set m(v) {} }` | `define_method m,5` / `,6` |
3389 /// | `{ [k]() {} }` | `define_method_computed 4` |
3390 /// | `{ ...v }` | `null` … `copy_data_properties 6` + two `drop`s |
3391 ///
3392 /// A computed *method* skips `to_propkey`: `define_method_computed` converts the
3393 /// key itself, which is why the trailing `drop` is absent there too.
3394 /// `tag`…``: a call whose first argument is the call site's template object.
3395 ///
3396 /// The template object is a frozen array of the cooked chunks with a frozen `raw`
3397 /// array beside it, so `String.raw` can read the source text back. It is a constant
3398 /// because its contents never change; the reference builds one per call site and
3399 /// reuses it, while this builds one per evaluation, which only `tag` code that
3400 /// compares template objects across calls could tell apart.
3401 fn tagged_template(&mut self, tag: &Expr, quasi: &TemplateLiteral) -> Result<(), SyntaxError> {
3402 let cooked = quasi
3403 .quasis
3404 .iter()
3405 .map(|chunk| chunk.cooked.clone())
3406 .collect();
3407 let raw = quasi.quasis.iter().map(|chunk| chunk.raw.clone()).collect();
3408 let index = self.push_constant(Constant::Template { cooked, raw });
3409 let count = quasi.expressions.len() + 1;
3410 // `o.m`…`` passes `o` as `this`, exactly as `o.m(…)` does.
3411 if let ExprKind::Member {
3412 object, property, ..
3413 } = &tag.unparen().kind
3414 {
3415 self.expr(object)?;
3416 match property {
3417 MemberProp::Ident(name) => {
3418 self.emit(Opcode::GetField2, &[Op::Atom(Atom::from_text(&name.name))]);
3419 }
3420 MemberProp::Computed(key) => {
3421 self.expr(key)?;
3422 self.emit(Opcode::GetArrayEl2, &[]);
3423 }
3424 MemberProp::Private(_) => {
3425 return Err(SyntaxError::new(
3426 "private fields are not supported by the compiler yet",
3427 tag.span,
3428 ));
3429 }
3430 }
3431 self.emit(Opcode::PushConst, &[Op::Const(index)]);
3432 for expression in &quasi.expressions {
3433 self.expr(expression)?;
3434 }
3435 self.emit(Opcode::CallMethod, &[Op::Int(count as i32)]);
3436 return Ok(());
3437 }
3438 self.expr(tag)?;
3439 self.emit(Opcode::PushConst, &[Op::Const(index)]);
3440 for expression in &quasi.expressions {
3441 self.expr(expression)?;
3442 }
3443 self.emit(Opcode::Call, &[Op::Int(count as i32)]);
3444 Ok(())
3445 }
3446
3447 fn object_literal(
3448 &mut self,
3449 properties: &[ObjectProperty],
3450 span: Span,
3451 ) -> Result<(), SyntaxError> {
3452 self.emit(Opcode::Object, &[]);
3453 for property in properties {
3454 match property {
3455 ObjectProperty::Spread(value) => {
3456 // `copy_data_properties` takes the target, the source and an
3457 // exclusion list; a literal `null` means "exclude nothing".
3458 // Flag bit 1 copies symbols, bits 2/5 pick the source and the
3459 // exclusion list by stack offset.
3460 self.expr(spread_argument(value))?;
3461 self.emit(Opcode::Null, &[]);
3462 self.emit(Opcode::CopyDataProperties, &[Op::Int(COPY_ALL_PROPERTIES)]);
3463 self.emit(Opcode::Drop, &[]);
3464 self.emit(Opcode::Drop, &[]);
3465 }
3466 ObjectProperty::Property {
3467 key,
3468 value,
3469 kind,
3470 shorthand,
3471 span: property_span,
3472 } => match key {
3473 PropName::Computed(key_expr) => {
3474 self.expr(key_expr)?;
3475 match kind {
3476 PropertyKind::Value => {
3477 self.emit(Opcode::ToPropkey, &[]);
3478 self.expr(value)?;
3479 self.set_name_if_anonymous_computed(value);
3480 self.emit(Opcode::DefineArrayEl, &[]);
3481 // `define_array_el` leaves the object and the key;
3482 // the key is no longer needed.
3483 self.emit(Opcode::Drop, &[]);
3484 }
3485 PropertyKind::Method | PropertyKind::Get | PropertyKind::Set => {
3486 self.emit_method_function(value)?;
3487 self.emit(
3488 Opcode::DefineMethodComputed,
3489 &[Op::Int(define_method_flags(*kind))],
3490 );
3491 }
3492 }
3493 }
3494 PropName::Literal(key) => {
3495 let name = self.property_key_text(key, *property_span)?;
3496 match kind {
3497 PropertyKind::Method | PropertyKind::Get | PropertyKind::Set => {
3498 self.emit_method_function(value)?;
3499 self.emit(
3500 Opcode::DefineMethod,
3501 &[
3502 Op::Atom(Atom::from_text(&name)),
3503 Op::Int(define_method_flags(*kind)),
3504 ],
3505 );
3506 }
3507 PropertyKind::Value => {
3508 self.expr(value)?;
3509 // `{__proto__: x}` sets the prototype instead of
3510 // creating a property; the shorthand `{__proto__}`
3511 // is an ordinary property and does not.
3512 if name == "__proto__" && !shorthand {
3513 self.emit(Opcode::SetProto, &[]);
3514 } else {
3515 self.set_name_if_anonymous(value, &name);
3516 self.emit(
3517 Opcode::DefineField,
3518 &[Op::Atom(Atom::from_text(&name))],
3519 );
3520 }
3521 }
3522 }
3523 }
3524 PropName::Private(_) => {
3525 return Err(SyntaxError::new(
3526 "private names are not valid in object literals",
3527 *property_span,
3528 ));
3529 }
3530 },
3531 }
3532 }
3533 let _ = span;
3534 Ok(())
3535 }
3536
3537 /// Emit the function a method/accessor property defines.
3538 fn emit_method_function(&mut self, value: &Expr) -> Result<(), SyntaxError> {
3539 self.expr(value)
3540 }
3541
3542 /// The name a literal property key contributes.
3543 ///
3544 /// String keys are used as written. A numeric key is converted the way
3545 /// `ToString` would convert it, because the atom is made from that spelling:
3546 /// `{ 1e2: x }` and `{ 0x10: x }` both become `define_field 100` / `16`.
3547 fn property_key_text(&self, key: &PropKey, span: Span) -> Result<String, SyntaxError> {
3548 match key {
3549 PropKey::Str(text) => Ok(text.clone()),
3550 PropKey::Num(value) => numeric_key_text(*value, span),
3551 }
3552 }
3553
3554 /// Compile an optional chain.
3555 ///
3556 /// `?.` short-circuits the *whole remaining spine*, not just its own link:
3557 /// `a?.b.c` yields `undefined` when `a` is null, it does not read `.c` of
3558 /// `undefined`. So the chain is compiled with one end label and every guard
3559 /// jumps to it. The parser hands us the extent of that spine as an
3560 /// [`ExprKind::OptionalChain`] wrapper around the outermost link, which is
3561 /// exactly the scope the label has to cover.
3562 fn optional_chain(&mut self, inner: &Expr) -> Result<(), SyntaxError> {
3563 let end = self.new_label();
3564 self.chain_link(inner, end)?;
3565 self.place_label(end);
3566 Ok(())
3567 }
3568
3569 /// A member access or call reached from outside any optional chain.
3570 ///
3571 /// Such a link cannot contain a `?.` — if it did, the parser would have wrapped
3572 /// it in [`ExprKind::OptionalChain`] — so there is no guard and no label; one is
3573 /// still created because [`Self::chain_link`] takes it, and placing it at the
3574 /// end is a no-op that keeps a single code path.
3575 fn chain_link_top(&mut self, expr: &Expr) -> Result<(), SyntaxError> {
3576 let end = self.new_label();
3577 self.chain_link(expr, end)?;
3578 self.place_label(end);
3579 Ok(())
3580 }
3581
3582 /// One link of a chain, where `end` is the label a `?.` guard jumps to.
3583 fn chain_link(&mut self, expr: &Expr, end: Label) -> Result<(), SyntaxError> {
3584 match &expr.kind {
3585 ExprKind::Member {
3586 object,
3587 property,
3588 optional,
3589 } => {
3590 // `super.x` is not a lookup on a value: it starts at the home object's
3591 // prototype and keeps `this` as the receiver, so it cannot go through
3592 // `chain_link` and the ordinary field read.
3593 if matches!(object.unparen().kind, ExprKind::SuperProp) {
3594 self.super_base();
3595 match property {
3596 MemberProp::Ident(name) => self.emit(
3597 Opcode::PushAtomValue,
3598 &[Op::Atom(Atom::from_text(&name.name))],
3599 ),
3600 MemberProp::Computed(index) => self.expr(index)?,
3601 MemberProp::Private(_) => {
3602 return Err(SyntaxError::new(
3603 "private fields are not supported by the compiler yet",
3604 expr.span,
3605 ));
3606 }
3607 }
3608 self.emit(Opcode::GetSuperValue, &[]);
3609 return Ok(());
3610 }
3611 self.chain_link(object, end)?;
3612 if *optional {
3613 self.optional_guard(end);
3614 }
3615 match property {
3616 // `.length` has its own opcode. The reference emits it for every
3617 // object, not just arrays, so a name-based rule is right and
3618 // cheaper than the generic field read.
3619 MemberProp::Ident(name) if name.name == "length" => {
3620 self.emit(Opcode::GetLength, &[]);
3621 }
3622 MemberProp::Ident(name) => {
3623 self.emit(Opcode::GetField, &[Op::Atom(Atom::from_text(&name.name))]);
3624 }
3625 MemberProp::Computed(index) => {
3626 self.expr(index)?;
3627 self.emit(Opcode::GetArrayEl, &[]);
3628 }
3629 MemberProp::Private(_) => {
3630 return Err(SyntaxError::new(
3631 "private fields are not supported by the compiler yet",
3632 expr.span,
3633 ));
3634 }
3635 }
3636 Ok(())
3637 }
3638 ExprKind::Call {
3639 callee,
3640 arguments,
3641 optional,
3642 } => {
3643 // `o.m(args)` has to pass `o` as `this`, which a plain `call`
3644 // cannot: it reads the function and then calls it with no
3645 // receiver at all. The reference's answer is to keep the object
3646 // under the function value — `get_field2` reads a field and leaves
3647 // its base in place — and to use `call_method`, which takes the
3648 // receiver from the stack. Missing this does not just cost an
3649 // instruction, it loses the `this` binding.
3650 if let ExprKind::Member {
3651 object,
3652 property,
3653 optional: member_optional,
3654 } = &callee.unparen().kind
3655 {
3656 // `super.m()` reads the method off the home object's prototype but
3657 // calls it with `this`, so the receiver goes under the read instead of
3658 // being replaced by it.
3659 if matches!(object.unparen().kind, ExprKind::SuperProp) {
3660 self.super_base();
3661 match property {
3662 MemberProp::Ident(name) => self.emit(
3663 Opcode::PushAtomValue,
3664 &[Op::Atom(Atom::from_text(&name.name))],
3665 ),
3666 MemberProp::Computed(index) => self.expr(index)?,
3667 MemberProp::Private(_) => {
3668 return Err(SyntaxError::new(
3669 "private fields are not supported by the compiler yet",
3670 expr.span,
3671 ));
3672 }
3673 }
3674 // The two-output form would drop the receiver; this one replaces
3675 // the prototype and the key, leaving `this` underneath.
3676 self.emit(Opcode::GetArrayEl, &[]);
3677 if Self::has_spread(arguments) {
3678 self.argument_array(arguments)?;
3679 self.emit(Opcode::Perm3, &[]);
3680 self.emit(Opcode::Apply, &[Op::Int(0)]);
3681 return Ok(());
3682 }
3683 for argument in arguments {
3684 self.expr(argument)?;
3685 }
3686 self.emit(Opcode::CallMethod, &[Op::Int(arguments.len() as i32)]);
3687 return Ok(());
3688 }
3689 self.chain_link(object, end)?;
3690 if *member_optional {
3691 self.optional_guard(end);
3692 }
3693 match property {
3694 MemberProp::Ident(name) => {
3695 self.emit(Opcode::GetField2, &[Op::Atom(Atom::from_text(&name.name))])
3696 }
3697 MemberProp::Computed(index) => {
3698 self.expr(index)?;
3699 // The key is not needed after the read, so this is the
3700 // two-output form: object, value.
3701 self.emit(Opcode::GetArrayEl2, &[]);
3702 }
3703 MemberProp::Private(_) => {
3704 return Err(SyntaxError::new(
3705 "private fields are not supported by the compiler yet",
3706 expr.span,
3707 ));
3708 }
3709 }
3710 if Self::has_spread(arguments) {
3711 // Stack is `obj func`; the array goes on top, then `perm3`
3712 // reorders to the `func this array` that `apply` wants.
3713 self.argument_array(arguments)?;
3714 self.emit(Opcode::Perm3, &[]);
3715 self.emit(Opcode::Apply, &[Op::Int(0)]);
3716 return Ok(());
3717 }
3718 for argument in arguments {
3719 self.expr(argument)?;
3720 }
3721 self.emit(Opcode::CallMethod, &[Op::Int(arguments.len() as i32)]);
3722 return Ok(());
3723 }
3724 // `(a?.b)()` keeps `a` as the receiver: the reference reads the method
3725 // with `get_field2` so the base stays under it, and on the short-circuit
3726 // path pushes an extra `undefined` as a placeholder receiver — the call
3727 // then throws, which is what calling a missing optional chain should do.
3728 if let ExprKind::OptionalChain(inner) = &callee.unparen().kind
3729 && let ExprKind::Member {
3730 object,
3731 property,
3732 optional: member_optional,
3733 } = &inner.unparen().kind
3734 {
3735 let call = self.new_label();
3736 // A guard target of its own: the outer `end` skips the whole
3737 // expression, and a short-circuited receiver still has to reach the
3738 // call so that calling it throws.
3739 let short = self.new_label();
3740 self.chain_link(object, end)?;
3741 if *member_optional {
3742 self.optional_guard(short);
3743 }
3744 match property {
3745 MemberProp::Ident(name) => {
3746 self.emit(Opcode::GetField2, &[Op::Atom(Atom::from_text(&name.name))])
3747 }
3748 MemberProp::Computed(index) => {
3749 self.expr(index)?;
3750 self.emit(Opcode::GetArrayEl2, &[]);
3751 }
3752 MemberProp::Private(_) => {
3753 return Err(SyntaxError::new(
3754 "private fields are not supported by the compiler yet",
3755 expr.span,
3756 ));
3757 }
3758 }
3759 self.emit_jump(Opcode::Goto, call, &[]);
3760 self.place_label(short);
3761 self.emit(Opcode::Undefined, &[]);
3762 self.place_label(call);
3763 if Self::has_spread(arguments) {
3764 self.argument_array(arguments)?;
3765 self.emit(Opcode::Perm3, &[]);
3766 self.emit(Opcode::Apply, &[Op::Int(0)]);
3767 return Ok(());
3768 }
3769 for argument in arguments {
3770 self.expr(argument)?;
3771 }
3772 self.emit(Opcode::CallMethod, &[Op::Int(arguments.len() as i32)]);
3773 return Ok(());
3774 }
3775 self.chain_link(callee, end)?;
3776 if *optional {
3777 self.optional_guard(end);
3778 }
3779 if Self::has_spread(arguments) {
3780 // `func array -> func undefined array`, which is the plain-call
3781 // form of `apply`: the receiver is `undefined`.
3782 self.argument_array(arguments)?;
3783 self.emit(Opcode::Undefined, &[]);
3784 self.emit(Opcode::Swap, &[]);
3785 self.emit(Opcode::Apply, &[Op::Int(0)]);
3786 return Ok(());
3787 }
3788 for argument in arguments {
3789 self.expr(argument)?;
3790 }
3791 self.emit(Opcode::Call, &[Op::Int(arguments.len() as i32)]);
3792 Ok(())
3793 }
3794 _ => self.expr(expr),
3795 }
3796 }
3797
3798 /// Compile `expr` as a tail call when it is one, reporting whether it was.
3799 ///
3800 /// `tail_call` reuses the current frame instead of pushing a new one, so a
3801 /// tail-recursive function runs in constant stack space. It also has to be the
3802 /// *last* thing the function does, which is why only a `return` reaches here.
3803 fn expr_if_tail_call(&mut self, expr: &Expr) -> Result<bool, SyntaxError> {
3804 let ExprKind::Call {
3805 callee,
3806 arguments,
3807 optional: false,
3808 } = &expr.unparen().kind
3809 else {
3810 return Ok(false);
3811 };
3812 let end = self.new_label();
3813 if let ExprKind::Member {
3814 object,
3815 property,
3816 optional: false,
3817 } = &callee.unparen().kind
3818 {
3819 // `super.m()` in tail position is still an ordinary method call with `this`
3820 // as the receiver; only the read of the method differs.
3821 if matches!(object.unparen().kind, ExprKind::SuperProp) {
3822 self.super_base();
3823 match property {
3824 MemberProp::Ident(name) => self.emit(
3825 Opcode::PushAtomValue,
3826 &[Op::Atom(Atom::from_text(&name.name))],
3827 ),
3828 MemberProp::Computed(index) => self.expr(index)?,
3829 MemberProp::Private(_) => return Ok(false),
3830 }
3831 self.emit(Opcode::GetArrayEl, &[]);
3832 for argument in arguments {
3833 self.expr(argument)?;
3834 }
3835 self.emit(Opcode::TailCallMethod, &[Op::Int(arguments.len() as i32)]);
3836 self.place_label(end);
3837 return Ok(true);
3838 }
3839 self.chain_link(object, end)?;
3840 match property {
3841 MemberProp::Ident(name) => {
3842 self.emit(Opcode::GetField2, &[Op::Atom(Atom::from_text(&name.name))])
3843 }
3844 MemberProp::Computed(index) => {
3845 self.expr(index)?;
3846 self.emit(Opcode::GetArrayEl2, &[]);
3847 }
3848 MemberProp::Private(_) => return Ok(false),
3849 }
3850 for argument in arguments {
3851 self.expr(argument)?;
3852 }
3853 self.emit(Opcode::TailCallMethod, &[Op::Int(arguments.len() as i32)]);
3854 self.place_label(end);
3855 return Ok(true);
3856 }
3857 self.chain_link(callee, end)?;
3858 for argument in arguments {
3859 self.expr(argument)?;
3860 }
3861 self.emit(Opcode::TailCall, &[Op::Int(arguments.len() as i32)]);
3862 self.place_label(end);
3863 Ok(true)
3864 }
3865
3866 /// The `?.` guard: keep the value if it is neither null nor undefined,
3867 /// otherwise replace it with `undefined` and leave the whole chain.
3868 fn optional_guard(&mut self, end: Label) {
3869 let cont = self.new_label();
3870 self.emit(Opcode::Dup, &[]);
3871 self.emit(Opcode::IsUndefinedOrNull, &[]);
3872 self.emit_jump(Opcode::IfFalse, cont, &[]);
3873 self.emit(Opcode::Drop, &[]);
3874 self.emit(Opcode::Undefined, &[]);
3875 self.emit_jump(Opcode::Goto, end, &[]);
3876 self.place_label(cont);
3877 }
3878
3879 fn push_number(&mut self, value: f64) {
3880 // `push_N` / `push_i8` / `push_i32` cover small integers; everything else
3881 // goes into the constant pool.
3882 if value == value.trunc() && value.abs() <= i32::MAX as f64 {
3883 let int = value as i32;
3884 if (-1..=7).contains(&int) {
3885 self.emit(Opcode::PushI32, &[Op::Int(int)]);
3886 return;
3887 }
3888 if (-128..=127).contains(&int) {
3889 self.emit(Opcode::PushI8, &[Op::Int(int)]);
3890 return;
3891 }
3892 if (-32768..=32767).contains(&int) {
3893 self.emit(Opcode::PushI16, &[Op::Int(int)]);
3894 return;
3895 }
3896 self.emit(Opcode::PushI32, &[Op::Int(int)]);
3897 return;
3898 }
3899 let index = self.push_constant(Constant::Number(value));
3900 self.emit(Opcode::PushConst, &[Op::Const(index)]);
3901 }
3902
3903 /// Push a `BigInt` literal.
3904 ///
3905 /// A value that fits an `i32` uses the immediate form, which is what the reference
3906 /// emits too; anything larger goes into the constant pool, because the operand of
3907 /// `push_bigint` is only four bytes wide.
3908 fn push_bigint(&mut self, digits: &str, radix: u32) {
3909 if radix == 10
3910 && let Ok(value) = digits.parse::<i64>()
3911 && (i32::MIN as i64..=i32::MAX as i64).contains(&value)
3912 {
3913 self.emit(Opcode::PushBigintI32, &[Op::Int(value as i32)]);
3914 return;
3915 }
3916 let index = self.push_constant(Constant::BigInt {
3917 digits: digits.to_string(),
3918 radix,
3919 });
3920 self.emit(Opcode::PushConst, &[Op::Const(index)]);
3921 }
3922
3923 fn push_string(&mut self, text: &str) {
3924 if text.is_empty() {
3925 self.emit(Opcode::PushEmptyString, &[]);
3926 return;
3927 }
3928 self.emit(Opcode::PushAtomValue, &[Op::Atom(Atom::from_text(text))]);
3929 }
3930
3931 /// Name an anonymous function from the binding it is assigned to.
3932 ///
3933 /// `var f = function(){}` produces a function whose `name` is `f`, which the
3934 /// runtime cannot know without being told: the function object is created
3935 /// before the store. `set_name` carries the name across.
3936 fn set_name_if_anonymous(&mut self, value: &Expr, name: &str) {
3937 if value.is_anonymous_function_definition() {
3938 self.emit(Opcode::SetName, &[Op::Atom(Atom::from_text(name))]);
3939 }
3940 }
3941
3942 /// The same, for a computed key: the name comes from the value on the stack
3943 /// rather than from an atom, so a different instruction carries it.
3944 fn set_name_if_anonymous_computed(&mut self, value: &Expr) {
3945 if value.is_anonymous_function_definition() {
3946 self.emit(Opcode::SetNameComputed, &[]);
3947 }
3948 }
3949
3950 /// Compile a function body that exists only in the compiler's head — a class's
3951 /// implicit constructor or its field initialiser.
3952 ///
3953 /// Everything structural is the same as a written function: a fresh `FnState`, its
3954 /// own body block, and resolution while the frame is still on the stack. Only the
3955 /// statements differ.
3956 fn compile_synthetic_function(
3957 &mut self,
3958 name: &str,
3959 strict: bool,
3960 span: Span,
3961 body: impl FnOnce(&mut Self) -> Result<(), SyntaxError>,
3962 ) -> Result<CompiledFunction, SyntaxError> {
3963 let mut state = FnState::new(name.to_string(), FunctionKind::Normal);
3964 state.strict = strict;
3965 state.created_in_block = self.cur().current_block;
3966 state.with_names = self.cur().with_names.clone();
3967 state.line = span.start.line;
3968 state.column = span.start.column;
3969 let depth = self.stack.len();
3970 self.stack.push(state);
3971 let body_key = span.start.offset as u64;
3972 self.push_block(body_key, NO_PARENT);
3973 self.state().body_block = body_key;
3974 let result = (|| {
3975 self.emit_scope_enter(body_key);
3976 body(self)?;
3977 if self.end_is_reachable() {
3978 self.emit(Opcode::ReturnUndef, &[]);
3979 }
3980 Ok(())
3981 })();
3982 if result.is_err() {
3983 self.stack.truncate(depth);
3984 return result.map(|()| unreachable!());
3985 }
3986 Ok(self.finish_current())
3987 }
3988
3989 /// The implicit return of a class constructor.
3990 ///
3991 /// A constructor that falls off the end initialises its instance fields first, and a
3992 /// derived one returns `this` — which is what makes `new D()` the object `super()`
3993 /// built rather than `undefined`.
3994 fn emit_class_constructor_tail(&mut self) {
3995 match self.cur().ctor_kind {
3996 CtorKind::None => self.emit(Opcode::ReturnUndef, &[]),
3997 CtorKind::Base => {
3998 if self.cur().has_instance_fields {
3999 self.call_field_initialiser();
4000 }
4001 self.emit(Opcode::ReturnUndef, &[]);
4002 }
4003 CtorKind::Derived => {
4004 if self.cur().has_instance_fields {
4005 self.call_field_initialiser();
4006 }
4007 // `get_loc_check` rather than `get_loc`: reaching the end without ever
4008 // running `super()` is a ReferenceError, not `undefined`.
4009 self.emit_var(VarAction::Get, "this");
4010 self.emit(Opcode::Return, &[]);
4011 }
4012 }
4013 }
4014
4015 /// `yield expr` / `yield* expr`.
4016 ///
4017 /// The suspension itself is one instruction: the value is on the stack, `yield` hands
4018 /// it to the caller and parks the frame. On resume the stack holds the value the
4019 /// caller passed *and* a "magic" number saying which method resumed it — `next`
4020 /// passes `0`, `return` passes `1`, `throw` passes `2` — so the emitted
4021 /// `if_false <continue>` asks whether this was an ordinary `next`:
4022 ///
4023 /// * `next(v)` → the magic is falsy, jump over the `return_async` and `drop` `v`.
4024 /// * `return(v)`/`throw(e)` → fall into `return_async`, which finishes the generator
4025 /// and uses the value sitting under the magic number.
4026 ///
4027 /// A `throw` never reaches here: the interpreter unwinds instead (see
4028 /// `Interp::resume_generator`), so the `return_async` arm only ever carries `return`.
4029 fn yield_expression(
4030 &mut self,
4031 argument: Option<&Expr>,
4032 delegate: bool,
4033 ) -> Result<(), SyntaxError> {
4034 if delegate {
4035 return self.yield_star(argument);
4036 }
4037 match argument {
4038 Some(value) => self.expr(value)?,
4039 None => self.emit(Opcode::Undefined, &[]),
4040 }
4041 self.emit(Opcode::Yield, &[]);
4042 let resume = self.new_label();
4043 self.emit_jump(Opcode::IfFalse, resume, &[]);
4044 self.emit(Opcode::ReturnAsync, &[]);
4045 self.place_label(resume);
4046 // Nothing is emitted here: the value the caller passed to `next` *is* the value
4047 // of the `yield` expression, so `var x = yield 1` stores it and `yield 1;` drops
4048 // it through the ordinary expression-statement discard.
4049 Ok(())
4050 }
4051
4052 /// `yield* iterable`.
4053 ///
4054 /// The shape is the reference's, and it is a fall-through chain rather than a
4055 /// decision tree: drive the inner iterator, forward each value with `yield_star`, and
4056 /// on resume decide what the caller asked for — `next` keeps looping, `return` closes
4057 /// the inner iterator and finishes, `throw` forwards the exception into it and
4058 /// continues only if it has a `throw` method.
4059 ///
4060 /// The stack is `iter next catch value` throughout, `catch` being the offset
4061 /// `for_of_start` pushed; the `nip`s at the end uncover the value that is returned.
4062 fn yield_star(&mut self, argument: Option<&Expr>) -> Result<(), SyntaxError> {
4063 match argument {
4064 Some(value) => self.expr(value)?,
4065 // The parser rejects a bare `yield*`, so this is unreachable in practice.
4066 None => return Err(SyntaxError::new("yield* needs an operand", Span::default())),
4067 }
4068 // `for_of_start` validates the iterable and pushes the iterator triple, which is
4069 // the same protocol `for (… of …)` uses.
4070 self.emit(Opcode::ForOfStart, &[]);
4071 self.emit(Opcode::Drop, &[]);
4072 self.emit(Opcode::Undefined, &[]);
4073 self.emit(Opcode::Undefined, &[]);
4074 let next = self.new_label();
4075 let resume = self.new_label();
4076 let finished = self.new_label();
4077 let rethrow = self.new_label();
4078 let throw_no_method = self.new_label();
4079 let done = self.new_label();
4080 self.place_label(next);
4081 self.emit(Opcode::IteratorNext, &[]);
4082 self.emit(Opcode::IteratorCheckObject, &[]);
4083 self.emit(Opcode::GetField2, &[Op::Atom(Atom::from_text("done"))]);
4084 self.emit_jump(Opcode::IfTrue, done, &[]);
4085 // `yield_star` suspends with the inner result's value; `resume` is where the
4086 // caller's answer arrives, as the value followed by the magic number.
4087 self.place_label(resume);
4088 self.emit(Opcode::YieldStar, &[]);
4089 self.emit(Opcode::Dup, &[]);
4090 self.emit_jump(Opcode::IfTrue, rethrow, &[]);
4091 self.emit(Opcode::Drop, &[]);
4092 self.emit_jump(Opcode::Goto, next, &[]);
4093
4094 // `return(v)` / `throw(e)`: `2 === magic` tells them apart.
4095 self.place_label(rethrow);
4096 self.emit(Opcode::PushI32, &[Op::Int(2)]);
4097 self.emit(Opcode::StrictEq, &[]);
4098 self.emit_jump(Opcode::IfTrue, throw_no_method, &[]);
4099 // A `return` closes the inner iterator; if it had none, the delegate simply
4100 // finishes with the requested value.
4101 self.emit(Opcode::IteratorCall, &[Op::Int(0)]);
4102 self.emit_jump(Opcode::IfTrue, finished, &[]);
4103 self.emit(Opcode::IteratorCheckObject, &[]);
4104 self.emit(Opcode::GetField2, &[Op::Atom(Atom::from_text("done"))]);
4105 self.emit_jump(Opcode::IfFalse, resume, &[]);
4106 self.emit(Opcode::GetField, &[Op::Atom(Atom::from_text("value"))]);
4107 self.place_label(finished);
4108 self.emit(Opcode::Nip, &[]);
4109 self.emit(Opcode::Nip, &[]);
4110 self.emit(Opcode::Nip, &[]);
4111 self.emit(Opcode::ReturnAsync, &[]);
4112
4113 // `throw(e)`: forward it into the inner iterator.
4114 self.place_label(throw_no_method);
4115 self.emit(Opcode::IteratorCall, &[Op::Int(1)]);
4116 let no_throw = self.new_label();
4117 self.emit_jump(Opcode::IfTrue, no_throw, &[]);
4118 self.emit(Opcode::IteratorCheckObject, &[]);
4119 self.emit(Opcode::GetField2, &[Op::Atom(Atom::from_text("done"))]);
4120 self.emit_jump(Opcode::IfFalse, resume, &[]);
4121 self.emit_jump(Opcode::Goto, done, &[]);
4122 // No `throw` method: close the iterator, then report the spec's TypeError.
4123 self.place_label(no_throw);
4124 self.emit(Opcode::IteratorCall, &[Op::Int(2)]);
4125 self.emit(Opcode::Drop, &[]);
4126 self.emit(
4127 Opcode::ThrowError,
4128 &[Op::Atom(Atom::from_text("")), Op::Int(4)],
4129 );
4130
4131 // The inner iterator finished: the delegate's value is the `yield*` expression's
4132 // value, so it is left on the stack for whatever consumes it.
4133 self.place_label(done);
4134 self.emit(Opcode::GetField, &[Op::Atom(Atom::from_text("value"))]);
4135 self.emit(Opcode::Nip, &[]);
4136 self.emit(Opcode::Nip, &[]);
4137 self.emit(Opcode::Nip, &[]);
4138 Ok(())
4139 }
4140
4141 /// `await expr`: exactly one instruction.
4142 ///
4143 /// No resume-magic branch follows it. The reference's `await` leaves a single value
4144 /// on the stack and completion is signalled by the `return_async` at the end of the
4145 /// body; an `if_false`/`return_async` pair here would be an instruction sequence the
4146 /// reference never emits, and a `for await` loop — which reaches `await` through the
4147 /// same opcode — would then spill a value the loop's unpacking does not expect.
4148 fn await_expression(&mut self, argument: &Expr) -> Result<(), SyntaxError> {
4149 self.expr(argument)?;
4150 self.emit(Opcode::Await, &[]);
4151 Ok(())
4152 }
4153
4154 /// The `super` base: the receiver followed by the home object's prototype.
4155 ///
4156 /// Everything `super` does needs both. A *read* starts at the prototype but reports
4157 /// to the receiver (so a getter sees `this`), and a *call* reads the method off the
4158 /// prototype but calls it with the receiver.
4159 fn super_base(&mut self) {
4160 self.this_expression();
4161 self.emit(Opcode::SpecialObject, &[Op::Int(4)]);
4162 self.emit(Opcode::GetSuper, &[]);
4163 }
4164
4165 /// `super(args)`: construct the parent class and adopt the result as `this`.
4166 ///
4167 /// The parent is the prototype of the constructor that is running, which is exactly
4168 /// what `extends` set up. `new.target` is passed through unchanged so that
4169 /// `new.target` inside the parent is the class actually being constructed.
4170 fn super_call(&mut self, arguments: &[Expr]) -> Result<(), SyntaxError> {
4171 self.emit(Opcode::SpecialObject, &[Op::Int(2)]);
4172 self.emit(Opcode::GetSuper, &[]);
4173 self.emit(Opcode::SpecialObject, &[Op::Int(3)]);
4174 if Self::has_spread(arguments) {
4175 self.argument_array(arguments)?;
4176 self.emit(Opcode::Apply, &[Op::Int(1)]);
4177 } else {
4178 for argument in arguments {
4179 self.expr(argument)?;
4180 }
4181 self.emit(Opcode::CallConstructor, &[Op::Int(arguments.len() as i32)]);
4182 }
4183 // The value stays on the stack: `super()` is an expression, and a derived
4184 // constructor's `this` may only be initialised once.
4185 self.emit(Opcode::Dup, &[]);
4186 self.emit_var(VarAction::PutInitChecked, "this");
4187 Ok(())
4188 }
4189
4190 /// `this` as a local, which every class constructor and field initialiser needs.
4191 ///
4192 /// The reference materialises the receiver into a local rather than reading
4193 /// `push_this` inline, because `super()` in a derived constructor *replaces* `this`
4194 /// and a field initialiser has to see the final value.
4195 fn begin_this_local(&mut self) {
4196 self.declare_hidden_local("this", VarKind::Normal);
4197 self.emit(Opcode::PushThis, &[]);
4198 self.emit_var(VarAction::Put, "this");
4199 }
4200
4201 /// Compile a constructor the class wrote.
4202 ///
4203 /// The flags have to be in place before the body is compiled, but
4204 /// `compile_function_with_name` creates its own state — so the caller's state is
4205 /// marked instead and the new one inherits it. That is the same trick the parameter
4206 /// prologue uses, and it keeps one code path for both.
4207 fn compile_class_constructor(
4208 &mut self,
4209 func: &ast::Function,
4210 has_heritage: bool,
4211 has_instance_fields: bool,
4212 ) -> Result<CompiledFunction, SyntaxError> {
4213 let saved = (self.cur().ctor_kind, self.cur().has_instance_fields);
4214 self.state().class_ctor_pending = Some((
4215 if has_heritage {
4216 CtorKind::Derived
4217 } else {
4218 CtorKind::Base
4219 },
4220 has_instance_fields,
4221 ));
4222 let result = self.compile_function_with_name(func, false);
4223 self.state().ctor_kind = saved.0;
4224 self.state().has_instance_fields = saved.1;
4225 self.state().class_ctor_pending = None;
4226 result
4227 }
4228
4229 /// The constructor a class gets when it does not declare one.
4230 ///
4231 /// A base class's is empty; a derived class's forwards every argument to the parent
4232 /// and is expressed by `init_ctor`, which also keeps `new.target`. Both run the
4233 /// instance field initialiser afterwards when the class has fields, which is why the
4234 /// initialiser is captured rather than inlined.
4235 fn compile_implicit_constructor(
4236 &mut self,
4237 class: &Class,
4238 has_heritage: bool,
4239 ) -> Result<CompiledFunction, SyntaxError> {
4240 let has_fields = class.elements.iter().any(|element| {
4241 matches!(
4242 element,
4243 ClassElement::Field {
4244 is_static: false,
4245 ..
4246 }
4247 )
4248 });
4249 self.compile_synthetic_function("", true, class.span, |compiler| {
4250 if has_heritage {
4251 // A derived constructor's `this` does not exist until `super()` returns,
4252 // so it starts in the dead zone and `init_ctor` fills it.
4253 compiler.declare("this", VarDef::lexical("this"));
4254 compiler.emit(
4255 Opcode::SetLocUninitialized,
4256 &[Op::Slot(Slot::Loc(compiler.cur().vars.len() as u32 - 1))],
4257 );
4258 compiler.emit(Opcode::InitCtor, &[]);
4259 compiler.emit(
4260 Opcode::PutLocCheckInit,
4261 &[Op::Slot(Slot::Loc(compiler.cur().vars.len() as u32 - 1))],
4262 );
4263 } else {
4264 compiler.begin_this_local();
4265 compiler.emit(Opcode::CheckCtor, &[]);
4266 }
4267 if has_fields {
4268 compiler.call_field_initialiser();
4269 }
4270 // A derived constructor returns `this`, the object `super()` built. Without
4271 // this the implicit constructor fell through to `return_undef`, and `new B()`
4272 // handed back the empty object `construct` had made instead of the one the
4273 // parent constructor initialised.
4274 if has_heritage {
4275 compiler.emit_var(VarAction::Get, "this");
4276 compiler.emit(Opcode::Return, &[]);
4277 }
4278 Ok(())
4279 })
4280 }
4281
4282 /// Emit the call to `<class_fields_init>`, guarded by an `undefined` test.
4283 ///
4284 /// A class with no instance fields leaves the binding `undefined`, and calling it
4285 /// would throw; the reference emits the same guard rather than branching at compile
4286 /// time because a class can be extended by a subclass whose fields still have to run.
4287 fn call_field_initialiser(&mut self) {
4288 let skip = self.new_label();
4289 self.emit_var(VarAction::Get, "<class_fields_init>");
4290 self.emit(Opcode::Dup, &[]);
4291 self.emit_jump(Opcode::IfFalse, skip, &[]);
4292 self.emit_var(VarAction::Get, "this");
4293 self.emit(Opcode::Swap, &[]);
4294 self.emit(Opcode::CallMethod, &[Op::Int(0)]);
4295 self.place_label(skip);
4296 self.emit(Opcode::Drop, &[]);
4297 }
4298
4299 /// The function that defines one class's fields on `this`.
4300 ///
4301 /// `define_field` rather than `put_field`: a field is an own property created
4302 /// without consulting a setter on the prototype, so `class C { set x(v){} }` with an
4303 /// `x = 1` field must not call the setter.
4304 fn compile_field_initialiser(
4305 &mut self,
4306 fields: &[(&PropName, Option<&Expr>)],
4307 span: Span,
4308 ) -> Result<CompiledFunction, SyntaxError> {
4309 self.compile_synthetic_function("", true, span, |compiler| {
4310 compiler.begin_this_local();
4311 for (key, value) in fields {
4312 compiler.emit_var(VarAction::Get, "this");
4313 match value {
4314 Some(value) => compiler.expr(value)?,
4315 None => compiler.emit(Opcode::Undefined, &[]),
4316 }
4317 match key {
4318 PropName::Literal(literal) => {
4319 let text = compiler.property_key_text(literal, span)?;
4320 compiler.emit(Opcode::DefineField, &[Op::Atom(Atom::from_text(&text))]);
4321 }
4322 PropName::Computed(index) => {
4323 compiler.expr(index)?;
4324 compiler.emit(Opcode::DefineArrayEl, &[]);
4325 compiler.emit(Opcode::Drop, &[]);
4326 }
4327 PropName::Private(_) => {
4328 return Err(SyntaxError::new(
4329 "private class fields are not supported by the compiler yet",
4330 span,
4331 ));
4332 }
4333 }
4334 compiler.emit(Opcode::Drop, &[]);
4335 }
4336 Ok(())
4337 })
4338 }
4339
4340 /// Compile a class, leaving the constructor on the stack when `keep`.
4341 ///
4342 /// The shape follows the reference: the class body is its own scope holding the
4343 /// class's *inner* name as a `const` — which is what lets a method refer to the
4344 /// class by name — plus a `<class_fields_init>` binding for the initialiser function.
4345 /// `define_class` turns `parent ctor` into `ctor proto`, then the members are defined
4346 /// on the top of the stack: the prototype for instance members, the constructor
4347 /// itself for `static` ones, which is why a static member costs an extra `swap`.
4348 fn class_definition(&mut self, class: &Class, keep: bool) -> Result<(), SyntaxError> {
4349 let parent_block = self.cur().current_block;
4350 let key = class.span.start.offset as u64;
4351 self.push_block(key, parent_block);
4352 let name = class.name.as_ref().map(|ident| ident.name.clone());
4353 // The class's own name is bound inside the body, so `class E { static F(){ return E } }`
4354 // resolves `E` without a global lookup. An *unnamed* class expression has no such
4355 // binding, and `define_class` is handed the empty name.
4356 if let Some(name) = &name {
4357 self.declare(name, VarDef::constant(name.clone()));
4358 }
4359 // `let` rather than `const`: the binding starts in the dead zone and is filled
4360 // once the initialiser has been compiled, which a `const` would refuse as a second
4361 // store.
4362 self.declare(
4363 "<class_fields_init>",
4364 VarDef::lexical("<class_fields_init>"),
4365 );
4366 self.emit_scope_enter(key);
4367
4368 // The heritage clause is evaluated outside the class's own scope: it cannot see
4369 // the class binding it is about to initialise.
4370 let saved_block = self.cur().current_block;
4371 self.state().current_block = parent_block;
4372 match &class.super_class {
4373 Some(parent) => self.expr(parent)?,
4374 None => self.emit(Opcode::Undefined, &[]),
4375 }
4376 self.state().current_block = saved_block;
4377 let has_heritage = class.super_class.is_some();
4378
4379 // The constructor is compiled before `define_class` because that instruction
4380 // consumes it; a class without one gets the implicit version.
4381 let constructor = class.elements.iter().find_map(|element| match element {
4382 ClassElement::Method {
4383 kind: MethodKind::Constructor,
4384 func,
4385 ..
4386 } => Some(&**func),
4387 _ => None,
4388 });
4389 // A constructor is compiled differently from a method: it owns `this`. The flags
4390 // go on the *enclosing* state because a constructor is a nested function and
4391 // `compile_function_with_name` starts a fresh one.
4392 let has_instance_fields = class.elements.iter().any(|element| {
4393 matches!(
4394 element,
4395 ClassElement::Field {
4396 is_static: false,
4397 ..
4398 }
4399 )
4400 });
4401 let ctor = match constructor {
4402 Some(func) => {
4403 self.compile_class_constructor(func, has_heritage, has_instance_fields)?
4404 }
4405 None => self.compile_implicit_constructor(class, has_heritage)?,
4406 };
4407 let ctor_index = self.push_constant(Constant::Function(Box::new(ctor)));
4408 // A closure, not the bare constant: the constructor captures
4409 // `<class_fields_init>`, which is only filled after `define_class` has run, so it
4410 // has to hold the cell rather than a copy of its value.
4411 self.emit(Opcode::Fclosure, &[Op::Const(ctor_index)]);
4412 let flags = if has_heritage { 1 } else { 0 };
4413 self.emit(
4414 Opcode::DefineClass,
4415 &[
4416 Op::Atom(Atom::from_text(name.as_deref().unwrap_or(""))),
4417 Op::Int(flags),
4418 ],
4419 );
4420
4421 // Instance fields and static fields are two different functions: the first runs
4422 // per instance from the constructor, the second runs once, here.
4423 let mut instance_fields: Vec<(&PropName, Option<&Expr>)> = Vec::new();
4424 let mut static_fields: Vec<(&PropName, Option<&Expr>)> = Vec::new();
4425 for element in &class.elements {
4426 match element {
4427 ClassElement::Method {
4428 key: member_key,
4429 is_static,
4430 kind,
4431 func,
4432 span,
4433 } => {
4434 if *kind == MethodKind::Constructor {
4435 continue;
4436 }
4437 // `static(x)` is a *method* named `static`, not a static method; the
4438 // parser already decided which by putting it in `kind`.
4439 if *is_static {
4440 self.emit(Opcode::Swap, &[]);
4441 }
4442 let function = self.compile_function_with_name(func, true)?;
4443 let index = self.push_constant(Constant::Function(Box::new(function)));
4444 self.emit(Opcode::Fclosure, &[Op::Const(index)]);
4445 match member_key {
4446 PropName::Computed(key) => {
4447 self.emit(Opcode::Swap, &[]);
4448 self.expr(key)?;
4449 self.emit(
4450 Opcode::DefineMethodComputed,
4451 &[Op::Int(class_method_flags(*kind))],
4452 );
4453 // `define_method_computed` leaves the key; drop it.
4454 self.emit(Opcode::Drop, &[]);
4455 }
4456 PropName::Literal(literal) => {
4457 let text = self.property_key_text(literal, *span)?;
4458 self.emit(
4459 Opcode::DefineMethod,
4460 &[
4461 Op::Atom(Atom::from_text(&text)),
4462 Op::Int(class_method_flags(*kind)),
4463 ],
4464 );
4465 }
4466 PropName::Private(_) => {
4467 return Err(SyntaxError::new(
4468 "private class members are not supported by the compiler yet",
4469 *span,
4470 ));
4471 }
4472 }
4473 if *is_static {
4474 self.emit(Opcode::Swap, &[]);
4475 }
4476 }
4477 ClassElement::Field {
4478 key: field_key,
4479 is_static,
4480 value,
4481 span,
4482 } => {
4483 if matches!(field_key, PropName::Private(_)) {
4484 return Err(SyntaxError::new(
4485 "private class fields are not supported by the compiler yet",
4486 *span,
4487 ));
4488 }
4489 if *is_static {
4490 static_fields.push((field_key, value.as_deref()));
4491 } else {
4492 instance_fields.push((field_key, value.as_deref()));
4493 }
4494 }
4495 ClassElement::StaticBlock { span, .. } => {
4496 return Err(SyntaxError::new(
4497 "static blocks are not supported by the compiler yet",
4498 *span,
4499 ));
4500 }
4501 }
4502 }
4503
4504 // `<class_fields_init>` holds the instance initialiser, or `undefined` when the
4505 // class has no instance fields. The constructor calls it only when it is defined.
4506 if instance_fields.is_empty() {
4507 self.emit(Opcode::Undefined, &[]);
4508 } else {
4509 let initialiser = self.compile_field_initialiser(&instance_fields, class.span)?;
4510 let index = self.push_constant(Constant::Function(Box::new(initialiser)));
4511 self.emit(Opcode::Fclosure, &[Op::Const(index)]);
4512 // `set_home_object` reads `obj func`, so the prototype stays where it is.
4513 self.emit(Opcode::SetHomeObject, &[]);
4514 }
4515 self.emit_var(VarAction::PutInit, "<class_fields_init>");
4516 // The prototype has done its job: every instance member is defined on it. What
4517 // is left under it is the constructor.
4518 self.emit(Opcode::Drop, &[]);
4519
4520 // The class binding is initialised *before* static fields run, so a static field
4521 // can refer to the class by name (`static y = S.x`).
4522 // `set_loc` leaves the constructor on the stack, which is what the static field
4523 // call and the outer store both consume.
4524 self.emit_var(VarAction::SetInit, &name.clone().unwrap_or_default());
4525 if !static_fields.is_empty() {
4526 let initialiser = self.compile_field_initialiser(&static_fields, class.span)?;
4527 let index = self.push_constant(Constant::Function(Box::new(initialiser)));
4528 self.emit(Opcode::Dup, &[]);
4529 self.emit(Opcode::Fclosure, &[Op::Const(index)]);
4530 self.emit(Opcode::SetHomeObject, &[]);
4531 self.emit(Opcode::CallMethod, &[Op::Int(0)]);
4532 self.emit(Opcode::Drop, &[]);
4533 }
4534 self.emit_scope_leave(key);
4535 self.state().current_block = parent_block;
4536 if keep {
4537 // A class *expression* is its own value; the class-scope binding was only
4538 // ever an alias for it.
4539 return Ok(());
4540 }
4541 // A declaration stores into the binding the enclosing statement declared.
4542 self.emit_var(VarAction::PutInit, &name.unwrap_or_default());
4543 Ok(())
4544 }
4545
4546 fn push_this(&mut self) {
4547 self.emit(Opcode::PushThis, &[]);
4548 }
4549
4550 /// `this`, which an arrow does not have of its own.
4551 ///
4552 /// The reference gives the enclosing function a local named `this`, initialised from
4553 /// `push_this` at the top of its body, and the arrow then reads it as a captured
4554 /// variable. That is why `(() => this)()` inside `f` yields `f`'s receiver even when
4555 /// the arrow is called with none.
4556 fn this_expression(&mut self) {
4557 // In a class constructor `this` is a local: a derived constructor only gets one
4558 // when `super()` returns, and reading the raw receiver would give the *outer*
4559 // one instead.
4560 if self.cur().ctor_kind != CtorKind::None {
4561 self.emit_var(VarAction::Get, "this");
4562 return;
4563 }
4564 if !self.cur().is_arrow {
4565 self.push_this();
4566 return;
4567 }
4568 if let Some(target) = self.enclosing_function() {
4569 self.state_at(target).needs_this_local = true;
4570 self.declare_at(target, "this");
4571 }
4572 self.emit_var(VarAction::Get, "this");
4573 }
4574
4575 /// `new.target`, which an arrow likewise does not own.
4576 fn new_target_expression(&mut self) {
4577 if !self.cur().is_arrow {
4578 self.emit(Opcode::SpecialObject, &[Op::Int(3)]);
4579 return;
4580 }
4581 if let Some(target) = self.enclosing_function() {
4582 self.state_at(target).needs_new_target_local = true;
4583 self.declare_at(target, "new_target");
4584 }
4585 self.emit_var(VarAction::Get, "new_target");
4586 }
4587
4588 /// Give the function a local `new.target`, for an arrow inside it to capture.
4589 fn provide_new_target_local(&mut self) {
4590 let current = self.stack.len() - 1;
4591 if !self.stack[current].needs_new_target_local {
4592 return;
4593 }
4594 if !self.stack[current]
4595 .vars
4596 .iter()
4597 .any(|var| var.name == "new_target")
4598 {
4599 self.declare_hidden_local("new_target", VarKind::Normal);
4600 }
4601 self.prepend_initialiser(
4602 "new_target",
4603 Insn::Fixed {
4604 op: Opcode::SpecialObject,
4605 operands: vec![Op::Int(3)],
4606 },
4607 );
4608 }
4609
4610 /// `arguments` reached from an arrow, which likewise belongs to the enclosing
4611 /// function.
4612 fn ensure_enclosing_arguments(&mut self) {
4613 // An arrow created in a parameter list needs the *parameter* scope's
4614 // `arguments`, not the body's: the two are separate bindings and the arrow was
4615 // born before the body existed.
4616 let from_params = self.cur().created_in_params;
4617 if let Some(target) = self.enclosing_function() {
4618 self.state_at(target).needs_arguments_local = true;
4619 if from_params {
4620 self.state_at(target).needs_param_arguments = true;
4621 // Declare it now, not at the enclosing function's `finish_current`: the
4622 // arrow resolves its own `arguments` before that runs, and a binding that
4623 // does not exist yet resolves as a global.
4624 declare_param_var_at(&mut self.stack[target], "arguments");
4625 }
4626 self.declare_at(target, "arguments");
4627 }
4628 }
4629
4630 /// The innermost enclosing frame that is a real function — an arrow inherits from it
4631 /// rather than starting a scope of its own.
4632 fn enclosing_function(&self) -> Option<usize> {
4633 (0..self.stack.len())
4634 .rev()
4635 .find(|index| !self.stack[*index].is_arrow && !self.stack[*index].is_script)
4636 }
4637
4638 fn state_at(&mut self, index: usize) -> &mut FnState {
4639 &mut self.stack[index]
4640 }
4641
4642 /// Declare a `var` binding directly in a specific frame.
4643 fn declare_at(&mut self, index: usize, name: &str) {
4644 let state = &mut self.stack[index];
4645 if state.vars.iter().any(|var| var.name == name) {
4646 return;
4647 }
4648 state.var_block.push(FUNCTION_SCOPE);
4649 state.vars.push(VarDef::var(name));
4650 }
4651
4652 /// Prepend `<value-producing insn>; put <name>` to the body, which is how a binding
4653 /// the reference calls a `special_object` gets initialised on entry.
4654 fn prepend_initialiser(&mut self, name: &str, producer: Insn) {
4655 let current = self.stack.len() - 1;
4656 let init = [
4657 producer,
4658 Insn::Var {
4659 action: VarAction::Put,
4660 name: name.to_string(),
4661 block: 0,
4662 // A prologue initialiser runs before the body proper, but it is body
4663 // code: `this` and `arguments` are provided for it, not by it.
4664 in_params: false,
4665 },
4666 ];
4667 let inserted = init.len();
4668 for (index, instruction) in init.into_iter().enumerate() {
4669 self.stack[current].insns.insert(index, instruction);
4670 }
4671 for placed in self.stack[current].labels.iter_mut().flatten() {
4672 *placed += inserted;
4673 }
4674 self.stack[current].label_since_insn = true;
4675 }
4676
4677 fn push_constant(&mut self, constant: Constant) -> u32 {
4678 let state = self.state();
4679 let index = state.cpool.len() as u32;
4680 state.cpool.push(constant);
4681 index
4682 }
4683
4684 /// Compile `a && b`, `a || b`, `a ?? b`.
4685 ///
4686 /// A run of the *same* operator shares one end label, so `a || b || c` tests
4687 /// `a` once and jumps past everything when it is truthy, instead of falling
4688 /// into `b`'s test. The parser builds such a run left-associated —
4689 /// `((a || b) || c)` — so the operands are collected off the left spine.
4690 ///
4691 /// A *different* operator starts its own chain: `(a || b) && c` keeps the inner
4692 /// `||`'s label, because the inner chain really does end before `&&` begins.
4693 fn logical(&mut self, op: LogicalOp, left: &Expr, right: &Expr) -> Result<(), SyntaxError> {
4694 let mut operands = Vec::new();
4695 collect_same_operator(op, left, &mut operands);
4696 operands.push(right);
4697
4698 let end = self.new_label();
4699 // Every operand but the last decides whether the chain stops here.
4700 let last = operands.pop().expect("the right operand is always present");
4701 for operand in operands {
4702 self.expr(operand)?;
4703 self.emit(Opcode::Dup, &[]);
4704 match op {
4705 LogicalOp::And => self.emit_jump(Opcode::IfFalse, end, &[]),
4706 LogicalOp::Or => self.emit_jump(Opcode::IfTrue, end, &[]),
4707 // `??` cannot reuse the truthiness jumps: `0 ?? b` is `0` while
4708 // `0 || b` is `b`. The dedicated test keeps the value unless it is
4709 // null-ish, so the jump is taken on `false`.
4710 LogicalOp::Coalesce => {
4711 self.emit(Opcode::IsUndefinedOrNull, &[]);
4712 self.emit_jump(Opcode::IfFalse, end, &[]);
4713 }
4714 }
4715 self.emit(Opcode::Drop, &[]);
4716 }
4717 self.expr(last)?;
4718 self.place_label(end);
4719 Ok(())
4720 }
4721
4722 fn unary(&mut self, op: UnaryOp, argument: &Expr) -> Result<(), SyntaxError> {
4723 match op {
4724 UnaryOp::Typeof => {
4725 // `typeof x` must not throw on an undeclared name.
4726 if let ExprKind::Ident(name) = &argument.kind {
4727 self.emit_var(VarAction::GetUndef, &name.name);
4728 } else {
4729 self.expr(argument)?;
4730 }
4731 self.emit(Opcode::Typeof, &[]);
4732 }
4733 UnaryOp::Delete => {
4734 // `delete obj.prop` really deletes, and answers whether it could.
4735 // Deleting a *binding* is always `false`: a local, an argument and a
4736 // declared global are all non-configurable, which the reference encodes
4737 // as a constant `push_false` rather than a runtime check. Only a
4738 // property access has anything to do at run time.
4739 // `delete super.x` is not a delete at all: the spec refuses it, and the
4740 // reference encodes the refusal as a `throw_error`. The receiver and the
4741 // key are still evaluated first, which is what keeps the evaluation order
4742 // of the operand intact.
4743 // `delete z?.b.c` answers `true` when the chain short-circuits: there is
4744 // nothing to delete, and a failed delete is not the same as a skipped
4745 // one. The reference emits the guards so they land on a `drop; push_true`
4746 // tail, which is what this reproduces.
4747 if let ExprKind::OptionalChain(inner) = &argument.unparen().kind
4748 && let ExprKind::Member {
4749 object, property, ..
4750 } = &inner.unparen().kind
4751 {
4752 let end = self.new_label();
4753 let done = self.new_label();
4754 self.chain_link(object, end)?;
4755 match property {
4756 MemberProp::Ident(name) => self.emit(
4757 Opcode::PushAtomValue,
4758 &[Op::Atom(Atom::from_text(&name.name))],
4759 ),
4760 MemberProp::Computed(index) => self.expr(index)?,
4761 MemberProp::Private(_) => {
4762 return Err(SyntaxError::new(
4763 "deleting a private field is not allowed",
4764 argument.span,
4765 ));
4766 }
4767 }
4768 self.emit(Opcode::Delete, &[]);
4769 self.emit_jump(Opcode::Goto, done, &[]);
4770 self.place_label(end);
4771 self.emit(Opcode::Drop, &[]);
4772 self.emit(Opcode::PushTrue, &[]);
4773 self.place_label(done);
4774 return Ok(());
4775 }
4776 if let ExprKind::Member { object, .. } = &argument.unparen().kind
4777 && matches!(object.unparen().kind, ExprKind::SuperProp)
4778 {
4779 self.super_base();
4780 self.emit(
4781 Opcode::ThrowError,
4782 &[Op::Atom(Atom::from_text("")), Op::Int(3)],
4783 );
4784 return Ok(());
4785 }
4786 match &argument.kind {
4787 ExprKind::Member {
4788 object, property, ..
4789 } => {
4790 self.expr(object)?;
4791 match property {
4792 MemberProp::Ident(name) => {
4793 self.emit(
4794 Opcode::PushAtomValue,
4795 &[Op::Atom(Atom::from_text(&name.name))],
4796 );
4797 }
4798 MemberProp::Computed(index) => self.expr(index)?,
4799 MemberProp::Private(_) => {
4800 return Err(SyntaxError::new(
4801 "deleting a private field is not allowed",
4802 argument.span,
4803 ));
4804 }
4805 }
4806 self.emit(Opcode::Delete, &[]);
4807 }
4808 ExprKind::Ident(name) => {
4809 // `delete name`: a declared global, a local and an argument all
4810 // answer `false`, but an *implicit* global (`x = 1` with no
4811 // declaration) is a configurable property of the global object
4812 // and really goes away. Which of those a name is only the
4813 // resolver knows, so the decision waits for it.
4814 let pos = self.cur().cur_pos;
4815 self.state().insns.push(Insn::DeleteVar {
4816 name: name.name.clone(),
4817 });
4818 self.state().insn_pos.push(pos);
4819 }
4820 _ => self.emit(Opcode::PushFalse, &[]),
4821 }
4822 }
4823 UnaryOp::Void => {
4824 self.expr(argument)?;
4825 self.emit(Opcode::Drop, &[]);
4826 self.emit(Opcode::Undefined, &[]);
4827 }
4828 UnaryOp::Minus => {
4829 self.expr(argument)?;
4830 self.emit(Opcode::Neg, &[]);
4831 }
4832 UnaryOp::Plus => {
4833 self.expr(argument)?;
4834 self.emit(Opcode::Plus, &[]);
4835 }
4836 UnaryOp::Not => {
4837 self.expr(argument)?;
4838 self.emit(Opcode::Lnot, &[]);
4839 }
4840 UnaryOp::BitNot => {
4841 self.expr(argument)?;
4842 self.emit(Opcode::Not, &[]);
4843 }
4844 }
4845 Ok(())
4846 }
4847
4848 /// Compile an assignment.
4849 ///
4850 /// Three operator families, three shapes:
4851 ///
4852 /// * **plain** `=` — evaluate, store. A member needs `insert2`/`insert3` when
4853 /// the value is kept, because `put_field`/`put_array_el` consume both the
4854 /// object and the value: `insert2` is `obj a -> a obj a`, so the store sees
4855 /// the pair it wants and leaves a copy on top.
4856 /// * **compound** `+=` … — read the place, apply the operator, store. A member
4857 /// reads through `get_field2`/`get_array_el3`, which leave the object (and
4858 /// index) underneath the value precisely so the store can follow.
4859 /// * **logical** `||=`, `&&=`, `??=` — read, test, and only then evaluate the
4860 /// right-hand side. The test *keeps* the current value and skips the store
4861 /// entirely, which is the whole point: `a ||= b` must not evaluate `b` when
4862 /// `a` is already truthy.
4863 fn assign(&mut self, op: AssignOp, target: &Pattern, value: &Expr) -> Result<(), SyntaxError> {
4864 // Reading the flag clears it: only the outermost assignment of an
4865 // expression statement may drop its value.
4866 let keep = !std::mem::take(&mut self.state().discard_value);
4867 match &target.kind {
4868 PatternKind::Ident(name) => {
4869 // A *simple* store is blamed on the identifier, not on the `=`: a
4870 // strict-mode `not_def = 1` raises when the name is written, which the
4871 // reference reports at the name's column. A compound store is blamed on
4872 // the operator instead (`a += poisoned` raises inside `ToPrimitive`,
4873 // which the reference reports at the `+=`), so only the simple case
4874 // moves the position.
4875 let saved = self.cur().cur_pos;
4876 let name_pos = Some(name.span.start);
4877 if matches!(op, AssignOp::Assign) {
4878 self.state().cur_pos = name_pos;
4879 }
4880 // A *compound* store reads the binding before it combines, and that read
4881 // is blamed on the identifier: `not_def += 2` fails while reading
4882 // `not_def`, so the position is the name's, not the `+=`'s. The
4883 // combination that follows is blamed on the operator, which is why
4884 // `cur_pos` is put back to the operator position before it is emitted.
4885 self.state().cur_pos = name_pos;
4886 match op {
4887 AssignOp::Assign => {
4888 self.expr(value)?;
4889 self.set_name_if_anonymous(value, &name.name);
4890 // A discarded store to a *slot* consumes its value, so no copy
4891 // is needed. A global store goes through `put_var`, which the
4892 // reference always pairs with a `dup` — matching it keeps the
4893 // bytecode identical. Getting this wrong is not only an extra
4894 // instruction: a stray copy gives the peephole a chance to fold
4895 // the store into an unrelated later read.
4896 let slot = self.is_slot(&name.name);
4897 if keep || !slot {
4898 self.emit(Opcode::Dup, &[]);
4899 }
4900 self.state().no_value = !keep && slot;
4901 self.emit_var(VarAction::Put, &name.name);
4902 }
4903 AssignOp::And | AssignOp::Or | AssignOp::Coalesce => {
4904 let end = self.new_label();
4905 self.emit_var(VarAction::Get, &name.name);
4906 self.state().cur_pos = saved;
4907 self.emit(Opcode::Dup, &[]);
4908 self.emit_logical_test(op);
4909 self.emit_jump(logical_jump(op), end, &[]);
4910 self.emit(Opcode::Drop, &[]);
4911 self.expr(value)?;
4912 self.emit(Opcode::Dup, &[]);
4913 self.emit_var(VarAction::Put, &name.name);
4914 self.place_label(end);
4915 }
4916 _ => {
4917 self.emit_var(VarAction::Get, &name.name);
4918 self.expr(value)?;
4919 self.state().cur_pos = saved;
4920 self.emit(compound_opcode(op), &[]);
4921 self.emit(Opcode::Dup, &[]);
4922 self.emit_var(VarAction::Put, &name.name);
4923 }
4924 }
4925 self.state().cur_pos = saved;
4926 Ok(())
4927 }
4928 PatternKind::Member(member) => {
4929 // A store is blamed on the selector punctuator (`.` or `[`), the same
4930 // token a load is blamed on — the reference records `put_field obj.a`
4931 // at the `.`, so a setter that throws reports that column and not the
4932 // `=` of the assignment it sits in. The inner expressions restore their
4933 // own positions, so the selector's sticks for the store instructions.
4934 let saved = self.cur().cur_pos;
4935 self.state().cur_pos = member.op_pos.or(Some(member.span.start));
4936 self.expr(&member.object)?;
4937 match &member.property {
4938 MemberProp::Ident(property) => {
4939 let atom = Atom::from_text(&property.name);
4940 match op {
4941 AssignOp::Assign => {
4942 self.expr(value)?;
4943 // `put_field` consumes the object and the value, so
4944 // without `insert2` nothing is left over for the
4945 // statement to drop.
4946 self.state().no_value = !keep;
4947 if keep {
4948 self.emit(Opcode::Insert2, &[]);
4949 }
4950 self.emit(Opcode::PutField, &[Op::Atom(atom.clone())]);
4951 }
4952 AssignOp::And | AssignOp::Or | AssignOp::Coalesce => {
4953 // `get_field2` leaves the object under the value, so
4954 // the keep path has an object to dispose of. The store
4955 // path must jump *over* that cleanup: falling into it
4956 // would `nip` a stack that only holds the value.
4957 let (keep_label, end) = (self.new_label(), self.new_label());
4958 self.emit(Opcode::GetField2, &[Op::Atom(atom.clone())]);
4959 self.emit(Opcode::Dup, &[]);
4960 self.emit_logical_test(op);
4961 self.emit_jump(logical_jump(op), keep_label, &[]);
4962 self.emit(Opcode::Drop, &[]);
4963 self.expr(value)?;
4964 self.emit(Opcode::Insert2, &[]);
4965 self.emit(Opcode::PutField, &[Op::Atom(atom.clone())]);
4966 self.emit_jump(Opcode::Goto, end, &[]);
4967 self.place_label(keep_label);
4968 self.emit(Opcode::Nip, &[]);
4969 self.place_label(end);
4970 }
4971 _ => {
4972 self.emit(Opcode::GetField2, &[Op::Atom(atom.clone())]);
4973 self.expr(value)?;
4974 self.emit(compound_opcode(op), &[]);
4975 self.state().no_value = !keep;
4976 if keep {
4977 self.emit(Opcode::Insert2, &[]);
4978 }
4979 self.emit(Opcode::PutField, &[Op::Atom(atom.clone())]);
4980 }
4981 }
4982 }
4983 MemberProp::Computed(index) => {
4984 self.expr(index)?;
4985 match op {
4986 AssignOp::Assign => {
4987 self.expr(value)?;
4988 self.state().no_value = !keep;
4989 if keep {
4990 self.emit(Opcode::Insert3, &[]);
4991 }
4992 self.emit(Opcode::PutArrayEl, &[]);
4993 }
4994 AssignOp::And | AssignOp::Or | AssignOp::Coalesce => {
4995 let (keep_label, end) = (self.new_label(), self.new_label());
4996 self.emit(Opcode::GetArrayEl3, &[]);
4997 self.emit(Opcode::Dup, &[]);
4998 self.emit_logical_test(op);
4999 self.emit_jump(logical_jump(op), keep_label, &[]);
5000 self.emit(Opcode::Drop, &[]);
5001 self.expr(value)?;
5002 self.emit(Opcode::Insert3, &[]);
5003 self.emit(Opcode::PutArrayEl, &[]);
5004 self.emit_jump(Opcode::Goto, end, &[]);
5005 self.place_label(keep_label);
5006 // Both the object and the index are left over.
5007 self.emit(Opcode::Nip, &[]);
5008 self.emit(Opcode::Nip, &[]);
5009 self.place_label(end);
5010 }
5011 _ => {
5012 self.emit(Opcode::GetArrayEl3, &[]);
5013 self.expr(value)?;
5014 self.emit(compound_opcode(op), &[]);
5015 self.state().no_value = !keep;
5016 if keep {
5017 self.emit(Opcode::Insert3, &[]);
5018 }
5019 self.emit(Opcode::PutArrayEl, &[]);
5020 }
5021 }
5022 }
5023 MemberProp::Private(_) => {
5024 return Err(SyntaxError::new(
5025 "private fields are not supported by the compiler yet",
5026 member.span,
5027 ));
5028 }
5029 }
5030 self.state().cur_pos = saved;
5031 Ok(())
5032 }
5033 // A destructuring assignment: the right-hand side is the expression's own
5034 // value, so it is evaluated once and kept under the pattern's stores.
5035 PatternKind::Array { .. } | PatternKind::Object { .. } => {
5036 self.expr(value)?;
5037 if keep {
5038 self.emit(Opcode::Dup, &[]);
5039 }
5040 self.destructure(target, None)?;
5041 self.state().no_value = !keep;
5042 Ok(())
5043 }
5044 _ => Err(SyntaxError::new(
5045 "this assignment target is not supported by the compiler yet",
5046 target.span,
5047 )),
5048 }
5049 }
5050
5051 /// The test a logical assignment applies to the current value.
5052 ///
5053 /// `??=` needs a real opcode rather than a truthiness jump: `0 ??= b` must
5054 /// assign, while `0 ||= b` must not.
5055 fn emit_logical_test(&mut self, op: AssignOp) {
5056 if op == AssignOp::Coalesce {
5057 self.emit(Opcode::IsUndefinedOrNull, &[]);
5058 }
5059 }
5060
5061 fn update(&mut self, op: UpdateOp, argument: &Expr, prefix: bool) -> Result<(), SyntaxError> {
5062 let instruction = match (op, prefix) {
5063 (UpdateOp::Increment, true) => Opcode::Inc,
5064 (UpdateOp::Increment, false) => Opcode::PostInc,
5065 (UpdateOp::Decrement, true) => Opcode::Dec,
5066 (UpdateOp::Decrement, false) => Opcode::PostDec,
5067 };
5068 if let ExprKind::Member {
5069 object,
5070 property,
5071 optional: _,
5072 } = &argument.kind
5073 {
5074 // `o.x++` needs the receiver twice, so the last link is read with the
5075 // `get_*2`/`get_*3` form that keeps it, and the update is written back
5076 // with `put_field`/`put_array_el`. The reordering in between is what puts
5077 // the old value below the receiver for a postfix update and the new one
5078 // above it for a prefix one:
5079 //
5080 // `obj val` → `post_inc` → `obj old new` → `perm3` → `old obj new`
5081 // `obj val` → `inc` → `obj new new` → `insert2` → `new obj new`
5082 //
5083 // This mirrors the reference instruction for instruction.
5084 self.expr(object)?;
5085 match property {
5086 MemberProp::Ident(name) => {
5087 self.emit(Opcode::GetField2, &[Op::Atom(Atom::from_text(&name.name))]);
5088 self.emit(instruction, &[]);
5089 self.emit(
5090 if prefix {
5091 Opcode::Insert2
5092 } else {
5093 Opcode::Perm3
5094 },
5095 &[],
5096 );
5097 self.emit(Opcode::PutField, &[Op::Atom(Atom::from_text(&name.name))]);
5098 }
5099 MemberProp::Computed(index) => {
5100 self.expr(index)?;
5101 self.emit(Opcode::GetArrayEl3, &[]);
5102 self.emit(instruction, &[]);
5103 self.emit(
5104 if prefix {
5105 Opcode::Insert3
5106 } else {
5107 Opcode::Perm4
5108 },
5109 &[],
5110 );
5111 self.emit(Opcode::PutArrayEl, &[]);
5112 }
5113 MemberProp::Private(_) => {
5114 return Err(SyntaxError::new(
5115 "private fields are not supported by the compiler yet",
5116 argument.span,
5117 ));
5118 }
5119 }
5120 return Ok(());
5121 }
5122 let ExprKind::Ident(name) = &argument.kind else {
5123 return Err(SyntaxError::new(
5124 "increment of a non-variable is not supported by the compiler yet",
5125 argument.span,
5126 ));
5127 };
5128 // A discarded `i++` keeps the plain `get`/`post_inc`/`put` shape. The
5129 // reference's `inc_loc` folds those three into one, but it does so only in some
5130 // positions (a `for` update and not a bare statement, and never for a lexical
5131 // binding), so emitting it unconditionally would move *away* from its output.
5132 // The instruction is equivalent either way; matching the reference matters more
5133 // than saving two instructions.
5134 let _ = !std::mem::take(&mut self.state().discard_value);
5135 self.emit_var(VarAction::Get, &name.name);
5136 self.emit(instruction, &[]);
5137 if prefix {
5138 self.emit(Opcode::Dup, &[]);
5139 }
5140 self.emit_var(VarAction::Put, &name.name);
5141 Ok(())
5142 }
5143
5144 /// Compile an array literal.
5145 ///
5146 /// The reference splits this into three phases, and the split is load-bearing
5147 /// rather than an optimisation detail:
5148 ///
5149 /// 1. **A leading run of plain elements** becomes `array_from n`, which builds
5150 /// the array in one instruction.
5151 /// 2. **Everything up to the first spread** is appended with explicit indices
5152 /// (`define_field <index>`), because a hole has no element to pass to
5153 /// `array_from`. A hole here is what makes `length` need fixing up: an
5154 /// explicit index does not extend the array the way a pushed element does.
5155 /// 3. **From the first spread on** the index lives on the stack, so `append` and
5156 /// `define_array_el` can consume it and `inc` advances it.
5157 ///
5158 /// So `[1,,3]` and `[1,2,3]` are not two spellings of one program: the hole
5159 /// forces phase 2, and `[...a]` forces phase 3.
5160 fn array_literal(
5161 &mut self,
5162 elements: &[Option<ArrayElement>],
5163 span: Span,
5164 ) -> Result<(), SyntaxError> {
5165 let _ = span;
5166 let mut index: u32 = 0;
5167 let mut cursor = 0usize;
5168
5169 // Phase 1: a leading run of plain elements, at most 32 of them.
5170 while let Some(Some(ArrayElement::Expr(element))) = elements.get(cursor) {
5171 if index >= 32 {
5172 break;
5173 }
5174 self.expr(element)?;
5175 index += 1;
5176 cursor += 1;
5177 }
5178 self.emit(Opcode::ArrayFrom, &[Op::Int(index as i32)]);
5179
5180 // Phase 2: explicit indices, up to the first spread.
5181 let mut need_length = false;
5182 while let Some(element) = elements.get(cursor) {
5183 if matches!(element, Some(ArrayElement::Spread(_))) {
5184 break;
5185 }
5186 need_length = true;
5187 if let Some(ArrayElement::Expr(expression)) = element {
5188 self.expr(expression)?;
5189 self.emit_define_index(index);
5190 need_length = false;
5191 }
5192 index += 1;
5193 cursor += 1;
5194 }
5195
5196 if cursor >= elements.len() {
5197 if need_length {
5198 // `define_field` cannot set `length`, which is not configurable.
5199 self.emit(Opcode::Dup, &[]);
5200 self.push_number(index as f64);
5201 self.emit(Opcode::PutField, &[Op::Atom(Atom::from_text("length"))]);
5202 }
5203 return Ok(());
5204 }
5205
5206 // Phase 3: the index moves onto the stack for the spreading tail.
5207 //
5208 // `need_length` deliberately carries over from phase 2: a hole before the
5209 // first spread still has to be reflected in `length`, and only the final
5210 // check can do it because the array is not finished until the tail is
5211 // appended.
5212 self.push_number(index as f64);
5213 while let Some(element) = elements.get(cursor) {
5214 match element {
5215 Some(ArrayElement::Spread(expression)) => {
5216 // `append` copies an iterable and leaves the next index behind,
5217 // so no `inc` is needed here.
5218 self.expr(spread_argument(expression))?;
5219 self.emit(Opcode::Append, &[]);
5220 }
5221 None | Some(ArrayElement::Expr(_)) => {
5222 need_length = true;
5223 if let Some(ArrayElement::Expr(expression)) = element {
5224 self.expr(expression)?;
5225 self.emit(Opcode::DefineArrayEl, &[]);
5226 need_length = false;
5227 }
5228 self.emit(Opcode::Inc, &[]);
5229 }
5230 }
5231 cursor += 1;
5232 }
5233 if need_length {
5234 self.emit(Opcode::Dup1, &[]);
5235 self.emit(Opcode::PutField, &[Op::Atom(Atom::from_text("length"))]);
5236 } else {
5237 self.emit(Opcode::Drop, &[]);
5238 }
5239 Ok(())
5240 }
5241
5242 /// `define_field` with an array-index atom, which is how phase 2 stores elements.
5243 fn emit_define_index(&mut self, index: u32) {
5244 self.emit(
5245 Opcode::DefineField,
5246 &[Op::Atom(Atom::from_text(&index.to_string()))],
5247 );
5248 }
5249
5250 // -- functions ---------------------------------------------------------
5251
5252 fn compile_function(&mut self, func: &ast::Function) -> Result<CompiledFunction, SyntaxError> {
5253 self.compile_function_with_name(func, false)
5254 }
5255
5256 /// Compile a function, recording whether it is a *named function expression*.
5257 ///
5258 /// `var f = function g(){ return g }` has to see `g` inside its own body, but `g`
5259 /// must not leak outside. The reference does that by declaring `g` as a local of
5260 /// the function itself and initialising it with `special_object 2` (the current
5261 /// function), which is why this has to be known at compile time.
5262 fn compile_function_with_name(
5263 &mut self,
5264 func: &ast::Function,
5265 is_expression: bool,
5266 ) -> Result<CompiledFunction, SyntaxError> {
5267 let kind = match (func.is_generator, func.is_async) {
5268 (false, false) => FunctionKind::Normal,
5269 (true, false) => FunctionKind::Generator,
5270 (false, true) => FunctionKind::Async,
5271 (true, true) => FunctionKind::AsyncGenerator,
5272 };
5273 let mut state = FnState::new(
5274 func.name
5275 .as_ref()
5276 .map(|n| n.name.clone())
5277 .unwrap_or_default(),
5278 kind,
5279 );
5280 // The function's own mode, recorded by the parser. Inheriting the enclosing
5281 // function's instead let a nested `"use strict"` directive be ignored, so the
5282 // body ran with sloppy `this`, sloppy `arguments` and no const checks.
5283 state.strict = func.strict;
5284 // A function defined inside a `with` block keeps seeing that object: the guard
5285 // chain names the enclosing `<with>` locals, which resolve outward into closure
5286 // variables exactly like any other captured binding.
5287 state.with_names = self.cur().with_names.clone();
5288 state.is_arrow = func.is_arrow;
5289 state.created_in_block = self.cur().current_block;
5290 // A default anywhere in the parameter list is what gives the function two
5291 // variable environments. The reference decides this the same way: it scans the
5292 // parenthesis for a top-level `=`, so a destructured name without a default
5293 // stays a plain function-scope binding.
5294 state.in_params = false;
5295 state.has_parameter_expressions = func
5296 .params
5297 .iter()
5298 .any(|param| matches!(param.kind, PatternKind::Assign { .. }));
5299 // A function born inside a parameter list inherits the prohibition: it must not
5300 // see the body bindings of the function it was created in.
5301 state.created_in_params = self.cur().in_params || self.cur().created_in_params;
5302 // A class constructor knows what it is only because the class told it.
5303 if let Some((kind, has_fields)) = self.cur().class_ctor_pending {
5304 state.ctor_kind = kind;
5305 state.has_instance_fields = has_fields;
5306 }
5307 // A named *expression* binds its own name; a declaration's name is already
5308 // bound in the enclosing scope.
5309 state.self_name = if is_expression && !func.is_arrow {
5310 func.name.as_ref().map(|n| n.name.clone())
5311 } else {
5312 None
5313 };
5314 state.line = func.span.start.line;
5315 state.column = func.span.start.column;
5316 // A function body has no hidden `<ret>` local; the value comes back on
5317 // the stack. Only a script keeps one.
5318 // Parameters are positional, so even a pattern occupies one argument slot. A
5319 // simple name is that slot itself; anything else (a pattern, a default, a rest
5320 // parameter) takes an anonymous slot and is unpicked into locals at the top of
5321 // the body, which is the only way one argument can bind several names.
5322 let mut prologue: Vec<(usize, Pattern)> = Vec::new();
5323 // `.length` stops at the first parameter that can be substituted: a default
5324 // fills a missing argument in, and a rest parameter absorbs the rest.
5325 let mut defined_args = func.params.len() as u32;
5326 for (index, param) in func.params.iter().enumerate() {
5327 match ¶m.kind {
5328 PatternKind::Ident(name) => state.args.push(VarDef::var(name.name.clone())),
5329 _ => {
5330 state.args.push(VarDef::var("<null>"));
5331 prologue.push((index, param.clone()));
5332 }
5333 }
5334 }
5335 // A default anywhere before the end also ends the count, which the loop above
5336 // only catches for the parameter that carries it; `(a, b = 1, c)` is arity 1.
5337 for (position, param) in func.params.iter().enumerate() {
5338 if matches!(
5339 param.kind,
5340 PatternKind::Assign { .. } | PatternKind::Rest(_)
5341 ) {
5342 defined_args = position as u32;
5343 break;
5344 }
5345 }
5346 state.defined_args = defined_args;
5347 state.param_prologue = prologue;
5348 let depth = self.stack.len();
5349 self.stack.push(state);
5350 let result = self.compile_function_body(func);
5351 if result.is_err() {
5352 // A failed compile must not leave its `FnState` behind. Every caller
5353 // reads `self.state()` as "the function being compiled", so a leftover
5354 // frame silently retargets all later bookkeeping at a dead function.
5355 self.stack.truncate(depth);
5356 }
5357 result
5358 }
5359
5360 /// The body of a function, with its frame already pushed.
5361 fn compile_function_body(
5362 &mut self,
5363 func: &ast::Function,
5364 ) -> Result<CompiledFunction, SyntaxError> {
5365 let body_key = func.params_span.end.offset as u64;
5366 // Where the body begins, in source order. The runtime needs this to tell a
5367 // closure created by a default expression from one the body creates — the two see
5368 // different variable environments — and a bytecode offset would not survive the
5369 // instruction shuffling that building the frame does. Positions are in source
5370 // order, so a comparison answers it.
5371 self.state().body_start = (func.params_span.end.line, func.params_span.end.column);
5372 self.push_block(body_key, NO_PARENT);
5373 self.state().body_block = body_key;
5374 // An arrow with an expression body has no statements; the expression is
5375 // its `return`. Building the statement here keeps one code path below, and
5376 // matters for correctness beyond convenience: returning early with the new
5377 // `FnState` still on the stack would leave the compiler looking at the
5378 // wrong function, which surfaces as an unrelated underflow later.
5379 let concise = match &func.body {
5380 js_parse::ast::FunctionBody::Expr(value) => Some(Stmt::new(
5381 StmtKind::Return(Some(Box::new((**value).clone()))),
5382 value.span,
5383 )),
5384 js_parse::ast::FunctionBody::Block(_) => None,
5385 };
5386 let body: &[Stmt] = match &concise {
5387 Some(stmt) => std::slice::from_ref(stmt),
5388 None => func
5389 .body
5390 .statements()
5391 .ok_or_else(|| SyntaxError::new("unsupported function body", func.span))?,
5392 };
5393 // A pattern parameter binds its names as function-scope locals, so they have to
5394 // exist — and be unpicked from the argument — before the body runs.
5395 let prologue = std::mem::take(&mut self.state().param_prologue);
5396 for (_, pattern) in &prologue {
5397 let mut names = Vec::new();
5398 pattern.bound_names(&mut names);
5399 for name in names {
5400 self.declare_var(&name.name.clone(), VarDef::var(name.name.clone()));
5401 }
5402 }
5403 // With parameter expressions, every parameter also gets a binding in the
5404 // parameter scope, which is what the defaults and any closure created among them
5405 // resolve against. A simple parameter needs both: the argument slot for the body
5406 // and the parameter binding for the list.
5407 let has_param_scope = self.cur().has_parameter_expressions;
5408 if has_param_scope {
5409 for param in &func.params {
5410 let mut names = Vec::new();
5411 param.bound_names(&mut names);
5412 for name in names {
5413 self.declare_param_var(&name.name.clone());
5414 }
5415 }
5416 }
5417 self.hoist(body, body_key)?;
5418 // A generator starts suspended: `initial_yield` is its first instruction, so
5419 // creating one runs no body code until the first `next()`.
5420 //
5421 // An async function does **not** get one. Its body runs synchronously up to the
5422 // first `await` — `async function f(){ log.push("a"); await 0 }` records `a`
5423 // before its caller's next statement — so emitting `initial_yield` here would
5424 // park the body before it started, which is not fixable at run time: the
5425 // suspension looks exactly like a real `await`. The reference's disassembly
5426 // confirms the difference (a generator's first opcode is `initial_yield`, an
5427 // async function's is its first statement).
5428 if self.cur().kind.is_generator() {
5429 self.emit(Opcode::InitialYield, &[]);
5430 }
5431 self.emit_scope_enter(body_key);
5432 // A constructor's prologue is not a parameter unpacking but the `this` binding:
5433 // a base constructor takes the receiver, a derived one starts in the dead zone
5434 // because only `super()` may produce it.
5435 match self.cur().ctor_kind {
5436 CtorKind::None => {}
5437 CtorKind::Base => {
5438 self.begin_this_local();
5439 self.emit(Opcode::CheckCtor, &[]);
5440 }
5441 CtorKind::Derived => {
5442 self.declare("this", VarDef::lexical("this"));
5443 let slot = self.cur().vars.len() as u32 - 1;
5444 self.emit(Opcode::SetLocUninitialized, &[Op::Slot(Slot::Loc(slot))]);
5445 self.emit(Opcode::CheckCtor, &[]);
5446 }
5447 }
5448 // The whole parameter list is one scope, and nothing in the body exists yet, so
5449 // every name it mentions resolves against the parameter bindings and outward.
5450 self.state().in_params = has_param_scope;
5451 for (index, param) in func.params.iter().enumerate() {
5452 if let Some((_, pattern)) = prologue.iter().find(|(at, _)| *at == index) {
5453 match &pattern.kind {
5454 // `...rest` collects what is left rather than reading one slot.
5455 PatternKind::Rest(inner) => {
5456 self.emit(Opcode::Rest, &[Op::Int(index as i32)]);
5457 self.destructure(inner, Some(VarDeclKind::Var))?;
5458 }
5459 _ => {
5460 self.emit(Opcode::GetArg, &[Op::Slot(Slot::Arg(index as u32))]);
5461 self.destructure(pattern, Some(VarDeclKind::Var))?;
5462 }
5463 }
5464 }
5465 if !has_param_scope {
5466 continue;
5467 }
5468 // Mirror the value into the parameter scope. For a plain parameter that is
5469 // a copy of its argument slot; for a pattern, one copy per name it bound.
5470 let mut names = Vec::new();
5471 param.bound_names(&mut names);
5472 for name in names {
5473 let Some(var) = self.cur().vars.iter().enumerate().position(|(index, var)| {
5474 var.name == name.name
5475 && self.cur().var_block.get(index).copied() == Some(FUNCTION_SCOPE)
5476 }) else {
5477 continue;
5478 };
5479 let target = self.declare_param_var(&name.name);
5480 self.emit(Opcode::GetLoc, &[Op::Slot(Slot::Loc(var as u32))]);
5481 self.emit(Opcode::PutLoc, &[Op::Slot(Slot::Loc(target))]);
5482 }
5483 }
5484 // The parameter list is over; from here on a direct `eval` belongs to the body.
5485 self.state().in_params = false;
5486 // Through `stmts`: the body is a block, and a `using` declaration in it is a
5487 // disposal region.
5488 self.stmts(body)?;
5489 // The implicit return only exists if control can actually get here: an
5490 // infinite loop never falls off the end.
5491 if self.end_is_reachable() {
5492 if self.cur().is_suspending() {
5493 // Falling off the end finishes the generator with `undefined`, and the
5494 // value is what tells the resume machinery "completed" rather than
5495 // "suspended".
5496 self.emit(Opcode::Undefined, &[]);
5497 self.emit(Opcode::ReturnAsync, &[]);
5498 } else {
5499 self.emit_class_constructor_tail();
5500 }
5501 }
5502 // Resolution runs while this function is still on the stack: capturing a
5503 // variable from an enclosing function means reaching into that
5504 // function's state, which requires the whole chain to be present.
5505 Ok(self.finish_current())
5506 }
5507
5508 /// Put every binding of a function that contains a direct `eval` into a cell.
5509 ///
5510 /// A direct eval can name any binding in scope, and any closure it creates has to
5511 /// keep sharing that binding after the function returns — `for (let i …)
5512 /// eval("push(() => i)")` collects one closure per iteration and each must read its
5513 /// own `i`. A copy in a side table would freeze the value, so the binding has to be
5514 /// a cell. Doing this unconditionally for such functions is the cheap, honest
5515 /// answer: the alternative is knowing at compile time which names a string will
5516 /// mention.
5517 fn capture_everything_for_eval(&mut self) {
5518 let current = self.stack.len() - 1;
5519 if !self.stack[current].has_direct_eval {
5520 return;
5521 }
5522 for arg in &mut self.stack[current].args {
5523 arg.is_captured = true;
5524 }
5525 for var in &mut self.stack[current].vars {
5526 var.is_captured = true;
5527 }
5528 }
5529
5530 /// Whether the current position in the instruction stream can be reached.
5531 ///
5532 /// A walk over the control-flow graph, using labels as instruction indices.
5533 /// The reference does the same thing to decide whether an implicit
5534 /// `return_undef` is needed.
5535 fn end_is_reachable(&self) -> bool {
5536 let state = self.cur();
5537 reachable_instructions(state, state.insns.len())[state.insns.len()]
5538 }
5539
5540 /// Resolve and assemble the function on top of the compiler stack, then pop
5541 /// it.
5542 fn finish_current(&mut self) -> CompiledFunction {
5543 self.provide_param_arguments();
5544 self.provide_arguments();
5545 self.provide_this_local();
5546 self.provide_new_target_local();
5547 self.provide_self_name();
5548 self.materialize_eval_sites();
5549 self.capture_everything_for_eval();
5550 let (mut resolved, resolved_pos) = resolve(&mut self.stack);
5551 // Captured bindings need a reference cell; the count goes in the header so
5552 // the runtime knows how many cells to allocate on entry.
5553 let current = self.stack.len() - 1;
5554 let captured = self.stack[current]
5555 .args
5556 .iter()
5557 .filter(|a| a.is_captured)
5558 .count()
5559 + self.stack[current]
5560 .vars
5561 .iter()
5562 .filter(|v| v.is_captured)
5563 .count();
5564 self.stack[current].var_ref_count = captured as u32;
5565 // The scope chain is only final now that every binding is known.
5566 rebuild_scope_chain(&mut self.stack[current]);
5567 let (code, stack_size, positions) =
5568 assemble(&mut resolved, &resolved_pos, &mut self.stack[current]);
5569 let _ = &mut resolved;
5570 let state = self.stack.pop().expect("a function is being compiled");
5571 CompiledFunction {
5572 name: state.name,
5573 kind: state.kind,
5574 strict: state.strict,
5575 is_arrow: state.is_arrow,
5576 has_parameter_expressions: state.has_parameter_expressions,
5577 body_start: state.body_start,
5578 args: state.args,
5579 defined_args: state.defined_args,
5580 vars: state.vars,
5581 closure_vars: state.closure_vars,
5582 cpool: state.cpool,
5583 atoms: state.atoms,
5584 code,
5585 stack_size,
5586 var_ref_count: state.var_ref_count,
5587 positions,
5588 source: None,
5589 line: state.line,
5590 column: state.column,
5591 filename: None,
5592 eval_sites: state.eval_sites,
5593 }
5594 }
5595}
5596
5597/// Assign each binding a scope level and rebuild the scope chains.
5598///
5599/// Levels are numbered in the order the blocks appear, with 0 reserved for the
5600/// function scope where `var` and hoisted functions live. Every binding outside
5601/// level 0 gets a `scope_next` link to the next binding visible from the same
5602/// point, so walking a block's chain enumerates exactly the bindings live there.
5603///
5604/// The links cannot be filled in while hoisting: `{ let a } let b` needs `a` to
5605/// point at `b`, which is declared later in the source but earlier in the chain.
5606fn rebuild_scope_chain(state: &mut FnState) {
5607 // Block key -> level. Level 0 is the function scope, keyed by the sentinel so a
5608 // real block that happens to start at offset zero keeps its own level instead of
5609 // being merged into the function scope.
5610 let mut levels: Vec<u64> = vec![FUNCTION_SCOPE];
5611 for block in &state.blocks {
5612 if !levels.contains(&block.key) {
5613 levels.push(block.key);
5614 }
5615 }
5616 let level_of = |key: u64| -> usize { levels.iter().position(|k| *k == key).unwrap_or(0) };
5617 let parent_level = |level: usize| -> usize {
5618 if level == 0 {
5619 return 0;
5620 }
5621 let key = levels[level];
5622 let parent = state
5623 .blocks
5624 .iter()
5625 .find(|b| b.key == key)
5626 .map(|b| b.parent)
5627 .unwrap_or(FUNCTION_SCOPE);
5628 level_of(parent)
5629 };
5630
5631 // Own bindings per level, in declaration order.
5632 let mut own: Vec<Vec<usize>> = vec![Vec::new(); levels.len()];
5633 let keys: Vec<u64> = (0..state.vars.len())
5634 .map(|index| {
5635 state
5636 .var_block
5637 .get(index)
5638 .copied()
5639 .unwrap_or(FUNCTION_SCOPE)
5640 })
5641 .collect();
5642 for (index, key) in keys.into_iter().enumerate() {
5643 let level = level_of(key);
5644 state.vars[index].scope_level = level as u32;
5645 // A `catch` parameter is part of the runtime scope chain even though it is
5646 // not lexical: the handler's own bindings chain on to it, which is why the
5647 // reference prints `let y [next:1]` with `e` at 1.
5648 if state.vars[index].is_lexical || state.vars[index].kind == crate::bytecode::VarKind::Catch
5649 {
5650 own[level].push(index);
5651 }
5652 }
5653
5654 // A scope's chain is its own bindings in reverse declaration order followed
5655 // by the enclosing scope's chain.
5656 let mut head = vec![-1i32; levels.len()];
5657 for level in 0..levels.len() {
5658 let inherited = if level == 0 {
5659 -1
5660 } else {
5661 head[parent_level(level)]
5662 };
5663 let chain: Vec<usize> = own[level].iter().rev().copied().collect();
5664 head[level] = chain.first().map_or(inherited, |first| *first as i32);
5665 for (position, &index) in chain.iter().enumerate() {
5666 let next = chain
5667 .get(position + 1)
5668 .map_or(inherited, |next| *next as i32);
5669 state.vars[index].scope_next = if next < 0 { None } else { Some(next) };
5670 }
5671 }
5672 state.block_heads = head;
5673}
5674
5675/// This is where names become slots and where the temporal dead zone shows up in
5676/// the instruction stream: a read of a `let`/`const` binding compiles to
5677/// `get_loc_check`, which throws if the binding is still uninitialised.
5678///
5679/// The peephole pass from the reference implementation is applied at the end,
5680/// for the same reason it is applied to resolved bytecode there: the patterns are
5681/// stated in terms of `put_loc`/`set_loc` pairs, which only exist after
5682/// resolution. Deleted instructions stay in the list as `None` so that label
5683/// indices remain valid; [`Assembler`] maps them to byte offsets.
5684/// A resolved instruction and the source position it came from.
5685type ResolvedInsn = Option<(Opcode, Vec<Op>)>;
5686
5687/// A resolved instruction paired with its position, which is what `assemble` consumes.
5688type PositionedInsn = (Opcode, Vec<Op>);
5689
5690fn resolve(stack: &mut [FnState]) -> (Vec<ResolvedInsn>, Vec<Option<Position>>) {
5691 let current = stack.len() - 1;
5692 // Dead-code elimination, on the symbolic form where labels are still
5693 // instruction indices. A `break` inside a loop leaves the trailing `goto`
5694 // unreachable, and a `return` leaves everything after it unreachable; the
5695 // reference drops both. Doing it here means the emitter never has to think
5696 // about reachability.
5697 strip_empty_gosubs(stack, current);
5698 eliminate_dead_code(stack, current);
5699 let insns = std::mem::take(&mut stack[current].insns);
5700 // One entry per instruction, carried alongside: `insn_pos` is index-aligned with
5701 // `insns`, and every arm below pushes exactly one instruction, so the positions
5702 // stay aligned with `out`.
5703 let positions = std::mem::take(&mut stack[current].insn_pos);
5704 let mut out: Vec<Option<(Opcode, Vec<Op>)>> = Vec::with_capacity(insns.len());
5705 let mut out_pos: Vec<Option<Position>> = Vec::with_capacity(insns.len());
5706 for (index, insn) in insns.iter().enumerate() {
5707 let pos = positions.get(index).copied().flatten();
5708 out_pos.push(pos);
5709 match insn {
5710 Insn::Fixed { op, operands } => {
5711 let operands = operands
5712 .iter()
5713 .map(|operand| match operand {
5714 Op::Atom(atom) => {
5715 Op::AtomId(intern_atom(&mut stack[current], &atom.to_string()))
5716 }
5717 other => other.clone(),
5718 })
5719 .collect();
5720 out.push(Some((*op, operands)));
5721 }
5722 Insn::Var {
5723 action,
5724 name,
5725 block,
5726 in_params,
5727 } => {
5728 // Only a *read* prefers the parameter scope. A store in the parameter
5729 // list is binding its parameter or assigning inside a default; either
5730 // way it has to reach the slot the body reads, and the mirror into the
5731 // parameter scope is emitted separately (see `compile_function_body`).
5732 let reads = matches!(action, VarAction::Get | VarAction::GetUndef);
5733 let slot = resolve_slot(stack, current, name, *block, *in_params && reads);
5734 // A store to the name of a named function expression is special: the
5735 // reference drops it in sloppy mode and throws in strict mode, because
5736 // the binding is immutable but only *checked* when the body is strict.
5737 // The same rule applies when the name is reached through a closure:
5738 // `var f = function myfunc() { (() => { myfunc = 1 })() }` has to drop
5739 // the store in the arrow too, not just in the function that owns the
5740 // binding. Reaching the owner means walking the chain of closure
5741 // entries, which is what `self_name_binding` does.
5742 let self_name = matches!(action, VarAction::Put | VarAction::Set)
5743 .then(|| {
5744 // A local of this function is the common case and needs no
5745 // chain walk; only an access that resolves elsewhere can be
5746 // pointing at an enclosing function's name binding.
5747 if let Slot::Loc(index) = slot {
5748 stack[current]
5749 .vars
5750 .get(index as usize)
5751 .filter(|var| var.kind == VarKind::FunctionName)
5752 .map(|var| var.is_const)
5753 } else {
5754 self_name_binding(stack, current, name, *block)
5755 }
5756 })
5757 .flatten();
5758 if let Some(is_const) = self_name {
5759 out.push(Some(if is_const {
5760 (
5761 Opcode::ThrowError,
5762 vec![
5763 Op::AtomId(intern_atom(&mut stack[current], name)),
5764 Op::Int(0),
5765 ],
5766 )
5767 } else {
5768 (Opcode::Drop, Vec::new())
5769 }));
5770 continue;
5771 }
5772 out.push(Some(variable_instruction(stack, current, *action, slot)));
5773 }
5774 Insn::CloseCaptured { name, block } => {
5775 // The block matters: a loop variable is scoped to the `for` head's own
5776 // block, so resolving it against block 0 would miss it entirely and
5777 // silently emit nothing.
5778 let slot = resolve_slot(stack, current, name, *block, false);
5779 // Only a local with a reference cell has anything to close. A global
5780 // or a never-captured local resolves to no instruction at all, which
5781 // keeps the bytecode identical to the reference's.
5782 if let Slot::Loc(index) = slot
5783 && stack[current]
5784 .vars
5785 .get(index as usize)
5786 .is_some_and(|v| v.is_captured)
5787 {
5788 out.push(Some((Opcode::CloseLoc, vec![Op::Slot(slot)])));
5789 } else {
5790 out.push(None);
5791 }
5792 }
5793 Insn::DeleteVar { name } => {
5794 // A binding — a local, an argument, or a declared global — cannot be
5795 // deleted, and the reference encodes that as a constant `push_false`.
5796 // Only an implicit global needs the runtime lookup.
5797 if matches!(
5798 resolve_slot(stack, current, name, 0, false),
5799 Slot::Global(_)
5800 ) {
5801 let atom = intern_atom(&mut stack[current], name);
5802 out.push(Some((Opcode::DeleteVar, vec![Op::AtomId(atom)])));
5803 } else {
5804 out.push(Some((Opcode::PushFalse, Vec::new())));
5805 }
5806 }
5807 Insn::Dead => out.push(None),
5808 }
5809 }
5810 // Which label (if any) sits on each instruction, so the jump patterns can
5811 // tell whether they would cross a jump target.
5812 let mut label_at: Vec<Option<u32>> = vec![None; out.len() + 1];
5813 for (id, placed) in stack[current].labels.iter().enumerate() {
5814 if let Some(index) = *placed
5815 && index < label_at.len()
5816 && label_at[index].is_none()
5817 {
5818 label_at[index] = Some(id as u32);
5819 }
5820 }
5821 if std::env::var_os("QJS_DEBUG").is_some() {
5822 eprintln!("--- peephole entry ---");
5823 for (i, e) in out.iter().enumerate() {
5824 eprintln!("{i}: {e:?}");
5825 }
5826 eprintln!("label_at: {label_at:?}");
5827 }
5828 peephole(&mut out, &label_at, &stack[current].labels);
5829 (out, out_pos)
5830}
5831
5832/// Find where `name` lives, capturing it in an enclosing function when needed.
5833///
5834/// The search runs outward through the enclosing functions' states, which are
5835/// still on the compiler stack while a nested function is resolved. Finding the
5836/// name in an enclosing function is what creates a closure reference, and every
5837/// function in between has to forward it — a function can only reach its own
5838/// parent's frame.
5839///
5840/// A name declared nowhere is a global. The reference does *not* look it up by
5841/// name from the inner function: the top-level function gets one `[global]`
5842/// entry and every nested function gets a `[global_ref<n>]` pointing at its
5843/// parent's entry, which is why `function f(){ g(); }` shows `[global_ref0]`
5844/// rather than `[global]`.
5845/// The lexical blocks enclosing `block`, innermost first.
5846fn block_chain(state: &FnState, block: u64) -> Vec<u64> {
5847 let mut chain = Vec::new();
5848 let mut current = Some(block);
5849 while let Some(key) = current {
5850 // `NO_PARENT` is not a block, so the walk ends here. Stopping on the sentinel
5851 // explicitly (rather than on "no block with this key") is what keeps a block
5852 // that happens to sit at offset zero from being mistaken for the terminator.
5853 if key == NO_PARENT || chain.contains(&key) {
5854 break;
5855 }
5856 chain.push(key);
5857 current = state.blocks.iter().find(|b| b.key == key).map(|b| b.parent);
5858 }
5859 chain
5860}
5861
5862/// The `const`-ness of a named function expression's own name, if `name` resolves to one.
5863///
5864/// The binding may be several functions away: an arrow nested in `function myfunc`
5865/// reaches `myfunc` through a chain of closure entries, so finding out *what* it names
5866/// means following `Ref` entries down and then reading the owning function's var table.
5867fn self_name_binding(stack: &[FnState], current: usize, name: &str, block: u64) -> Option<bool> {
5868 let state = stack.get(current)?;
5869 // A parameter shadows everything and is never a function-expression name.
5870 if state.args.iter().any(|arg| arg.name == name) {
5871 return None;
5872 }
5873 // A local of this very function: the answer is in its var table.
5874 if let Some(index) = local_slot_index(state, name, block) {
5875 let var = state.vars.get(index)?;
5876 return (var.kind == VarKind::FunctionName).then_some(var.is_const);
5877 }
5878 // Otherwise the name lives further out, and the closure entry says how to get
5879 // there. `Local` names the owner's slot directly; `Ref` names the next level's
5880 // closure entry, so the walk continues downwards.
5881 let mut level = current;
5882 let mut index = state
5883 .closure_vars
5884 .iter()
5885 .position(|closure| closure.name == name)?;
5886 loop {
5887 let state = stack.get(level)?;
5888 let closure = state.closure_vars.get(index)?;
5889 match closure.closure_type {
5890 ClosureType::Local => {
5891 let owner = stack.get(level.checked_sub(1)?)?;
5892 let var = owner.vars.get(closure.var_idx as usize)?;
5893 return (var.kind == VarKind::FunctionName).then_some(var.is_const);
5894 }
5895 ClosureType::Arg => return None,
5896 ClosureType::Ref => {
5897 level -= 1;
5898 index = closure.var_idx as usize;
5899 }
5900 // A global is never a function-expression name.
5901 ClosureType::Global
5902 | ClosureType::GlobalDecl
5903 | ClosureType::GlobalRef
5904 | ClosureType::ModuleDecl
5905 | ClosureType::ModuleImport => return None,
5906 }
5907 }
5908}
5909
5910/// The index of `name`'s binding in `state`, looked up the way [`resolve_slot`] does.
5911fn local_slot_index(state: &FnState, name: &str, block: u64) -> Option<usize> {
5912 block_chain(state, block).into_iter().find_map(|scope| {
5913 state.vars.iter().enumerate().find_map(|(index, var)| {
5914 (var.name == name && state.var_block.get(index).copied() == Some(scope))
5915 .then_some(index)
5916 })
5917 })
5918}
5919
5920/// Declare `name` as a binding of `state`'s parameter scope, returning its slot.
5921fn declare_param_var_at(state: &mut FnState, name: &str) -> u32 {
5922 if let Some(index) = state.vars.iter().enumerate().position(|(index, var)| {
5923 var.name == name && state.var_block.get(index).copied() == Some(PARAM_SCOPE)
5924 }) {
5925 return index as u32;
5926 }
5927 state.var_block.push(PARAM_SCOPE);
5928 state.vars.push(VarDef::var(name));
5929 state.vars.len() as u32 - 1
5930}
5931
5932/// Whether a function-scope binding is visible to the parameter list.
5933///
5934/// The parameter list runs before the body, so the body's `var`s and function
5935/// declarations do not exist yet — a name that only the body declares has to resolve
5936/// outward instead. What *does* exist by then is the compiler's own prologue: the
5937/// self-name of a named function expression (bound by `special_object 2` before anything
5938/// else), `this` and `new.target`. Those stay visible, which is what makes
5939/// `function f(a = this)` and `var f = function f(a = f)` work.
5940///
5941/// `arguments` is handled separately, as a binding of the parameter scope itself: with
5942/// parameter expressions the reference creates two of them, and the one the parameter
5943/// list sees is not the one the body sees (`function f(a = eval("var arguments = 1"))`).
5944fn visible_in_params(var: &VarDef) -> bool {
5945 var.kind == VarKind::FunctionName || var.name == "this" || var.name == "new.target"
5946}
5947
5948fn resolve_slot(
5949 stack: &mut [FnState],
5950 current: usize,
5951 name: &str,
5952 block: u64,
5953 in_params: bool,
5954) -> Slot {
5955 // The parameter list's own bindings. They are consulted first because they shadow
5956 // the argument slots they were copied from: `function f(a = 1, p = () => a)` keeps
5957 // `a` in the parameter scope, so a closure made there reads the parameter even after
5958 // the body assigns to its own `a`.
5959 if in_params
5960 && let Some(index) = stack[current]
5961 .vars
5962 .iter()
5963 .enumerate()
5964 .position(|(index, var)| {
5965 var.name == name
5966 && stack[current].var_block.get(index).copied() == Some(PARAM_SCOPE)
5967 })
5968 {
5969 return Slot::Loc(index as u32);
5970 }
5971 if let Some(index) = stack[current].args.iter().position(|a| a.name == name) {
5972 return Slot::Arg(index as u32);
5973 }
5974 // A name can be bound more than once: two `catch` parameters in nested
5975 // handlers are two slots. The binding that wins is the one whose scope encloses
5976 // the access, and among those the innermost — so the blocks are walked outward
5977 // and the first binding found on the way is the one that counts. A binding in
5978 // no block (`var`) is reachable from anywhere, which is why the function scope
5979 // is the end of the walk.
5980 let chain = block_chain(&stack[current], block);
5981 for scope in &chain {
5982 let found = stack[current]
5983 .vars
5984 .iter()
5985 .enumerate()
5986 .find(|(index, var)| {
5987 var.name == name && stack[current].var_block.get(*index).copied() == Some(*scope)
5988 })
5989 .map(|(index, _)| index);
5990 if let Some(index) = found {
5991 return Slot::Loc(index as u32);
5992 }
5993 }
5994 // Function-scope bindings — `var` and function declarations — are recorded with
5995 // the sentinel block `0`, which no real scope uses, so the walk above cannot see
5996 // them. They are reachable from anywhere in the function, which is exactly what
5997 // the sentinel means.
5998 //
5999 // This pass is *only* for those. A lexical binding has to be found through the
6000 // chain or not at all, and looking a name up without its block is precisely how
6001 // `var x = 1; { let x = 2; } x` used to see the inner `x`, and how a `let` in a
6002 // block leaked out of it.
6003 let function_scoped = stack[current]
6004 .vars
6005 .iter()
6006 .enumerate()
6007 .find(|(index, var)| {
6008 var.name == name
6009 && stack[current].var_block.get(*index).copied() == Some(FUNCTION_SCOPE)
6010 && (!in_params || visible_in_params(var))
6011 })
6012 .map(|(index, _)| index);
6013 if let Some(index) = function_scoped {
6014 return Slot::Loc(index as u32);
6015 }
6016 if let Some(index) = stack[current]
6017 .closure_vars
6018 .iter()
6019 .position(|c| c.name == name)
6020 {
6021 return slot_for_closure(&stack[current].closure_vars[index], index as u32);
6022 }
6023
6024 for owner in (0..current).rev() {
6025 // The nested function was created inside one of this frame's blocks, and the
6026 // outermost visible binding is the innermost block on that chain — not whatever
6027 // comes first in the variable table. `function f(){ class S{} }` has two `S`
6028 // bindings: the `let S` inside `f` and the `const S` inside the class body, and
6029 // the class body is the one a method may see.
6030 let entry = stack
6031 .get(owner + 1)
6032 .map(|s| s.created_in_block)
6033 .unwrap_or(0);
6034 let lexical = block_chain(&stack[owner], entry)
6035 .into_iter()
6036 .find_map(|scope| {
6037 stack[owner]
6038 .vars
6039 .iter()
6040 .enumerate()
6041 .find(|(index, var)| {
6042 var.name == name
6043 && stack[owner].var_block.get(*index).copied() == Some(scope)
6044 })
6045 .map(|(index, _)| index)
6046 });
6047 // A function born in a parameter list sees that list's bindings, not the body's:
6048 // the parameter scope is the environment it was created in.
6049 let in_param_scope = stack
6050 .get(owner + 1)
6051 .is_some_and(|child| child.created_in_params)
6052 .then(|| {
6053 stack[owner]
6054 .vars
6055 .iter()
6056 .enumerate()
6057 .position(|(index, var)| {
6058 var.name == name
6059 && stack[owner].var_block.get(index).copied() == Some(PARAM_SCOPE)
6060 })
6061 })
6062 .flatten();
6063 let found = if let Some(index) = in_param_scope {
6064 let var = &stack[owner].vars[index];
6065 Some(Found::Local(
6066 ClosureType::Local,
6067 index as u32,
6068 var.is_const,
6069 var.is_lexical,
6070 ))
6071 } else if let Some(index) = stack[owner].args.iter().position(|a| a.name == name) {
6072 Some(Found::Local(ClosureType::Arg, index as u32, false, false))
6073 } else if let Some(index) = lexical {
6074 let var = &stack[owner].vars[index];
6075 Some(Found::Local(
6076 ClosureType::Local,
6077 index as u32,
6078 var.is_const,
6079 var.is_lexical,
6080 ))
6081 } else if let Some(index) = stack[owner]
6082 .vars
6083 .iter()
6084 .enumerate()
6085 .find_map(|(index, var)| {
6086 // A function created inside a parameter list must not see the body of the
6087 // function it was born in; see [`FnState::created_in_params`].
6088 let hidden = stack
6089 .get(owner + 1)
6090 .is_some_and(|child| child.created_in_params);
6091 (var.name == name && (!hidden || visible_in_params(var))).then_some(index)
6092 })
6093 {
6094 let var = &stack[owner].vars[index];
6095 Some(Found::Local(
6096 ClosureType::Local,
6097 index as u32,
6098 var.is_const,
6099 var.is_lexical,
6100 ))
6101 } else if stack[owner].self_name.as_deref() == Some(name) {
6102 // A named function expression's own name. The reference declares it here,
6103 // on the first lookup that fails, rather than up front — and that is what
6104 // makes it reachable from a *nested* function: the nested lookup is what
6105 // walks out and creates the binding. A direct reference in the body is
6106 // caught the same way, which is why `provide_self_name` only has to add
6107 // the prologue.
6108 let strict = stack[owner].strict;
6109 stack[owner].var_block.push(FUNCTION_SCOPE);
6110 stack[owner].vars.push(VarDef {
6111 kind: VarKind::FunctionName,
6112 // In strict mode the name is immutable, so a store raises; sloppy
6113 // mode drops the store instead (see `variable_instruction`).
6114 is_const: strict,
6115 ..VarDef::var(name)
6116 });
6117 let index = stack[owner].vars.len() as u32 - 1;
6118 Some(Found::Local(ClosureType::Local, index, strict, false))
6119 } else if let Some(index) = stack[owner]
6120 .closure_vars
6121 .iter()
6122 .position(|c| c.name == name)
6123 {
6124 let closure = &stack[owner].closure_vars[index];
6125 Some(match closure.closure_type {
6126 // `GlobalRef` belongs here too: it is a *global* reached through this
6127 // frame's reference table, so treating it as a `Ref` to a local cell makes
6128 // the reader look for a cell no frame ever fills. That is how a second
6129 // function using `eval` in its parameter list read `undefined` after a
6130 // sibling had already made `eval` a closure entry.
6131 ClosureType::Global
6132 | ClosureType::GlobalDecl
6133 | ClosureType::GlobalRef
6134 | ClosureType::ModuleDecl
6135 | ClosureType::ModuleImport => Found::Global(index as u32),
6136 _ => Found::Local(
6137 ClosureType::Ref,
6138 index as u32,
6139 closure.is_const,
6140 closure.is_lexical,
6141 ),
6142 })
6143 } else {
6144 None
6145 };
6146 let Some(found) = found else { continue };
6147
6148 let (is_const, is_lexical) = match found {
6149 Found::Local(_, _, is_const, is_lexical) => (is_const, is_lexical),
6150 Found::Global(_) => (false, false),
6151 };
6152 // Mark the owner's binding as captured so it moves into a reference cell.
6153 if let Found::Local(ClosureType::Arg | ClosureType::Local, index, _, _) = found {
6154 let slot = match found {
6155 Found::Local(ClosureType::Arg, _, _, _) => &mut stack[owner].args[index as usize],
6156 _ => &mut stack[owner].vars[index as usize],
6157 };
6158 slot.is_captured = true;
6159 }
6160 // Forward the reference through every function in between.
6161 let mut previous = match found {
6162 Found::Local(kind, index, _, _) => (kind, index),
6163 Found::Global(index) => (ClosureType::Global, index),
6164 };
6165 for level in owner + 1..=current {
6166 let kind = match (previous.0, level) {
6167 // A global stays a global at *every* level. Without `GlobalRef` in
6168 // this arm the second nested function over the same global got a
6169 // `Ref` to a cell no frame ever held, so the innermost closure read
6170 // `undefined` — which is how a two-deep getter lost its outer
6171 // variable.
6172 (ClosureType::Global | ClosureType::GlobalDecl | ClosureType::GlobalRef, _) => {
6173 ClosureType::GlobalRef
6174 }
6175 (ClosureType::Arg | ClosureType::Local, level) if level == owner + 1 => previous.0,
6176 _ => ClosureType::Ref,
6177 };
6178 let index = ensure_closure(stack, level, name, is_const, is_lexical, kind, previous.1);
6179 previous = (kind, index);
6180 }
6181 let index = previous.1;
6182 return slot_for_closure(&stack[current].closure_vars[index as usize], index);
6183 }
6184
6185 // Declared nowhere: a dynamic global lookup, which sloppy mode may satisfy by
6186 // creating a property. The top-level function holds the entry.
6187 let mut previous = (
6188 ClosureType::Global,
6189 ensure_closure(stack, 0, name, false, false, ClosureType::Global, 0),
6190 );
6191 for level in 1..=current {
6192 let index = ensure_closure(
6193 stack,
6194 level,
6195 name,
6196 false,
6197 false,
6198 ClosureType::GlobalRef,
6199 previous.1,
6200 );
6201 previous = (ClosureType::GlobalRef, index);
6202 }
6203 Slot::Global(previous.1)
6204}
6205
6206/// What an outward search turned up.
6207#[derive(Debug, Clone, Copy)]
6208enum Found {
6209 /// A binding in an enclosing function, reachable through a closure of this
6210 /// type, with its const/lexical flags.
6211 Local(ClosureType, u32, bool, bool),
6212 /// A global, reached through the enclosing function's closure entry.
6213 Global(u32),
6214}
6215
6216/// Add a closure entry to `level` if it is not there yet.
6217fn ensure_closure(
6218 stack: &mut [FnState],
6219 level: usize,
6220 name: &str,
6221 is_const: bool,
6222 is_lexical: bool,
6223 closure_type: ClosureType,
6224 var_idx: u32,
6225) -> u32 {
6226 if let Some(index) = stack[level]
6227 .closure_vars
6228 .iter()
6229 .position(|c| c.name == name)
6230 {
6231 return index as u32;
6232 }
6233 stack[level].closure_vars.push(ClosureVar {
6234 name: name.to_string(),
6235 is_const,
6236 is_lexical,
6237 closure_type,
6238 var_idx: var_idx as u16,
6239 });
6240 stack[level].closure_vars.len() as u32 - 1
6241}
6242
6243fn slot_for_closure(closure: &ClosureVar, index: u32) -> Slot {
6244 match closure.closure_type {
6245 // A `global_ref` only says *how* the binding is found (through the
6246 // parent's closure table); the access itself is an ordinary global one.
6247 ClosureType::Global | ClosureType::GlobalRef => Slot::Global(index),
6248 ClosureType::GlobalDecl | ClosureType::ModuleDecl | ClosureType::ModuleImport => {
6249 Slot::GlobalDecl(index)
6250 }
6251 _ => Slot::VarRef(index),
6252 }
6253}
6254
6255/// Pick the opcode for one variable access.
6256///
6257/// The `_check` variants are what enforce the temporal dead zone. They are used
6258/// for every access to a `let`/`const` binding except its own initialisation —
6259/// which is exactly the operation that takes the binding out of the dead zone.
6260fn variable_instruction(
6261 stack: &[FnState],
6262 current: usize,
6263 action: VarAction,
6264 slot: Slot,
6265) -> (Opcode, Vec<Op>) {
6266 let lexical = match slot {
6267 Slot::Loc(index) => stack[current]
6268 .vars
6269 .get(index as usize)
6270 .is_some_and(|v| v.needs_check()),
6271 Slot::VarRef(index) => stack[current]
6272 .closure_vars
6273 .get(index as usize)
6274 .is_some_and(|c| c.is_lexical),
6275 _ => false,
6276 };
6277 let operand = vec![Op::Slot(slot)];
6278 match (action, slot) {
6279 (VarAction::Get, Slot::Loc(index)) => (
6280 if lexical {
6281 Opcode::GetLocCheck
6282 } else {
6283 Opcode::GetLoc
6284 },
6285 vec![Op::Slot(Slot::Loc(index))],
6286 ),
6287 (VarAction::Get, Slot::Arg(index)) => (Opcode::GetArg, vec![Op::Slot(Slot::Arg(index))]),
6288 (VarAction::Get, Slot::VarRef(index)) => (
6289 if lexical {
6290 Opcode::GetVarRefCheck
6291 } else {
6292 Opcode::GetVarRef
6293 },
6294 vec![Op::Slot(Slot::VarRef(index))],
6295 ),
6296 (VarAction::Get, Slot::Global(_)) => (Opcode::GetVar, operand),
6297 (VarAction::Get, Slot::GlobalDecl(_)) => (Opcode::GetVar, operand),
6298 (VarAction::GetUndef, Slot::Loc(_)) => (Opcode::GetLoc, operand),
6299 (VarAction::GetUndef, Slot::Arg(_)) => (Opcode::GetArg, operand),
6300 (VarAction::GetUndef, Slot::VarRef(_)) => (Opcode::GetVarRef, operand),
6301 (VarAction::GetUndef, Slot::Global(_) | Slot::GlobalDecl(_)) => {
6302 (Opcode::GetVarUndef, operand)
6303 }
6304
6305 (VarAction::Put, Slot::Loc(_)) => (
6306 if lexical {
6307 Opcode::PutLocCheck
6308 } else {
6309 Opcode::PutLoc
6310 },
6311 operand,
6312 ),
6313 (VarAction::Put, Slot::Arg(_)) => (Opcode::PutArg, operand),
6314 (VarAction::Put, Slot::VarRef(_)) => (
6315 if lexical {
6316 Opcode::PutVarRefCheck
6317 } else {
6318 Opcode::PutVarRef
6319 },
6320 operand,
6321 ),
6322 (VarAction::Put, Slot::Global(_)) => (Opcode::PutVar, operand),
6323 (VarAction::Put, Slot::GlobalDecl(_)) => (Opcode::PutVar, operand),
6324 // Initialisation is what ends the dead zone, so it never checks.
6325 (VarAction::PutInit, Slot::Loc(_)) => (Opcode::PutLoc, operand),
6326 (VarAction::PutInitChecked, Slot::Loc(_)) => (Opcode::PutLocCheckInit, operand),
6327 // `this` in a derived constructor is always a local, so these cannot happen;
6328 // routing them to the ordinary forms keeps the match total without inventing
6329 // opcodes the reference does not have.
6330 (VarAction::PutInitChecked, Slot::Arg(_)) => (Opcode::PutArg, operand),
6331 (VarAction::PutInitChecked, Slot::VarRef(_)) => (Opcode::PutVarRef, operand),
6332 (VarAction::PutInitChecked, Slot::Global(_) | Slot::GlobalDecl(_)) => {
6333 (Opcode::PutVarInit, operand)
6334 }
6335 (VarAction::PutInit, Slot::Arg(_)) => (Opcode::PutArg, operand),
6336 (VarAction::PutInit, Slot::VarRef(_)) => (Opcode::PutVarRef, operand),
6337 (VarAction::PutInit, Slot::Global(_) | Slot::GlobalDecl(_)) => {
6338 (Opcode::PutVarInit, operand)
6339 }
6340 (VarAction::Set, Slot::Loc(_)) => (
6341 if lexical {
6342 Opcode::SetLocCheck
6343 } else {
6344 Opcode::SetLoc
6345 },
6346 operand,
6347 ),
6348 (VarAction::SetInit, Slot::Loc(_)) => (Opcode::SetLoc, operand),
6349 (VarAction::SetInit, Slot::Arg(_)) => (Opcode::SetArg, operand),
6350 (VarAction::SetInit, Slot::VarRef(_)) => (Opcode::SetVarRef, operand),
6351 (VarAction::SetInit, Slot::Global(_) | Slot::GlobalDecl(_)) => (Opcode::PutVar, operand),
6352 (VarAction::Set, Slot::Arg(_)) => (Opcode::SetArg, operand),
6353 (VarAction::Set, Slot::VarRef(_)) => (Opcode::SetVarRef, operand),
6354 (VarAction::Set, Slot::Global(_)) => (Opcode::PutVar, operand),
6355 (VarAction::Set, Slot::GlobalDecl(_)) => (Opcode::SetVarRef, operand),
6356 (VarAction::PutRef, Slot::Loc(_)) => (Opcode::PutLoc, operand),
6357 (VarAction::PutRef, Slot::Arg(_)) => (Opcode::PutArg, operand),
6358 (VarAction::PutRef, Slot::VarRef(_)) => (Opcode::PutVarRef, operand),
6359 (VarAction::PutRef, Slot::Global(_) | Slot::GlobalDecl(_)) => (Opcode::PutVarRef, operand),
6360 }
6361}
6362
6363/// The instruction-rewriting pass.
6364///
6365/// These are the reference implementation's patterns, restricted to the ones the
6366/// constructs this compiler supports can produce. Each entry is a comment on the
6367/// bytecode it removes, because the whole point is that the result is one
6368/// instruction shorter than the literal translation of the AST.
6369fn peephole(
6370 insns: &mut [Option<(Opcode, Vec<Op>)>],
6371 label_at: &[Option<u32>],
6372 placed: &[Option<usize>],
6373) {
6374 fold_dup_patterns(insns, label_at);
6375
6376 // `drop` before `return_undef` is dead: the return discards the whole frame
6377 // anyway. This runs *after* the `dup` folds, because a `dup; put; drop` there
6378 // consumes its own `drop`; removing the drop first would leave the `dup` and
6379 // produce a `set_` where the reference has a `put_`.
6380 for index in 0..insns.len() {
6381 if opcode_at(insns, index) != Some(Opcode::Drop) {
6382 continue;
6383 }
6384 // Skip over a run of drops, but stop at a jump target: removing code on
6385 // one side of a label would silently retarget the jump.
6386 let mut next = index + 1;
6387 while opcode_at(insns, next) == Some(Opcode::Drop) && !is_label_at(label_at, next) {
6388 next += 1;
6389 }
6390 if is_label_at(label_at, next) {
6391 continue;
6392 }
6393 if opcode_at(insns, next) == Some(Opcode::ReturnUndef) {
6394 for entry in &mut insns[index..next] {
6395 *entry = None;
6396 }
6397 }
6398 }
6399
6400 // The rewrites below all decide against one fixed snapshot, which is what the
6401 // reference sees: `code_match` reads the bytecode buffer as it was on entry to
6402 // the pass, so a rule never observes what an earlier rule removed. Gathering
6403 // every deletion first and applying them together reproduces that.
6404 let snapshot: Vec<Option<Opcode>> = insns
6405 .iter()
6406 .map(|entry| entry.as_ref().map(|(op, _)| *op))
6407 .collect();
6408 // The next instruction that is still there. Holes left by dead-code
6409 // elimination are not instructions, so a rule looks past them.
6410 let next_op = |index: usize| -> Option<usize> {
6411 (index + 1..snapshot.len()).find(|position| snapshot[*position].is_some())
6412 };
6413
6414 let mut doomed = vec![false; insns.len()];
6415 for index in 0..insns.len() {
6416 // A constant pushed only to be dropped does nothing at all. This is what a
6417 // comma expression with a literal left operand compiles to — `(0, f)()` — and
6418 // the reference removes the pair rather than making the reader step over it.
6419 let constant = matches!(
6420 snapshot[index],
6421 Some(
6422 Opcode::Undefined
6423 | Opcode::Null
6424 | Opcode::PushMinus1
6425 | Opcode::Push0
6426 | Opcode::Push1
6427 | Opcode::Push2
6428 | Opcode::Push3
6429 | Opcode::Push4
6430 | Opcode::Push5
6431 | Opcode::Push6
6432 | Opcode::Push7
6433 | Opcode::PushTrue
6434 | Opcode::PushFalse
6435 | Opcode::PushI32
6436 )
6437 );
6438 if constant
6439 && let Some(next) = next_op(index)
6440 && snapshot[next] == Some(Opcode::Drop)
6441 {
6442 doomed[index] = true;
6443 doomed[next] = true;
6444 }
6445 }
6446 for (index, entry) in insns.iter_mut().enumerate() {
6447 if doomed[index] {
6448 *entry = None;
6449 }
6450 }
6451
6452 // A conditional whose destination is the very next instruction just pops its
6453 // condition, so it becomes a plain `drop`. This is what an empty `case` clause
6454 // compiles to.
6455 //
6456 // Order matters, and it is the reference's order: this runs *before* the
6457 // folding below, on the instruction the conditional originally had. Folding
6458 // moves a conditional's destination, and the reference never re-examines it
6459 // afterwards — which is why `if (c) continue;` at the end of a `do` body stays
6460 // a conditional even though folding leaves it pointing at the next
6461 // instruction.
6462 for (index, entry) in insns.iter_mut().enumerate() {
6463 let Some((op, operands)) = entry.clone() else {
6464 continue;
6465 };
6466 if !matches!(op, Opcode::IfTrue | Opcode::IfFalse) {
6467 continue;
6468 }
6469 let Some(id) = label_id(&operands) else {
6470 continue;
6471 };
6472 if placed.get(id as usize).copied().flatten() == Some(index + 1) {
6473 *entry = Some((Opcode::Drop, Vec::new()));
6474 }
6475 }
6476
6477 // A constant condition is decided here rather than at run time.
6478 fold_constant_conditions(insns);
6479 // The conditional folding below is about pairs of *real* branches, so it runs
6480 // before a jump to the next instruction is dropped: `do { … if (c) continue }
6481 // while (t)` puts `continue` exactly on the condition, and the reference inverts
6482 // the branch first and only then notices the jump goes nowhere.
6483 fold_conditional_jumps(insns, label_at, placed);
6484
6485 // A jump whose destination is the very next instruction does nothing, which is
6486 // what constant folding leaves behind for `while (1) { … }`.
6487 remove_jump_to_next(insns, placed);
6488
6489 // `put_x(n) get_x(n)` -> `set_x(n)`, which is what a declaration followed by
6490 // a use of the same variable boils down to.
6491 for index in 0..insns.len() {
6492 let Some((put_op, _)) = insns[index].clone() else {
6493 continue;
6494 };
6495 if !is_foldable_put(put_op) {
6496 continue;
6497 }
6498 if is_label_at(label_at, index + 1) {
6499 continue;
6500 }
6501 let Some((get_op, get_operands)) = insns.get(index + 1).cloned().flatten() else {
6502 continue;
6503 };
6504 if get_op != get_form_of(put_op) {
6505 continue;
6506 }
6507 let put_slot = insns[index].as_ref().and_then(|(_, o)| o.first().cloned());
6508 if put_slot.is_none() || put_slot != get_operands.first().cloned() {
6509 continue;
6510 }
6511 insns[index] = Some((set_form_of(put_op), get_operands));
6512 insns[index + 1] = None;
6513 }
6514}
6515
6516/// Drop `gosub`s that call an empty subroutine.
6517///
6518/// A `gosub` whose target starts with `ret` returns immediately, so the reference
6519/// drops the call. This is how `try`/`catch` without a `finally` loses its
6520/// finalizer plumbing: the finalizer block is empty, its first instruction is
6521/// `ret`, and every `gosub` to it disappears — leaving the `ret` unreachable, which
6522/// [`eliminate_dead_code`] then removes.
6523fn strip_empty_gosubs(stack: &mut [FnState], current: usize) {
6524 let state = &stack[current];
6525 let mut targets = Vec::new();
6526 for insn in &state.insns {
6527 if let Insn::Fixed { op, operands } = insn
6528 && *op == Opcode::Gosub
6529 && let Some(id) = label_id(operands)
6530 && let Some(target) = state.labels.get(id as usize).copied().flatten()
6531 {
6532 targets.push(target);
6533 }
6534 }
6535 let empty: Vec<usize> = targets
6536 .into_iter()
6537 .filter(|target| {
6538 stack[current]
6539 .insns
6540 .get(*target)
6541 .map(|insn| {
6542 matches!(
6543 insn,
6544 Insn::Fixed {
6545 op: Opcode::Ret,
6546 ..
6547 }
6548 )
6549 })
6550 .unwrap_or(false)
6551 })
6552 .collect();
6553 if empty.is_empty() {
6554 return;
6555 }
6556 for insn in stack[current].insns.iter_mut() {
6557 if let Insn::Fixed { op, operands } = insn
6558 && *op == Opcode::Gosub
6559 && let Some(id) = label_id(operands)
6560 && let Some(target) = stack[current].labels.get(id as usize).copied().flatten()
6561 && empty.contains(&target)
6562 {
6563 *insn = Insn::Dead;
6564 }
6565 }
6566}
6567
6568/// Replace unreachable instructions with [`Insn::Dead`].
6569fn eliminate_dead_code(stack: &mut [FnState], current: usize) {
6570 let reachable = reachable_instructions(&stack[current], stack[current].insns.len());
6571 for (index, insn) in stack[current].insns.iter_mut().enumerate() {
6572 if !reachable[index] {
6573 *insn = Insn::Dead;
6574 }
6575 }
6576}
6577
6578/// Mark every instruction index reachable from the entry, plus the index one past
6579/// the last instruction.
6580///
6581/// `seen[len]` answers "can control reach the end of this function", and the
6582/// entries before it identify dead code. Both DCE and the implicit-return decision
6583/// read the same result, which keeps them from disagreeing.
6584fn reachable_instructions(state: &FnState, count: usize) -> Vec<bool> {
6585 let mut seen = vec![false; count + 1];
6586 let mut worklist = vec![0usize];
6587 while let Some(index) = worklist.pop() {
6588 if index > count || seen[index] {
6589 continue;
6590 }
6591 seen[index] = true;
6592 if index == count {
6593 continue;
6594 }
6595 let (op, operands) = match &state.insns[index] {
6596 Insn::Fixed { op, operands } => (*op, operands.as_slice()),
6597 // A variable access never transfers control, and a removed
6598 // instruction is only reachable if it is already marked.
6599 Insn::Var { .. } | Insn::CloseCaptured { .. } | Insn::DeleteVar { .. } | Insn::Dead => {
6600 worklist.push(index + 1);
6601 continue;
6602 }
6603 };
6604 match op {
6605 // A return, a throw and a `ret` all leave this instruction stream: the
6606 // first two give control to the caller or the handler, and `ret`
6607 // returns to a `gosub` elsewhere.
6608 // A tail call leaves the function too: the callee's result becomes this
6609 // function's result, so nothing after it runs.
6610 Opcode::Return
6611 | Opcode::ReturnUndef
6612 | Opcode::TailCall
6613 | Opcode::TailCallMethod
6614 | Opcode::Throw
6615 | Opcode::ThrowError
6616 | Opcode::Ret => {}
6617 // A `catch` records where exceptions from the code that follows go.
6618 // That code is not reachable through normal control flow, but it is
6619 // reachable — through the exception edge — so the walk has to follow
6620 // it, or dead-code elimination would delete every handler.
6621 Opcode::Catch => {
6622 if let Some(target) = placed_label(state, operands) {
6623 worklist.push(target);
6624 }
6625 worklist.push(index + 1);
6626 }
6627 // A `gosub` calls a subroutine and then continues, so both edges count.
6628 Opcode::Gosub => {
6629 if let Some(target) = placed_label(state, operands) {
6630 worklist.push(target);
6631 }
6632 worklist.push(index + 1);
6633 }
6634 Opcode::Goto => {
6635 if let Some(target) = placed_label(state, operands) {
6636 worklist.push(target);
6637 }
6638 }
6639 Opcode::IfTrue | Opcode::IfFalse => {
6640 if let Some(target) = placed_label(state, operands) {
6641 worklist.push(target);
6642 }
6643 worklist.push(index + 1);
6644 }
6645 _ => worklist.push(index + 1),
6646 }
6647 }
6648 seen
6649}
6650
6651/// The instruction index a jump operand points at, resolved through the label
6652/// placement table.
6653fn placed_label(state: &FnState, operands: &[Op]) -> Option<usize> {
6654 let id = label_id(operands)?;
6655 state.labels.get(id as usize).copied().flatten()
6656}
6657
6658/// The label an instruction refers to.
6659fn label_id(operands: &[Op]) -> Option<u32> {
6660 operands.iter().find_map(|operand| match operand {
6661 Op::Label(label) => Some(label.0),
6662 _ => None,
6663 })
6664}
6665
6666/// Turn `if_false L; goto M; L:` into `if_true M`.
6667///
6668/// A conditional whose alternate branch is an unconditional jump needs one jump,
6669/// not two. This is the shape `if (c) break;` produces, so folding it removes an
6670/// instruction and a label from every conditional `break`.
6671/// The boolean a constant-push instruction produces, or `None` if it is not one.
6672///
6673/// Only the operators whose truthiness is decided by the opcode are covered; a
6674/// constant that needs the constant pool (a string) is left alone, because reading it
6675/// would mean threading the pool through the peephole for a case the reference also
6676/// skips.
6677fn constant_truth(op: Opcode, operands: &[Op]) -> Option<bool> {
6678 match op {
6679 // `push_0` returns -1 for zero, `push_1` 1, and so on.
6680 Opcode::PushMinus1 => Some(true),
6681 Opcode::Push0 => Some(false),
6682 Opcode::Push1
6683 | Opcode::Push2
6684 | Opcode::Push3
6685 | Opcode::Push4
6686 | Opcode::Push5
6687 | Opcode::Push6
6688 | Opcode::Push7 => Some(true),
6689 Opcode::PushTrue => Some(true),
6690 Opcode::PushFalse => Some(false),
6691 Opcode::Undefined | Opcode::Null => Some(false),
6692 Opcode::PushI32 => match operands.first() {
6693 Some(Op::Int(value)) => Some(*value != 0),
6694 _ => None,
6695 },
6696 _ => None,
6697 }
6698}
6699
6700/// Fold a branch on a constant condition.
6701///
6702/// `if (0) a() else b()` must not test anything at run time, and the reference
6703/// compiles it to a plain `goto`. Removing the test also removes the unreachable arm,
6704/// which is why the bytecode for a `while (1)` loop has no condition at all.
6705///
6706/// Two instructions become one, so the slot the test occupied is left empty rather
6707/// than shifting everything after it: labels have already been resolved to indices.
6708fn fold_constant_conditions(insns: &mut [Option<(Opcode, Vec<Op>)>]) {
6709 for index in 0..insns.len() {
6710 let Some((push_op, push_operands)) = insns[index].clone() else {
6711 continue;
6712 };
6713 let Some(truth) = constant_truth(push_op, &push_operands) else {
6714 continue;
6715 };
6716 let Some((branch_op, branch_operands)) = insns.get(index + 1).cloned().flatten() else {
6717 continue;
6718 };
6719 let (destination, taken) = match branch_op {
6720 Opcode::IfTrue => (branch_operands.first().cloned(), truth),
6721 Opcode::IfFalse => (branch_operands.first().cloned(), !truth),
6722 _ => continue,
6723 };
6724 let Some(destination) = destination else {
6725 continue;
6726 };
6727 insns[index] = if taken {
6728 // The branch is always taken, so it becomes an unconditional jump.
6729 Some((Opcode::Goto, vec![destination]))
6730 } else {
6731 // The branch never runs: both instructions disappear and control falls
6732 // through to what came after.
6733 None
6734 };
6735 insns[index + 1] = None;
6736 }
6737}
6738
6739/// Remove a jump whose destination is the instruction right after it.
6740///
6741/// Folding a constant condition leaves these behind often: `while (1) { ... }` turns
6742/// its test into nothing, and the loop-end jump then points at the following
6743/// instruction. The reference drops them, so `stack_size` and the listing agree.
6744fn remove_jump_to_next(insns: &mut [Option<(Opcode, Vec<Op>)>], placed: &[Option<usize>]) {
6745 for index in 0..insns.len() {
6746 let Some((op, operands)) = insns[index].clone() else {
6747 continue;
6748 };
6749 if !is_goto(op) {
6750 continue;
6751 }
6752 let Some(id) = label_id(&operands) else {
6753 continue;
6754 };
6755 // The next instruction that still exists, which is what "the instruction
6756 // after this jump" means once earlier folds have punched holes.
6757 let next = (index + 1..insns.len()).find(|position| insns[*position].is_some());
6758 if placed.get(id as usize).copied().flatten() == next {
6759 insns[index] = None;
6760 }
6761 }
6762}
6763
6764fn fold_conditional_jumps(
6765 insns: &mut [Option<(Opcode, Vec<Op>)>],
6766 label_at: &[Option<u32>],
6767 placed: &[Option<usize>],
6768) {
6769 for index in 0..insns.len() {
6770 let Some((op, operands)) = insns[index].clone() else {
6771 continue;
6772 };
6773 let inverted = match op {
6774 Opcode::IfFalse => Opcode::IfTrue,
6775 Opcode::IfTrue => Opcode::IfFalse,
6776 _ => continue,
6777 };
6778 // Next must be an unconditional jump that is not itself a target, and the
6779 // instruction after it must be exactly where the conditional goes.
6780 let Some((next_op, next_operands)) = insns.get(index + 1).cloned().flatten() else {
6781 continue;
6782 };
6783 if !is_goto(next_op) || is_label_at(label_at, index + 1) {
6784 continue;
6785 }
6786 // The conditional must land on the instruction *after* the jump. Several
6787 // labels can share a position, so this asks where *this* label was put
6788 // rather than what label happens to sit there.
6789 let Some(taken) = label_id(&operands) else {
6790 continue;
6791 };
6792 if placed.get(taken as usize).copied().flatten() != Some(index + 2) {
6793 continue;
6794 }
6795 let Some(destination) = next_operands.first().cloned() else {
6796 continue;
6797 };
6798 insns[index] = Some((inverted, vec![destination]));
6799 insns[index + 1] = None;
6800 }
6801}
6802
6803/// Whether a jump target is placed at this instruction index.
6804fn is_label_at(label_at: &[Option<u32>], index: usize) -> bool {
6805 label_at.get(index).copied().flatten().is_some()
6806}
6807
6808fn fold_dup_patterns(insns: &mut [Option<(Opcode, Vec<Op>)>], label_at: &[Option<u32>]) {
6809 // `dup put_x(n)` -> `set_x(n)`
6810 // `dup put_x(n) drop` -> `put_x(n)`
6811 // `dup put_x(n) drop get_x(n)` -> `set_x(n)`
6812 for index in 0..insns.len() {
6813 if opcode_at(insns, index) != Some(Opcode::Dup) {
6814 continue;
6815 }
6816 if is_label_at(label_at, index + 1) {
6817 continue;
6818 }
6819 let Some((put_op, put_operands)) = insns[index + 1].clone() else {
6820 continue;
6821 };
6822 if !is_foldable_put(put_op) {
6823 continue;
6824 }
6825 let Some(Op::Slot(slot)) = put_operands.first().cloned() else {
6826 continue;
6827 };
6828 let mut new_op = set_form_of(put_op);
6829 let mut end = index + 2;
6830 if is_label_at(label_at, end) {
6831 // The `put` has to stay as it is; only the `dup` can be folded.
6832 insns[index] = Some((set_form_of(put_op), vec![Op::Slot(slot)]));
6833 insns[index + 1] = None;
6834 continue;
6835 }
6836 if opcode_at(insns, end) == Some(Opcode::Drop) {
6837 new_op = put_op;
6838 end += 1;
6839 if opcode_at(insns, end) == Some(get_form_of(put_op))
6840 && insns[end]
6841 .as_ref()
6842 .is_some_and(|(_, operands)| operands.first() == Some(&Op::Slot(slot)))
6843 {
6844 new_op = set_form_of(put_op);
6845 end += 1;
6846 }
6847 }
6848 insns[index] = Some((new_op, vec![Op::Slot(slot)]));
6849 for entry in &mut insns[index + 1..end] {
6850 *entry = None;
6851 }
6852 }
6853}
6854
6855fn opcode_at(insns: &[Option<(Opcode, Vec<Op>)>], index: usize) -> Option<Opcode> {
6856 insns
6857 .get(index)
6858 .and_then(|entry| entry.as_ref())
6859 .map(|(op, _)| *op)
6860}
6861
6862/// The four `put_` families that have a `set_` twin. Deliberately not including
6863/// the global forms or `put_var_ref_check`: the reference's peephole lists exactly
6864/// these, and folding the others would produce instructions that do not exist.
6865fn is_foldable_put(op: Opcode) -> bool {
6866 matches!(
6867 op,
6868 Opcode::PutLoc | Opcode::PutLocCheck | Opcode::PutArg | Opcode::PutVarRef
6869 )
6870}
6871
6872fn set_form_of(op: Opcode) -> Opcode {
6873 match op {
6874 Opcode::PutLoc => Opcode::SetLoc,
6875 Opcode::PutLocCheck => Opcode::SetLocCheck,
6876 Opcode::PutArg => Opcode::SetArg,
6877 Opcode::PutVarRef => Opcode::SetVarRef,
6878 other => other,
6879 }
6880}
6881
6882fn get_form_of(op: Opcode) -> Opcode {
6883 match op {
6884 Opcode::PutLoc => Opcode::GetLoc,
6885 Opcode::PutLocCheck => Opcode::GetLocCheck,
6886 Opcode::PutArg => Opcode::GetArg,
6887 Opcode::PutVarRef => Opcode::GetVarRef,
6888 other => other,
6889 }
6890}
6891
6892/// Atom interning, per function.
6893///
6894/// Everything the reference interns goes through `JS_NewAtomStr`, including plain
6895/// identifiers, so the array-index rule applies here rather than at the handful of
6896/// call sites that build property keys.
6897fn intern_atom(state: &mut FnState, name: &str) -> u32 {
6898 let atom = Atom::from_text(name);
6899 if let Some(index) = state.atoms.iter().position(|a| *a == atom) {
6900 return index as u32;
6901 }
6902 state.atoms.push(atom);
6903 state.atoms.len() as u32 - 1
6904}
6905
6906fn binary_opcode(op: BinaryOp) -> Opcode {
6907 match op {
6908 BinaryOp::Add => Opcode::Add,
6909 BinaryOp::Sub => Opcode::Sub,
6910 BinaryOp::Mul => Opcode::Mul,
6911 BinaryOp::Div => Opcode::Div,
6912 BinaryOp::Mod => Opcode::Mod,
6913 BinaryOp::Pow => Opcode::Pow,
6914 BinaryOp::BitOr => Opcode::Or,
6915 BinaryOp::BitXor => Opcode::Xor,
6916 BinaryOp::BitAnd => Opcode::And,
6917 BinaryOp::Shl => Opcode::Shl,
6918 BinaryOp::Shr => Opcode::Sar,
6919 BinaryOp::UShr => Opcode::Shr,
6920 BinaryOp::Lt => Opcode::Lt,
6921 BinaryOp::LtEq => Opcode::Lte,
6922 BinaryOp::Gt => Opcode::Gt,
6923 BinaryOp::GtEq => Opcode::Gte,
6924 BinaryOp::Eq => Opcode::Eq,
6925 BinaryOp::NotEq => Opcode::Neq,
6926 BinaryOp::StrictEq => Opcode::StrictEq,
6927 BinaryOp::StrictNotEq => Opcode::StrictNeq,
6928 BinaryOp::In => Opcode::In,
6929 BinaryOp::Instanceof => Opcode::Instanceof,
6930 }
6931}
6932
6933fn compound_opcode(op: AssignOp) -> Opcode {
6934 match op {
6935 AssignOp::Add => Opcode::Add,
6936 AssignOp::Sub => Opcode::Sub,
6937 AssignOp::Mul => Opcode::Mul,
6938 AssignOp::Div => Opcode::Div,
6939 AssignOp::Mod => Opcode::Mod,
6940 AssignOp::Pow => Opcode::Pow,
6941 AssignOp::Shl => Opcode::Shl,
6942 AssignOp::Shr => Opcode::Sar,
6943 AssignOp::UShr => Opcode::Shr,
6944 AssignOp::BitOr => Opcode::Or,
6945 AssignOp::BitXor => Opcode::Xor,
6946 AssignOp::BitAnd => Opcode::And,
6947 AssignOp::Assign | AssignOp::And | AssignOp::Or | AssignOp::Coalesce => Opcode::Nop,
6948 }
6949}
6950
6951/// Encode the resolved instruction stream, choosing short forms where possible.
6952///
6953/// The peephole pass leaves holes in the instruction list so that label indices
6954/// stay valid. A label names an *instruction index*, and an index that was
6955/// deleted has to resolve to the next surviving instruction, which is what
6956/// [`resolve_label`] does before the byte offsets are known.
6957fn assemble(
6958 insns: &mut [Option<(Opcode, Vec<Op>)>],
6959 insn_pos: &[Option<Position>],
6960 state: &mut FnState,
6961) -> (Vec<u8>, u32, Vec<LineCol>) {
6962 // Compaction: surviving instructions in order, plus the index mapping.
6963 //
6964 // `spans` runs parallel to `kept` and is compacted in lock step with it, at every
6965 // point below where instructions are removed — otherwise a stack trace would point
6966 // at the wrong source line as soon as dead-code elimination kicked in.
6967 let mut kept: Vec<(Opcode, Vec<Op>)> = Vec::with_capacity(insns.len());
6968 let mut spans: Vec<Option<Position>> = Vec::with_capacity(insns.len());
6969 let mut original_to_kept: Vec<Option<usize>> = vec![None; insns.len()];
6970 for (original, entry) in insns.iter_mut().enumerate() {
6971 if let Some((op, operands)) = entry.take() {
6972 original_to_kept[original] = Some(kept.len());
6973 kept.push((op, operands));
6974 spans.push(insn_pos.get(original).copied().flatten());
6975 }
6976 }
6977
6978 if std::env::var_os("QJS_DEBUG").is_some() {
6979 eprintln!("--- assemble entry --- {kept:?}");
6980 }
6981 // How many labels are real, as opposed to the per-instruction ones allocated
6982 // just below. Only a real label marks a spot in the source program.
6983 let real_labels = state.labels.len();
6984
6985 // Give every surviving instruction a label of its own. Jump cleanup below
6986 // redirects jumps to arbitrary instructions, and a jump target has to be a
6987 // label; pre-allocating one per index means a redirect never has to invent
6988 // anything.
6989 let existing = state.labels.len();
6990 let base = kept.len();
6991 let mut index_label: Vec<Label> = Vec::with_capacity(kept.len() + 1);
6992 for offset in 0..=kept.len() {
6993 state.labels.push(Some(0));
6994 index_label.push(Label((existing + offset) as u32));
6995 }
6996 // Point each pre-allocated label at its instruction, reusing the count from
6997 // `original_to_kept` so the mapping survives compaction.
6998 let place_index_labels = |state: &mut FnState,
6999 original_to_kept: &[Option<usize>],
7000 kept_len: usize,
7001 index_label: &[Label]| {
7002 for (original, mapped) in original_to_kept.iter().enumerate() {
7003 if let Some(kept_index) = mapped {
7004 let label = index_label[*kept_index].0 as usize;
7005 state.labels[label] = Some(original);
7006 }
7007 }
7008 state.labels[index_label[kept_len].0 as usize] = Some(usize::MAX);
7009 };
7010 place_index_labels(state, &original_to_kept, base, &index_label);
7011
7012 // Resolve every label to a kept index once; the placement table maps labels
7013 // to original indices, so a second hop lands in kept space.
7014 let mut label_kept: Vec<Option<usize>> = vec![None; state.labels.len()];
7015 for (id, placed) in state.labels.iter().enumerate() {
7016 let Some(original) = placed else { continue };
7017 label_kept[id] = if *original == usize::MAX {
7018 Some(base)
7019 } else {
7020 (*original..original_to_kept.len()).find_map(|i| original_to_kept[i])
7021 };
7022 }
7023
7024 // Code after an unconditional transfer is unreachable, and the reference drops it
7025 // as it walks past the transfer — the `skip_dead_code` in its first pass. It
7026 // scans forward until it finds a label something still jumps to, so a run of
7027 // dead instructions between a `throw` and the next live target disappears.
7028 //
7029 // The scan repeats because dropping a jump lowers the reference count of the
7030 // label it pointed at, which can strand what follows. Only a real label keeps an
7031 // instruction alive here; the per-instruction labels allocated above belong to
7032 // this pass, not to the program.
7033 loop {
7034 let mut references = vec![false; kept.len() + 1];
7035 for (_, operands) in &kept {
7036 if let Some(target) = target_kept_index(operands, &label_kept)
7037 && target < references.len()
7038 {
7039 references[target] = true;
7040 }
7041 }
7042 let mut doomed = vec![false; kept.len()];
7043 let mut any = false;
7044 for (index, (op, _)) in kept.iter().enumerate() {
7045 if !is_transfer(*op) {
7046 continue;
7047 }
7048 for next in index + 1..kept.len() {
7049 if references[next] {
7050 break;
7051 }
7052 doomed[next] = true;
7053 any = true;
7054 }
7055 }
7056 if !any {
7057 break;
7058 }
7059 (kept, spans) = drop_instructions(kept, spans, &mut label_kept, &doomed);
7060 }
7061
7062 // A label that lands on an unconditional jump stands for wherever that jump
7063 // goes, so retarget it once and every jump to the label follows for free.
7064 // This is what makes `continue` in a `for` head reach the loop top instead of
7065 // stopping at the update's trailing jump.
7066 let folded: Vec<Option<usize>> = label_kept
7067 .iter()
7068 .map(|slot| slot.map(|target| follow_jump_chain(&kept, &label_kept, target)))
7069 .collect();
7070 label_kept = folded;
7071
7072 // Jump cleanup, in compacted index space. Two rewrites the reference also
7073 // applies while it resolves labels:
7074 // * a jump whose destination is the very next instruction does nothing;
7075 // * a jump to a jump is redirected to its final destination.
7076 // The second can expose the first, so this repeats until it settles.
7077 loop {
7078 let mut delete = vec![false; kept.len()];
7079 let mut changed = false;
7080 for index in 0..kept.len() {
7081 let (op, operands) = &kept[index];
7082 if !is_goto(*op) {
7083 continue;
7084 }
7085 let Some(immediate) = target_kept_index(operands, &label_kept) else {
7086 continue;
7087 };
7088 let target = follow_jump_chain(&kept, &label_kept, immediate);
7089 if target == index + 1 {
7090 delete[index] = true;
7091 changed = true;
7092 } else if matches!(
7093 kept.get(target).map(|(op, _)| *op),
7094 Some(Opcode::Return | Opcode::ReturnUndef | Opcode::Throw)
7095 ) {
7096 // Jumping straight to a return or throw is the same as doing it
7097 // here, so the jump becomes that instruction.
7098 kept[index] = (kept[target].0, Vec::new());
7099 changed = true;
7100 } else if target != immediate {
7101 // Redirect to the end of the chain.
7102 let label = index_label[target];
7103 kept[index].1 = vec![Op::Label(label)];
7104 changed = true;
7105 }
7106 }
7107 if !changed {
7108 break;
7109 }
7110 if !delete.iter().any(|deleted| *deleted) {
7111 break;
7112 }
7113 // Drop the deleted instructions and renumber everything.
7114 let mut next: Vec<(Opcode, Vec<Op>)> = Vec::with_capacity(kept.len());
7115 let mut next_spans: Vec<Option<Position>> = Vec::with_capacity(kept.len());
7116 let mut moved: Vec<Option<usize>> = vec![None; kept.len()];
7117 for (old, entry) in kept.into_iter().enumerate() {
7118 if delete[old] {
7119 continue;
7120 }
7121 moved[old] = Some(next.len());
7122 next.push(entry);
7123 next_spans.push(spans[old]);
7124 }
7125 for (id, slot) in label_kept.iter_mut().enumerate() {
7126 let Some(old) = *slot else { continue };
7127 *slot = match moved.get(old).copied().flatten() {
7128 Some(new) => Some(new),
7129 // The target was deleted: the jump now lands on whatever follows.
7130 None => (old..moved.len())
7131 .find_map(|i| moved[i])
7132 .or(Some(next.len())),
7133 };
7134 let _ = id;
7135 }
7136 kept = next;
7137 spans = next_spans;
7138 }
7139
7140 // The same walk at the end of the function: `try`/`catch`'s `goto end` becomes a
7141 // jump to the next instruction and is deleted, leaving the label at the end with
7142 // nothing pointing at it. If that also strands the last instruction, it goes
7143 // too — which is how a `try` whose body always returns ends on its `ret` rather
7144 // than an implicit `return_undef`.
7145 // Which instructions something still jumps to. Reading the surviving jumps is
7146 // what the reference's reference counts amount to: once a jump has been folded
7147 // away the label it named is unreferenced, even though the program still has a
7148 // label there.
7149 let mut references = vec![false; kept.len() + 1];
7150 let _ = real_labels;
7151 for (_, operands) in &kept {
7152 if let Some(target) = target_kept_index(operands, &label_kept)
7153 && target < references.len()
7154 {
7155 references[target] = true;
7156 }
7157 }
7158 let mut end = kept.len();
7159 while end > 0 {
7160 let last = end - 1;
7161 let reachable = references[last] || end < kept.len();
7162 if reachable {
7163 break;
7164 }
7165 let after_transfer = last
7166 .checked_sub(1)
7167 .map(|previous| {
7168 matches!(
7169 kept[previous].0,
7170 Opcode::Goto | Opcode::Return | Opcode::ReturnUndef | Opcode::Throw
7171 )
7172 })
7173 .unwrap_or(false);
7174 if !after_transfer {
7175 break;
7176 }
7177 end = last;
7178 }
7179 kept.truncate(end);
7180 spans.truncate(end);
7181
7182 // Choose an opcode for each instruction and its size, so label offsets can be
7183 // computed.
7184 let chosen = choose_opcodes(&kept, &label_kept);
7185 let offsets = instruction_offsets(&chosen);
7186 let offset = *offsets.last().unwrap_or(&0);
7187
7188 let mut code = Vec::with_capacity(offset);
7189 for (position, (_, operands)) in kept.iter().enumerate() {
7190 let op = chosen[position];
7191 code.push(op as u8);
7192 let operands = retarget_labels(operands, &label_kept, kept.len());
7193 encode_operands(&mut code, op, &operands, offsets[position], &offsets);
7194 }
7195 let stack_size = compute_stack_size(&code);
7196 // Keep only the offsets where the position actually changes: a run of
7197 // instructions on one line is one table entry, and the runtime binary searches
7198 // the table for the frame's pc.
7199 let mut positions: Vec<LineCol> = Vec::new();
7200 let mut last: Option<Position> = None;
7201 for (index, span) in spans.iter().enumerate() {
7202 let Some(pos) = *span else { continue };
7203 if last == Some(pos) {
7204 continue;
7205 }
7206 last = Some(pos);
7207 positions.push(LineCol {
7208 pc: offsets[index] as u32,
7209 line: pos.line,
7210 column: pos.column,
7211 });
7212 }
7213 (code, stack_size, positions)
7214}
7215
7216/// Whether an instruction always transfers control away, so anything after it in the
7217/// same stream is unreachable.
7218fn is_transfer(op: Opcode) -> bool {
7219 matches!(
7220 op,
7221 Opcode::Goto
7222 | Opcode::Goto8
7223 | Opcode::Goto16
7224 | Opcode::Return
7225 | Opcode::ReturnUndef
7226 | Opcode::Throw
7227 | Opcode::ThrowError
7228 | Opcode::Ret
7229 )
7230}
7231
7232/// Remove the marked instructions and renumber the label table so it keeps pointing
7233/// at the same instructions. A label whose instruction went away moves to whatever
7234/// follows it, since a jump is never left with nowhere to land.
7235fn drop_instructions(
7236 kept: Vec<(Opcode, Vec<Op>)>,
7237 spans: Vec<Option<Position>>,
7238 label_kept: &mut [Option<usize>],
7239 doomed: &[bool],
7240) -> (Vec<PositionedInsn>, Vec<Option<Position>>) {
7241 let mut result: Vec<(Opcode, Vec<Op>)> = Vec::with_capacity(kept.len());
7242 let mut result_spans: Vec<Option<Position>> = Vec::with_capacity(kept.len());
7243 let mut moved: Vec<Option<usize>> = vec![None; kept.len()];
7244 for (old, entry) in kept.into_iter().enumerate() {
7245 if doomed.get(old).copied().unwrap_or(false) {
7246 continue;
7247 }
7248 moved[old] = Some(result.len());
7249 result.push(entry);
7250 result_spans.push(spans[old]);
7251 }
7252 for slot in label_kept.iter_mut() {
7253 let Some(old) = *slot else { continue };
7254 *slot = match moved.get(old).copied().flatten() {
7255 Some(new) => Some(new),
7256 None => (old..moved.len())
7257 .find_map(|i| moved[i])
7258 .or(Some(result.len())),
7259 };
7260 }
7261 (result, result_spans)
7262}
7263
7264fn is_goto(op: Opcode) -> bool {
7265 matches!(op, Opcode::Goto | Opcode::Goto8 | Opcode::Goto16)
7266}
7267
7268/// The kept index a jump operand points at.
7269fn target_kept_index(operands: &[Op], label_kept: &[Option<usize>]) -> Option<usize> {
7270 let id = label_id(operands)?;
7271 label_kept.get(id as usize).copied().flatten()
7272}
7273
7274/// Follow a chain of unconditional jumps to its first real destination.
7275fn follow_jump_chain(
7276 kept: &[(Opcode, Vec<Op>)],
7277 label_kept: &[Option<usize>],
7278 start: usize,
7279) -> usize {
7280 let mut current = start;
7281 // `for(;;)` jumps to itself, so the walk has to be bounded.
7282 for _ in 0..kept.len() {
7283 let Some((op, operands)) = kept.get(current) else {
7284 return current;
7285 };
7286 if !is_goto(*op) {
7287 return current;
7288 }
7289 let Some(next) = target_kept_index(operands, label_kept) else {
7290 return current;
7291 };
7292 if next == current {
7293 return current;
7294 }
7295 current = next;
7296 }
7297 current
7298}
7299
7300/// Rewrite label operands from label ids to kept instruction indices.
7301fn retarget_labels(operands: &[Op], label_kept: &[Option<usize>], kept_len: usize) -> Vec<Op> {
7302 operands
7303 .iter()
7304 .map(|operand| match operand {
7305 Op::Label(label) => {
7306 let target = label_kept
7307 .get(label.0 as usize)
7308 .copied()
7309 .flatten()
7310 .unwrap_or(kept_len);
7311 Op::Label(Label(target as u32))
7312 }
7313 other => other.clone(),
7314 })
7315 .collect()
7316}
7317
7318/// Encode the resolved instruction stream, choosing short forms where possible.
7319///
7320/// Compute the maximum value-stack depth by exploring the control-flow graph.
7321///
7322/// This is a breadth-first walk from the first instruction, tracking the stack
7323/// depth on entry to each instruction. Every instruction has at most two
7324/// successors (fall through, and a jump target), so a worklist over byte offsets
7325/// is enough. The reference does the same thing in `compute_stack_size`, which is
7326/// why the resulting numbers match exactly.
7327///
7328/// Instructions that pop a variable number of values (`call`, `array_from`, …)
7329/// encode that count in their operand, which is added to the static `n_pop`.
7330fn compute_stack_size(code: &[u8]) -> u32 {
7331 let mut depth_at = vec![u16::MAX; code.len()];
7332 // Each entry carries the enclosing `catch` levels, innermost last, because
7333 // `nip_catch` needs them: it rewinds the stack to just above the innermost catch
7334 // offset and forgets that level.
7335 let mut worklist: Vec<(usize, u32, Vec<u32>)> = vec![(0, 0, Vec::new())];
7336 let mut max_depth = 0u32;
7337
7338 while let Some((pc, depth, catch_levels)) = worklist.pop() {
7339 if pc >= code.len() {
7340 continue;
7341 }
7342 if depth_at[pc] != u16::MAX {
7343 continue;
7344 }
7345 force_depth(&mut depth_at, pc, depth);
7346
7347 let Some(op) = Opcode::from_u8(code[pc]) else {
7348 break;
7349 };
7350 let info = op.info();
7351 let next = pc + info.size as usize;
7352 if next > code.len() {
7353 break;
7354 }
7355 let mut n_pop = info.n_pop as u32;
7356 let mut n_push = info.n_push as u32;
7357 // Variable-length forms carry their count in the operand.
7358 match info.format {
7359 crate::opcode::OpFormat::Npop | crate::opcode::OpFormat::NpopU16 => {
7360 n_pop += read_u16(code, pc + 1) as u32;
7361 }
7362 crate::opcode::OpFormat::Npopx => {
7363 n_pop += op.specialised_index().unwrap_or(0).max(0) as u32;
7364 }
7365 _ => {}
7366 }
7367 // `put_loc`/`put_arg`/`put_var_ref` keep the value on the stack when they
7368 // are the `set_` variant; the table already records that, so nothing to
7369 // adjust here.
7370 let _ = &mut n_push;
7371
7372 // The depth before this instruction's own push, which is what a `catch`
7373 // records as its level.
7374 let depth_before = depth;
7375 let mut depth = depth.saturating_sub(n_pop) + n_push;
7376 let mut catch_levels = catch_levels;
7377 if op == Opcode::NipCatch {
7378 // Discard everything above the innermost catch offset, keeping the value
7379 // on top: the frame the code after this sees is the same shape it would
7380 // have had if the `try` were not there.
7381 if let Some(base) = catch_levels.pop() {
7382 depth = base + 1;
7383 }
7384 }
7385 max_depth = max_depth.max(depth);
7386
7387 // Successors.
7388 let target = jump_target_of(code, pc, op);
7389 match op {
7390 Opcode::Goto | Opcode::Goto8 | Opcode::Goto16 => {
7391 if let Some(target) = target {
7392 worklist.push((target, depth, catch_levels));
7393 }
7394 }
7395 Opcode::IfFalse | Opcode::IfFalse8 | Opcode::IfTrue | Opcode::IfTrue8 => {
7396 if let Some(target) = target {
7397 worklist.push((target, depth, catch_levels.clone()));
7398 }
7399 worklist.push((next, depth, catch_levels));
7400 }
7401 // A `catch` records an exception edge to the handler. The handler is
7402 // entered with the thrown value on top of the stack, in the slot the
7403 // catch offset occupies on the normal path — which is why the handler's
7404 // first instruction can `put_loc` the exception away, and why the depth
7405 // is the same on both paths.
7406 Opcode::Catch => {
7407 if let Some(target) = target {
7408 // The handler is protected by the *enclosing* catch, not by this
7409 // one: an error raised inside it is what the handler's own
7410 // `catch` catches.
7411 worklist.push((target, depth, catch_levels.clone()));
7412 }
7413 catch_levels.push(depth_before);
7414 worklist.push((next, depth, catch_levels));
7415 }
7416 // A `for`/`of` loop keeps its own catch offset, and `nip_catch` has to
7417 // rewind past it too. Its level sits one slot higher than a `catch`'s:
7418 // the iterator and next-method slots occupy the offset's place.
7419 Opcode::ForOfStart | Opcode::ForAwaitOfStart => {
7420 if let Some(target) = target {
7421 worklist.push((target, depth, catch_levels.clone()));
7422 }
7423 catch_levels.push(depth_before + 1);
7424 worklist.push((next, depth, catch_levels));
7425 }
7426 // `gosub` calls a subroutine with the return address on top. The opcode
7427 // table records no push for it — `ret` is what pops the slot — so the
7428 // extra one is added here, where the depth of the subroutine's first
7429 // instruction is being computed.
7430 Opcode::Gosub => {
7431 if let Some(target) = target {
7432 worklist.push((target, depth + 1, catch_levels.clone()));
7433 }
7434 worklist.push((next, depth, catch_levels));
7435 }
7436 // `ret` goes back to a `gosub`; nothing here follows it.
7437 Opcode::Ret
7438 | Opcode::Return
7439 | Opcode::ReturnUndef
7440 | Opcode::Throw
7441 | Opcode::ThrowError => {}
7442 _ => worklist.push((next, depth, catch_levels)),
7443 }
7444 }
7445 max_depth
7446}
7447
7448/// Record the stack depth on entry to `pc`, keeping the deeper value if the
7449/// instruction is reachable more than once.
7450fn force_depth(depth_at: &mut [u16], pc: usize, depth: u32) {
7451 let clamped = depth.min(u16::MAX as u32 - 1) as u16;
7452 if depth_at[pc] == u16::MAX || depth_at[pc] < clamped {
7453 depth_at[pc] = clamped;
7454 }
7455}
7456
7457fn read_u16(code: &[u8], at: usize) -> u16 {
7458 let mut value = 0u16;
7459 for i in 0..2 {
7460 value = (value << 8) | code.get(at + i).copied().unwrap_or(0) as u16;
7461 }
7462 value
7463}
7464
7465/// The absolute target of a jump instruction, if it has one.
7466fn jump_target_of(code: &[u8], pc: usize, op: Opcode) -> Option<usize> {
7467 let info = op.info();
7468 let position = pc + 1;
7469 match info.format {
7470 crate::opcode::OpFormat::Label8 => {
7471 let offset = *code.get(position)? as i8 as i64;
7472 Some((position as i64 + offset) as usize)
7473 }
7474 crate::opcode::OpFormat::Label16 => {
7475 let offset = read_u16(code, position) as i16 as i64;
7476 Some((position as i64 + offset) as usize)
7477 }
7478 crate::opcode::OpFormat::Label => {
7479 let mut offset = 0i32;
7480 for i in 0..4 {
7481 offset = (offset << 8) | *code.get(position + i).unwrap_or(&0) as i32;
7482 }
7483 Some((position as i64 + offset as i64) as usize)
7484 }
7485 _ => None,
7486 }
7487}
7488
7489fn choose_short_form(op: Opcode, operands: &[Op]) -> Opcode {
7490 use Opcode::*;
7491 match (op, operands.first()) {
7492 (PushI32, Some(Op::Int(value))) if (-1..=7).contains(value) => {
7493 op.short_form(*value as u32).unwrap_or(op)
7494 }
7495 (PushConst, Some(Op::Const(index))) if *index < 256 => Opcode::PushConst8,
7496 (Fclosure, Some(Op::Const(index))) if *index < 256 => Opcode::Fclosure8,
7497 (GetLoc | PutLoc | SetLoc, Some(Op::Slot(Slot::Loc(index))))
7498 | (GetArg | PutArg | SetArg, Some(Op::Slot(Slot::Arg(index))))
7499 | (GetVarRef | PutVarRef | SetVarRef, Some(Op::Slot(Slot::VarRef(index))))
7500 // A declared global is reached through its reference cell, so it shares
7501 // the `var_ref` encodings, short forms included.
7502 | (GetVarRef | PutVarRef | SetVarRef, Some(Op::Slot(Slot::GlobalDecl(index)))) => {
7503 op.short_form(*index).unwrap_or(op)
7504 }
7505 (Call, Some(Op::Int(count))) if (0..=3).contains(count) => {
7506 op.short_form(*count as u32).unwrap_or(op)
7507 }
7508 _ => op,
7509 }
7510}
7511
7512/// The byte offset each instruction will start at, plus the total code size.
7513fn instruction_offsets(chosen: &[Opcode]) -> Vec<usize> {
7514 let mut offsets = Vec::with_capacity(chosen.len() + 1);
7515 let mut offset = 0usize;
7516 for op in chosen {
7517 offsets.push(offset);
7518 offset += op.size() as usize;
7519 }
7520 offsets.push(offset);
7521 offsets
7522}
7523
7524/// Pick an encoding for every instruction, shrinking a jump to its 8-bit form only when
7525/// the offset actually fits.
7526///
7527/// The choice is circular: an instruction's size decides the offsets of everything after
7528/// it, and the offsets decide whether a jump may be short. So this starts with every jump
7529/// in its widest form and shrinks what fits, repeating until a pass changes nothing.
7530/// Shrinking only ever *shortens* distances, so the loop converges.
7531///
7532/// Doing it in one pass instead — which is what this used to do — silently truncated any
7533/// jump further than 127 bytes: `goto8` with a mangled offset lands in the middle of the
7534/// bytecode, and the VM treats running off the end as a return. That is how a nested loop
7535/// with four closures in its body simply stopped, with no error and no output past the
7536/// first iteration.
7537fn choose_opcodes(kept: &[(Opcode, Vec<Op>)], label_kept: &[Option<usize>]) -> Vec<Opcode> {
7538 let mut chosen: Vec<Opcode> = kept
7539 .iter()
7540 .map(|(op, operands)| choose_short_form(*op, operands))
7541 .collect();
7542 // A jump the compiler emitted in its widest form, and the forms it may shrink to.
7543 let candidates = |op: Opcode| match op {
7544 Opcode::Goto => Some((Opcode::Goto8, Opcode::Goto16, true)),
7545 Opcode::IfFalse => Some((Opcode::IfFalse8, Opcode::IfFalse, false)),
7546 Opcode::IfTrue => Some((Opcode::IfTrue8, Opcode::IfTrue, false)),
7547 _ => None,
7548 };
7549 loop {
7550 let offsets = instruction_offsets(&chosen);
7551 let mut changed = false;
7552 for index in 0..kept.len() {
7553 let (op, operands) = &kept[index];
7554 let Some((short, medium, has_medium)) = candidates(*op) else {
7555 continue;
7556 };
7557 if chosen[index] == short {
7558 continue;
7559 }
7560 let Some(target) = target_kept_index(operands, label_kept) else {
7561 continue;
7562 };
7563 let Some(&target_offset) = offsets.get(target) else {
7564 continue;
7565 };
7566 // A jump is relative to the byte after its opcode, which is the convention
7567 // `jump_target_of` decodes with.
7568 let relative = target_offset as i64 - (offsets[index] as i64 + 1);
7569 if (-128..=127).contains(&relative) {
7570 chosen[index] = short;
7571 changed = true;
7572 } else if has_medium
7573 && chosen[index] == Opcode::Goto
7574 && (-32_768..=32_767).contains(&relative)
7575 {
7576 // Too far for 8 bits and close enough for 16. Only `goto` has a medium
7577 // form: `if_false`/`if_true` jump straight from 8 to 32 bits, exactly as
7578 // the reference encodes them.
7579 chosen[index] = medium;
7580 changed = true;
7581 }
7582 }
7583 if !changed {
7584 return chosen;
7585 }
7586 }
7587}
7588
7589fn encode_operands(
7590 code: &mut Vec<u8>,
7591 op: Opcode,
7592 operands: &[Op],
7593 position: usize,
7594 offsets: &[usize],
7595) {
7596 use crate::opcode::OpFormat::*;
7597 let info = op.info();
7598 let write_slot = |code: &mut Vec<u8>, slot: Slot| {
7599 let index = match slot {
7600 Slot::Arg(i)
7601 | Slot::Loc(i)
7602 | Slot::VarRef(i)
7603 | Slot::Global(i)
7604 | Slot::GlobalDecl(i) => i,
7605 };
7606 code.extend_from_slice(&(index as u16).to_be_bytes());
7607 };
7608 match info.format {
7609 None | NoneInt | NoneLoc | NoneArg | NoneVarRef | Npopx => {}
7610 U8 | Const8 => {
7611 if let Some(value) = operands.first().and_then(operand_uint) {
7612 code.push(value as u8);
7613 }
7614 }
7615 // The narrow slot forms (`inc_loc8` and friends) take a slot operand just
7616 // like their wide counterparts, only one byte wide.
7617 Loc8 => {
7618 if let Some(Op::Slot(slot)) = operands.first() {
7619 let index = match slot {
7620 Slot::Arg(i)
7621 | Slot::Loc(i)
7622 | Slot::VarRef(i)
7623 | Slot::Global(i)
7624 | Slot::GlobalDecl(i) => *i,
7625 };
7626 code.push(index as u8);
7627 }
7628 }
7629 I8 => {
7630 if let Some(value) = operands.first().and_then(operand_int) {
7631 code.push(value as i8 as u8);
7632 }
7633 }
7634 U16 | Npop => {
7635 if let Some(value) = operands.first().and_then(operand_int) {
7636 code.extend_from_slice(&(value as u16).to_be_bytes());
7637 }
7638 }
7639 I16 => {
7640 if let Some(value) = operands.first().and_then(operand_int) {
7641 code.extend_from_slice(&(value as i16 as u16).to_be_bytes());
7642 }
7643 }
7644 I32 => {
7645 if let Some(value) = operands.first().and_then(operand_int) {
7646 code.extend_from_slice(&value.to_be_bytes());
7647 }
7648 }
7649 U32 | Const => {
7650 if let Some(value) = operands.first().and_then(operand_uint) {
7651 code.extend_from_slice(&value.to_be_bytes());
7652 }
7653 }
7654 Loc | Arg | VarRef => {
7655 if let Some(Op::Slot(slot)) = operands.first() {
7656 write_slot(code, *slot);
7657 }
7658 }
7659 Atom | AtomU8 | AtomU16 | AtomLabelU8 | AtomLabelU16 => {
7660 if let Some(Op::AtomId(index)) = operands.first() {
7661 code.extend_from_slice(&index.to_be_bytes());
7662 }
7663 // The trailing immediate means different things per format, and the
7664 // atom forms that carry a *label* have to resolve it like any other
7665 // jump, so they cannot share the `U8`/`U16` arms above.
7666 match info.format {
7667 AtomU8 | AtomLabelU8 => {
7668 if let Some(value) = operands.get(1).and_then(operand_uint) {
7669 code.push(value as u8);
7670 }
7671 }
7672 AtomU16 | AtomLabelU16 => {
7673 if let Some(value) = operands.get(1).and_then(operand_uint) {
7674 code.extend_from_slice(&(value as u16).to_be_bytes());
7675 }
7676 }
7677 _ => {}
7678 }
7679 }
7680 NpopU16 => {
7681 for operand in operands.iter().take(2) {
7682 if let Some(value) = operand_uint(operand) {
7683 code.extend_from_slice(&(value as u16).to_be_bytes());
7684 }
7685 }
7686 }
7687 Label | Label8 | Label16 | LabelU16 => {
7688 if let Some(Op::Label(label)) = operands.first() {
7689 // Labels were already remapped to kept-instruction indices.
7690 let Some(&target) = offsets.get(label.0 as usize) else {
7691 debug_assert!(false, "label {} is past the end", label.0);
7692 return;
7693 };
7694 let relative = target as i64 - (position as i64 + 1);
7695 match info.format {
7696 Label8 => code.push(relative as i8 as u8),
7697 Label16 => code.extend_from_slice(&(relative as i16 as u16).to_be_bytes()),
7698 // `label_u16` stores the target followed by an unrelated u16.
7699 LabelU16 => {
7700 code.extend_from_slice(&(relative as i32).to_be_bytes());
7701 if let Some(value) = operands.get(1).and_then(operand_uint) {
7702 code.extend_from_slice(&(value as u16).to_be_bytes());
7703 }
7704 }
7705 _ => code.extend_from_slice(&(relative as i32).to_be_bytes()),
7706 }
7707 }
7708 }
7709 }
7710}
7711
7712fn operand_int(op: &Op) -> Option<i32> {
7713 match op {
7714 Op::Int(value) => Some(*value),
7715 _ => None,
7716 }
7717}
7718
7719fn operand_uint(op: &Op) -> Option<u32> {
7720 match op {
7721 Op::Const(value) | Op::AtomId(value) => Some(*value),
7722 Op::Int(value) => Some(*value as u32),
7723 _ => None,
7724 }
7725}
7726
7727/// Disassemble a compiled function.
7728pub fn disassemble(function: &CompiledFunction) -> String {
7729 disasm::disassemble_program(function)
7730}