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