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