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, Function as CompiledFunction, FunctionKind, VarDef,
27};
28use crate::disasm;
29use crate::opcode::Opcode;
30use js_parse::Position;
31use js_parse::Span;
32use js_parse::SyntaxError;
33use js_parse::ast::{self, *};
34
35/// A label id, local to the function being compiled.
36#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
37pub struct Label(u32);
38
39/// The `var_block` sentinel for a binding that lives at function scope.
40///
41/// It has to be a value a *real* block key can never take. Block keys are source
42/// offsets, so `0` is a perfectly ordinary key — the first block statement of a file
43/// gets it — and using `0` as the sentinel made `{ let y = 2 }` at offset zero look
44/// like a function-scoped `var`, which is how a top-level block's `let` leaked out of
45/// its block. The body block already uses `u64::MAX` to stay clear of offsets, so the
46/// sentinel takes the slot below it.
47const FUNCTION_SCOPE: u64 = u64::MAX - 3;
48
49/// The `blocks` parent sentinel for "this block has no enclosing block".
50///
51/// Same reasoning as [`FUNCTION_SCOPE`]: `0` is a legal block key, and when it was
52/// also the terminator the chain walk from the script body reached the file's
53/// offset-zero block and treated it as an *enclosing* block — so that block's `let`
54/// leaked into the body scope.
55const NO_PARENT: u64 = u64::MAX - 2;
56
57/// The block key for a script body. Distinct from both sentinels and unreachable from
58/// any source offset.
59const SCRIPT_BODY: u64 = u64::MAX - 1;
60
61/// An operand of a symbolic instruction.
62#[derive(Debug, Clone, PartialEq)]
63enum Op {
64 /// An immediate integer.
65 Int(i32),
66 /// A jump target.
67 Label(Label),
68 /// A constant pool index.
69 Const(u32),
70 /// An atom, before interning.
71 Atom(Atom),
72 /// An interned atom, as an index into [`Function::atoms`].
73 AtomId(u32),
74 /// A resolved slot.
75 Slot(Slot),
76}
77
78/// Where a resolved variable lives.
79#[derive(Debug, Clone, Copy, PartialEq, Eq)]
80enum Slot {
81 Arg(u32),
82 Loc(u32),
83 VarRef(u32),
84 /// A global, by closure-var index.
85 Global(u32),
86 /// A global *declared* in this script. The reference keeps these bindings in
87 /// reference cells so that the script and any closure share one variable, so
88 /// a store goes through `put_var_ref` while a read uses `get_var`.
89 GlobalDecl(u32),
90}
91
92/// What a symbolic variable access does, which decides the final opcode.
93#[derive(Debug, Clone, Copy, PartialEq, Eq)]
94enum VarAction {
95 /// Read the value.
96 Get,
97 /// Read the value, yielding `undefined` for an undeclared global.
98 GetUndef,
99 /// Write, leaving nothing on the stack.
100 Put,
101 /// Write and initialise, leaving the value on the stack.
102 PutInit,
103 /// Write, leaving the value on the stack.
104 Set,
105 /// Write a binding that lives in a reference cell.
106 PutRef,
107}
108
109#[derive(Debug, Clone)]
110enum Insn {
111 /// A fully determined instruction.
112 Fixed { op: Opcode, operands: Vec<Op> },
113 /// A variable access, resolved in the second pass.
114 ///
115 /// `block` is the lexical block the access appears in, which is what makes
116 /// shadowing work: two bindings can share a name, and the one that wins is
117 /// whichever scope encloses the access.
118 Var {
119 action: VarAction,
120 name: String,
121 block: u64,
122 },
123 /// Close a binding *if* it turned out to be captured.
124 ///
125 /// Whether a `for (let i ...)` loop variable needs a fresh per-iteration cell is
126 /// only known once the body has been compiled — a closure created there is the
127 /// thing that makes it necessary. The reference emits `close_loc` exactly in that
128 /// case and nothing otherwise, so the decision is deferred to [`resolve`] instead
129 /// of emitted blind.
130 CloseCaptured { name: String, block: u64 },
131 /// `delete name`, which can only answer `false` once the binding is known.
132 ///
133 /// It is not a `Var` action because `delete_var` carries an *atom*: the runtime
134 /// looks the name up on the global object, which is what distinguishes an implicit
135 /// global (configurable, deletable) from a declared one (a binding, always `false`).
136 DeleteVar { name: String },
137 /// An instruction that dead-code elimination removed. It keeps its slot so
138 /// that label indices stay valid, and resolves to no bytecode.
139 Dead,
140}
141
142/// Where `break` and `continue` jump to.
143///
144/// Targets are stacked as the compiler enters loops and labelled statements, so a
145/// bare `break` needs no analysis: it is simply the innermost target. A labelled
146/// one searches outward by name.
147#[derive(Debug, Clone)]
148struct JumpTarget {
149 /// The labels attached to this target. `l: for(;;)` gives one name; a bare
150 /// loop gives none; `a: b: for(;;)` gives two, because both labels name the
151 /// same statement and `break a` must reach the same place as `break b`.
152 names: Vec<String>,
153 /// Where `break` lands. `None` for a construct `break` may only leave, not
154 /// target — a `try`, whose entry exists purely to unwind.
155 break_label: Option<Label>,
156 /// Where `continue` lands. `None` for anything that is not a loop.
157 continue_label: Option<Label>,
158 /// Stack slots to discard when control leaves this construct by a jump.
159 ///
160 /// Both `switch` and `try` leave something on the value stack for the duration
161 /// of the construct — the discriminant, or the `catch` offset — and a jump out
162 /// has to take it with it. A loop leaves nothing.
163 drop_count: u32,
164 /// The finalizer to run when control leaves this construct.
165 ///
166 /// Set on a `try` even when it has no `finally`: the label is always emitted and
167 /// the empty-subroutine removal cleans up afterwards, so the code that unwinds
168 /// does not have to know whether a finalizer exists.
169 finally_label: Option<Label>,
170 /// Whether this is a labelled non-loop statement, which an unlabelled `break`
171 /// does not reach.
172 is_regular_stmt: bool,
173 /// Whether leaving this construct has to close an iterator.
174 ///
175 /// A `for`/`of` loop keeps an iterator on the value stack, and leaving early has
176 /// to run its `return` method. `for`/`in` keeps only an enumeration object, which
177 /// is dropped rather than closed.
178 has_iterator: bool,
179}
180
181/// `copy_data_properties` flags for an object-literal spread.
182///
183/// The byte packs three fields: the low bits are the stack offset of the source,
184/// the next three the offset of the exclusion list, and bit 2 asks for symbol keys
185/// as well as string keys. A spread passes a literal `null` exclusion list right
186/// below the source, so that field stays zero and only the source offset and the
187/// symbol bit are set — hence `{...v}` copies symbols, which the flag name says.
188const COPY_ALL_PROPERTIES: i32 = 2 | (1 << 2);
189
190/// The expression a `...` introduces.
191///
192/// The parser marks the spread in two places — the element/property variant and an
193/// [`ExprKind::Spread`] wrapper around the argument — so the wrapper has to be
194/// stepped through before the argument can be compiled.
195fn spread_argument(spread: &Expr) -> &Expr {
196 match &spread.kind {
197 ExprKind::Spread(inner) => inner,
198 _ => spread,
199 }
200}
201
202/// The flag byte `define_method` takes.
203///
204/// The low two bits pick value/getter/setter; bit 2 marks the property
205/// enumerable, which every object-literal method is.
206fn define_method_flags(kind: PropertyKind) -> i32 {
207 let base = match kind {
208 PropertyKind::Value | PropertyKind::Method => 0,
209 PropertyKind::Get => 1,
210 PropertyKind::Set => 2,
211 };
212 base | 4
213}
214
215/// Convert a numeric property key to the text an atom would be made from.
216///
217/// Only the range where Rust and JavaScript agree on the spelling is accepted.
218/// Both print the shortest representation that round-trips, so plain decimal
219/// digits match; they diverge at the extremes, where JavaScript switches to an
220/// exponent (`1e-7`, `1e+21`) and Rust does not. Rather than emit an atom that
221/// differs from the reference, those keys are rejected.
222fn numeric_key_text(value: f64, span: Span) -> Result<String, SyntaxError> {
223 if !value.is_finite() {
224 return Err(SyntaxError::new(
225 "a non-finite numeric property key is not supported by the compiler yet",
226 span,
227 ));
228 }
229 if value == value.trunc() && value.abs() < 1e21 {
230 return Ok(format!("{}", value as i64));
231 }
232 if value.abs() >= 1e-6 && value.abs() < 1e21 {
233 return Ok(format!("{value}"));
234 }
235 Err(SyntaxError::new(
236 "a numeric property key outside [1e-6, 1e21) is not supported by the compiler yet",
237 span,
238 ))
239}
240
241/// Collect the operands of a same-operator logical run, in source order.
242///
243/// Recurses down the left spine only: `((a || b) || c)` contributes `a`, `b`, then
244/// the caller appends `c`. A node with a different operator is one operand.
245fn collect_same_operator<'a>(op: LogicalOp, expr: &'a Expr, out: &mut Vec<&'a Expr>) {
246 if let ExprKind::Logical {
247 op: inner_op,
248 left,
249 right,
250 } = &expr.kind
251 && *inner_op == op
252 {
253 collect_same_operator(op, left, out);
254 out.push(right);
255 return;
256 }
257 out.push(expr);
258}
259
260/// The jump a logical assignment or `??` takes when the value is kept.
261///
262/// `||` and `&&` branch on truthiness, so the same opcode serves both the operator
263/// and `??` once [`Compiler::emit_logical_test`] has pushed a boolean. `??` keeps
264/// the value when it is *not* null-ish, so it is the `if_false` side.
265fn logical_jump(op: AssignOp) -> Opcode {
266 match op {
267 AssignOp::Or => Opcode::IfTrue,
268 AssignOp::And | AssignOp::Coalesce => Opcode::IfFalse,
269 _ => Opcode::IfFalse,
270 }
271}
272
273/// Whether a loop enumerates keys or values.
274#[derive(Debug, Clone, Copy, PartialEq, Eq)]
275enum ForLoopKind {
276 /// `for (x in o)` — the keys of an object.
277 In,
278 /// `for (x of o)` — the values of an iterable.
279 Of,
280}
281
282/// Which part of a `try` statement a block key refers to.
283#[derive(Debug, Clone, Copy)]
284enum TryPart {
285 /// The guarded block.
286 Block = 0,
287 /// The handler body, excluding the catch parameter.
288 Catch = 1,
289 /// The finalizer block.
290 Finally = 2,
291 /// The catch parameter's own scope.
292 Param = 3,
293}
294
295/// A lexical scope, identified while hoisting and numbered at the end.
296///
297/// Scope identity is needed in two passes that must agree: declarations are
298/// hoisted in source order (so slots come out in source order, as in the
299/// reference), but a binding belongs to the block it was written in, which is only
300/// entered later. Blocks are therefore keyed by the source position of their
301/// opening brace, which is stable across both walks.
302#[derive(Debug, Clone, Copy)]
303struct Block {
304 /// Source position of the block.
305 key: u64,
306 /// The block this one is nested in; `0` for the function scope.
307 parent: u64,
308}
309
310/// One function under construction.
311struct FnState {
312 name: String,
313 kind: FunctionKind,
314 strict: bool,
315 args: Vec<VarDef>,
316 vars: Vec<VarDef>,
317 closure_vars: Vec<ClosureVar>,
318 cpool: Vec<Constant>,
319 atoms: Vec<Atom>,
320 /// Every lexical scope, in creation order.
321 blocks: Vec<Block>,
322 /// The block currently being parsed or compiled.
323 current_block: u64,
324 /// The block each local was declared in, parallel to `vars`. `0` means the
325 /// function scope, where `var` bindings live.
326 var_block: Vec<u64>,
327 /// Set when the expression just compiled left no value on the stack.
328 ///
329 /// Only a store can do that: `put_field` consumes the object and the value, so
330 /// an assignment whose result is unused emits nothing extra. The expression
331 /// statement then has nothing to drop.
332 no_value: bool,
333 /// Whether a label was placed since the last instruction was emitted.
334 ///
335 /// The `put`/`get` fold is only valid when the two are adjacent in the final
336 /// stream; a label in between means a jump can land on the read, so the store has
337 /// to keep consuming its value. A flag is enough and avoids having to reason about
338 /// which index a label recorded.
339 label_since_insn: bool,
340 /// Whether the value of the expression being compiled is thrown away.
341 ///
342 /// Only an expression *statement* discards its value, and only the outermost
343 /// assignment in it may act on that: in `x = (o.a = 1)` the inner assignment
344 /// still has to produce a value. Consumed by [`Compiler::assign`], which is
345 /// the one construct whose bytecode depends on it.
346 discard_value: bool,
347 /// The block that holds the function body.
348 body_block: u64,
349 /// Head of each scope's binding chain, indexed by level. Filled in by
350 /// [`rebuild_scope_chain`]; the scope chain is only needed at run time.
351 block_heads: Vec<i32>,
352 /// Enclosing `break`/`continue` targets, innermost last.
353 jump_targets: Vec<JumpTarget>,
354 insns: Vec<Insn>,
355 labels: Vec<Option<usize>>,
356 /// Captured locals, which need a reference cell.
357 var_ref_count: u32,
358 line: u32,
359 column: u32,
360 /// Whether this is a script body. A script's top-level declarations create
361 /// global properties rather than locals, which is why they show up as
362 /// closure variables with `[global_decl]`.
363 is_script: bool,
364 /// Whether the function is an arrow, which never gets its own `arguments`.
365 is_arrow: bool,
366 /// The name a *named function expression* binds inside its own body.
367 self_name: Option<String>,
368 /// Whether the code emitted so far leaves the program's result on the stack.
369 /// The reference tracks this for the hidden `<ret>` local of an eval script.
370 leaves_value: bool,
371 /// Statement nesting depth, used to tell top-level statements apart.
372 stmt_depth: u32,
373 /// Function declarations waiting to be instantiated at scope entry, as
374 /// (target slot, constant pool index). The reference emits these from
375 /// `instantiate_hoisted_definitions` rather than at the statement, because a
376 /// declaration is visible before it is reached.
377 hoisted: Vec<(u64, HoistTarget, u32)>,
378 /// The source position of the node being compiled. Every instruction emitted
379 /// takes it, which is how the position table that feeds stack traces is built.
380 cur_pos: Option<Position>,
381 /// One position per entry in `insns`, index-aligned.
382 insn_pos: Vec<Option<Position>>,
383}
384
385/// Where a hoisted function declaration is stored.
386#[derive(Debug, Clone)]
387enum HoistTarget {
388 Arg(u32),
389 Loc(u32),
390 /// A global, which the resolver looks up by name.
391 Global(String),
392}
393
394impl FnState {
395 fn new(name: impl Into<String>, kind: FunctionKind) -> FnState {
396 FnState {
397 name: name.into(),
398 kind,
399 strict: false,
400 args: Vec::new(),
401 vars: Vec::new(),
402 closure_vars: Vec::new(),
403 cpool: Vec::new(),
404 atoms: Vec::new(),
405 blocks: Vec::new(),
406 current_block: 0,
407 var_block: Vec::new(),
408 no_value: false,
409 label_since_insn: false,
410 discard_value: false,
411 body_block: 0,
412 block_heads: Vec::new(),
413 jump_targets: Vec::new(),
414 insns: Vec::new(),
415 labels: Vec::new(),
416 var_ref_count: 0,
417 line: 1,
418 column: 1,
419 is_script: false,
420 is_arrow: false,
421 self_name: None,
422 leaves_value: false,
423 stmt_depth: 0,
424 hoisted: Vec::new(),
425 cur_pos: None,
426 insn_pos: Vec::new(),
427 }
428 }
429
430 /// The scope a declaration lands in: a script's top-level declarations are
431 /// globals, everything else gets a slot.
432 /// Whether a binding declared *now* becomes a property of the global object.
433 ///
434 /// For a script, a top-level `var` and the top-level `let`/`const` are globals.
435 /// The `var` case is decided by the keyword rather than by the cursor position:
436 /// `var` is function-scoped, so a `var i` in a `for` head is still the same
437 /// binding as a `var i` in the body, even though the head has its own block.
438 fn declares_globally(&self, def: &VarDef) -> bool {
439 self.is_script && (!def.is_lexical || self.current_block == self.body_block)
440 }
441}
442
443/// The compiler's entry point.
444pub struct Compiler {
445 module: bool,
446 /// Enclosing functions, outermost first. The last entry is the current one.
447 stack: Vec<FnState>,
448}
449
450/// Compile a script.
451pub fn compile_script(program: &Program) -> Result<CompiledFunction, SyntaxError> {
452 Compiler::new(false).compile(program)
453}
454
455/// Compile a module.
456pub fn compile_module(program: &Program) -> Result<CompiledFunction, SyntaxError> {
457 Compiler::new(true).compile(program)
458}
459
460impl Compiler {
461 /// Create a compiler.
462 pub fn new(module: bool) -> Compiler {
463 Compiler {
464 module,
465 stack: Vec::new(),
466 }
467 }
468
469 /// Compile a whole program into its top-level function.
470 pub fn compile(mut self, program: &Program) -> Result<CompiledFunction, SyntaxError> {
471 let mut state = FnState::new("<eval>", FunctionKind::Normal);
472 state.is_script = true;
473 state.strict = program.strict || self.module;
474 state.line = program.span.start.line;
475 state.column = program.span.start.column;
476 // Locals are numbered in declaration order; `<ret>` is always slot 0.
477 //
478 // `var_block` has to grow in step with `vars`: it is indexed by slot, so a
479 // slot that only appears in one of the two arrays shifts every later
480 // binding's block and silently loses the temporal-dead-zone marking for
481 // the script's own blocks. A function frame has no `<ret>`, which is why
482 // the misalignment only showed up at the top level.
483 state.vars.push(VarDef::var("<ret>"));
484 state.var_block.push(FUNCTION_SCOPE);
485 self.stack.push(state);
486 // The body is its own scope, keyed by the position of the program.
487 // The script body needs a key no statement can produce. Statement keys are
488 // source offsets, and the program's own start offset is `0` — which is also
489 // the offset of the first statement, so a top-level `{ let x }` or
490 // `for (let i …)` used to share the body's block and lose its scope.
491 let body_key = SCRIPT_BODY;
492 self.push_block(body_key, NO_PARENT);
493 self.state().body_block = body_key;
494 self.hoist(&program.body, body_key)?;
495 self.emit_scope_enter(body_key);
496 for stmt in &program.body {
497 self.stmt(stmt)?;
498 if Self::terminates(stmt) {
499 break;
500 }
501 }
502 // The program's value is whatever the last expression statement stored in
503 // the hidden `<ret>` local; `put_loc0`/`get_loc0` folding turns the common
504 // case into a single `set_loc0`.
505 self.emit(Opcode::GetLoc, &[Op::Slot(Slot::Loc(0))]);
506 self.emit(Opcode::Return, &[]);
507 Ok(self.finish_current())
508 }
509
510 // -- emitting ----------------------------------------------------------
511
512 fn state(&mut self) -> &mut FnState {
513 self.stack.last_mut().expect("a function is being compiled")
514 }
515
516 fn cur(&self) -> &FnState {
517 self.stack.last().expect("a function is being compiled")
518 }
519
520 fn emit(&mut self, op: Opcode, operands: &[Op]) {
521 self.state().label_since_insn = false;
522 let pos = self.cur().cur_pos;
523 self.state().insns.push(Insn::Fixed {
524 op,
525 operands: operands.to_vec(),
526 });
527 self.state().insn_pos.push(pos);
528 }
529
530 /// Reset the script's hidden return value to `undefined`.
531 ///
532 /// Called at the start of every statement that does not itself produce the
533 /// program's value, which is how the reference keeps `if`/loop results from
534 /// leaking into an eval result.
535 fn reset_value(&mut self) {
536 if !self.cur().is_script {
537 return;
538 }
539 self.emit(Opcode::Undefined, &[]);
540 self.emit(Opcode::PutLoc, &[Op::Slot(Slot::Loc(0))]);
541 self.state().leaves_value = false;
542 }
543
544 /// Whether `name` is a local or argument slot rather than a global.
545 fn is_slot(&self, name: &str) -> bool {
546 self.cur().vars.iter().any(|v| v.name == name)
547 || self.cur().args.iter().any(|a| a.name == name)
548 }
549
550 fn emit_var(&mut self, action: VarAction, name: &str) {
551 // Peephole: `put_x v` followed by `get_x v` becomes `set_x v`, which
552 // stores and keeps the value in one instruction. The reference does this
553 // in a post-pass; folding it at emit time keeps instruction indices
554 // stable, which matters because labels are recorded as indices.
555 //
556 // Only slots have a `set_` form: a global is stored with `put_var` and
557 // read with `get_var`, and the reference does not fold those.
558 //
559 // A label between the two cancels the fold. `set_x v` leaves the value on
560 // the stack, which is only equivalent when the read immediately follows the
561 // store; when a jump target sits in between, the store must *consume* the
562 // value and the read must fetch it afresh. A loop head is exactly that
563 // case — `for (var i = 0; i < 3; i++)` stores the initialiser, then the
564 // condition re-reads it — and folding across the label would make the
565 // condition compare whatever the previous iteration left on the stack.
566 if action == VarAction::Get {
567 let is_slot = self.is_slot(name);
568 let at_label = std::mem::take(&mut self.state().label_since_insn);
569 //
570 // `arguments` is excluded because the reference treats it as a special
571 // binding: it is initialised once and read many times, and folding its
572 // initialisation into a `set_` would leave the object on the stack where
573 // the reference leaves nothing.
574 if is_slot
575 && name != "arguments"
576 && !at_label
577 && let Some(Insn::Var {
578 action: previous,
579 name: previous_name,
580 ..
581 }) = self.state().insns.last_mut()
582 && *previous == VarAction::Put
583 && previous_name == name
584 {
585 *previous = VarAction::Set;
586 return;
587 }
588 }
589 let block = self.cur().current_block;
590 self.state().label_since_insn = false;
591 let pos = self.cur().cur_pos;
592 self.state().insns.push(Insn::Var {
593 action,
594 name: name.to_string(),
595 block,
596 });
597 self.state().insn_pos.push(pos);
598 }
599
600 fn new_label(&mut self) -> Label {
601 let state = self.state();
602 state.labels.push(None);
603 Label(state.labels.len() as u32 - 1)
604 }
605
606 fn place_label(&mut self, label: Label) {
607 let index = self.cur().insns.len();
608 self.state().label_since_insn = true;
609 self.state().labels[label.0 as usize] = Some(index);
610 }
611
612 fn emit_jump(&mut self, op: Opcode, label: Label, extra: &[Op]) {
613 let mut operands = vec![Op::Label(label)];
614 operands.extend_from_slice(extra);
615 self.emit(op, &operands);
616 }
617
618 // -- scopes ------------------------------------------------------------
619
620 /// Start a new lexical scope inside `parent`.
621 fn push_block(&mut self, key: u64, parent: u64) {
622 let state = self.state();
623 if !state.blocks.iter().any(|b| b.key == key) {
624 state.blocks.push(Block { key, parent });
625 }
626 state.current_block = key;
627 }
628
629 /// Emit the code that runs when a lexical scope is entered.
630 ///
631 /// Every `let`/`const`/`class` binding starts out in the temporal dead zone,
632 /// so entering its block marks it uninitialised. Hoisted function
633 /// declarations are created here instead, which is why a call before the
634 /// declaration still works.
635 ///
636 /// The order is not obvious: bindings are emitted in *reverse* declaration
637 /// order, because the reference walks its scope chain, which is built by
638 /// prepending.
639 fn emit_scope_enter(&mut self, block: u64) {
640 let hoisted = std::mem::take(&mut self.state().hoisted);
641 let mut mine: Vec<(HoistTarget, u32)> = hoisted
642 .into_iter()
643 .filter(|(owner, _, _)| *owner == block)
644 .map(|(_, target, pool_index)| (target, pool_index))
645 .collect();
646 mine.sort_by_key(|(target, _)| match target {
647 HoistTarget::Arg(index) | HoistTarget::Loc(index) => *index,
648 HoistTarget::Global(_) => u32::MAX,
649 });
650 for (target, pool_index) in mine {
651 self.emit(Opcode::Fclosure, &[Op::Const(pool_index)]);
652 match target {
653 HoistTarget::Arg(index) => self.emit(Opcode::PutArg, &[Op::Slot(Slot::Arg(index))]),
654 HoistTarget::Loc(index) => self.emit(Opcode::PutLoc, &[Op::Slot(Slot::Loc(index))]),
655 HoistTarget::Global(name) => {
656 // A global binding lives in a reference cell, so the store
657 // goes through `put_var_ref` while reads use `get_var`.
658 let block = self.cur().current_block;
659 let pos = self.cur().cur_pos;
660 self.state().insns.push(Insn::Var {
661 action: VarAction::PutRef,
662 name,
663 block,
664 });
665 self.state().insn_pos.push(pos);
666 }
667 }
668 }
669 for index in self.block_vars_reversed(block) {
670 self.emit(
671 Opcode::SetLocUninitialized,
672 &[Op::Slot(Slot::Loc(index as u32))],
673 );
674 }
675 }
676
677 /// Emit the code that runs when a lexical scope is exited.
678 ///
679 /// A captured binding has to be closed: detaching its reference cell freezes
680 /// the value the binding had when the block ended, which is what a closure
681 /// created inside the block must keep seeing.
682 fn emit_scope_leave(&mut self, block: u64) {
683 for index in self.block_vars_reversed(block) {
684 if self.cur().vars[index].is_captured {
685 self.emit(Opcode::CloseLoc, &[Op::Slot(Slot::Loc(index as u32))]);
686 }
687 }
688 }
689
690 /// Locals declared in `block`, in reverse declaration order.
691 fn block_vars_reversed(&self, block: u64) -> Vec<usize> {
692 let state = self.cur();
693 let mut out: Vec<usize> = (0..state.vars.len())
694 .filter(|index| {
695 state.var_block.get(*index).copied() == Some(block) && state.vars[*index].is_lexical
696 })
697 .collect();
698 out.reverse();
699 out
700 }
701
702 /// Declare a local, even at the top level of a script.
703 ///
704 /// A `catch` parameter is always a local: the reference puts it in the
705 /// function's own variable list (`1: catch e`), never in the global object,
706 /// because it only exists while the handler runs.
707 fn declare_local(&mut self, _name: &str, def: VarDef) -> u32 {
708 let state = self.state();
709 let index = state.vars.len() as u32;
710 // A `catch` parameter belongs to a scope even though it is not lexical: the
711 // runtime instantiates it per handler entry, but it never sits in the
712 // temporal dead zone.
713 let block = if def.is_lexical || def.kind == crate::bytecode::VarKind::Catch {
714 state.current_block
715 } else {
716 0
717 };
718 state.var_block.push(block);
719 state.vars.push(def);
720 index
721 }
722
723 fn declare(&mut self, name: &str, def: VarDef) -> u32 {
724 if self.cur().declares_globally(&def) {
725 self.declare_global(name, &def);
726 return 0;
727 }
728 let state = self.state();
729 let index = state.vars.len() as u32;
730 let block = if def.is_lexical {
731 state.current_block
732 } else {
733 0
734 };
735 state.var_block.push(block);
736 state.vars.push(def);
737 index
738 }
739
740 // -- statements --------------------------------------------------------
741
742 fn stmt(&mut self, stmt: &Stmt) -> Result<(), SyntaxError> {
743 self.stmt_labelled(stmt, &[])
744 }
745
746 /// Compile a statement that a chain of labels names.
747 ///
748 /// Only a loop consumes `labels`; every other statement ignores them (the
749 /// parser has already rejected a label on a statement that cannot use it).
750 fn stmt_labelled(&mut self, stmt: &Stmt, labels: &[String]) -> Result<(), SyntaxError> {
751 // Only a *top-level* expression statement supplies the program's value.
752 let saved = self.cur().leaves_value;
753 self.state().leaves_value =
754 matches!(stmt.kind, StmtKind::Expr(_)) && self.cur().stmt_depth == 0;
755 self.state().stmt_depth += 1;
756 let result = self.stmt_inner(stmt, labels);
757 self.state().stmt_depth -= 1;
758 // A nested statement never contributes the program's value, so the flag
759 // the wrapper set above is what survives.
760 let produced = self.cur().leaves_value && self.cur().stmt_depth == 0;
761 self.state().leaves_value = produced;
762 let _ = saved;
763 result
764 }
765
766 fn stmt_inner(&mut self, stmt: &Stmt, labels: &[String]) -> Result<(), SyntaxError> {
767 match &stmt.kind {
768 StmtKind::Empty | StmtKind::Debugger => {}
769 StmtKind::Expr(expr) => {
770 // An expression statement's value is thrown away — except in a
771 // script, where it becomes the program's result. `assign` reads this
772 // and clears it, so a nested assignment still produces a value.
773 self.state().discard_value = !self.cur().is_script;
774 let result = self.expr(expr);
775 self.state().discard_value = false;
776 result?;
777 if std::mem::take(&mut self.state().no_value) {
778 // A store whose value was discarded left nothing to drop.
779 } else if self.cur().is_script {
780 // The program's value lands in the hidden `<ret>` local.
781 self.emit(Opcode::PutLoc, &[Op::Slot(Slot::Loc(0))]);
782 } else {
783 self.emit(Opcode::Drop, &[]);
784 }
785 }
786 StmtKind::Block(body) => {
787 // The block's declarations were hoisted with its enclosing
788 // statement list, so there is nothing left to declare here.
789 let key = stmt.span.start.offset as u64;
790 let parent = self.cur().current_block;
791 self.push_block(key, parent);
792 self.emit_scope_enter(key);
793 for stmt in body {
794 self.stmt(stmt)?;
795 if Self::terminates(stmt) {
796 break;
797 }
798 }
799 self.emit_scope_leave(key);
800 self.state().current_block = parent;
801 }
802 StmtKind::VarDecl(decl) => self.var_decl(decl)?,
803 // A function declaration was already instantiated when its scope was
804 // entered, so the statement itself emits nothing.
805 StmtKind::FuncDecl(_) => {}
806 StmtKind::If { test, cons, alt } => {
807 self.reset_value();
808 let else_label = self.new_label();
809 let end_label = self.new_label();
810 self.expr(test)?;
811 self.emit_jump(Opcode::IfFalse, else_label, &[]);
812 self.stmt(cons)?;
813 if alt.is_some() {
814 self.emit_jump(Opcode::Goto, end_label, &[]);
815 }
816 self.place_label(else_label);
817 if let Some(alt) = alt {
818 self.stmt(alt)?;
819 self.place_label(end_label);
820 }
821 }
822 StmtKind::While { test, body } => {
823 self.reset_value();
824 let top = self.new_label();
825 let end = self.new_label();
826 self.place_label(top);
827 self.expr(test)?;
828 // The condition's false branch and `break` share one target,
829 // which is why a `while` loop needs only one end label.
830 self.emit_jump(Opcode::IfFalse, end, &[]);
831 self.loop_body(body, labels, top, end)?;
832 self.emit_jump(Opcode::Goto, top, &[]);
833 self.place_label(end);
834 }
835 StmtKind::DoWhile { body, test } => {
836 self.reset_value();
837 let top = self.new_label();
838 let cont = self.new_label();
839 let end = self.new_label();
840 self.place_label(top);
841 // `continue` in a `do…while` runs the test, so it lands on `cont`
842 // rather than on the loop head.
843 self.loop_body(body, labels, cont, end)?;
844 self.place_label(cont);
845 self.expr(test)?;
846 self.emit_jump(Opcode::IfTrue, top, &[]);
847 self.place_label(end);
848 }
849 StmtKind::For {
850 init,
851 test,
852 update,
853 body,
854 } => {
855 self.reset_value();
856 let for_key = stmt.span.start.offset as u64;
857 let for_parent = self.cur().current_block;
858 self.push_block(for_key, for_parent);
859 self.emit_scope_enter(for_key);
860 if let Some(init) = init {
861 match init {
862 ForInit::VarDecl(decl) => {
863 self.var_decl(decl)?;
864 }
865 ForInit::Expr(expr) => {
866 // The head's value is discarded. Saying so lets an
867 // assignment store with `put` instead of `dup`+`put`, which
868 // is what the reference emits — and the difference matters:
869 // a `dup`/`drop` pair around the store gives the peephole a
870 // chance to fold the store into the *condition's* read.
871 self.state().discard_value = true;
872 let result = self.expr(expr);
873 self.state().discard_value = false;
874 result?;
875 if !std::mem::take(&mut self.state().no_value) {
876 self.emit(Opcode::Drop, &[]);
877 }
878 }
879 }
880 }
881 // A `let`/`const` in the head gets a *fresh binding per iteration*,
882 // so a closure made in the body captures that iteration's value
883 // instead of sharing one. The reference expresses this with
884 // `close_loc`, which swaps in a new reference cell holding the
885 // current value; the three points below are the ones it uses — after
886 // the initialiser, before the update, and after the loop.
887 let loop_bindings = match init {
888 Some(ForInit::VarDecl(decl)) if decl.kind != VarDeclKind::Var => {
889 let mut names: Vec<String> = Vec::new();
890 for declarator in &decl.declarators {
891 let mut idents = Vec::new();
892 declarator.target.bound_names(&mut idents);
893 names.extend(idents.into_iter().map(|ident| ident.name));
894 }
895 names
896 }
897 _ => Vec::new(),
898 };
899 // The reference also closes right after the initialiser, so the first
900 // iteration's closures get their own cell rather than sharing the one
901 // the initialiser wrote into.
902 for name in &loop_bindings {
903 let pos = self.cur().cur_pos;
904 self.state().insns.push(Insn::CloseCaptured {
905 name: name.clone(),
906 block: for_key,
907 });
908 self.state().insn_pos.push(pos);
909 }
910 let top = self.new_label();
911 let cont = self.new_label();
912 let end = self.new_label();
913 self.place_label(top);
914 if let Some(test) = test {
915 self.expr(test)?;
916 self.emit_jump(Opcode::IfFalse, end, &[]);
917 }
918 // `continue` runs the update expression first, so it lands on
919 // `cont`, which sits just before the update.
920 self.loop_body(body, labels, cont, end)?;
921 self.place_label(cont);
922 // Each iteration ends with a fresh cell, so the closures the body just
923 // created keep the cell they captured and the update writes to a new
924 // one. Without this every closure in the loop shares one binding.
925 let binding_block = for_key;
926 for name in &loop_bindings {
927 let pos = self.cur().cur_pos;
928 self.state().insns.push(Insn::CloseCaptured {
929 name: name.clone(),
930 block: binding_block,
931 });
932 self.state().insn_pos.push(pos);
933 }
934 if let Some(update) = update {
935 self.state().discard_value = true;
936 let result = self.expr(update);
937 self.state().discard_value = false;
938 result?;
939 if !std::mem::take(&mut self.state().no_value) {
940 self.emit(Opcode::Drop, &[]);
941 }
942 }
943 self.emit_jump(Opcode::Goto, top, &[]);
944 self.place_label(end);
945 self.emit_scope_leave(for_key);
946 self.state().current_block = for_parent;
947 }
948 StmtKind::Return(value) => self.return_stmt(value.as_deref())?,
949 StmtKind::Throw(expr) => {
950 self.expr(expr)?;
951 self.emit(Opcode::Throw, &[]);
952 }
953 StmtKind::Break(_) | StmtKind::Continue(_) => {
954 // Labels and loops are wired up in a later milestone; a bare
955 // break/continue jumps to the innermost enclosing target, which
956 // the loop helpers register.
957 self.control_transfer(stmt)?;
958 }
959 StmtKind::Labeled { label, body } => {
960 self.labeled(label, body, stmt)?;
961 }
962 StmtKind::Switch {
963 discriminant,
964 cases,
965 } => {
966 self.switch(discriminant, cases, stmt)?;
967 }
968 StmtKind::Try {
969 block,
970 handler,
971 finalizer,
972 } => {
973 self.try_stmt(stmt, block, handler, finalizer.as_deref())?;
974 }
975 StmtKind::ForIn { left, right, body } => {
976 self.for_in_of(stmt, left, right, body, ForLoopKind::In)?;
977 }
978 StmtKind::ForOf {
979 left,
980 right,
981 body,
982 is_await,
983 } => {
984 if *is_await {
985 return Err(SyntaxError::new(
986 "for await is not supported by the compiler yet",
987 stmt.span,
988 ));
989 }
990 self.for_in_of(stmt, left, right, body, ForLoopKind::Of)?;
991 }
992 StmtKind::With { .. } => {
993 // `with` is sloppy-mode only and needs the object scope chain at
994 // run time; left for the milestone that adds it.
995 return Err(SyntaxError::new(
996 "'with' is not supported by the compiler yet",
997 stmt.span,
998 ));
999 }
1000 StmtKind::ClassDecl(_) => {
1001 return Err(SyntaxError::new(
1002 "class declarations are not supported by the compiler yet",
1003 stmt.span,
1004 ));
1005 }
1006 StmtKind::Import(_) | StmtKind::Export(_) => {
1007 return Err(SyntaxError::new(
1008 "modules are not supported by the compiler yet",
1009 stmt.span,
1010 ));
1011 }
1012 }
1013 Ok(())
1014 }
1015
1016 /// Compile `return`, running every enclosing finalizer on the way out.
1017 ///
1018 /// `nip_catch` is what makes this possible: it discards everything on the stack
1019 /// down to and including the `catch` offset while keeping the return value on
1020 /// top, so the frame the finalizer sees has the same shape as on the normal
1021 /// path.
1022 fn return_stmt(&mut self, value: Option<&Expr>) -> Result<(), SyntaxError> {
1023 let mut has_value = value.is_some();
1024 if let Some(expr) = value {
1025 // `return f(x)` is a tail call *only* when nothing has to happen to the
1026 // value afterwards. A `finally` or an open iterator in scope forces the
1027 // normal path, because the cleanup has to run after the call returns —
1028 // which is exactly what a tail call refuses to do.
1029 let plain = self
1030 .cur()
1031 .jump_targets
1032 .iter()
1033 .all(|target| target.finally_label.is_none() && !target.has_iterator);
1034 if plain && self.expr_if_tail_call(expr)? {
1035 return Ok(());
1036 }
1037 self.expr(expr)?;
1038 }
1039 let targets = self.cur().jump_targets.clone();
1040 for target in targets.iter().rev() {
1041 if target.finally_label.is_none() && !target.has_iterator {
1042 continue;
1043 }
1044 if !has_value {
1045 // The cleanup expects a value to pass through; with nothing to
1046 // return, `undefined` stands in.
1047 self.emit(Opcode::Undefined, &[]);
1048 has_value = true;
1049 }
1050 self.emit(Opcode::NipCatch, &[]);
1051 if target.has_iterator {
1052 // Rewind to the loop's own slots, then rotate the return value out
1053 // of the way and hand `iterator_close` a dummy catch offset: the
1054 // loop is being abandoned, so there is nothing left to catch.
1055 self.emit(Opcode::Rot3r, &[]);
1056 self.emit(Opcode::Undefined, &[]);
1057 self.emit(Opcode::IteratorClose, &[]);
1058 } else if let Some(finally) = target.finally_label {
1059 self.emit_jump(Opcode::Gosub, finally, &[]);
1060 }
1061 }
1062 if has_value {
1063 self.emit(Opcode::Return, &[]);
1064 } else {
1065 self.emit(Opcode::ReturnUndef, &[]);
1066 }
1067 Ok(())
1068 }
1069
1070 /// Compile a statement list, stopping at the first statement that cannot
1071 /// fall through.
1072 fn stmts(&mut self, body: &[Stmt]) -> Result<(), SyntaxError> {
1073 for stmt in body {
1074 self.stmt(stmt)?;
1075 if Self::terminates(stmt) {
1076 break;
1077 }
1078 }
1079 Ok(())
1080 }
1081
1082 /// Declare every name a statement list introduces, before compiling any of
1083 /// it, so a reference that appears textually before a declaration still
1084 /// resolves.
1085 ///
1086 /// Declarations are walked in source order because that is the order the
1087 /// reference numbers its slots in: `let a; var b;` gives `a` slot 0 and `b`
1088 /// slot 1, while `var b; let a;` gives the opposite. `var` and function
1089 /// declarations hoist out to the function scope; lexical names belong to the
1090 /// block they were written in, which `block` records.
1091 fn hoist(&mut self, body: &[Stmt], block: u64) -> Result<(), SyntaxError> {
1092 let saved = self.cur().current_block;
1093 self.state().current_block = block;
1094 let result = self.hoist_list(body);
1095 // `current_block` is restored by the caller for a block statement, since
1096 // it needs it set while compiling; only clean up on the hoist path.
1097 self.state().current_block = saved;
1098 result
1099 }
1100
1101 fn hoist_list(&mut self, body: &[Stmt]) -> Result<(), SyntaxError> {
1102 for stmt in body {
1103 self.hoist_stmt(stmt)?;
1104 }
1105 Ok(())
1106 }
1107
1108 /// Whether a statement always transfers control away, making everything after
1109 /// it in the same list unreachable.
1110 ///
1111 /// The reference drops such statements in `skip_dead_code`, so `return 1;
1112 /// let x = 2;` compiles to the same bytecode as `return 1;`.
1113 fn terminates(stmt: &Stmt) -> bool {
1114 matches!(
1115 stmt.kind,
1116 StmtKind::Return(_) | StmtKind::Throw(_) | StmtKind::Break(_) | StmtKind::Continue(_)
1117 )
1118 }
1119
1120 fn hoist_stmt(&mut self, stmt: &Stmt) -> Result<(), SyntaxError> {
1121 match &stmt.kind {
1122 StmtKind::VarDecl(decl) => {
1123 for declarator in &decl.declarators {
1124 let mut names = Vec::new();
1125 declarator.target.bound_names(&mut names);
1126 for name in names {
1127 let text = name.name.clone();
1128 if decl.kind == VarDeclKind::Var {
1129 let def = VarDef::var(text.clone());
1130 self.declare_var(&text, def);
1131 } else {
1132 let def = if decl.kind == VarDeclKind::Const {
1133 VarDef::constant(text.clone())
1134 } else {
1135 VarDef::lexical(text.clone())
1136 };
1137 self.declare(&text, def);
1138 }
1139 }
1140 }
1141 }
1142 StmtKind::FuncDecl(func) => {
1143 if let Some(name) = &func.name {
1144 // A function declaration is a `var` binding that happens to
1145 // hold a function, not a lexical one.
1146 let def = VarDef::var(name.name.clone());
1147 self.declare_var(&name.name.clone(), def);
1148 }
1149 // The function object is created when the scope is entered, so it
1150 // exists before the declaration is reached.
1151 self.func_decl(func)?;
1152 }
1153 StmtKind::ClassDecl(class) => {
1154 if let Some(name) = &class.name {
1155 self.declare(&name.name.clone(), VarDef::lexical(name.name.clone()));
1156 }
1157 }
1158 StmtKind::Block(inner) => self.hoist_block(stmt.span.start.offset as u64, inner)?,
1159 StmtKind::If { cons, alt, .. } => {
1160 self.hoist_stmt(cons)?;
1161 if let Some(alt) = alt {
1162 self.hoist_stmt(alt)?;
1163 }
1164 }
1165 StmtKind::While { body, .. }
1166 | StmtKind::DoWhile { body, .. }
1167 | StmtKind::Labeled { body, .. }
1168 | StmtKind::With { body, .. } => self.hoist_stmt(body)?,
1169 StmtKind::For { init, body, .. } => {
1170 // A `for` head gets its own scope even when it declares nothing,
1171 // because `let` in the head is scoped to the loop.
1172 let key = stmt.span.start.offset as u64;
1173 let parent = self.cur().current_block;
1174 self.push_block(key, parent);
1175 if let Some(init) = init
1176 && let ForInit::VarDecl(decl) = init
1177 {
1178 self.hoist_stmt(&Stmt::new(StmtKind::VarDecl(decl.clone()), stmt.span))?;
1179 }
1180 self.hoist_stmt(body)?;
1181 self.state().current_block = parent;
1182 }
1183 StmtKind::ForIn { left, body, .. } | StmtKind::ForOf { left, body, .. } => {
1184 let key = stmt.span.start.offset as u64;
1185 let parent = self.cur().current_block;
1186 self.push_block(key, parent);
1187 if let ForHead::VarDecl(decl) = left {
1188 self.hoist_stmt(&Stmt::new(StmtKind::VarDecl(decl.clone()), stmt.span))?;
1189 }
1190 self.hoist_stmt(body)?;
1191 self.state().current_block = parent;
1192 }
1193 StmtKind::Try {
1194 block,
1195 handler,
1196 finalizer,
1197 } => {
1198 self.hoist_block(Self::try_block_key(stmt, TryPart::Block), block)?;
1199 let try_parent = self.cur().current_block;
1200 if let Some(handler) = handler {
1201 // The catch parameter belongs to the function scope, not to a
1202 // block: it is a `catch` binding rather than a `let`, so it is
1203 // never in the temporal dead zone and `emit_scope_enter` must
1204 // not mark it uninitialised. It still has to be declared before
1205 // the handler body is hoisted, so it takes the slot the
1206 // reference gives it (bindings are numbered in source order).
1207 if let Some(Pattern {
1208 kind: PatternKind::Ident(name),
1209 ..
1210 }) = &handler.param
1211 {
1212 // The parameter gets its own scope, so entering the handler
1213 // does not have to re-declare it. It is not lexical, so it
1214 // is never marked uninitialised.
1215 let key = Self::try_block_key(stmt, TryPart::Param);
1216 let parent = self.cur().current_block;
1217 self.push_block(key, parent);
1218 let def = VarDef {
1219 name: name.name.clone(),
1220 is_const: false,
1221 is_lexical: false,
1222 kind: crate::bytecode::VarKind::Catch,
1223 is_captured: false,
1224 scope_level: 0,
1225 scope_next: None,
1226 };
1227 self.declare_local(&name.name.clone(), def);
1228 // The handler body nests inside the parameter's scope, so the
1229 // body's bindings chain on to the parameter (the reference
1230 // prints `let y [next:1]`, pointing at `e`).
1231 self.state().current_block = key;
1232 }
1233 self.hoist_block(Self::try_block_key(stmt, TryPart::Catch), &handler.body)?;
1234 // Back to the block the `try` itself lives in, so the finalizer
1235 // is a sibling of the handler rather than nested in it.
1236 self.state().current_block = try_parent;
1237 }
1238 if let Some(finalizer) = finalizer {
1239 self.hoist_block(Self::try_block_key(stmt, TryPart::Finally), finalizer)?;
1240 }
1241 }
1242 StmtKind::Switch { cases, .. } => {
1243 let key = stmt.span.start.offset as u64;
1244 let parent = self.cur().current_block;
1245 self.push_block(key, parent);
1246 for case in cases {
1247 self.hoist_list(&case.body)?;
1248 }
1249 self.state().current_block = parent;
1250 }
1251 _ => {}
1252 }
1253 Ok(())
1254 }
1255
1256 /// Hoist a nested statement list, which is its own lexical scope.
1257 fn hoist_block(&mut self, key: u64, body: &[Stmt]) -> Result<(), SyntaxError> {
1258 let parent = self.cur().current_block;
1259 self.push_block(key, parent);
1260 self.hoist_list(body)?;
1261 self.state().current_block = parent;
1262 Ok(())
1263 }
1264
1265 /// A block key for one part of a `try` statement.
1266 ///
1267 /// The three parts are three separate scopes, so they cannot share the key a
1268 /// statement's own offset would give them: the try block, the handler body and
1269 /// the finalizer would then look like one scope, and their `let` bindings would
1270 /// be marked uninitialised only on entering the first of them.
1271 fn try_block_key(stmt: &Stmt, part: TryPart) -> u64 {
1272 (stmt.span.start.offset as u64) * 4 + part as u64
1273 }
1274
1275 /// Declare a `var`: it lives in the function's own scope, not the block's.
1276 fn declare_var(&mut self, name: &str, def: VarDef) {
1277 if self.cur().declares_globally(&def) {
1278 self.declare_global(name, &def);
1279 return;
1280 }
1281 let state = self.state();
1282 if state.vars.iter().any(|v| v.name == name) {
1283 return;
1284 }
1285 // A `var` belongs to the function scope, never to the enclosing block.
1286 state.var_block.push(FUNCTION_SCOPE);
1287 state.vars.push(def);
1288 }
1289
1290 /// Give the function an `arguments` binding if its body mentions one.
1291 ///
1292 /// The check runs on the *instruction* stream rather than the AST: by this point
1293 /// every reference has become an `Insn::Var`, so scanning is exact and needs no
1294 /// AST walker. Declaring lazily matters for more than tidiness — always declaring
1295 /// would renumber every later local slot and stop the bytecode matching the
1296 /// reference, which only adds the binding when the body uses it.
1297 ///
1298 /// `arguments` is a local, initialised at the top of the body by
1299 /// `special_object`; that is the reference's shape, so the disassembly agrees.
1300 fn provide_arguments(&mut self) {
1301 let current = self.stack.len() - 1;
1302 if self.stack[current].is_script || self.stack[current].is_arrow {
1303 return;
1304 }
1305 if !self.mentions("arguments") {
1306 return;
1307 }
1308 // 0 is strict `arguments`, 1 is sloppy (mapped) `arguments`. The mapping
1309 // itself is not implemented, so the two behave alike for now.
1310 let magic = if self.stack[current].strict { 0 } else { 1 };
1311 self.prepend_binding("arguments", magic);
1312 }
1313
1314 /// Whether the function body's instruction stream refers to `name`.
1315 fn mentions(&self, name: &str) -> bool {
1316 let current = self.stack.len() - 1;
1317 if self.stack[current].vars.iter().any(|v| v.name == name) {
1318 return false;
1319 }
1320 self.stack[current]
1321 .insns
1322 .iter()
1323 .any(|insn| matches!(insn, Insn::Var { name: used, .. } if used == name))
1324 }
1325
1326 /// Bind the name a named function expression uses to refer to itself.
1327 ///
1328 /// The value is `special_object 2`, the function currently running, so the binding
1329 /// is the closure itself and not a copy. It is a local of this function, which is
1330 /// what keeps `g` out of the enclosing scope.
1331 fn provide_self_name(&mut self) {
1332 let current = self.stack.len() - 1;
1333 let Some(name) = self.stack[current].self_name.clone() else {
1334 return;
1335 };
1336 if !self.mentions(&name) {
1337 return;
1338 }
1339 self.prepend_binding(&name, 2);
1340 }
1341
1342 /// Insert `special_object magic` plus the store to `name` at the top of the body.
1343 ///
1344 /// Prepending shifts every label that has been placed, so they are all moved by
1345 /// the number of instructions inserted.
1346 fn prepend_binding(&mut self, name: &str, magic: i32) {
1347 let current = self.stack.len() - 1;
1348 self.declare_var(name, VarDef::var(name));
1349 let init = [
1350 Insn::Fixed {
1351 op: Opcode::SpecialObject,
1352 operands: vec![Op::Int(magic)],
1353 },
1354 Insn::Var {
1355 action: VarAction::Put,
1356 name: name.to_string(),
1357 block: 0,
1358 },
1359 ];
1360 let inserted = init.len();
1361 for (index, instruction) in init.into_iter().enumerate() {
1362 self.stack[current].insns.insert(index, instruction);
1363 }
1364 for placed in self.stack[current].labels.iter_mut().flatten() {
1365 *placed += inserted;
1366 }
1367 // A store sits at the insertion point now, so the `put`/`get` fold must not
1368 // reach across it.
1369 self.stack[current].label_since_insn = true;
1370 }
1371
1372 /// Record a top-level script declaration as a global.
1373 ///
1374 /// A script's top-level `var`/`let`/`function` create properties of the
1375 /// global object, not slots in the script's frame, so they show up as closure
1376 /// variables instead.
1377 fn declare_global(&mut self, name: &str, def: &VarDef) {
1378 let state = self.state();
1379 if let Some(existing) = state.closure_vars.iter_mut().find(|c| c.name == name) {
1380 // The name was already referenced, from a function compiled before this
1381 // declaration was reached — `function a(){ b() } function b(){}` resolves
1382 // `b` while `b` is still unknown, and that guess has to be corrected here.
1383 // Leaving it as a plain global meant the declaration was never registered,
1384 // so the binding did not exist at run time and `a()` threw
1385 // `b is not defined`.
1386 if matches!(existing.closure_type, ClosureType::Global) {
1387 existing.closure_type = ClosureType::GlobalDecl;
1388 existing.is_const = def.is_const;
1389 existing.is_lexical = def.is_lexical;
1390 }
1391 return;
1392 }
1393 state.closure_vars.push(ClosureVar {
1394 name: name.to_string(),
1395 is_const: def.is_const,
1396 is_lexical: def.is_lexical,
1397 closure_type: ClosureType::GlobalDecl,
1398 var_idx: 0,
1399 });
1400 }
1401
1402 /// Compile a loop body with a `break`/`continue` target pushed for it.
1403 fn loop_body(
1404 &mut self,
1405 body: &Stmt,
1406 labels: &[String],
1407 continue_label: Label,
1408 break_label: Label,
1409 ) -> Result<(), SyntaxError> {
1410 self.push_jump_target(JumpTarget {
1411 names: labels.to_vec(),
1412 break_label: Some(break_label),
1413 continue_label: Some(continue_label),
1414 // A loop leaves nothing of its own on the value stack.
1415 drop_count: 0,
1416 finally_label: None,
1417 is_regular_stmt: false,
1418 has_iterator: false,
1419 });
1420 let result = self.stmt(body);
1421 self.pop_jump_target();
1422 result
1423 }
1424
1425 fn push_jump_target(&mut self, target: JumpTarget) {
1426 self.state().jump_targets.push(target);
1427 }
1428
1429 fn pop_jump_target(&mut self) {
1430 self.state().jump_targets.pop();
1431 }
1432
1433 fn control_transfer(&mut self, stmt: &Stmt) -> Result<(), SyntaxError> {
1434 let (label, is_break) = match &stmt.kind {
1435 StmtKind::Break(label) => (label.as_ref(), true),
1436 StmtKind::Continue(label) => (label.as_ref(), false),
1437 _ => unreachable!("control_transfer is only called for break and continue"),
1438 };
1439
1440 // Walk outward from the innermost construct. Everything considered before
1441 // the match is a construct control is leaving, and leaving it has a cost:
1442 // its stack slots go, and its finalizer runs.
1443 let targets = self.cur().jump_targets.clone();
1444 for target in targets.iter().rev() {
1445 let destination = match (label, is_break) {
1446 // An unlabelled `break` skips a labelled non-loop statement: `break`
1447 // may name one, but the bare form only means "leave the loop".
1448 (None, true) => target.break_label.filter(|_| !target.is_regular_stmt),
1449 (None, false) => target.continue_label,
1450 (Some(name), true) => target
1451 .break_label
1452 .filter(|_| target.names.contains(&name.name)),
1453 (Some(name), false) => target
1454 .continue_label
1455 .filter(|_| target.names.contains(&name.name)),
1456 };
1457
1458 if let Some(destination) = destination {
1459 self.emit_jump(Opcode::Goto, destination, &[]);
1460 return Ok(());
1461 }
1462
1463 // Closing the iterator consumes the three slots the loop keeps on the
1464 // stack (iterator, next method, catch offset), so those are not dropped
1465 // again below.
1466 let mut remaining = target.drop_count;
1467 if target.has_iterator {
1468 self.emit(Opcode::IteratorClose, &[]);
1469 remaining = remaining.saturating_sub(3);
1470 }
1471 for _ in 0..remaining {
1472 self.emit(Opcode::Drop, &[]);
1473 }
1474 if let Some(finally) = target.finally_label {
1475 // The finalizer runs as a subroutine and is handed a dummy return
1476 // value, which is dropped afterwards to keep the stack the depth it
1477 // had before.
1478 self.emit(Opcode::Undefined, &[]);
1479 self.emit_jump(Opcode::Gosub, finally, &[]);
1480 self.emit(Opcode::Drop, &[]);
1481 }
1482 }
1483
1484 // The parser rejects a break/continue with no target, so reaching here
1485 // means the compiler's own bookkeeping is wrong.
1486 Err(SyntaxError::new(
1487 if is_break {
1488 "break has no enclosing loop or switch"
1489 } else {
1490 "continue has no enclosing loop"
1491 },
1492 stmt.span,
1493 ))
1494 }
1495
1496 /// Compile a labelled statement.
1497 ///
1498 /// `a: b: for(…)` is a chain of labels on one loop; every name has to reach
1499 /// that loop's targets, so the chain is collected and handed to the loop. A
1500 /// label on a non-loop statement only provides a `break` target, because
1501 /// `continue` may not target it.
1502 fn labeled(&mut self, label: &Ident, body: &Stmt, stmt: &Stmt) -> Result<(), SyntaxError> {
1503 let mut names = vec![label.name.clone()];
1504 let mut inner = body;
1505 while let StmtKind::Labeled {
1506 label: next,
1507 body: deeper,
1508 } = &inner.kind
1509 {
1510 names.push(next.name.clone());
1511 inner = deeper;
1512 }
1513 if Self::is_loop(inner) {
1514 return self.stmt_labelled(inner, &names);
1515 }
1516 let end = self.new_label();
1517 self.push_jump_target(JumpTarget {
1518 names,
1519 break_label: Some(end),
1520 continue_label: None,
1521 drop_count: 0,
1522 finally_label: None,
1523 is_regular_stmt: true,
1524 has_iterator: false,
1525 });
1526 let result = self.stmt(inner);
1527 self.pop_jump_target();
1528 result?;
1529 self.place_label(end);
1530 let _ = stmt;
1531 Ok(())
1532 }
1533
1534 /// Whether a statement is a loop, i.e. a valid target for `continue`.
1535 fn is_loop(stmt: &Stmt) -> bool {
1536 matches!(
1537 stmt.kind,
1538 StmtKind::While { .. }
1539 | StmtKind::DoWhile { .. }
1540 | StmtKind::For { .. }
1541 | StmtKind::ForIn { .. }
1542 | StmtKind::ForOf { .. }
1543 )
1544 }
1545
1546 /// Compile `switch`.
1547 ///
1548 /// The discriminant is evaluated once and stays on the value stack while the
1549 /// clauses compare against copies of it, so it is dropped at the end — which is
1550 /// why `switch (x) { }` still leaves `x` behind. Fallthrough is real: a
1551 /// clause's body jumps over the *next* clause's tests straight into its body.
1552 ///
1553 /// The tests form a chain: each `case` run compares and, on a miss, hands over to
1554 /// the next run's tests. Only the last run's miss reaches the `default` body, or
1555 /// the end of the switch when there is no `default`. That failure path can point
1556 /// backwards (`default` written first), so the runs and their labels are worked
1557 /// out before any code is emitted.
1558 fn switch(
1559 &mut self,
1560 discriminant: &Expr,
1561 cases: &[SwitchCase],
1562 stmt: &Stmt,
1563 ) -> Result<(), SyntaxError> {
1564 self.reset_value();
1565 // The discriminant is evaluated outside the switch's block scope, before
1566 // any `case` clause exists.
1567 self.expr(discriminant)?;
1568
1569 let switch_key = stmt.span.start.offset as u64;
1570 let switch_parent = self.cur().current_block;
1571 self.push_block(switch_key, switch_parent);
1572 self.emit_scope_enter(switch_key);
1573
1574 let break_label = self.new_label();
1575 self.push_jump_target(JumpTarget {
1576 names: Vec::new(),
1577 break_label: Some(break_label),
1578 // `switch` is a valid `break` target but not a `continue` target.
1579 continue_label: None,
1580 // The discriminant stays on the value stack for the whole statement, so
1581 // a `break` aimed further out has to discard it.
1582 drop_count: 1,
1583 finally_label: None,
1584 is_regular_stmt: false,
1585 has_iterator: false,
1586 });
1587
1588 // Runs of tests. `case 1: case 2: body` is one run: the empty clause hands
1589 // its label to the clause after it, so both tests reach the same body.
1590 let mut runs: Vec<(usize, usize)> = Vec::new();
1591 let mut scan = 0;
1592 while scan < cases.len() {
1593 if cases[scan].test.is_some() {
1594 let mut last = scan;
1595 while last + 1 < cases.len()
1596 && cases[last].test.is_some()
1597 && cases[last].body.is_empty()
1598 && cases[last + 1].test.is_some()
1599 {
1600 last += 1;
1601 }
1602 runs.push((scan, last));
1603 scan = last + 1;
1604 } else {
1605 scan += 1;
1606 }
1607 }
1608
1609 let body_labels: Vec<Label> = cases.iter().map(|_| self.new_label()).collect();
1610 let run_labels: Vec<Label> = runs.iter().map(|_| self.new_label()).collect();
1611 let default_at = cases.iter().position(|case| case.test.is_none());
1612 // Where the last run sends control when nothing matched.
1613 let miss_target = match default_at {
1614 Some(index) => body_labels[index],
1615 None => break_label,
1616 };
1617
1618 // When `default` comes first, control has to jump over it to reach the
1619 // tests. It only needs to when some clause actually has a test; otherwise
1620 // the default body is the entry point.
1621 let mut entry = None;
1622 if default_at == Some(0) && !runs.is_empty() {
1623 self.emit_jump(Opcode::Goto, run_labels[0], &[]);
1624 entry = Some(run_labels[0]);
1625 }
1626
1627 let mut index = 0;
1628 let mut run = 0;
1629 let result = (|| -> Result<(), SyntaxError> {
1630 while index < cases.len() {
1631 if cases[index].test.is_some() {
1632 let (first, last) = runs[run];
1633 // Reaching these tests from the preceding body is a
1634 // fallthrough, which continues inside the body and skips them.
1635 if index > 0 {
1636 self.emit_jump(Opcode::Goto, body_labels[index], &[]);
1637 }
1638 if let Some(label) = entry.take() {
1639 self.place_label(label);
1640 }
1641 self.place_label(run_labels[run]);
1642
1643 for (offset, case) in cases[first..=last].iter().enumerate() {
1644 let test = case.test.as_ref().unwrap();
1645 self.emit(Opcode::Dup, &[]);
1646 self.expr(test)?;
1647 self.emit(Opcode::StrictEq, &[]);
1648 if first + offset < last {
1649 self.emit_jump(Opcode::IfTrue, body_labels[index], &[]);
1650 } else {
1651 // Hand over to the next run's tests, or give up.
1652 let next = match runs.get(run + 1) {
1653 Some(_) => run_labels[run + 1],
1654 None => miss_target,
1655 };
1656 self.emit_jump(Opcode::IfFalse, next, &[]);
1657 }
1658 }
1659
1660 self.place_label(body_labels[index]);
1661 for case in &cases[first..=last] {
1662 self.stmts(&case.body)?;
1663 }
1664 index = last + 1;
1665 run += 1;
1666 } else {
1667 // `default`: control arrives here either by falling through or
1668 // because every test missed.
1669 self.place_label(body_labels[index]);
1670 self.stmts(&cases[index].body)?;
1671 index += 1;
1672 }
1673 }
1674 Ok(())
1675 })();
1676
1677 if result.is_ok() {
1678 self.place_label(break_label);
1679 // Discard the discriminant now that no test needs it.
1680 self.emit(Opcode::Drop, &[]);
1681 }
1682
1683 self.pop_jump_target();
1684 self.emit_scope_leave(switch_key);
1685 self.state().current_block = switch_parent;
1686 result
1687 }
1688
1689 /// Compile `try`/`catch`/`finally`.
1690 ///
1691 /// The shape is an exception table built out of `catch` instructions, each of
1692 /// which records where control goes if the instructions that follow raise:
1693 ///
1694 /// ```text
1695 /// catch HANDLER <- if the guarded block throws, jump to HANDLER
1696 /// <guarded block>
1697 /// drop <- discard the catch offset
1698 /// undefined; gosub FINALLY; drop
1699 /// goto END
1700 /// HANDLER:
1701 /// <bind the catch parameter>
1702 /// catch CATCH2 <- if the handler itself throws, go to CATCH2
1703 /// <handler body>
1704 /// drop; undefined; gosub FINALLY; drop; goto END
1705 /// CATCH2:
1706 /// gosub FINALLY; throw <- run the finalizer, then let the error out
1707 /// FINALLY:
1708 /// <finalizer>
1709 /// ret <- return to the `gosub`
1710 /// END:
1711 /// ```
1712 ///
1713 /// `gosub` is a subroutine call and `ret` returns to it, which is how one copy
1714 /// of the finalizer serves the normal path, the handler path and the
1715 /// propagating-exception path.
1716 ///
1717 /// The `undefined` before each `gosub` is a dummy return value: the finalizer
1718 /// runs with `ret_value` on the stack, and the normal path has no value to
1719 /// keep, so it pushes one to keep the stack depth identical on every path.
1720 fn try_stmt(
1721 &mut self,
1722 stmt: &Stmt,
1723 block: &[Stmt],
1724 handler: &Option<CatchClause>,
1725 finalizer: Option<&[Stmt]>,
1726 ) -> Result<(), SyntaxError> {
1727 self.reset_value();
1728
1729 let catch_label = self.new_label();
1730 let catch2_label = self.new_label();
1731 let finally_label = self.new_label();
1732 let end_label = self.new_label();
1733
1734 self.emit_jump(Opcode::Catch, catch_label, &[]);
1735
1736 // The guarded block. `break` may not target it, so its entry exists purely
1737 // to unwind: a jump out has to discard the catch offset and run the
1738 // finalizer.
1739 self.push_jump_target(JumpTarget {
1740 names: Vec::new(),
1741 break_label: None,
1742 continue_label: None,
1743 drop_count: 1,
1744 finally_label: Some(finally_label),
1745 is_regular_stmt: false,
1746 has_iterator: false,
1747 });
1748
1749 let block_key = Self::try_block_key(stmt, TryPart::Block);
1750 let block_parent = self.cur().current_block;
1751 self.push_block(block_key, block_parent);
1752 self.emit_scope_enter(block_key);
1753 self.stmts(block)?;
1754 self.emit_scope_leave(block_key);
1755 self.state().current_block = block_parent;
1756 // A guarded block that ends in a `return`/`throw` never reaches the
1757 // epilogue, so the reference does not emit one.
1758 self.pop_jump_target();
1759 let block_live = !block.last().is_some_and(Self::terminates);
1760
1761 if block_live {
1762 self.emit(Opcode::Drop, &[]);
1763 self.emit(Opcode::Undefined, &[]);
1764 self.emit_jump(Opcode::Gosub, finally_label, &[]);
1765 self.emit(Opcode::Drop, &[]);
1766 self.emit_jump(Opcode::Goto, end_label, &[]);
1767 }
1768
1769 if let Some(handler) = handler {
1770 self.place_label(catch_label);
1771 // The thrown value is on top of the stack: bind it, or discard it for
1772 // `catch { }`.
1773 match &handler.param {
1774 Some(Pattern {
1775 kind: PatternKind::Ident(name),
1776 ..
1777 }) => {
1778 // The store resolves the name, so it has to run inside the
1779 // parameter's own scope; otherwise a same-named `catch` further
1780 // out could win.
1781 let param_key = Self::try_block_key(stmt, TryPart::Param);
1782 let param_parent = self.cur().current_block;
1783 self.push_block(param_key, param_parent);
1784 self.emit_var(VarAction::Put, &name.name);
1785 self.state().current_block = param_parent;
1786 }
1787 Some(other) => {
1788 return Err(SyntaxError::new(
1789 "destructuring catch parameters are not supported by the compiler yet",
1790 other.span,
1791 ));
1792 }
1793 None => self.emit(Opcode::Drop, &[]),
1794 }
1795 self.emit_jump(Opcode::Catch, catch2_label, &[]);
1796
1797 self.push_jump_target(JumpTarget {
1798 names: Vec::new(),
1799 break_label: None,
1800 continue_label: None,
1801 drop_count: 1,
1802 finally_label: Some(finally_label),
1803 is_regular_stmt: false,
1804 has_iterator: false,
1805 });
1806 let catch_key = Self::try_block_key(stmt, TryPart::Catch);
1807 let catch_parent = self.cur().current_block;
1808 self.push_block(catch_key, catch_parent);
1809 self.emit_scope_enter(catch_key);
1810 self.stmts(&handler.body)?;
1811 self.emit_scope_leave(catch_key);
1812 self.state().current_block = catch_parent;
1813 self.pop_jump_target();
1814 let handler_live = !handler.body.last().is_some_and(Self::terminates);
1815
1816 if handler_live {
1817 self.emit(Opcode::Drop, &[]);
1818 self.emit(Opcode::Undefined, &[]);
1819 self.emit_jump(Opcode::Gosub, finally_label, &[]);
1820 self.emit(Opcode::Drop, &[]);
1821 self.emit_jump(Opcode::Goto, end_label, &[]);
1822 }
1823
1824 // An error raised inside the handler still has to run the finalizer.
1825 self.place_label(catch2_label);
1826 self.emit_jump(Opcode::Gosub, finally_label, &[]);
1827 self.emit(Opcode::Throw, &[]);
1828 } else {
1829 // `try`/`finally` with no handler: the finalizer runs, then the error
1830 // keeps propagating.
1831 self.place_label(catch_label);
1832 self.emit_jump(Opcode::Gosub, finally_label, &[]);
1833 self.emit(Opcode::Throw, &[]);
1834 }
1835
1836 self.place_label(finally_label);
1837 // Inside the finalizer, leaving has a different cost: the return value and
1838 // the `gosub` return address are both on the stack, and neither finalizer nor
1839 // any outer one may run before the block has finished.
1840 self.push_jump_target(JumpTarget {
1841 names: Vec::new(),
1842 break_label: None,
1843 continue_label: None,
1844 drop_count: 2,
1845 finally_label: None,
1846 is_regular_stmt: false,
1847 has_iterator: false,
1848 });
1849 if let Some(finalizer) = finalizer {
1850 let finally_key = Self::try_block_key(stmt, TryPart::Finally);
1851 let finally_parent = self.cur().current_block;
1852 self.push_block(finally_key, finally_parent);
1853 self.emit_scope_enter(finally_key);
1854 self.stmts(finalizer)?;
1855 self.emit_scope_leave(finally_key);
1856 self.state().current_block = finally_parent;
1857 }
1858 self.pop_jump_target();
1859 self.emit(Opcode::Ret, &[]);
1860 self.place_label(end_label);
1861 Ok(())
1862 }
1863
1864 /// Compile `for`/`in` and `for`/`of`.
1865 ///
1866 /// Both keep an enumeration record on the value stack for the whole loop, which
1867 /// is what makes leaving early expensive: the record has to be dropped, or the
1868 /// iterator closed. The layout is
1869 ///
1870 /// ```text
1871 /// <iterated expression>
1872 /// for_in_start | for_of_start <- pushes the record
1873 /// goto TEST
1874 /// NEXT:
1875 /// <bind the loop variable>
1876 /// <body>
1877 /// TEST:
1878 /// for_in_next | for_of_next 0
1879 /// if_false NEXT <- not finished: next iteration
1880 /// drop <- finished: discard the leftover value
1881 /// BREAK:
1882 /// drop | iterator_close <- the one cleanup `break` also uses
1883 /// ```
1884 ///
1885 /// `BREAK` sits *on* the cleanup rather than after it, so an early exit and the
1886 /// normal exit share one copy — which is why `break` inside the loop emits nothing
1887 /// of its own, and only a jump that passes *through* the loop pays for its record.
1888 fn for_in_of(
1889 &mut self,
1890 stmt: &Stmt,
1891 left: &ForHead,
1892 right: &Expr,
1893 body: &Stmt,
1894 kind: ForLoopKind,
1895 ) -> Result<(), SyntaxError> {
1896 self.reset_value();
1897
1898 let loop_key = stmt.span.start.offset as u64;
1899 let loop_parent = self.cur().current_block;
1900 self.push_block(loop_key, loop_parent);
1901 self.emit_scope_enter(loop_key);
1902
1903 // The iterated expression is evaluated inside the loop's scope, after the
1904 // bindings exist in the temporal dead zone.
1905 self.expr(right)?;
1906
1907 let next = self.new_label();
1908 let test = self.new_label();
1909 let break_target = self.new_label();
1910
1911 let has_iterator = kind == ForLoopKind::Of;
1912 match kind {
1913 ForLoopKind::In => self.emit(Opcode::ForInStart, &[]),
1914 ForLoopKind::Of => self.emit(Opcode::ForOfStart, &[]),
1915 }
1916 self.emit_jump(Opcode::Goto, test, &[]);
1917
1918 self.push_jump_target(JumpTarget {
1919 names: Vec::new(),
1920 break_label: Some(break_target),
1921 continue_label: Some(test),
1922 // Passing through the loop has to dispose of its record. A `for`/`of`
1923 // record is three slots, and closing the iterator consumes all of them.
1924 drop_count: if has_iterator { 3 } else { 1 },
1925 finally_label: None,
1926 is_regular_stmt: false,
1927 has_iterator,
1928 });
1929
1930 self.place_label(next);
1931 self.bind_loop_variable(left)?;
1932 // The reference marks the body with its own label here. Nothing jumps to it
1933 // once the loop is laid out, but it is not decoration: a label between the
1934 // store and the body is why `put_loc v; get_loc v` does *not* fold into
1935 // `set_loc v` when the body starts by reading the loop variable.
1936 let body_label = self.new_label();
1937 self.place_label(body_label);
1938 self.stmt(body)?;
1939
1940 self.place_label(test);
1941 match kind {
1942 ForLoopKind::In => self.emit(Opcode::ForInNext, &[]),
1943 ForLoopKind::Of => self.emit(Opcode::ForOfNext, &[Op::Int(0)]),
1944 }
1945 self.emit_jump(Opcode::IfFalse, next, &[]);
1946 // The loop is finished; `for_xx_next` left an `undefined` behind.
1947 self.emit(Opcode::Drop, &[]);
1948
1949 self.pop_jump_target();
1950 self.place_label(break_target);
1951 if has_iterator {
1952 self.emit(Opcode::IteratorClose, &[]);
1953 } else {
1954 self.emit(Opcode::Drop, &[]);
1955 }
1956
1957 self.emit_scope_leave(loop_key);
1958 self.state().current_block = loop_parent;
1959 Ok(())
1960 }
1961
1962 /// Store the value `for_xx_next` left on the stack into the loop variable.
1963 fn bind_loop_variable(&mut self, left: &ForHead) -> Result<(), SyntaxError> {
1964 // A declaration *initialises* the binding, which is what takes a `let` out of
1965 // the temporal dead zone, so the store is the unchecked form. Assigning to a
1966 // binding declared elsewhere is an ordinary write and keeps its check.
1967 let (pattern, action) = match left {
1968 ForHead::VarDecl(decl) => (&decl.declarators[0].target, VarAction::PutInit),
1969 ForHead::Assign(pattern) => (pattern.as_ref(), VarAction::Put),
1970 };
1971 match &pattern.kind {
1972 PatternKind::Ident(name) => {
1973 self.emit_var(action, &name.name);
1974 Ok(())
1975 }
1976 _ => Err(SyntaxError::new(
1977 "destructuring loop targets are not supported by the compiler yet",
1978 pattern.span,
1979 )),
1980 }
1981 }
1982
1983 fn var_decl(&mut self, decl: &VarDecl) -> Result<(), SyntaxError> {
1984 for declarator in &decl.declarators {
1985 let Some(init) = &declarator.init else {
1986 // `var x;` stays `undefined`. A lexical binding is different: it
1987 // has to be *initialised* to leave the temporal dead zone, so the
1988 // compiler supplies an explicit `undefined`.
1989 if decl.kind.is_lexical()
1990 && let PatternKind::Ident(name) = &declarator.target.kind
1991 {
1992 self.emit(Opcode::Undefined, &[]);
1993 self.emit_var(VarAction::PutInit, &name.name);
1994 }
1995 continue;
1996 };
1997 match &declarator.target.kind {
1998 PatternKind::Ident(name) => {
1999 self.expr(init)?;
2000 self.set_name_if_anonymous(init, &name.name);
2001 // A declaration statement produces no value, so nothing is
2002 // duplicated onto the stack.
2003 match decl.kind {
2004 VarDeclKind::Var => self.emit_var(VarAction::Put, &name.name),
2005 _ => self.emit_var(VarAction::PutInit, &name.name),
2006 }
2007 }
2008 _ => {
2009 return Err(SyntaxError::new(
2010 "destructuring declarations are not supported by the compiler yet",
2011 declarator.span,
2012 ));
2013 }
2014 }
2015 }
2016 Ok(())
2017 }
2018
2019 /// Compile a function declaration and queue it for instantiation at scope
2020 /// entry.
2021 ///
2022 /// A declaration is visible before the statement that declares it, so the
2023 /// code that creates the function object belongs at the top of the enclosing
2024 /// scope, not at the declaration.
2025 fn func_decl(&mut self, func: &ast::Function) -> Result<(), SyntaxError> {
2026 let name = func.name.as_ref().expect("a declaration has a name");
2027 let function = self.compile_function(func)?;
2028 let pool_index = self.push_constant(Constant::Function(Box::new(function)));
2029 let target = self.hoist_target(&name.name);
2030 let block = self.cur().current_block;
2031 self.state().hoisted.push((block, target, pool_index));
2032 Ok(())
2033 }
2034
2035 /// Where a name lives, for a hoisted declaration.
2036 fn hoist_target(&self, name: &str) -> HoistTarget {
2037 let state = self.cur();
2038 if let Some(index) = state.args.iter().position(|a| a.name == name) {
2039 return HoistTarget::Arg(index as u32);
2040 }
2041 if let Some(index) = state.vars.iter().position(|v| v.name == name) {
2042 return HoistTarget::Loc(index as u32);
2043 }
2044 // A global function declaration is not a slot at all.
2045 HoistTarget::Global(name.to_string())
2046 }
2047
2048 // -- expressions -------------------------------------------------------
2049
2050 /// Compile one expression, recording where its instructions sit.
2051 ///
2052 /// The position is the node's operator when it has one and its first token
2053 /// otherwise, and it is restored on the way out so a parent's own instructions —
2054 /// which are emitted *after* its children — are blamed on the parent. Without the
2055 /// restore the `add` in `a + b` would inherit `b`'s position instead of the `+`.
2056 fn expr(&mut self, expr: &Expr) -> Result<(), SyntaxError> {
2057 let saved = self.cur().cur_pos;
2058 self.state().cur_pos = Some(expr.op_pos.unwrap_or(expr.span.start));
2059 let result = self.expr_inner(expr);
2060 self.state().cur_pos = saved;
2061 result
2062 }
2063
2064 fn expr_inner(&mut self, expr: &Expr) -> Result<(), SyntaxError> {
2065 match &expr.kind {
2066 ExprKind::Number(value) => self.push_number(*value),
2067 ExprKind::Bool(true) => self.emit(Opcode::PushTrue, &[]),
2068 ExprKind::Bool(false) => self.emit(Opcode::PushFalse, &[]),
2069 ExprKind::Null => self.emit(Opcode::Null, &[]),
2070 ExprKind::String(text) => self.push_string(text),
2071 ExprKind::Ident(name) => self.emit_var(VarAction::Get, &name.name),
2072 ExprKind::This => self.push_this(),
2073 ExprKind::Paren(inner) => self.expr(inner)?,
2074 ExprKind::Binary { op, left, right } => {
2075 self.expr(left)?;
2076 self.expr(right)?;
2077 self.emit(binary_opcode(*op), &[]);
2078 }
2079 ExprKind::Logical { op, left, right } => self.logical(*op, left, right)?,
2080 ExprKind::Unary {
2081 op: UnaryOp::Minus,
2082 argument,
2083 } if matches!(argument.unparen().kind, ExprKind::Number(_)) => {
2084 let ExprKind::Number(value) = argument.unparen().kind else {
2085 unreachable!("matched above")
2086 };
2087 // The reference folds a negative literal only when the negation is
2088 // exact in the integer range: `-1` becomes `push_minus1` and
2089 // `-1.5e3` becomes `push_i16 -1500`, but `-0` and `-2.5` keep a
2090 // runtime `neg`. Folding `-0` would lose the sign — `1/-0` is
2091 // `-Infinity`, not `Infinity` — and folding a fraction would change
2092 // which instruction the reference emits.
2093 let negated = -value;
2094 // `-2147483648` is deliberately excluded: its magnitude is one past
2095 // `i32::MAX`, so the reference sends it through the constant pool and
2096 // negates at run time instead.
2097 if value > 0.0
2098 && negated == negated.trunc()
2099 && negated >= -(i32::MAX as f64)
2100 && negated < 0.0
2101 {
2102 self.push_number(negated);
2103 } else {
2104 self.push_number(value);
2105 self.emit(Opcode::Neg, &[]);
2106 }
2107 }
2108 ExprKind::Unary { op, argument } => self.unary(*op, argument)?,
2109 ExprKind::Conditional { test, cons, alt } => {
2110 let else_label = self.new_label();
2111 let end_label = self.new_label();
2112 self.expr(test)?;
2113 self.emit_jump(Opcode::IfFalse, else_label, &[]);
2114 self.expr(cons)?;
2115 self.emit_jump(Opcode::Goto, end_label, &[]);
2116 self.place_label(else_label);
2117 self.expr(alt)?;
2118 self.place_label(end_label);
2119 }
2120 ExprKind::Assign { op, target, value } => self.assign(*op, target, value)?,
2121 ExprKind::Update {
2122 op,
2123 argument,
2124 prefix,
2125 } => self.update(*op, argument, *prefix)?,
2126 ExprKind::Sequence(items) => {
2127 for (index, item) in items.iter().enumerate() {
2128 self.expr(item)?;
2129 if index + 1 != items.len() {
2130 self.emit(Opcode::Drop, &[]);
2131 }
2132 }
2133 }
2134 ExprKind::Call { .. } => self.chain_link_top(expr)?,
2135 ExprKind::Member { .. } => self.chain_link_top(expr)?,
2136 ExprKind::OptionalChain(inner) => self.optional_chain(inner)?,
2137 ExprKind::Array { elements } => self.array_literal(elements, expr.span)?,
2138 ExprKind::Object(properties) => self.object_literal(properties, expr.span)?,
2139 ExprKind::Template(template) => self.template_literal(template)?,
2140 ExprKind::New { callee, arguments } => {
2141 // `new C(args)` compiles to `C; dup; args…; call_constructor n`.
2142 // The `dup` is not redundant: `call_constructor` takes the
2143 // constructor twice, once as the target and once as `new.target`,
2144 // which is what makes `new.target === C` inside the body.
2145 self.expr(callee)?;
2146 self.emit(Opcode::Dup, &[]);
2147 let args = arguments.as_deref().unwrap_or(&[]);
2148 for argument in args {
2149 self.expr(argument)?;
2150 }
2151 self.emit(Opcode::CallConstructor, &[Op::Int(args.len() as i32)]);
2152 }
2153 ExprKind::Arrow(func) => {
2154 let function = self.compile_function(func)?;
2155 let index = self.push_constant(Constant::Function(Box::new(function)));
2156 self.emit(Opcode::Fclosure, &[Op::Const(index)]);
2157 }
2158 ExprKind::Function(func) => {
2159 let function = self.compile_function_with_name(func, true)?;
2160 let index = self.push_constant(Constant::Function(Box::new(function)));
2161 self.emit(Opcode::Fclosure, &[Op::Const(index)]);
2162 }
2163 _ => {
2164 return Err(SyntaxError::new(
2165 "this expression form is not supported by the compiler yet",
2166 expr.span,
2167 ));
2168 }
2169 }
2170 Ok(())
2171 }
2172
2173 /// Compile `a${x}b`.
2174 ///
2175 /// A template is a `+` chain built left to right: the leading chunk (or an empty
2176 /// string when the template starts with a substitution), then for each
2177 /// substitution its value, `to_propkey` and `add`, then the following chunk when
2178 /// it is not empty. `to_propkey` is what makes a number or object substitute the
2179 /// way `ToString` would while leaving the result a string for `add` to
2180 /// concatenate.
2181 ///
2182 /// The chunk is an atom rather than a constant-pool string, because a non-empty
2183 /// chunk always lands where a value is pushed and `push_atom_value` is the
2184 /// instruction the reference uses for it; the empty first chunk has its own
2185 /// zero-byte form.
2186 fn template_literal(&mut self, template: &TemplateLiteral) -> Result<(), SyntaxError> {
2187 let first = template.quasis.first();
2188 match first.and_then(|quasi| quasi.cooked.clone()) {
2189 Some(text) if !text.is_empty() => {
2190 self.emit(Opcode::PushAtomValue, &[Op::Atom(Atom::from_text(&text))]);
2191 }
2192 // Either the template begins with a substitution, or the chunk is
2193 // empty — in both cases the chain needs a string to start from.
2194 _ => self.emit(Opcode::PushEmptyString, &[]),
2195 }
2196 for (index, expression) in template.expressions.iter().enumerate() {
2197 self.expr(expression)?;
2198 self.emit(Opcode::ToPropkey, &[]);
2199 self.emit(Opcode::Add, &[]);
2200 if let Some(text) = template
2201 .quasis
2202 .get(index + 1)
2203 .and_then(|quasi| quasi.cooked.clone())
2204 && !text.is_empty()
2205 {
2206 self.emit(Opcode::PushAtomValue, &[Op::Atom(Atom::from_text(&text))]);
2207 self.emit(Opcode::Add, &[]);
2208 }
2209 }
2210 Ok(())
2211 }
2212
2213 /// Compile an object literal.
2214 ///
2215 /// The object is built in place: `object` pushes it, and each property leaves it
2216 /// on the stack with one field more, so no temporary is needed and later
2217 /// properties can overwrite earlier ones.
2218 ///
2219 /// The instruction depends on *how* the property was written, not on what kind
2220 /// of value it holds:
2221 ///
2222 /// | source | instruction |
2223 /// |---|---|
2224 /// | `{ a: v }` | `define_field a` |
2225 /// | `{ __proto__: v }` | `set_proto` |
2226 /// | `{ [k]: v }` | `to_propkey` … `define_array_el` + `drop` |
2227 /// | `{ m() {} }` | `define_method m,4` |
2228 /// | `{ get m() {} }` / `{ set m(v) {} }` | `define_method m,5` / `,6` |
2229 /// | `{ [k]() {} }` | `define_method_computed 4` |
2230 /// | `{ ...v }` | `null` … `copy_data_properties 6` + two `drop`s |
2231 ///
2232 /// A computed *method* skips `to_propkey`: `define_method_computed` converts the
2233 /// key itself, which is why the trailing `drop` is absent there too.
2234 fn object_literal(
2235 &mut self,
2236 properties: &[ObjectProperty],
2237 span: Span,
2238 ) -> Result<(), SyntaxError> {
2239 self.emit(Opcode::Object, &[]);
2240 for property in properties {
2241 match property {
2242 ObjectProperty::Spread(value) => {
2243 // `copy_data_properties` takes the target, the source and an
2244 // exclusion list; a literal `null` means "exclude nothing".
2245 // Flag bit 1 copies symbols, bits 2/5 pick the source and the
2246 // exclusion list by stack offset.
2247 self.expr(spread_argument(value))?;
2248 self.emit(Opcode::Null, &[]);
2249 self.emit(Opcode::CopyDataProperties, &[Op::Int(COPY_ALL_PROPERTIES)]);
2250 self.emit(Opcode::Drop, &[]);
2251 self.emit(Opcode::Drop, &[]);
2252 }
2253 ObjectProperty::Property {
2254 key,
2255 value,
2256 kind,
2257 shorthand,
2258 span: property_span,
2259 } => match key {
2260 PropName::Computed(key_expr) => {
2261 self.expr(key_expr)?;
2262 match kind {
2263 PropertyKind::Value => {
2264 self.emit(Opcode::ToPropkey, &[]);
2265 self.expr(value)?;
2266 self.set_name_if_anonymous_computed(value);
2267 self.emit(Opcode::DefineArrayEl, &[]);
2268 // `define_array_el` leaves the object and the key;
2269 // the key is no longer needed.
2270 self.emit(Opcode::Drop, &[]);
2271 }
2272 PropertyKind::Method | PropertyKind::Get | PropertyKind::Set => {
2273 self.emit_method_function(value)?;
2274 self.emit(
2275 Opcode::DefineMethodComputed,
2276 &[Op::Int(define_method_flags(*kind))],
2277 );
2278 }
2279 }
2280 }
2281 PropName::Literal(key) => {
2282 let name = self.property_key_text(key, *property_span)?;
2283 match kind {
2284 PropertyKind::Method | PropertyKind::Get | PropertyKind::Set => {
2285 self.emit_method_function(value)?;
2286 self.emit(
2287 Opcode::DefineMethod,
2288 &[
2289 Op::Atom(Atom::from_text(&name)),
2290 Op::Int(define_method_flags(*kind)),
2291 ],
2292 );
2293 }
2294 PropertyKind::Value => {
2295 self.expr(value)?;
2296 // `{__proto__: x}` sets the prototype instead of
2297 // creating a property; the shorthand `{__proto__}`
2298 // is an ordinary property and does not.
2299 if name == "__proto__" && !shorthand {
2300 self.emit(Opcode::SetProto, &[]);
2301 } else {
2302 self.set_name_if_anonymous(value, &name);
2303 self.emit(
2304 Opcode::DefineField,
2305 &[Op::Atom(Atom::from_text(&name))],
2306 );
2307 }
2308 }
2309 }
2310 }
2311 PropName::Private(_) => {
2312 return Err(SyntaxError::new(
2313 "private names are not valid in object literals",
2314 *property_span,
2315 ));
2316 }
2317 },
2318 }
2319 }
2320 let _ = span;
2321 Ok(())
2322 }
2323
2324 /// Emit the function a method/accessor property defines.
2325 fn emit_method_function(&mut self, value: &Expr) -> Result<(), SyntaxError> {
2326 self.expr(value)
2327 }
2328
2329 /// The name a literal property key contributes.
2330 ///
2331 /// String keys are used as written. A numeric key is converted the way
2332 /// `ToString` would convert it, because the atom is made from that spelling:
2333 /// `{ 1e2: x }` and `{ 0x10: x }` both become `define_field 100` / `16`.
2334 fn property_key_text(&self, key: &PropKey, span: Span) -> Result<String, SyntaxError> {
2335 match key {
2336 PropKey::Str(text) => Ok(text.clone()),
2337 PropKey::Num(value) => numeric_key_text(*value, span),
2338 }
2339 }
2340
2341 /// Compile an optional chain.
2342 ///
2343 /// `?.` short-circuits the *whole remaining spine*, not just its own link:
2344 /// `a?.b.c` yields `undefined` when `a` is null, it does not read `.c` of
2345 /// `undefined`. So the chain is compiled with one end label and every guard
2346 /// jumps to it. The parser hands us the extent of that spine as an
2347 /// [`ExprKind::OptionalChain`] wrapper around the outermost link, which is
2348 /// exactly the scope the label has to cover.
2349 fn optional_chain(&mut self, inner: &Expr) -> Result<(), SyntaxError> {
2350 let end = self.new_label();
2351 self.chain_link(inner, end)?;
2352 self.place_label(end);
2353 Ok(())
2354 }
2355
2356 /// A member access or call reached from outside any optional chain.
2357 ///
2358 /// Such a link cannot contain a `?.` — if it did, the parser would have wrapped
2359 /// it in [`ExprKind::OptionalChain`] — so there is no guard and no label; one is
2360 /// still created because [`Self::chain_link`] takes it, and placing it at the
2361 /// end is a no-op that keeps a single code path.
2362 fn chain_link_top(&mut self, expr: &Expr) -> Result<(), SyntaxError> {
2363 let end = self.new_label();
2364 self.chain_link(expr, end)?;
2365 self.place_label(end);
2366 Ok(())
2367 }
2368
2369 /// One link of a chain, where `end` is the label a `?.` guard jumps to.
2370 fn chain_link(&mut self, expr: &Expr, end: Label) -> Result<(), SyntaxError> {
2371 match &expr.kind {
2372 ExprKind::Member {
2373 object,
2374 property,
2375 optional,
2376 } => {
2377 self.chain_link(object, end)?;
2378 if *optional {
2379 self.optional_guard(end);
2380 }
2381 match property {
2382 // `.length` has its own opcode. The reference emits it for every
2383 // object, not just arrays, so a name-based rule is right and
2384 // cheaper than the generic field read.
2385 MemberProp::Ident(name) if name.name == "length" => {
2386 self.emit(Opcode::GetLength, &[]);
2387 }
2388 MemberProp::Ident(name) => {
2389 self.emit(Opcode::GetField, &[Op::Atom(Atom::from_text(&name.name))]);
2390 }
2391 MemberProp::Computed(index) => {
2392 self.expr(index)?;
2393 self.emit(Opcode::GetArrayEl, &[]);
2394 }
2395 MemberProp::Private(_) => {
2396 return Err(SyntaxError::new(
2397 "private fields are not supported by the compiler yet",
2398 expr.span,
2399 ));
2400 }
2401 }
2402 Ok(())
2403 }
2404 ExprKind::Call {
2405 callee,
2406 arguments,
2407 optional,
2408 } => {
2409 // `o.m(args)` has to pass `o` as `this`, which a plain `call`
2410 // cannot: it reads the function and then calls it with no
2411 // receiver at all. The reference's answer is to keep the object
2412 // under the function value — `get_field2` reads a field and leaves
2413 // its base in place — and to use `call_method`, which takes the
2414 // receiver from the stack. Missing this does not just cost an
2415 // instruction, it loses the `this` binding.
2416 if let ExprKind::Member {
2417 object,
2418 property,
2419 optional: member_optional,
2420 } = &callee.unparen().kind
2421 {
2422 self.chain_link(object, end)?;
2423 if *member_optional {
2424 self.optional_guard(end);
2425 }
2426 match property {
2427 MemberProp::Ident(name) => {
2428 self.emit(Opcode::GetField2, &[Op::Atom(Atom::from_text(&name.name))])
2429 }
2430 MemberProp::Computed(index) => {
2431 self.expr(index)?;
2432 // The key is not needed after the read, so this is the
2433 // two-output form: object, value.
2434 self.emit(Opcode::GetArrayEl2, &[]);
2435 }
2436 MemberProp::Private(_) => {
2437 return Err(SyntaxError::new(
2438 "private fields are not supported by the compiler yet",
2439 expr.span,
2440 ));
2441 }
2442 }
2443 for argument in arguments {
2444 self.expr(argument)?;
2445 }
2446 self.emit(Opcode::CallMethod, &[Op::Int(arguments.len() as i32)]);
2447 return Ok(());
2448 }
2449 self.chain_link(callee, end)?;
2450 if *optional {
2451 self.optional_guard(end);
2452 }
2453 for argument in arguments {
2454 self.expr(argument)?;
2455 }
2456 self.emit(Opcode::Call, &[Op::Int(arguments.len() as i32)]);
2457 Ok(())
2458 }
2459 _ => self.expr(expr),
2460 }
2461 }
2462
2463 /// Compile `expr` as a tail call when it is one, reporting whether it was.
2464 ///
2465 /// `tail_call` reuses the current frame instead of pushing a new one, so a
2466 /// tail-recursive function runs in constant stack space. It also has to be the
2467 /// *last* thing the function does, which is why only a `return` reaches here.
2468 fn expr_if_tail_call(&mut self, expr: &Expr) -> Result<bool, SyntaxError> {
2469 let ExprKind::Call {
2470 callee,
2471 arguments,
2472 optional: false,
2473 } = &expr.unparen().kind
2474 else {
2475 return Ok(false);
2476 };
2477 let end = self.new_label();
2478 if let ExprKind::Member {
2479 object,
2480 property,
2481 optional: false,
2482 } = &callee.unparen().kind
2483 {
2484 self.chain_link(object, end)?;
2485 match property {
2486 MemberProp::Ident(name) => {
2487 self.emit(Opcode::GetField2, &[Op::Atom(Atom::from_text(&name.name))])
2488 }
2489 MemberProp::Computed(index) => {
2490 self.expr(index)?;
2491 self.emit(Opcode::GetArrayEl2, &[]);
2492 }
2493 MemberProp::Private(_) => return Ok(false),
2494 }
2495 for argument in arguments {
2496 self.expr(argument)?;
2497 }
2498 self.emit(Opcode::TailCallMethod, &[Op::Int(arguments.len() as i32)]);
2499 self.place_label(end);
2500 return Ok(true);
2501 }
2502 self.chain_link(callee, end)?;
2503 for argument in arguments {
2504 self.expr(argument)?;
2505 }
2506 self.emit(Opcode::TailCall, &[Op::Int(arguments.len() as i32)]);
2507 self.place_label(end);
2508 Ok(true)
2509 }
2510
2511 /// The `?.` guard: keep the value if it is neither null nor undefined,
2512 /// otherwise replace it with `undefined` and leave the whole chain.
2513 fn optional_guard(&mut self, end: Label) {
2514 let cont = self.new_label();
2515 self.emit(Opcode::Dup, &[]);
2516 self.emit(Opcode::IsUndefinedOrNull, &[]);
2517 self.emit_jump(Opcode::IfFalse, cont, &[]);
2518 self.emit(Opcode::Drop, &[]);
2519 self.emit(Opcode::Undefined, &[]);
2520 self.emit_jump(Opcode::Goto, end, &[]);
2521 self.place_label(cont);
2522 }
2523
2524 fn push_number(&mut self, value: f64) {
2525 // `push_N` / `push_i8` / `push_i32` cover small integers; everything else
2526 // goes into the constant pool.
2527 if value == value.trunc() && value.abs() <= i32::MAX as f64 {
2528 let int = value as i32;
2529 if (-1..=7).contains(&int) {
2530 self.emit(Opcode::PushI32, &[Op::Int(int)]);
2531 return;
2532 }
2533 if (-128..=127).contains(&int) {
2534 self.emit(Opcode::PushI8, &[Op::Int(int)]);
2535 return;
2536 }
2537 if (-32768..=32767).contains(&int) {
2538 self.emit(Opcode::PushI16, &[Op::Int(int)]);
2539 return;
2540 }
2541 self.emit(Opcode::PushI32, &[Op::Int(int)]);
2542 return;
2543 }
2544 let index = self.push_constant(Constant::Number(value));
2545 self.emit(Opcode::PushConst, &[Op::Const(index)]);
2546 }
2547
2548 fn push_string(&mut self, text: &str) {
2549 if text.is_empty() {
2550 self.emit(Opcode::PushEmptyString, &[]);
2551 return;
2552 }
2553 self.emit(Opcode::PushAtomValue, &[Op::Atom(Atom::from_text(text))]);
2554 }
2555
2556 /// Name an anonymous function from the binding it is assigned to.
2557 ///
2558 /// `var f = function(){}` produces a function whose `name` is `f`, which the
2559 /// runtime cannot know without being told: the function object is created
2560 /// before the store. `set_name` carries the name across.
2561 fn set_name_if_anonymous(&mut self, value: &Expr, name: &str) {
2562 if value.is_anonymous_function_definition() {
2563 self.emit(Opcode::SetName, &[Op::Atom(Atom::from_text(name))]);
2564 }
2565 }
2566
2567 /// The same, for a computed key: the name comes from the value on the stack
2568 /// rather than from an atom, so a different instruction carries it.
2569 fn set_name_if_anonymous_computed(&mut self, value: &Expr) {
2570 if value.is_anonymous_function_definition() {
2571 self.emit(Opcode::SetNameComputed, &[]);
2572 }
2573 }
2574
2575 fn push_this(&mut self) {
2576 self.emit(Opcode::PushThis, &[]);
2577 }
2578
2579 fn push_constant(&mut self, constant: Constant) -> u32 {
2580 let state = self.state();
2581 let index = state.cpool.len() as u32;
2582 state.cpool.push(constant);
2583 index
2584 }
2585
2586 /// Compile `a && b`, `a || b`, `a ?? b`.
2587 ///
2588 /// A run of the *same* operator shares one end label, so `a || b || c` tests
2589 /// `a` once and jumps past everything when it is truthy, instead of falling
2590 /// into `b`'s test. The parser builds such a run left-associated —
2591 /// `((a || b) || c)` — so the operands are collected off the left spine.
2592 ///
2593 /// A *different* operator starts its own chain: `(a || b) && c` keeps the inner
2594 /// `||`'s label, because the inner chain really does end before `&&` begins.
2595 fn logical(&mut self, op: LogicalOp, left: &Expr, right: &Expr) -> Result<(), SyntaxError> {
2596 let mut operands = Vec::new();
2597 collect_same_operator(op, left, &mut operands);
2598 operands.push(right);
2599
2600 let end = self.new_label();
2601 // Every operand but the last decides whether the chain stops here.
2602 let last = operands.pop().expect("the right operand is always present");
2603 for operand in operands {
2604 self.expr(operand)?;
2605 self.emit(Opcode::Dup, &[]);
2606 match op {
2607 LogicalOp::And => self.emit_jump(Opcode::IfFalse, end, &[]),
2608 LogicalOp::Or => self.emit_jump(Opcode::IfTrue, end, &[]),
2609 // `??` cannot reuse the truthiness jumps: `0 ?? b` is `0` while
2610 // `0 || b` is `b`. The dedicated test keeps the value unless it is
2611 // null-ish, so the jump is taken on `false`.
2612 LogicalOp::Coalesce => {
2613 self.emit(Opcode::IsUndefinedOrNull, &[]);
2614 self.emit_jump(Opcode::IfFalse, end, &[]);
2615 }
2616 }
2617 self.emit(Opcode::Drop, &[]);
2618 }
2619 self.expr(last)?;
2620 self.place_label(end);
2621 Ok(())
2622 }
2623
2624 fn unary(&mut self, op: UnaryOp, argument: &Expr) -> Result<(), SyntaxError> {
2625 match op {
2626 UnaryOp::Typeof => {
2627 // `typeof x` must not throw on an undeclared name.
2628 if let ExprKind::Ident(name) = &argument.kind {
2629 self.emit_var(VarAction::GetUndef, &name.name);
2630 } else {
2631 self.expr(argument)?;
2632 }
2633 self.emit(Opcode::Typeof, &[]);
2634 }
2635 UnaryOp::Delete => {
2636 // `delete obj.prop` really deletes, and answers whether it could.
2637 // Deleting a *binding* is always `false`: a local, an argument and a
2638 // declared global are all non-configurable, which the reference encodes
2639 // as a constant `push_false` rather than a runtime check. Only a
2640 // property access has anything to do at run time.
2641 match &argument.kind {
2642 ExprKind::Member {
2643 object, property, ..
2644 } => {
2645 self.expr(object)?;
2646 match property {
2647 MemberProp::Ident(name) => {
2648 self.emit(
2649 Opcode::PushAtomValue,
2650 &[Op::Atom(Atom::from_text(&name.name))],
2651 );
2652 }
2653 MemberProp::Computed(index) => self.expr(index)?,
2654 MemberProp::Private(_) => {
2655 return Err(SyntaxError::new(
2656 "deleting a private field is not allowed",
2657 argument.span,
2658 ));
2659 }
2660 }
2661 self.emit(Opcode::Delete, &[]);
2662 }
2663 ExprKind::Ident(name) => {
2664 // `delete name`: a declared global, a local and an argument all
2665 // answer `false`, but an *implicit* global (`x = 1` with no
2666 // declaration) is a configurable property of the global object
2667 // and really goes away. Which of those a name is only the
2668 // resolver knows, so the decision waits for it.
2669 let pos = self.cur().cur_pos;
2670 self.state().insns.push(Insn::DeleteVar {
2671 name: name.name.clone(),
2672 });
2673 self.state().insn_pos.push(pos);
2674 }
2675 _ => self.emit(Opcode::PushFalse, &[]),
2676 }
2677 }
2678 UnaryOp::Void => {
2679 self.expr(argument)?;
2680 self.emit(Opcode::Drop, &[]);
2681 self.emit(Opcode::Undefined, &[]);
2682 }
2683 UnaryOp::Minus => {
2684 self.expr(argument)?;
2685 self.emit(Opcode::Neg, &[]);
2686 }
2687 UnaryOp::Plus => {
2688 self.expr(argument)?;
2689 self.emit(Opcode::Plus, &[]);
2690 }
2691 UnaryOp::Not => {
2692 self.expr(argument)?;
2693 self.emit(Opcode::Lnot, &[]);
2694 }
2695 UnaryOp::BitNot => {
2696 self.expr(argument)?;
2697 self.emit(Opcode::Not, &[]);
2698 }
2699 }
2700 Ok(())
2701 }
2702
2703 /// Compile an assignment.
2704 ///
2705 /// Three operator families, three shapes:
2706 ///
2707 /// * **plain** `=` — evaluate, store. A member needs `insert2`/`insert3` when
2708 /// the value is kept, because `put_field`/`put_array_el` consume both the
2709 /// object and the value: `insert2` is `obj a -> a obj a`, so the store sees
2710 /// the pair it wants and leaves a copy on top.
2711 /// * **compound** `+=` … — read the place, apply the operator, store. A member
2712 /// reads through `get_field2`/`get_array_el3`, which leave the object (and
2713 /// index) underneath the value precisely so the store can follow.
2714 /// * **logical** `||=`, `&&=`, `??=` — read, test, and only then evaluate the
2715 /// right-hand side. The test *keeps* the current value and skips the store
2716 /// entirely, which is the whole point: `a ||= b` must not evaluate `b` when
2717 /// `a` is already truthy.
2718 fn assign(&mut self, op: AssignOp, target: &Pattern, value: &Expr) -> Result<(), SyntaxError> {
2719 // Reading the flag clears it: only the outermost assignment of an
2720 // expression statement may drop its value.
2721 let keep = !std::mem::take(&mut self.state().discard_value);
2722 match &target.kind {
2723 PatternKind::Ident(name) => {
2724 // A *simple* store is blamed on the identifier, not on the `=`: a
2725 // strict-mode `not_def = 1` raises when the name is written, which the
2726 // reference reports at the name's column. A compound store is blamed on
2727 // the operator instead (`a += poisoned` raises inside `ToPrimitive`,
2728 // which the reference reports at the `+=`), so only the simple case
2729 // moves the position.
2730 let saved = self.cur().cur_pos;
2731 let name_pos = Some(name.span.start);
2732 if matches!(op, AssignOp::Assign) {
2733 self.state().cur_pos = name_pos;
2734 }
2735 // A *compound* store reads the binding before it combines, and that read
2736 // is blamed on the identifier: `not_def += 2` fails while reading
2737 // `not_def`, so the position is the name's, not the `+=`'s. The
2738 // combination that follows is blamed on the operator, which is why
2739 // `cur_pos` is put back to the operator position before it is emitted.
2740 self.state().cur_pos = name_pos;
2741 match op {
2742 AssignOp::Assign => {
2743 self.expr(value)?;
2744 self.set_name_if_anonymous(value, &name.name);
2745 // A discarded store to a *slot* consumes its value, so no copy
2746 // is needed. A global store goes through `put_var`, which the
2747 // reference always pairs with a `dup` — matching it keeps the
2748 // bytecode identical. Getting this wrong is not only an extra
2749 // instruction: a stray copy gives the peephole a chance to fold
2750 // the store into an unrelated later read.
2751 let slot = self.is_slot(&name.name);
2752 if keep || !slot {
2753 self.emit(Opcode::Dup, &[]);
2754 }
2755 self.state().no_value = !keep && slot;
2756 self.emit_var(VarAction::Put, &name.name);
2757 }
2758 AssignOp::And | AssignOp::Or | AssignOp::Coalesce => {
2759 let end = self.new_label();
2760 self.emit_var(VarAction::Get, &name.name);
2761 self.state().cur_pos = saved;
2762 self.emit(Opcode::Dup, &[]);
2763 self.emit_logical_test(op);
2764 self.emit_jump(logical_jump(op), end, &[]);
2765 self.emit(Opcode::Drop, &[]);
2766 self.expr(value)?;
2767 self.emit(Opcode::Dup, &[]);
2768 self.emit_var(VarAction::Put, &name.name);
2769 self.place_label(end);
2770 }
2771 _ => {
2772 self.emit_var(VarAction::Get, &name.name);
2773 self.expr(value)?;
2774 self.state().cur_pos = saved;
2775 self.emit(compound_opcode(op), &[]);
2776 self.emit(Opcode::Dup, &[]);
2777 self.emit_var(VarAction::Put, &name.name);
2778 }
2779 }
2780 self.state().cur_pos = saved;
2781 Ok(())
2782 }
2783 PatternKind::Member(member) => {
2784 // A store is blamed on the selector punctuator (`.` or `[`), the same
2785 // token a load is blamed on — the reference records `put_field obj.a`
2786 // at the `.`, so a setter that throws reports that column and not the
2787 // `=` of the assignment it sits in. The inner expressions restore their
2788 // own positions, so the selector's sticks for the store instructions.
2789 let saved = self.cur().cur_pos;
2790 self.state().cur_pos = member.op_pos.or(Some(member.span.start));
2791 self.expr(&member.object)?;
2792 match &member.property {
2793 MemberProp::Ident(property) => {
2794 let atom = Atom::from_text(&property.name);
2795 match op {
2796 AssignOp::Assign => {
2797 self.expr(value)?;
2798 // `put_field` consumes the object and the value, so
2799 // without `insert2` nothing is left over for the
2800 // statement to drop.
2801 self.state().no_value = !keep;
2802 if keep {
2803 self.emit(Opcode::Insert2, &[]);
2804 }
2805 self.emit(Opcode::PutField, &[Op::Atom(atom.clone())]);
2806 }
2807 AssignOp::And | AssignOp::Or | AssignOp::Coalesce => {
2808 // `get_field2` leaves the object under the value, so
2809 // the keep path has an object to dispose of. The store
2810 // path must jump *over* that cleanup: falling into it
2811 // would `nip` a stack that only holds the value.
2812 let (keep_label, end) = (self.new_label(), self.new_label());
2813 self.emit(Opcode::GetField2, &[Op::Atom(atom.clone())]);
2814 self.emit(Opcode::Dup, &[]);
2815 self.emit_logical_test(op);
2816 self.emit_jump(logical_jump(op), keep_label, &[]);
2817 self.emit(Opcode::Drop, &[]);
2818 self.expr(value)?;
2819 self.emit(Opcode::Insert2, &[]);
2820 self.emit(Opcode::PutField, &[Op::Atom(atom.clone())]);
2821 self.emit_jump(Opcode::Goto, end, &[]);
2822 self.place_label(keep_label);
2823 self.emit(Opcode::Nip, &[]);
2824 self.place_label(end);
2825 }
2826 _ => {
2827 self.emit(Opcode::GetField2, &[Op::Atom(atom.clone())]);
2828 self.expr(value)?;
2829 self.emit(compound_opcode(op), &[]);
2830 self.state().no_value = !keep;
2831 if keep {
2832 self.emit(Opcode::Insert2, &[]);
2833 }
2834 self.emit(Opcode::PutField, &[Op::Atom(atom.clone())]);
2835 }
2836 }
2837 }
2838 MemberProp::Computed(index) => {
2839 self.expr(index)?;
2840 match op {
2841 AssignOp::Assign => {
2842 self.expr(value)?;
2843 self.state().no_value = !keep;
2844 if keep {
2845 self.emit(Opcode::Insert3, &[]);
2846 }
2847 self.emit(Opcode::PutArrayEl, &[]);
2848 }
2849 AssignOp::And | AssignOp::Or | AssignOp::Coalesce => {
2850 let (keep_label, end) = (self.new_label(), self.new_label());
2851 self.emit(Opcode::GetArrayEl3, &[]);
2852 self.emit(Opcode::Dup, &[]);
2853 self.emit_logical_test(op);
2854 self.emit_jump(logical_jump(op), keep_label, &[]);
2855 self.emit(Opcode::Drop, &[]);
2856 self.expr(value)?;
2857 self.emit(Opcode::Insert3, &[]);
2858 self.emit(Opcode::PutArrayEl, &[]);
2859 self.emit_jump(Opcode::Goto, end, &[]);
2860 self.place_label(keep_label);
2861 // Both the object and the index are left over.
2862 self.emit(Opcode::Nip, &[]);
2863 self.emit(Opcode::Nip, &[]);
2864 self.place_label(end);
2865 }
2866 _ => {
2867 self.emit(Opcode::GetArrayEl3, &[]);
2868 self.expr(value)?;
2869 self.emit(compound_opcode(op), &[]);
2870 self.state().no_value = !keep;
2871 if keep {
2872 self.emit(Opcode::Insert3, &[]);
2873 }
2874 self.emit(Opcode::PutArrayEl, &[]);
2875 }
2876 }
2877 }
2878 MemberProp::Private(_) => {
2879 return Err(SyntaxError::new(
2880 "private fields are not supported by the compiler yet",
2881 member.span,
2882 ));
2883 }
2884 }
2885 self.state().cur_pos = saved;
2886 Ok(())
2887 }
2888 _ => Err(SyntaxError::new(
2889 "this assignment target is not supported by the compiler yet",
2890 target.span,
2891 )),
2892 }
2893 }
2894
2895 /// The test a logical assignment applies to the current value.
2896 ///
2897 /// `??=` needs a real opcode rather than a truthiness jump: `0 ??= b` must
2898 /// assign, while `0 ||= b` must not.
2899 fn emit_logical_test(&mut self, op: AssignOp) {
2900 if op == AssignOp::Coalesce {
2901 self.emit(Opcode::IsUndefinedOrNull, &[]);
2902 }
2903 }
2904
2905 fn update(&mut self, op: UpdateOp, argument: &Expr, prefix: bool) -> Result<(), SyntaxError> {
2906 let ExprKind::Ident(name) = &argument.kind else {
2907 return Err(SyntaxError::new(
2908 "increment of a non-variable is not supported by the compiler yet",
2909 argument.span,
2910 ));
2911 };
2912 // A discarded `i++` keeps the plain `get`/`post_inc`/`put` shape. The
2913 // reference's `inc_loc` folds those three into one, but it does so only in some
2914 // positions (a `for` update and not a bare statement, and never for a lexical
2915 // binding), so emitting it unconditionally would move *away* from its output.
2916 // The instruction is equivalent either way; matching the reference matters more
2917 // than saving two instructions.
2918 let _ = !std::mem::take(&mut self.state().discard_value);
2919 self.emit_var(VarAction::Get, &name.name);
2920 let instruction = match (op, prefix) {
2921 (UpdateOp::Increment, true) => Opcode::Inc,
2922 (UpdateOp::Increment, false) => Opcode::PostInc,
2923 (UpdateOp::Decrement, true) => Opcode::Dec,
2924 (UpdateOp::Decrement, false) => Opcode::PostDec,
2925 };
2926 self.emit(instruction, &[]);
2927 if prefix {
2928 self.emit(Opcode::Dup, &[]);
2929 }
2930 self.emit_var(VarAction::Put, &name.name);
2931 Ok(())
2932 }
2933
2934 /// Compile an array literal.
2935 ///
2936 /// The reference splits this into three phases, and the split is load-bearing
2937 /// rather than an optimisation detail:
2938 ///
2939 /// 1. **A leading run of plain elements** becomes `array_from n`, which builds
2940 /// the array in one instruction.
2941 /// 2. **Everything up to the first spread** is appended with explicit indices
2942 /// (`define_field <index>`), because a hole has no element to pass to
2943 /// `array_from`. A hole here is what makes `length` need fixing up: an
2944 /// explicit index does not extend the array the way a pushed element does.
2945 /// 3. **From the first spread on** the index lives on the stack, so `append` and
2946 /// `define_array_el` can consume it and `inc` advances it.
2947 ///
2948 /// So `[1,,3]` and `[1,2,3]` are not two spellings of one program: the hole
2949 /// forces phase 2, and `[...a]` forces phase 3.
2950 fn array_literal(
2951 &mut self,
2952 elements: &[Option<ArrayElement>],
2953 span: Span,
2954 ) -> Result<(), SyntaxError> {
2955 let _ = span;
2956 let mut index: u32 = 0;
2957 let mut cursor = 0usize;
2958
2959 // Phase 1: a leading run of plain elements, at most 32 of them.
2960 while let Some(Some(ArrayElement::Expr(element))) = elements.get(cursor) {
2961 if index >= 32 {
2962 break;
2963 }
2964 self.expr(element)?;
2965 index += 1;
2966 cursor += 1;
2967 }
2968 self.emit(Opcode::ArrayFrom, &[Op::Int(index as i32)]);
2969
2970 // Phase 2: explicit indices, up to the first spread.
2971 let mut need_length = false;
2972 while let Some(element) = elements.get(cursor) {
2973 if matches!(element, Some(ArrayElement::Spread(_))) {
2974 break;
2975 }
2976 need_length = true;
2977 if let Some(ArrayElement::Expr(expression)) = element {
2978 self.expr(expression)?;
2979 self.emit_define_index(index);
2980 need_length = false;
2981 }
2982 index += 1;
2983 cursor += 1;
2984 }
2985
2986 if cursor >= elements.len() {
2987 if need_length {
2988 // `define_field` cannot set `length`, which is not configurable.
2989 self.emit(Opcode::Dup, &[]);
2990 self.push_number(index as f64);
2991 self.emit(Opcode::PutField, &[Op::Atom(Atom::from_text("length"))]);
2992 }
2993 return Ok(());
2994 }
2995
2996 // Phase 3: the index moves onto the stack for the spreading tail.
2997 //
2998 // `need_length` deliberately carries over from phase 2: a hole before the
2999 // first spread still has to be reflected in `length`, and only the final
3000 // check can do it because the array is not finished until the tail is
3001 // appended.
3002 self.push_number(index as f64);
3003 while let Some(element) = elements.get(cursor) {
3004 match element {
3005 Some(ArrayElement::Spread(expression)) => {
3006 // `append` copies an iterable and leaves the next index behind,
3007 // so no `inc` is needed here.
3008 self.expr(spread_argument(expression))?;
3009 self.emit(Opcode::Append, &[]);
3010 }
3011 None | Some(ArrayElement::Expr(_)) => {
3012 need_length = true;
3013 if let Some(ArrayElement::Expr(expression)) = element {
3014 self.expr(expression)?;
3015 self.emit(Opcode::DefineArrayEl, &[]);
3016 need_length = false;
3017 }
3018 self.emit(Opcode::Inc, &[]);
3019 }
3020 }
3021 cursor += 1;
3022 }
3023 if need_length {
3024 self.emit(Opcode::Dup1, &[]);
3025 self.emit(Opcode::PutField, &[Op::Atom(Atom::from_text("length"))]);
3026 } else {
3027 self.emit(Opcode::Drop, &[]);
3028 }
3029 Ok(())
3030 }
3031
3032 /// `define_field` with an array-index atom, which is how phase 2 stores elements.
3033 fn emit_define_index(&mut self, index: u32) {
3034 self.emit(
3035 Opcode::DefineField,
3036 &[Op::Atom(Atom::from_text(&index.to_string()))],
3037 );
3038 }
3039
3040 // -- functions ---------------------------------------------------------
3041
3042 fn compile_function(&mut self, func: &ast::Function) -> Result<CompiledFunction, SyntaxError> {
3043 self.compile_function_with_name(func, false)
3044 }
3045
3046 /// Compile a function, recording whether it is a *named function expression*.
3047 ///
3048 /// `var f = function g(){ return g }` has to see `g` inside its own body, but `g`
3049 /// must not leak outside. The reference does that by declaring `g` as a local of
3050 /// the function itself and initialising it with `special_object 2` (the current
3051 /// function), which is why this has to be known at compile time.
3052 fn compile_function_with_name(
3053 &mut self,
3054 func: &ast::Function,
3055 is_expression: bool,
3056 ) -> Result<CompiledFunction, SyntaxError> {
3057 if func.is_generator || func.is_async {
3058 return Err(SyntaxError::new(
3059 "generators and async functions are not supported by the compiler yet",
3060 func.span,
3061 ));
3062 }
3063 let kind = FunctionKind::Normal;
3064 let mut state = FnState::new(
3065 func.name
3066 .as_ref()
3067 .map(|n| n.name.clone())
3068 .unwrap_or_default(),
3069 kind,
3070 );
3071 state.strict = self.cur().strict;
3072 state.is_arrow = func.is_arrow;
3073 // A named *expression* binds its own name; a declaration's name is already
3074 // bound in the enclosing scope.
3075 state.self_name = if is_expression && !func.is_arrow {
3076 func.name.as_ref().map(|n| n.name.clone())
3077 } else {
3078 None
3079 };
3080 state.line = func.span.start.line;
3081 state.column = func.span.start.column;
3082 // A function body has no hidden `<ret>` local; the value comes back on
3083 // the stack. Only a script keeps one.
3084 for param in &func.params {
3085 let PatternKind::Ident(name) = ¶m.kind else {
3086 return Err(SyntaxError::new(
3087 "destructuring parameters are not supported by the compiler yet",
3088 param.span,
3089 ));
3090 };
3091 state.args.push(VarDef::var(name.name.clone()));
3092 }
3093 let depth = self.stack.len();
3094 self.stack.push(state);
3095 let result = self.compile_function_body(func);
3096 if result.is_err() {
3097 // A failed compile must not leave its `FnState` behind. Every caller
3098 // reads `self.state()` as "the function being compiled", so a leftover
3099 // frame silently retargets all later bookkeeping at a dead function.
3100 self.stack.truncate(depth);
3101 }
3102 result
3103 }
3104
3105 /// The body of a function, with its frame already pushed.
3106 fn compile_function_body(
3107 &mut self,
3108 func: &ast::Function,
3109 ) -> Result<CompiledFunction, SyntaxError> {
3110 let body_key = func.params_span.end.offset as u64;
3111 self.push_block(body_key, NO_PARENT);
3112 self.state().body_block = body_key;
3113 // An arrow with an expression body has no statements; the expression is
3114 // its `return`. Building the statement here keeps one code path below, and
3115 // matters for correctness beyond convenience: returning early with the new
3116 // `FnState` still on the stack would leave the compiler looking at the
3117 // wrong function, which surfaces as an unrelated underflow later.
3118 let concise = match &func.body {
3119 js_parse::ast::FunctionBody::Expr(value) => Some(Stmt::new(
3120 StmtKind::Return(Some(Box::new((**value).clone()))),
3121 value.span,
3122 )),
3123 js_parse::ast::FunctionBody::Block(_) => None,
3124 };
3125 let body: &[Stmt] = match &concise {
3126 Some(stmt) => std::slice::from_ref(stmt),
3127 None => func
3128 .body
3129 .statements()
3130 .ok_or_else(|| SyntaxError::new("unsupported function body", func.span))?,
3131 };
3132 self.hoist(body, body_key)?;
3133 self.emit_scope_enter(body_key);
3134 for stmt in body {
3135 self.stmt(stmt)?;
3136 if Self::terminates(stmt) {
3137 break;
3138 }
3139 }
3140 // The implicit return only exists if control can actually get here: an
3141 // infinite loop never falls off the end.
3142 if self.end_is_reachable() {
3143 self.emit(Opcode::ReturnUndef, &[]);
3144 }
3145 // Resolution runs while this function is still on the stack: capturing a
3146 // variable from an enclosing function means reaching into that
3147 // function's state, which requires the whole chain to be present.
3148 Ok(self.finish_current())
3149 }
3150
3151 /// Whether the current position in the instruction stream can be reached.
3152 ///
3153 /// A walk over the control-flow graph, using labels as instruction indices.
3154 /// The reference does the same thing to decide whether an implicit
3155 /// `return_undef` is needed.
3156 fn end_is_reachable(&self) -> bool {
3157 let state = self.cur();
3158 reachable_instructions(state, state.insns.len())[state.insns.len()]
3159 }
3160
3161 /// Resolve and assemble the function on top of the compiler stack, then pop
3162 /// it.
3163 fn finish_current(&mut self) -> CompiledFunction {
3164 self.provide_arguments();
3165 self.provide_self_name();
3166 let (mut resolved, resolved_pos) = resolve(&mut self.stack);
3167 // Captured bindings need a reference cell; the count goes in the header so
3168 // the runtime knows how many cells to allocate on entry.
3169 let current = self.stack.len() - 1;
3170 let captured = self.stack[current]
3171 .args
3172 .iter()
3173 .filter(|a| a.is_captured)
3174 .count()
3175 + self.stack[current]
3176 .vars
3177 .iter()
3178 .filter(|v| v.is_captured)
3179 .count();
3180 self.stack[current].var_ref_count = captured as u32;
3181 // The scope chain is only final now that every binding is known.
3182 rebuild_scope_chain(&mut self.stack[current]);
3183 let (code, stack_size, positions) =
3184 assemble(&mut resolved, &resolved_pos, &mut self.stack[current]);
3185 let _ = &mut resolved;
3186 let state = self.stack.pop().expect("a function is being compiled");
3187 CompiledFunction {
3188 name: state.name,
3189 kind: state.kind,
3190 strict: state.strict,
3191 args: state.args,
3192 vars: state.vars,
3193 closure_vars: state.closure_vars,
3194 cpool: state.cpool,
3195 atoms: state.atoms,
3196 code,
3197 stack_size,
3198 var_ref_count: state.var_ref_count,
3199 positions,
3200 source: None,
3201 line: state.line,
3202 column: state.column,
3203 filename: None,
3204 }
3205 }
3206}
3207
3208/// Assign each binding a scope level and rebuild the scope chains.
3209///
3210/// Levels are numbered in the order the blocks appear, with 0 reserved for the
3211/// function scope where `var` and hoisted functions live. Every binding outside
3212/// level 0 gets a `scope_next` link to the next binding visible from the same
3213/// point, so walking a block's chain enumerates exactly the bindings live there.
3214///
3215/// The links cannot be filled in while hoisting: `{ let a } let b` needs `a` to
3216/// point at `b`, which is declared later in the source but earlier in the chain.
3217fn rebuild_scope_chain(state: &mut FnState) {
3218 // Block key -> level. Level 0 is the function scope, keyed by the sentinel so a
3219 // real block that happens to start at offset zero keeps its own level instead of
3220 // being merged into the function scope.
3221 let mut levels: Vec<u64> = vec![FUNCTION_SCOPE];
3222 for block in &state.blocks {
3223 if !levels.contains(&block.key) {
3224 levels.push(block.key);
3225 }
3226 }
3227 let level_of = |key: u64| -> usize { levels.iter().position(|k| *k == key).unwrap_or(0) };
3228 let parent_level = |level: usize| -> usize {
3229 if level == 0 {
3230 return 0;
3231 }
3232 let key = levels[level];
3233 let parent = state
3234 .blocks
3235 .iter()
3236 .find(|b| b.key == key)
3237 .map(|b| b.parent)
3238 .unwrap_or(FUNCTION_SCOPE);
3239 level_of(parent)
3240 };
3241
3242 // Own bindings per level, in declaration order.
3243 let mut own: Vec<Vec<usize>> = vec![Vec::new(); levels.len()];
3244 let keys: Vec<u64> = (0..state.vars.len())
3245 .map(|index| {
3246 state
3247 .var_block
3248 .get(index)
3249 .copied()
3250 .unwrap_or(FUNCTION_SCOPE)
3251 })
3252 .collect();
3253 for (index, key) in keys.into_iter().enumerate() {
3254 let level = level_of(key);
3255 state.vars[index].scope_level = level as u32;
3256 // A `catch` parameter is part of the runtime scope chain even though it is
3257 // not lexical: the handler's own bindings chain on to it, which is why the
3258 // reference prints `let y [next:1]` with `e` at 1.
3259 if state.vars[index].is_lexical || state.vars[index].kind == crate::bytecode::VarKind::Catch
3260 {
3261 own[level].push(index);
3262 }
3263 }
3264
3265 // A scope's chain is its own bindings in reverse declaration order followed
3266 // by the enclosing scope's chain.
3267 let mut head = vec![-1i32; levels.len()];
3268 for level in 0..levels.len() {
3269 let inherited = if level == 0 {
3270 -1
3271 } else {
3272 head[parent_level(level)]
3273 };
3274 let chain: Vec<usize> = own[level].iter().rev().copied().collect();
3275 head[level] = chain.first().map_or(inherited, |first| *first as i32);
3276 for (position, &index) in chain.iter().enumerate() {
3277 let next = chain
3278 .get(position + 1)
3279 .map_or(inherited, |next| *next as i32);
3280 state.vars[index].scope_next = if next < 0 { None } else { Some(next) };
3281 }
3282 }
3283 state.block_heads = head;
3284}
3285
3286/// This is where names become slots and where the temporal dead zone shows up in
3287/// the instruction stream: a read of a `let`/`const` binding compiles to
3288/// `get_loc_check`, which throws if the binding is still uninitialised.
3289///
3290/// The peephole pass from the reference implementation is applied at the end,
3291/// for the same reason it is applied to resolved bytecode there: the patterns are
3292/// stated in terms of `put_loc`/`set_loc` pairs, which only exist after
3293/// resolution. Deleted instructions stay in the list as `None` so that label
3294/// indices remain valid; [`Assembler`] maps them to byte offsets.
3295/// A resolved instruction and the source position it came from.
3296type ResolvedInsn = Option<(Opcode, Vec<Op>)>;
3297
3298/// A resolved instruction paired with its position, which is what `assemble` consumes.
3299type PositionedInsn = (Opcode, Vec<Op>);
3300
3301fn resolve(stack: &mut [FnState]) -> (Vec<ResolvedInsn>, Vec<Option<Position>>) {
3302 let current = stack.len() - 1;
3303 // Dead-code elimination, on the symbolic form where labels are still
3304 // instruction indices. A `break` inside a loop leaves the trailing `goto`
3305 // unreachable, and a `return` leaves everything after it unreachable; the
3306 // reference drops both. Doing it here means the emitter never has to think
3307 // about reachability.
3308 strip_empty_gosubs(stack, current);
3309 eliminate_dead_code(stack, current);
3310 let insns = std::mem::take(&mut stack[current].insns);
3311 // One entry per instruction, carried alongside: `insn_pos` is index-aligned with
3312 // `insns`, and every arm below pushes exactly one instruction, so the positions
3313 // stay aligned with `out`.
3314 let positions = std::mem::take(&mut stack[current].insn_pos);
3315 let mut out: Vec<Option<(Opcode, Vec<Op>)>> = Vec::with_capacity(insns.len());
3316 let mut out_pos: Vec<Option<Position>> = Vec::with_capacity(insns.len());
3317 for (index, insn) in insns.iter().enumerate() {
3318 let pos = positions.get(index).copied().flatten();
3319 out_pos.push(pos);
3320 match insn {
3321 Insn::Fixed { op, operands } => {
3322 let operands = operands
3323 .iter()
3324 .map(|operand| match operand {
3325 Op::Atom(atom) => {
3326 Op::AtomId(intern_atom(&mut stack[current], &atom.to_string()))
3327 }
3328 other => other.clone(),
3329 })
3330 .collect();
3331 out.push(Some((*op, operands)));
3332 }
3333 Insn::Var {
3334 action,
3335 name,
3336 block,
3337 } => {
3338 let slot = resolve_slot(stack, current, name, *block);
3339 out.push(Some(variable_instruction(stack, current, *action, slot)));
3340 }
3341 Insn::CloseCaptured { name, block } => {
3342 // The block matters: a loop variable is scoped to the `for` head's own
3343 // block, so resolving it against block 0 would miss it entirely and
3344 // silently emit nothing.
3345 let slot = resolve_slot(stack, current, name, *block);
3346 // Only a local with a reference cell has anything to close. A global
3347 // or a never-captured local resolves to no instruction at all, which
3348 // keeps the bytecode identical to the reference's.
3349 if let Slot::Loc(index) = slot
3350 && stack[current]
3351 .vars
3352 .get(index as usize)
3353 .is_some_and(|v| v.is_captured)
3354 {
3355 out.push(Some((Opcode::CloseLoc, vec![Op::Slot(slot)])));
3356 } else {
3357 out.push(None);
3358 }
3359 }
3360 Insn::DeleteVar { name } => {
3361 // A binding — a local, an argument, or a declared global — cannot be
3362 // deleted, and the reference encodes that as a constant `push_false`.
3363 // Only an implicit global needs the runtime lookup.
3364 if matches!(resolve_slot(stack, current, name, 0), Slot::Global(_)) {
3365 let atom = intern_atom(&mut stack[current], name);
3366 out.push(Some((Opcode::DeleteVar, vec![Op::AtomId(atom)])));
3367 } else {
3368 out.push(Some((Opcode::PushFalse, Vec::new())));
3369 }
3370 }
3371 Insn::Dead => out.push(None),
3372 }
3373 }
3374 // Which label (if any) sits on each instruction, so the jump patterns can
3375 // tell whether they would cross a jump target.
3376 let mut label_at: Vec<Option<u32>> = vec![None; out.len() + 1];
3377 for (id, placed) in stack[current].labels.iter().enumerate() {
3378 if let Some(index) = *placed
3379 && index < label_at.len()
3380 && label_at[index].is_none()
3381 {
3382 label_at[index] = Some(id as u32);
3383 }
3384 }
3385 if std::env::var_os("QJS_DEBUG").is_some() {
3386 eprintln!("--- peephole entry ---");
3387 for (i, e) in out.iter().enumerate() {
3388 eprintln!("{i}: {e:?}");
3389 }
3390 eprintln!("label_at: {label_at:?}");
3391 }
3392 peephole(&mut out, &label_at, &stack[current].labels);
3393 (out, out_pos)
3394}
3395
3396/// Find where `name` lives, capturing it in an enclosing function when needed.
3397///
3398/// The search runs outward through the enclosing functions' states, which are
3399/// still on the compiler stack while a nested function is resolved. Finding the
3400/// name in an enclosing function is what creates a closure reference, and every
3401/// function in between has to forward it — a function can only reach its own
3402/// parent's frame.
3403///
3404/// A name declared nowhere is a global. The reference does *not* look it up by
3405/// name from the inner function: the top-level function gets one `[global]`
3406/// entry and every nested function gets a `[global_ref<n>]` pointing at its
3407/// parent's entry, which is why `function f(){ g(); }` shows `[global_ref0]`
3408/// rather than `[global]`.
3409/// The lexical blocks enclosing `block`, innermost first.
3410fn block_chain(state: &FnState, block: u64) -> Vec<u64> {
3411 let mut chain = Vec::new();
3412 let mut current = Some(block);
3413 while let Some(key) = current {
3414 // `NO_PARENT` is not a block, so the walk ends here. Stopping on the sentinel
3415 // explicitly (rather than on "no block with this key") is what keeps a block
3416 // that happens to sit at offset zero from being mistaken for the terminator.
3417 if key == NO_PARENT || chain.contains(&key) {
3418 break;
3419 }
3420 chain.push(key);
3421 current = state.blocks.iter().find(|b| b.key == key).map(|b| b.parent);
3422 }
3423 chain
3424}
3425
3426fn resolve_slot(stack: &mut [FnState], current: usize, name: &str, block: u64) -> Slot {
3427 if let Some(index) = stack[current].args.iter().position(|a| a.name == name) {
3428 return Slot::Arg(index as u32);
3429 }
3430 // A name can be bound more than once: two `catch` parameters in nested
3431 // handlers are two slots. The binding that wins is the one whose scope encloses
3432 // the access, and among those the innermost — so the blocks are walked outward
3433 // and the first binding found on the way is the one that counts. A binding in
3434 // no block (`var`) is reachable from anywhere, which is why the function scope
3435 // is the end of the walk.
3436 let chain = block_chain(&stack[current], block);
3437 for scope in &chain {
3438 let found = stack[current]
3439 .vars
3440 .iter()
3441 .enumerate()
3442 .find(|(index, var)| {
3443 var.name == name && stack[current].var_block.get(*index).copied() == Some(*scope)
3444 })
3445 .map(|(index, _)| index);
3446 if let Some(index) = found {
3447 return Slot::Loc(index as u32);
3448 }
3449 }
3450 // Function-scope bindings — `var` and function declarations — are recorded with
3451 // the sentinel block `0`, which no real scope uses, so the walk above cannot see
3452 // them. They are reachable from anywhere in the function, which is exactly what
3453 // the sentinel means.
3454 //
3455 // This pass is *only* for those. A lexical binding has to be found through the
3456 // chain or not at all, and looking a name up without its block is precisely how
3457 // `var x = 1; { let x = 2; } x` used to see the inner `x`, and how a `let` in a
3458 // block leaked out of it.
3459 let function_scoped = stack[current]
3460 .vars
3461 .iter()
3462 .enumerate()
3463 .find(|(index, var)| {
3464 var.name == name
3465 && stack[current].var_block.get(*index).copied() == Some(FUNCTION_SCOPE)
3466 })
3467 .map(|(index, _)| index);
3468 if let Some(index) = function_scoped {
3469 return Slot::Loc(index as u32);
3470 }
3471 if let Some(index) = stack[current]
3472 .closure_vars
3473 .iter()
3474 .position(|c| c.name == name)
3475 {
3476 return slot_for_closure(&stack[current].closure_vars[index], index as u32);
3477 }
3478
3479 for owner in (0..current).rev() {
3480 let found = if let Some(index) = stack[owner].args.iter().position(|a| a.name == name) {
3481 Some(Found::Local(ClosureType::Arg, index as u32, false, false))
3482 } else if let Some(index) = stack[owner].vars.iter().position(|v| v.name == name) {
3483 let var = &stack[owner].vars[index];
3484 Some(Found::Local(
3485 ClosureType::Local,
3486 index as u32,
3487 var.is_const,
3488 var.is_lexical,
3489 ))
3490 } else if let Some(index) = stack[owner]
3491 .closure_vars
3492 .iter()
3493 .position(|c| c.name == name)
3494 {
3495 let closure = &stack[owner].closure_vars[index];
3496 Some(match closure.closure_type {
3497 ClosureType::Global
3498 | ClosureType::GlobalDecl
3499 | ClosureType::ModuleDecl
3500 | ClosureType::ModuleImport => Found::Global(index as u32),
3501 _ => Found::Local(
3502 ClosureType::Ref,
3503 index as u32,
3504 closure.is_const,
3505 closure.is_lexical,
3506 ),
3507 })
3508 } else {
3509 None
3510 };
3511 let Some(found) = found else { continue };
3512
3513 let (is_const, is_lexical) = match found {
3514 Found::Local(_, _, is_const, is_lexical) => (is_const, is_lexical),
3515 Found::Global(_) => (false, false),
3516 };
3517 // Mark the owner's binding as captured so it moves into a reference cell.
3518 if let Found::Local(ClosureType::Arg | ClosureType::Local, index, _, _) = found {
3519 let slot = match found {
3520 Found::Local(ClosureType::Arg, _, _, _) => &mut stack[owner].args[index as usize],
3521 _ => &mut stack[owner].vars[index as usize],
3522 };
3523 slot.is_captured = true;
3524 }
3525 // Forward the reference through every function in between.
3526 let mut previous = match found {
3527 Found::Local(kind, index, _, _) => (kind, index),
3528 Found::Global(index) => (ClosureType::Global, index),
3529 };
3530 for level in owner + 1..=current {
3531 let kind = match (previous.0, level) {
3532 // A global stays a global at *every* level. Without `GlobalRef` in
3533 // this arm the second nested function over the same global got a
3534 // `Ref` to a cell no frame ever held, so the innermost closure read
3535 // `undefined` — which is how a two-deep getter lost its outer
3536 // variable.
3537 (ClosureType::Global | ClosureType::GlobalDecl | ClosureType::GlobalRef, _) => {
3538 ClosureType::GlobalRef
3539 }
3540 (ClosureType::Arg | ClosureType::Local, level) if level == owner + 1 => previous.0,
3541 _ => ClosureType::Ref,
3542 };
3543 let index = ensure_closure(stack, level, name, is_const, is_lexical, kind, previous.1);
3544 previous = (kind, index);
3545 }
3546 let index = previous.1;
3547 return slot_for_closure(&stack[current].closure_vars[index as usize], index);
3548 }
3549
3550 // Declared nowhere: a dynamic global lookup, which sloppy mode may satisfy by
3551 // creating a property. The top-level function holds the entry.
3552 let mut previous = (
3553 ClosureType::Global,
3554 ensure_closure(stack, 0, name, false, false, ClosureType::Global, 0),
3555 );
3556 for level in 1..=current {
3557 let index = ensure_closure(
3558 stack,
3559 level,
3560 name,
3561 false,
3562 false,
3563 ClosureType::GlobalRef,
3564 previous.1,
3565 );
3566 previous = (ClosureType::GlobalRef, index);
3567 }
3568 Slot::Global(previous.1)
3569}
3570
3571/// What an outward search turned up.
3572#[derive(Debug, Clone, Copy)]
3573enum Found {
3574 /// A binding in an enclosing function, reachable through a closure of this
3575 /// type, with its const/lexical flags.
3576 Local(ClosureType, u32, bool, bool),
3577 /// A global, reached through the enclosing function's closure entry.
3578 Global(u32),
3579}
3580
3581/// Add a closure entry to `level` if it is not there yet.
3582fn ensure_closure(
3583 stack: &mut [FnState],
3584 level: usize,
3585 name: &str,
3586 is_const: bool,
3587 is_lexical: bool,
3588 closure_type: ClosureType,
3589 var_idx: u32,
3590) -> u32 {
3591 if let Some(index) = stack[level]
3592 .closure_vars
3593 .iter()
3594 .position(|c| c.name == name)
3595 {
3596 return index as u32;
3597 }
3598 stack[level].closure_vars.push(ClosureVar {
3599 name: name.to_string(),
3600 is_const,
3601 is_lexical,
3602 closure_type,
3603 var_idx: var_idx as u16,
3604 });
3605 stack[level].closure_vars.len() as u32 - 1
3606}
3607
3608fn slot_for_closure(closure: &ClosureVar, index: u32) -> Slot {
3609 match closure.closure_type {
3610 // A `global_ref` only says *how* the binding is found (through the
3611 // parent's closure table); the access itself is an ordinary global one.
3612 ClosureType::Global | ClosureType::GlobalRef => Slot::Global(index),
3613 ClosureType::GlobalDecl | ClosureType::ModuleDecl | ClosureType::ModuleImport => {
3614 Slot::GlobalDecl(index)
3615 }
3616 _ => Slot::VarRef(index),
3617 }
3618}
3619
3620/// Pick the opcode for one variable access.
3621///
3622/// The `_check` variants are what enforce the temporal dead zone. They are used
3623/// for every access to a `let`/`const` binding except its own initialisation —
3624/// which is exactly the operation that takes the binding out of the dead zone.
3625fn variable_instruction(
3626 stack: &[FnState],
3627 current: usize,
3628 action: VarAction,
3629 slot: Slot,
3630) -> (Opcode, Vec<Op>) {
3631 let lexical = match slot {
3632 Slot::Loc(index) => stack[current]
3633 .vars
3634 .get(index as usize)
3635 .is_some_and(|v| v.needs_check()),
3636 Slot::VarRef(index) => stack[current]
3637 .closure_vars
3638 .get(index as usize)
3639 .is_some_and(|c| c.is_lexical),
3640 _ => false,
3641 };
3642 let operand = vec![Op::Slot(slot)];
3643 match (action, slot) {
3644 (VarAction::Get, Slot::Loc(index)) => (
3645 if lexical {
3646 Opcode::GetLocCheck
3647 } else {
3648 Opcode::GetLoc
3649 },
3650 vec![Op::Slot(Slot::Loc(index))],
3651 ),
3652 (VarAction::Get, Slot::Arg(index)) => (Opcode::GetArg, vec![Op::Slot(Slot::Arg(index))]),
3653 (VarAction::Get, Slot::VarRef(index)) => (
3654 if lexical {
3655 Opcode::GetVarRefCheck
3656 } else {
3657 Opcode::GetVarRef
3658 },
3659 vec![Op::Slot(Slot::VarRef(index))],
3660 ),
3661 (VarAction::Get, Slot::Global(_)) => (Opcode::GetVar, operand),
3662 (VarAction::Get, Slot::GlobalDecl(_)) => (Opcode::GetVar, operand),
3663 (VarAction::GetUndef, Slot::Loc(_)) => (Opcode::GetLoc, operand),
3664 (VarAction::GetUndef, Slot::Arg(_)) => (Opcode::GetArg, operand),
3665 (VarAction::GetUndef, Slot::VarRef(_)) => (Opcode::GetVarRef, operand),
3666 (VarAction::GetUndef, Slot::Global(_) | Slot::GlobalDecl(_)) => {
3667 (Opcode::GetVarUndef, operand)
3668 }
3669
3670 (VarAction::Put, Slot::Loc(_)) => (
3671 if lexical {
3672 Opcode::PutLocCheck
3673 } else {
3674 Opcode::PutLoc
3675 },
3676 operand,
3677 ),
3678 (VarAction::Put, Slot::Arg(_)) => (Opcode::PutArg, operand),
3679 (VarAction::Put, Slot::VarRef(_)) => (
3680 if lexical {
3681 Opcode::PutVarRefCheck
3682 } else {
3683 Opcode::PutVarRef
3684 },
3685 operand,
3686 ),
3687 (VarAction::Put, Slot::Global(_)) => (Opcode::PutVar, operand),
3688 (VarAction::Put, Slot::GlobalDecl(_)) => (Opcode::PutVar, operand),
3689 // Initialisation is what ends the dead zone, so it never checks.
3690 (VarAction::PutInit, Slot::Loc(_)) => (Opcode::PutLoc, operand),
3691 (VarAction::PutInit, Slot::Arg(_)) => (Opcode::PutArg, operand),
3692 (VarAction::PutInit, Slot::VarRef(_)) => (Opcode::PutVarRef, operand),
3693 (VarAction::PutInit, Slot::Global(_) | Slot::GlobalDecl(_)) => {
3694 (Opcode::PutVarInit, operand)
3695 }
3696 (VarAction::Set, Slot::Loc(_)) => (
3697 if lexical {
3698 Opcode::SetLocCheck
3699 } else {
3700 Opcode::SetLoc
3701 },
3702 operand,
3703 ),
3704 (VarAction::Set, Slot::Arg(_)) => (Opcode::SetArg, operand),
3705 (VarAction::Set, Slot::VarRef(_)) => (Opcode::SetVarRef, operand),
3706 (VarAction::Set, Slot::Global(_)) => (Opcode::PutVar, operand),
3707 (VarAction::Set, Slot::GlobalDecl(_)) => (Opcode::SetVarRef, operand),
3708 (VarAction::PutRef, Slot::Loc(_)) => (Opcode::PutLoc, operand),
3709 (VarAction::PutRef, Slot::Arg(_)) => (Opcode::PutArg, operand),
3710 (VarAction::PutRef, Slot::VarRef(_)) => (Opcode::PutVarRef, operand),
3711 (VarAction::PutRef, Slot::Global(_) | Slot::GlobalDecl(_)) => (Opcode::PutVarRef, operand),
3712 }
3713}
3714
3715/// The instruction-rewriting pass.
3716///
3717/// These are the reference implementation's patterns, restricted to the ones the
3718/// constructs this compiler supports can produce. Each entry is a comment on the
3719/// bytecode it removes, because the whole point is that the result is one
3720/// instruction shorter than the literal translation of the AST.
3721fn peephole(
3722 insns: &mut [Option<(Opcode, Vec<Op>)>],
3723 label_at: &[Option<u32>],
3724 placed: &[Option<usize>],
3725) {
3726 fold_dup_patterns(insns, label_at);
3727
3728 // `drop` before `return_undef` is dead: the return discards the whole frame
3729 // anyway. This runs *after* the `dup` folds, because a `dup; put; drop` there
3730 // consumes its own `drop`; removing the drop first would leave the `dup` and
3731 // produce a `set_` where the reference has a `put_`.
3732 for index in 0..insns.len() {
3733 if opcode_at(insns, index) != Some(Opcode::Drop) {
3734 continue;
3735 }
3736 // Skip over a run of drops, but stop at a jump target: removing code on
3737 // one side of a label would silently retarget the jump.
3738 let mut next = index + 1;
3739 while opcode_at(insns, next) == Some(Opcode::Drop) && !is_label_at(label_at, next) {
3740 next += 1;
3741 }
3742 if is_label_at(label_at, next) {
3743 continue;
3744 }
3745 if opcode_at(insns, next) == Some(Opcode::ReturnUndef) {
3746 for entry in &mut insns[index..next] {
3747 *entry = None;
3748 }
3749 }
3750 }
3751
3752 // The rewrites below all decide against one fixed snapshot, which is what the
3753 // reference sees: `code_match` reads the bytecode buffer as it was on entry to
3754 // the pass, so a rule never observes what an earlier rule removed. Gathering
3755 // every deletion first and applying them together reproduces that.
3756 let snapshot: Vec<Option<Opcode>> = insns
3757 .iter()
3758 .map(|entry| entry.as_ref().map(|(op, _)| *op))
3759 .collect();
3760 // The next instruction that is still there. Holes left by dead-code
3761 // elimination are not instructions, so a rule looks past them.
3762 let next_op = |index: usize| -> Option<usize> {
3763 (index + 1..snapshot.len()).find(|position| snapshot[*position].is_some())
3764 };
3765
3766 let mut doomed = vec![false; insns.len()];
3767 for index in 0..insns.len() {
3768 // A constant pushed only to be dropped does nothing at all. This is what a
3769 // comma expression with a literal left operand compiles to — `(0, f)()` — and
3770 // the reference removes the pair rather than making the reader step over it.
3771 let constant = matches!(
3772 snapshot[index],
3773 Some(
3774 Opcode::Undefined
3775 | Opcode::Null
3776 | Opcode::PushMinus1
3777 | Opcode::Push0
3778 | Opcode::Push1
3779 | Opcode::Push2
3780 | Opcode::Push3
3781 | Opcode::Push4
3782 | Opcode::Push5
3783 | Opcode::Push6
3784 | Opcode::Push7
3785 | Opcode::PushTrue
3786 | Opcode::PushFalse
3787 | Opcode::PushI32
3788 )
3789 );
3790 if constant
3791 && let Some(next) = next_op(index)
3792 && snapshot[next] == Some(Opcode::Drop)
3793 {
3794 doomed[index] = true;
3795 doomed[next] = true;
3796 }
3797 }
3798 for (index, entry) in insns.iter_mut().enumerate() {
3799 if doomed[index] {
3800 *entry = None;
3801 }
3802 }
3803
3804 // A conditional whose destination is the very next instruction just pops its
3805 // condition, so it becomes a plain `drop`. This is what an empty `case` clause
3806 // compiles to.
3807 //
3808 // Order matters, and it is the reference's order: this runs *before* the
3809 // folding below, on the instruction the conditional originally had. Folding
3810 // moves a conditional's destination, and the reference never re-examines it
3811 // afterwards — which is why `if (c) continue;` at the end of a `do` body stays
3812 // a conditional even though folding leaves it pointing at the next
3813 // instruction.
3814 for (index, entry) in insns.iter_mut().enumerate() {
3815 let Some((op, operands)) = entry.clone() else {
3816 continue;
3817 };
3818 if !matches!(op, Opcode::IfTrue | Opcode::IfFalse) {
3819 continue;
3820 }
3821 let Some(id) = label_id(&operands) else {
3822 continue;
3823 };
3824 if placed.get(id as usize).copied().flatten() == Some(index + 1) {
3825 *entry = Some((Opcode::Drop, Vec::new()));
3826 }
3827 }
3828
3829 // A constant condition is decided here rather than at run time.
3830 fold_constant_conditions(insns);
3831 // The conditional folding below is about pairs of *real* branches, so it runs
3832 // before a jump to the next instruction is dropped: `do { … if (c) continue }
3833 // while (t)` puts `continue` exactly on the condition, and the reference inverts
3834 // the branch first and only then notices the jump goes nowhere.
3835 fold_conditional_jumps(insns, label_at, placed);
3836
3837 // A jump whose destination is the very next instruction does nothing, which is
3838 // what constant folding leaves behind for `while (1) { … }`.
3839 remove_jump_to_next(insns, placed);
3840
3841 // `put_x(n) get_x(n)` -> `set_x(n)`, which is what a declaration followed by
3842 // a use of the same variable boils down to.
3843 for index in 0..insns.len() {
3844 let Some((put_op, _)) = insns[index].clone() else {
3845 continue;
3846 };
3847 if !is_foldable_put(put_op) {
3848 continue;
3849 }
3850 if is_label_at(label_at, index + 1) {
3851 continue;
3852 }
3853 let Some((get_op, get_operands)) = insns.get(index + 1).cloned().flatten() else {
3854 continue;
3855 };
3856 if get_op != get_form_of(put_op) {
3857 continue;
3858 }
3859 let put_slot = insns[index].as_ref().and_then(|(_, o)| o.first().cloned());
3860 if put_slot.is_none() || put_slot != get_operands.first().cloned() {
3861 continue;
3862 }
3863 insns[index] = Some((set_form_of(put_op), get_operands));
3864 insns[index + 1] = None;
3865 }
3866}
3867
3868/// Drop `gosub`s that call an empty subroutine.
3869///
3870/// A `gosub` whose target starts with `ret` returns immediately, so the reference
3871/// drops the call. This is how `try`/`catch` without a `finally` loses its
3872/// finalizer plumbing: the finalizer block is empty, its first instruction is
3873/// `ret`, and every `gosub` to it disappears — leaving the `ret` unreachable, which
3874/// [`eliminate_dead_code`] then removes.
3875fn strip_empty_gosubs(stack: &mut [FnState], current: usize) {
3876 let state = &stack[current];
3877 let mut targets = Vec::new();
3878 for insn in &state.insns {
3879 if let Insn::Fixed { op, operands } = insn
3880 && *op == Opcode::Gosub
3881 && let Some(id) = label_id(operands)
3882 && let Some(target) = state.labels.get(id as usize).copied().flatten()
3883 {
3884 targets.push(target);
3885 }
3886 }
3887 let empty: Vec<usize> = targets
3888 .into_iter()
3889 .filter(|target| {
3890 stack[current]
3891 .insns
3892 .get(*target)
3893 .map(|insn| {
3894 matches!(
3895 insn,
3896 Insn::Fixed {
3897 op: Opcode::Ret,
3898 ..
3899 }
3900 )
3901 })
3902 .unwrap_or(false)
3903 })
3904 .collect();
3905 if empty.is_empty() {
3906 return;
3907 }
3908 for insn in stack[current].insns.iter_mut() {
3909 if let Insn::Fixed { op, operands } = insn
3910 && *op == Opcode::Gosub
3911 && let Some(id) = label_id(operands)
3912 && let Some(target) = stack[current].labels.get(id as usize).copied().flatten()
3913 && empty.contains(&target)
3914 {
3915 *insn = Insn::Dead;
3916 }
3917 }
3918}
3919
3920/// Replace unreachable instructions with [`Insn::Dead`].
3921fn eliminate_dead_code(stack: &mut [FnState], current: usize) {
3922 let reachable = reachable_instructions(&stack[current], stack[current].insns.len());
3923 for (index, insn) in stack[current].insns.iter_mut().enumerate() {
3924 if !reachable[index] {
3925 *insn = Insn::Dead;
3926 }
3927 }
3928}
3929
3930/// Mark every instruction index reachable from the entry, plus the index one past
3931/// the last instruction.
3932///
3933/// `seen[len]` answers "can control reach the end of this function", and the
3934/// entries before it identify dead code. Both DCE and the implicit-return decision
3935/// read the same result, which keeps them from disagreeing.
3936fn reachable_instructions(state: &FnState, count: usize) -> Vec<bool> {
3937 let mut seen = vec![false; count + 1];
3938 let mut worklist = vec![0usize];
3939 while let Some(index) = worklist.pop() {
3940 if index > count || seen[index] {
3941 continue;
3942 }
3943 seen[index] = true;
3944 if index == count {
3945 continue;
3946 }
3947 let (op, operands) = match &state.insns[index] {
3948 Insn::Fixed { op, operands } => (*op, operands.as_slice()),
3949 // A variable access never transfers control, and a removed
3950 // instruction is only reachable if it is already marked.
3951 Insn::Var { .. } | Insn::CloseCaptured { .. } | Insn::DeleteVar { .. } | Insn::Dead => {
3952 worklist.push(index + 1);
3953 continue;
3954 }
3955 };
3956 match op {
3957 // A return, a throw and a `ret` all leave this instruction stream: the
3958 // first two give control to the caller or the handler, and `ret`
3959 // returns to a `gosub` elsewhere.
3960 // A tail call leaves the function too: the callee's result becomes this
3961 // function's result, so nothing after it runs.
3962 Opcode::Return
3963 | Opcode::ReturnUndef
3964 | Opcode::TailCall
3965 | Opcode::TailCallMethod
3966 | Opcode::Throw
3967 | Opcode::ThrowError
3968 | Opcode::Ret => {}
3969 // A `catch` records where exceptions from the code that follows go.
3970 // That code is not reachable through normal control flow, but it is
3971 // reachable — through the exception edge — so the walk has to follow
3972 // it, or dead-code elimination would delete every handler.
3973 Opcode::Catch => {
3974 if let Some(target) = placed_label(state, operands) {
3975 worklist.push(target);
3976 }
3977 worklist.push(index + 1);
3978 }
3979 // A `gosub` calls a subroutine and then continues, so both edges count.
3980 Opcode::Gosub => {
3981 if let Some(target) = placed_label(state, operands) {
3982 worklist.push(target);
3983 }
3984 worklist.push(index + 1);
3985 }
3986 Opcode::Goto => {
3987 if let Some(target) = placed_label(state, operands) {
3988 worklist.push(target);
3989 }
3990 }
3991 Opcode::IfTrue | Opcode::IfFalse => {
3992 if let Some(target) = placed_label(state, operands) {
3993 worklist.push(target);
3994 }
3995 worklist.push(index + 1);
3996 }
3997 _ => worklist.push(index + 1),
3998 }
3999 }
4000 seen
4001}
4002
4003/// The instruction index a jump operand points at, resolved through the label
4004/// placement table.
4005fn placed_label(state: &FnState, operands: &[Op]) -> Option<usize> {
4006 let id = label_id(operands)?;
4007 state.labels.get(id as usize).copied().flatten()
4008}
4009
4010/// The label an instruction refers to.
4011fn label_id(operands: &[Op]) -> Option<u32> {
4012 operands.iter().find_map(|operand| match operand {
4013 Op::Label(label) => Some(label.0),
4014 _ => None,
4015 })
4016}
4017
4018/// Turn `if_false L; goto M; L:` into `if_true M`.
4019///
4020/// A conditional whose alternate branch is an unconditional jump needs one jump,
4021/// not two. This is the shape `if (c) break;` produces, so folding it removes an
4022/// instruction and a label from every conditional `break`.
4023/// The boolean a constant-push instruction produces, or `None` if it is not one.
4024///
4025/// Only the operators whose truthiness is decided by the opcode are covered; a
4026/// constant that needs the constant pool (a string) is left alone, because reading it
4027/// would mean threading the pool through the peephole for a case the reference also
4028/// skips.
4029fn constant_truth(op: Opcode, operands: &[Op]) -> Option<bool> {
4030 match op {
4031 // `push_0` returns -1 for zero, `push_1` 1, and so on.
4032 Opcode::PushMinus1 => Some(true),
4033 Opcode::Push0 => Some(false),
4034 Opcode::Push1
4035 | Opcode::Push2
4036 | Opcode::Push3
4037 | Opcode::Push4
4038 | Opcode::Push5
4039 | Opcode::Push6
4040 | Opcode::Push7 => Some(true),
4041 Opcode::PushTrue => Some(true),
4042 Opcode::PushFalse => Some(false),
4043 Opcode::Undefined | Opcode::Null => Some(false),
4044 Opcode::PushI32 => match operands.first() {
4045 Some(Op::Int(value)) => Some(*value != 0),
4046 _ => None,
4047 },
4048 _ => None,
4049 }
4050}
4051
4052/// Fold a branch on a constant condition.
4053///
4054/// `if (0) a() else b()` must not test anything at run time, and the reference
4055/// compiles it to a plain `goto`. Removing the test also removes the unreachable arm,
4056/// which is why the bytecode for a `while (1)` loop has no condition at all.
4057///
4058/// Two instructions become one, so the slot the test occupied is left empty rather
4059/// than shifting everything after it: labels have already been resolved to indices.
4060fn fold_constant_conditions(insns: &mut [Option<(Opcode, Vec<Op>)>]) {
4061 for index in 0..insns.len() {
4062 let Some((push_op, push_operands)) = insns[index].clone() else {
4063 continue;
4064 };
4065 let Some(truth) = constant_truth(push_op, &push_operands) else {
4066 continue;
4067 };
4068 let Some((branch_op, branch_operands)) = insns.get(index + 1).cloned().flatten() else {
4069 continue;
4070 };
4071 let (destination, taken) = match branch_op {
4072 Opcode::IfTrue => (branch_operands.first().cloned(), truth),
4073 Opcode::IfFalse => (branch_operands.first().cloned(), !truth),
4074 _ => continue,
4075 };
4076 let Some(destination) = destination else {
4077 continue;
4078 };
4079 insns[index] = if taken {
4080 // The branch is always taken, so it becomes an unconditional jump.
4081 Some((Opcode::Goto, vec![destination]))
4082 } else {
4083 // The branch never runs: both instructions disappear and control falls
4084 // through to what came after.
4085 None
4086 };
4087 insns[index + 1] = None;
4088 }
4089}
4090
4091/// Remove a jump whose destination is the instruction right after it.
4092///
4093/// Folding a constant condition leaves these behind often: `while (1) { ... }` turns
4094/// its test into nothing, and the loop-end jump then points at the following
4095/// instruction. The reference drops them, so `stack_size` and the listing agree.
4096fn remove_jump_to_next(insns: &mut [Option<(Opcode, Vec<Op>)>], placed: &[Option<usize>]) {
4097 for index in 0..insns.len() {
4098 let Some((op, operands)) = insns[index].clone() else {
4099 continue;
4100 };
4101 if !is_goto(op) {
4102 continue;
4103 }
4104 let Some(id) = label_id(&operands) else {
4105 continue;
4106 };
4107 // The next instruction that still exists, which is what "the instruction
4108 // after this jump" means once earlier folds have punched holes.
4109 let next = (index + 1..insns.len()).find(|position| insns[*position].is_some());
4110 if placed.get(id as usize).copied().flatten() == next {
4111 insns[index] = None;
4112 }
4113 }
4114}
4115
4116fn fold_conditional_jumps(
4117 insns: &mut [Option<(Opcode, Vec<Op>)>],
4118 label_at: &[Option<u32>],
4119 placed: &[Option<usize>],
4120) {
4121 for index in 0..insns.len() {
4122 let Some((op, operands)) = insns[index].clone() else {
4123 continue;
4124 };
4125 let inverted = match op {
4126 Opcode::IfFalse => Opcode::IfTrue,
4127 Opcode::IfTrue => Opcode::IfFalse,
4128 _ => continue,
4129 };
4130 // Next must be an unconditional jump that is not itself a target, and the
4131 // instruction after it must be exactly where the conditional goes.
4132 let Some((next_op, next_operands)) = insns.get(index + 1).cloned().flatten() else {
4133 continue;
4134 };
4135 if !is_goto(next_op) || is_label_at(label_at, index + 1) {
4136 continue;
4137 }
4138 // The conditional must land on the instruction *after* the jump. Several
4139 // labels can share a position, so this asks where *this* label was put
4140 // rather than what label happens to sit there.
4141 let Some(taken) = label_id(&operands) else {
4142 continue;
4143 };
4144 if placed.get(taken as usize).copied().flatten() != Some(index + 2) {
4145 continue;
4146 }
4147 let Some(destination) = next_operands.first().cloned() else {
4148 continue;
4149 };
4150 insns[index] = Some((inverted, vec![destination]));
4151 insns[index + 1] = None;
4152 }
4153}
4154
4155/// Whether a jump target is placed at this instruction index.
4156fn is_label_at(label_at: &[Option<u32>], index: usize) -> bool {
4157 label_at.get(index).copied().flatten().is_some()
4158}
4159
4160fn fold_dup_patterns(insns: &mut [Option<(Opcode, Vec<Op>)>], label_at: &[Option<u32>]) {
4161 // `dup put_x(n)` -> `set_x(n)`
4162 // `dup put_x(n) drop` -> `put_x(n)`
4163 // `dup put_x(n) drop get_x(n)` -> `set_x(n)`
4164 for index in 0..insns.len() {
4165 if opcode_at(insns, index) != Some(Opcode::Dup) {
4166 continue;
4167 }
4168 if is_label_at(label_at, index + 1) {
4169 continue;
4170 }
4171 let Some((put_op, put_operands)) = insns[index + 1].clone() else {
4172 continue;
4173 };
4174 if !is_foldable_put(put_op) {
4175 continue;
4176 }
4177 let Some(Op::Slot(slot)) = put_operands.first().cloned() else {
4178 continue;
4179 };
4180 let mut new_op = set_form_of(put_op);
4181 let mut end = index + 2;
4182 if is_label_at(label_at, end) {
4183 // The `put` has to stay as it is; only the `dup` can be folded.
4184 insns[index] = Some((set_form_of(put_op), vec![Op::Slot(slot)]));
4185 insns[index + 1] = None;
4186 continue;
4187 }
4188 if opcode_at(insns, end) == Some(Opcode::Drop) {
4189 new_op = put_op;
4190 end += 1;
4191 if opcode_at(insns, end) == Some(get_form_of(put_op))
4192 && insns[end]
4193 .as_ref()
4194 .is_some_and(|(_, operands)| operands.first() == Some(&Op::Slot(slot)))
4195 {
4196 new_op = set_form_of(put_op);
4197 end += 1;
4198 }
4199 }
4200 insns[index] = Some((new_op, vec![Op::Slot(slot)]));
4201 for entry in &mut insns[index + 1..end] {
4202 *entry = None;
4203 }
4204 }
4205}
4206
4207fn opcode_at(insns: &[Option<(Opcode, Vec<Op>)>], index: usize) -> Option<Opcode> {
4208 insns
4209 .get(index)
4210 .and_then(|entry| entry.as_ref())
4211 .map(|(op, _)| *op)
4212}
4213
4214/// The four `put_` families that have a `set_` twin. Deliberately not including
4215/// the global forms or `put_var_ref_check`: the reference's peephole lists exactly
4216/// these, and folding the others would produce instructions that do not exist.
4217fn is_foldable_put(op: Opcode) -> bool {
4218 matches!(
4219 op,
4220 Opcode::PutLoc | Opcode::PutLocCheck | Opcode::PutArg | Opcode::PutVarRef
4221 )
4222}
4223
4224fn set_form_of(op: Opcode) -> Opcode {
4225 match op {
4226 Opcode::PutLoc => Opcode::SetLoc,
4227 Opcode::PutLocCheck => Opcode::SetLocCheck,
4228 Opcode::PutArg => Opcode::SetArg,
4229 Opcode::PutVarRef => Opcode::SetVarRef,
4230 other => other,
4231 }
4232}
4233
4234fn get_form_of(op: Opcode) -> Opcode {
4235 match op {
4236 Opcode::PutLoc => Opcode::GetLoc,
4237 Opcode::PutLocCheck => Opcode::GetLocCheck,
4238 Opcode::PutArg => Opcode::GetArg,
4239 Opcode::PutVarRef => Opcode::GetVarRef,
4240 other => other,
4241 }
4242}
4243
4244/// Atom interning, per function.
4245///
4246/// Everything the reference interns goes through `JS_NewAtomStr`, including plain
4247/// identifiers, so the array-index rule applies here rather than at the handful of
4248/// call sites that build property keys.
4249fn intern_atom(state: &mut FnState, name: &str) -> u32 {
4250 let atom = Atom::from_text(name);
4251 if let Some(index) = state.atoms.iter().position(|a| *a == atom) {
4252 return index as u32;
4253 }
4254 state.atoms.push(atom);
4255 state.atoms.len() as u32 - 1
4256}
4257
4258fn binary_opcode(op: BinaryOp) -> Opcode {
4259 match op {
4260 BinaryOp::Add => Opcode::Add,
4261 BinaryOp::Sub => Opcode::Sub,
4262 BinaryOp::Mul => Opcode::Mul,
4263 BinaryOp::Div => Opcode::Div,
4264 BinaryOp::Mod => Opcode::Mod,
4265 BinaryOp::Pow => Opcode::Pow,
4266 BinaryOp::BitOr => Opcode::Or,
4267 BinaryOp::BitXor => Opcode::Xor,
4268 BinaryOp::BitAnd => Opcode::And,
4269 BinaryOp::Shl => Opcode::Shl,
4270 BinaryOp::Shr => Opcode::Sar,
4271 BinaryOp::UShr => Opcode::Shr,
4272 BinaryOp::Lt => Opcode::Lt,
4273 BinaryOp::LtEq => Opcode::Lte,
4274 BinaryOp::Gt => Opcode::Gt,
4275 BinaryOp::GtEq => Opcode::Gte,
4276 BinaryOp::Eq => Opcode::Eq,
4277 BinaryOp::NotEq => Opcode::Neq,
4278 BinaryOp::StrictEq => Opcode::StrictEq,
4279 BinaryOp::StrictNotEq => Opcode::StrictNeq,
4280 BinaryOp::In => Opcode::In,
4281 BinaryOp::Instanceof => Opcode::Instanceof,
4282 }
4283}
4284
4285fn compound_opcode(op: AssignOp) -> Opcode {
4286 match op {
4287 AssignOp::Add => Opcode::Add,
4288 AssignOp::Sub => Opcode::Sub,
4289 AssignOp::Mul => Opcode::Mul,
4290 AssignOp::Div => Opcode::Div,
4291 AssignOp::Mod => Opcode::Mod,
4292 AssignOp::Pow => Opcode::Pow,
4293 AssignOp::Shl => Opcode::Shl,
4294 AssignOp::Shr => Opcode::Sar,
4295 AssignOp::UShr => Opcode::Shr,
4296 AssignOp::BitOr => Opcode::Or,
4297 AssignOp::BitXor => Opcode::Xor,
4298 AssignOp::BitAnd => Opcode::And,
4299 AssignOp::Assign | AssignOp::And | AssignOp::Or | AssignOp::Coalesce => Opcode::Nop,
4300 }
4301}
4302
4303/// Encode the resolved instruction stream, choosing short forms where possible.
4304///
4305/// The peephole pass leaves holes in the instruction list so that label indices
4306/// stay valid. A label names an *instruction index*, and an index that was
4307/// deleted has to resolve to the next surviving instruction, which is what
4308/// [`resolve_label`] does before the byte offsets are known.
4309fn assemble(
4310 insns: &mut [Option<(Opcode, Vec<Op>)>],
4311 insn_pos: &[Option<Position>],
4312 state: &mut FnState,
4313) -> (Vec<u8>, u32, Vec<LineCol>) {
4314 // Compaction: surviving instructions in order, plus the index mapping.
4315 //
4316 // `spans` runs parallel to `kept` and is compacted in lock step with it, at every
4317 // point below where instructions are removed — otherwise a stack trace would point
4318 // at the wrong source line as soon as dead-code elimination kicked in.
4319 let mut kept: Vec<(Opcode, Vec<Op>)> = Vec::with_capacity(insns.len());
4320 let mut spans: Vec<Option<Position>> = Vec::with_capacity(insns.len());
4321 let mut original_to_kept: Vec<Option<usize>> = vec![None; insns.len()];
4322 for (original, entry) in insns.iter_mut().enumerate() {
4323 if let Some((op, operands)) = entry.take() {
4324 original_to_kept[original] = Some(kept.len());
4325 kept.push((op, operands));
4326 spans.push(insn_pos.get(original).copied().flatten());
4327 }
4328 }
4329
4330 if std::env::var_os("QJS_DEBUG").is_some() {
4331 eprintln!("--- assemble entry --- {kept:?}");
4332 }
4333 // How many labels are real, as opposed to the per-instruction ones allocated
4334 // just below. Only a real label marks a spot in the source program.
4335 let real_labels = state.labels.len();
4336
4337 // Give every surviving instruction a label of its own. Jump cleanup below
4338 // redirects jumps to arbitrary instructions, and a jump target has to be a
4339 // label; pre-allocating one per index means a redirect never has to invent
4340 // anything.
4341 let existing = state.labels.len();
4342 let base = kept.len();
4343 let mut index_label: Vec<Label> = Vec::with_capacity(kept.len() + 1);
4344 for offset in 0..=kept.len() {
4345 state.labels.push(Some(0));
4346 index_label.push(Label((existing + offset) as u32));
4347 }
4348 // Point each pre-allocated label at its instruction, reusing the count from
4349 // `original_to_kept` so the mapping survives compaction.
4350 let place_index_labels = |state: &mut FnState,
4351 original_to_kept: &[Option<usize>],
4352 kept_len: usize,
4353 index_label: &[Label]| {
4354 for (original, mapped) in original_to_kept.iter().enumerate() {
4355 if let Some(kept_index) = mapped {
4356 let label = index_label[*kept_index].0 as usize;
4357 state.labels[label] = Some(original);
4358 }
4359 }
4360 state.labels[index_label[kept_len].0 as usize] = Some(usize::MAX);
4361 };
4362 place_index_labels(state, &original_to_kept, base, &index_label);
4363
4364 // Resolve every label to a kept index once; the placement table maps labels
4365 // to original indices, so a second hop lands in kept space.
4366 let mut label_kept: Vec<Option<usize>> = vec![None; state.labels.len()];
4367 for (id, placed) in state.labels.iter().enumerate() {
4368 let Some(original) = placed else { continue };
4369 label_kept[id] = if *original == usize::MAX {
4370 Some(base)
4371 } else {
4372 (*original..original_to_kept.len()).find_map(|i| original_to_kept[i])
4373 };
4374 }
4375
4376 // Code after an unconditional transfer is unreachable, and the reference drops it
4377 // as it walks past the transfer — the `skip_dead_code` in its first pass. It
4378 // scans forward until it finds a label something still jumps to, so a run of
4379 // dead instructions between a `throw` and the next live target disappears.
4380 //
4381 // The scan repeats because dropping a jump lowers the reference count of the
4382 // label it pointed at, which can strand what follows. Only a real label keeps an
4383 // instruction alive here; the per-instruction labels allocated above belong to
4384 // this pass, not to the program.
4385 loop {
4386 let mut references = vec![false; kept.len() + 1];
4387 for (_, operands) in &kept {
4388 if let Some(target) = target_kept_index(operands, &label_kept)
4389 && target < references.len()
4390 {
4391 references[target] = true;
4392 }
4393 }
4394 let mut doomed = vec![false; kept.len()];
4395 let mut any = false;
4396 for (index, (op, _)) in kept.iter().enumerate() {
4397 if !is_transfer(*op) {
4398 continue;
4399 }
4400 for next in index + 1..kept.len() {
4401 if references[next] {
4402 break;
4403 }
4404 doomed[next] = true;
4405 any = true;
4406 }
4407 }
4408 if !any {
4409 break;
4410 }
4411 (kept, spans) = drop_instructions(kept, spans, &mut label_kept, &doomed);
4412 }
4413
4414 // A label that lands on an unconditional jump stands for wherever that jump
4415 // goes, so retarget it once and every jump to the label follows for free.
4416 // This is what makes `continue` in a `for` head reach the loop top instead of
4417 // stopping at the update's trailing jump.
4418 let folded: Vec<Option<usize>> = label_kept
4419 .iter()
4420 .map(|slot| slot.map(|target| follow_jump_chain(&kept, &label_kept, target)))
4421 .collect();
4422 label_kept = folded;
4423
4424 // Jump cleanup, in compacted index space. Two rewrites the reference also
4425 // applies while it resolves labels:
4426 // * a jump whose destination is the very next instruction does nothing;
4427 // * a jump to a jump is redirected to its final destination.
4428 // The second can expose the first, so this repeats until it settles.
4429 loop {
4430 let mut delete = vec![false; kept.len()];
4431 let mut changed = false;
4432 for index in 0..kept.len() {
4433 let (op, operands) = &kept[index];
4434 if !is_goto(*op) {
4435 continue;
4436 }
4437 let Some(immediate) = target_kept_index(operands, &label_kept) else {
4438 continue;
4439 };
4440 let target = follow_jump_chain(&kept, &label_kept, immediate);
4441 if target == index + 1 {
4442 delete[index] = true;
4443 changed = true;
4444 } else if matches!(
4445 kept.get(target).map(|(op, _)| *op),
4446 Some(Opcode::Return | Opcode::ReturnUndef | Opcode::Throw)
4447 ) {
4448 // Jumping straight to a return or throw is the same as doing it
4449 // here, so the jump becomes that instruction.
4450 kept[index] = (kept[target].0, Vec::new());
4451 changed = true;
4452 } else if target != immediate {
4453 // Redirect to the end of the chain.
4454 let label = index_label[target];
4455 kept[index].1 = vec![Op::Label(label)];
4456 changed = true;
4457 }
4458 }
4459 if !changed {
4460 break;
4461 }
4462 if !delete.iter().any(|deleted| *deleted) {
4463 break;
4464 }
4465 // Drop the deleted instructions and renumber everything.
4466 let mut next: Vec<(Opcode, Vec<Op>)> = Vec::with_capacity(kept.len());
4467 let mut next_spans: Vec<Option<Position>> = Vec::with_capacity(kept.len());
4468 let mut moved: Vec<Option<usize>> = vec![None; kept.len()];
4469 for (old, entry) in kept.into_iter().enumerate() {
4470 if delete[old] {
4471 continue;
4472 }
4473 moved[old] = Some(next.len());
4474 next.push(entry);
4475 next_spans.push(spans[old]);
4476 }
4477 for (id, slot) in label_kept.iter_mut().enumerate() {
4478 let Some(old) = *slot else { continue };
4479 *slot = match moved.get(old).copied().flatten() {
4480 Some(new) => Some(new),
4481 // The target was deleted: the jump now lands on whatever follows.
4482 None => (old..moved.len())
4483 .find_map(|i| moved[i])
4484 .or(Some(next.len())),
4485 };
4486 let _ = id;
4487 }
4488 kept = next;
4489 spans = next_spans;
4490 }
4491
4492 // The same walk at the end of the function: `try`/`catch`'s `goto end` becomes a
4493 // jump to the next instruction and is deleted, leaving the label at the end with
4494 // nothing pointing at it. If that also strands the last instruction, it goes
4495 // too — which is how a `try` whose body always returns ends on its `ret` rather
4496 // than an implicit `return_undef`.
4497 // Which instructions something still jumps to. Reading the surviving jumps is
4498 // what the reference's reference counts amount to: once a jump has been folded
4499 // away the label it named is unreferenced, even though the program still has a
4500 // label there.
4501 let mut references = vec![false; kept.len() + 1];
4502 let _ = real_labels;
4503 for (_, operands) in &kept {
4504 if let Some(target) = target_kept_index(operands, &label_kept)
4505 && target < references.len()
4506 {
4507 references[target] = true;
4508 }
4509 }
4510 let mut end = kept.len();
4511 while end > 0 {
4512 let last = end - 1;
4513 let reachable = references[last] || end < kept.len();
4514 if reachable {
4515 break;
4516 }
4517 let after_transfer = last
4518 .checked_sub(1)
4519 .map(|previous| {
4520 matches!(
4521 kept[previous].0,
4522 Opcode::Goto | Opcode::Return | Opcode::ReturnUndef | Opcode::Throw
4523 )
4524 })
4525 .unwrap_or(false);
4526 if !after_transfer {
4527 break;
4528 }
4529 end = last;
4530 }
4531 kept.truncate(end);
4532 spans.truncate(end);
4533
4534 // Choose an opcode for each instruction and its size, so label offsets can be
4535 // computed.
4536 let mut chosen = Vec::with_capacity(kept.len());
4537 let mut offsets = Vec::with_capacity(kept.len() + 1);
4538 let mut offset = 0usize;
4539 for (op, operands) in &kept {
4540 let op = choose_short_form(*op, operands);
4541 offsets.push(offset);
4542 chosen.push(op);
4543 offset += op.size() as usize;
4544 }
4545 offsets.push(offset);
4546
4547 let mut code = Vec::with_capacity(offset);
4548 for (position, (_, operands)) in kept.iter().enumerate() {
4549 let op = chosen[position];
4550 code.push(op as u8);
4551 let operands = retarget_labels(operands, &label_kept, kept.len());
4552 encode_operands(&mut code, op, &operands, offsets[position], &offsets);
4553 }
4554 let stack_size = compute_stack_size(&code);
4555 // Keep only the offsets where the position actually changes: a run of
4556 // instructions on one line is one table entry, and the runtime binary searches
4557 // the table for the frame's pc.
4558 let mut positions: Vec<LineCol> = Vec::new();
4559 let mut last: Option<Position> = None;
4560 for (index, span) in spans.iter().enumerate() {
4561 let Some(pos) = *span else { continue };
4562 if last == Some(pos) {
4563 continue;
4564 }
4565 last = Some(pos);
4566 positions.push(LineCol {
4567 pc: offsets[index] as u32,
4568 line: pos.line,
4569 column: pos.column,
4570 });
4571 }
4572 (code, stack_size, positions)
4573}
4574
4575/// Whether an instruction always transfers control away, so anything after it in the
4576/// same stream is unreachable.
4577fn is_transfer(op: Opcode) -> bool {
4578 matches!(
4579 op,
4580 Opcode::Goto
4581 | Opcode::Goto8
4582 | Opcode::Goto16
4583 | Opcode::Return
4584 | Opcode::ReturnUndef
4585 | Opcode::Throw
4586 | Opcode::ThrowError
4587 | Opcode::Ret
4588 )
4589}
4590
4591/// Remove the marked instructions and renumber the label table so it keeps pointing
4592/// at the same instructions. A label whose instruction went away moves to whatever
4593/// follows it, since a jump is never left with nowhere to land.
4594fn drop_instructions(
4595 kept: Vec<(Opcode, Vec<Op>)>,
4596 spans: Vec<Option<Position>>,
4597 label_kept: &mut [Option<usize>],
4598 doomed: &[bool],
4599) -> (Vec<PositionedInsn>, Vec<Option<Position>>) {
4600 let mut result: Vec<(Opcode, Vec<Op>)> = Vec::with_capacity(kept.len());
4601 let mut result_spans: Vec<Option<Position>> = Vec::with_capacity(kept.len());
4602 let mut moved: Vec<Option<usize>> = vec![None; kept.len()];
4603 for (old, entry) in kept.into_iter().enumerate() {
4604 if doomed.get(old).copied().unwrap_or(false) {
4605 continue;
4606 }
4607 moved[old] = Some(result.len());
4608 result.push(entry);
4609 result_spans.push(spans[old]);
4610 }
4611 for slot in label_kept.iter_mut() {
4612 let Some(old) = *slot else { continue };
4613 *slot = match moved.get(old).copied().flatten() {
4614 Some(new) => Some(new),
4615 None => (old..moved.len())
4616 .find_map(|i| moved[i])
4617 .or(Some(result.len())),
4618 };
4619 }
4620 (result, result_spans)
4621}
4622
4623fn is_goto(op: Opcode) -> bool {
4624 matches!(op, Opcode::Goto | Opcode::Goto8 | Opcode::Goto16)
4625}
4626
4627/// The kept index a jump operand points at.
4628fn target_kept_index(operands: &[Op], label_kept: &[Option<usize>]) -> Option<usize> {
4629 let id = label_id(operands)?;
4630 label_kept.get(id as usize).copied().flatten()
4631}
4632
4633/// Follow a chain of unconditional jumps to its first real destination.
4634fn follow_jump_chain(
4635 kept: &[(Opcode, Vec<Op>)],
4636 label_kept: &[Option<usize>],
4637 start: usize,
4638) -> usize {
4639 let mut current = start;
4640 // `for(;;)` jumps to itself, so the walk has to be bounded.
4641 for _ in 0..kept.len() {
4642 let Some((op, operands)) = kept.get(current) else {
4643 return current;
4644 };
4645 if !is_goto(*op) {
4646 return current;
4647 }
4648 let Some(next) = target_kept_index(operands, label_kept) else {
4649 return current;
4650 };
4651 if next == current {
4652 return current;
4653 }
4654 current = next;
4655 }
4656 current
4657}
4658
4659/// Rewrite label operands from label ids to kept instruction indices.
4660fn retarget_labels(operands: &[Op], label_kept: &[Option<usize>], kept_len: usize) -> Vec<Op> {
4661 operands
4662 .iter()
4663 .map(|operand| match operand {
4664 Op::Label(label) => {
4665 let target = label_kept
4666 .get(label.0 as usize)
4667 .copied()
4668 .flatten()
4669 .unwrap_or(kept_len);
4670 Op::Label(Label(target as u32))
4671 }
4672 other => other.clone(),
4673 })
4674 .collect()
4675}
4676
4677/// Encode the resolved instruction stream, choosing short forms where possible.
4678///
4679/// Compute the maximum value-stack depth by exploring the control-flow graph.
4680///
4681/// This is a breadth-first walk from the first instruction, tracking the stack
4682/// depth on entry to each instruction. Every instruction has at most two
4683/// successors (fall through, and a jump target), so a worklist over byte offsets
4684/// is enough. The reference does the same thing in `compute_stack_size`, which is
4685/// why the resulting numbers match exactly.
4686///
4687/// Instructions that pop a variable number of values (`call`, `array_from`, …)
4688/// encode that count in their operand, which is added to the static `n_pop`.
4689fn compute_stack_size(code: &[u8]) -> u32 {
4690 let mut depth_at = vec![u16::MAX; code.len()];
4691 // Each entry carries the enclosing `catch` levels, innermost last, because
4692 // `nip_catch` needs them: it rewinds the stack to just above the innermost catch
4693 // offset and forgets that level.
4694 let mut worklist: Vec<(usize, u32, Vec<u32>)> = vec![(0, 0, Vec::new())];
4695 let mut max_depth = 0u32;
4696
4697 while let Some((pc, depth, catch_levels)) = worklist.pop() {
4698 if pc >= code.len() {
4699 continue;
4700 }
4701 if depth_at[pc] != u16::MAX {
4702 continue;
4703 }
4704 force_depth(&mut depth_at, pc, depth);
4705
4706 let Some(op) = Opcode::from_u8(code[pc]) else {
4707 break;
4708 };
4709 let info = op.info();
4710 let next = pc + info.size as usize;
4711 if next > code.len() {
4712 break;
4713 }
4714 let mut n_pop = info.n_pop as u32;
4715 let mut n_push = info.n_push as u32;
4716 // Variable-length forms carry their count in the operand.
4717 match info.format {
4718 crate::opcode::OpFormat::Npop | crate::opcode::OpFormat::NpopU16 => {
4719 n_pop += read_u16(code, pc + 1) as u32;
4720 }
4721 crate::opcode::OpFormat::Npopx => {
4722 n_pop += op.specialised_index().unwrap_or(0).max(0) as u32;
4723 }
4724 _ => {}
4725 }
4726 // `put_loc`/`put_arg`/`put_var_ref` keep the value on the stack when they
4727 // are the `set_` variant; the table already records that, so nothing to
4728 // adjust here.
4729 let _ = &mut n_push;
4730
4731 // The depth before this instruction's own push, which is what a `catch`
4732 // records as its level.
4733 let depth_before = depth;
4734 let mut depth = depth.saturating_sub(n_pop) + n_push;
4735 let mut catch_levels = catch_levels;
4736 if op == Opcode::NipCatch {
4737 // Discard everything above the innermost catch offset, keeping the value
4738 // on top: the frame the code after this sees is the same shape it would
4739 // have had if the `try` were not there.
4740 if let Some(base) = catch_levels.pop() {
4741 depth = base + 1;
4742 }
4743 }
4744 max_depth = max_depth.max(depth);
4745
4746 // Successors.
4747 let target = jump_target_of(code, pc, op);
4748 match op {
4749 Opcode::Goto | Opcode::Goto8 | Opcode::Goto16 => {
4750 if let Some(target) = target {
4751 worklist.push((target, depth, catch_levels));
4752 }
4753 }
4754 Opcode::IfFalse | Opcode::IfFalse8 | Opcode::IfTrue | Opcode::IfTrue8 => {
4755 if let Some(target) = target {
4756 worklist.push((target, depth, catch_levels.clone()));
4757 }
4758 worklist.push((next, depth, catch_levels));
4759 }
4760 // A `catch` records an exception edge to the handler. The handler is
4761 // entered with the thrown value on top of the stack, in the slot the
4762 // catch offset occupies on the normal path — which is why the handler's
4763 // first instruction can `put_loc` the exception away, and why the depth
4764 // is the same on both paths.
4765 Opcode::Catch => {
4766 if let Some(target) = target {
4767 // The handler is protected by the *enclosing* catch, not by this
4768 // one: an error raised inside it is what the handler's own
4769 // `catch` catches.
4770 worklist.push((target, depth, catch_levels.clone()));
4771 }
4772 catch_levels.push(depth_before);
4773 worklist.push((next, depth, catch_levels));
4774 }
4775 // A `for`/`of` loop keeps its own catch offset, and `nip_catch` has to
4776 // rewind past it too. Its level sits one slot higher than a `catch`'s:
4777 // the iterator and next-method slots occupy the offset's place.
4778 Opcode::ForOfStart | Opcode::ForAwaitOfStart => {
4779 if let Some(target) = target {
4780 worklist.push((target, depth, catch_levels.clone()));
4781 }
4782 catch_levels.push(depth_before + 1);
4783 worklist.push((next, depth, catch_levels));
4784 }
4785 // `gosub` calls a subroutine with the return address on top. The opcode
4786 // table records no push for it — `ret` is what pops the slot — so the
4787 // extra one is added here, where the depth of the subroutine's first
4788 // instruction is being computed.
4789 Opcode::Gosub => {
4790 if let Some(target) = target {
4791 worklist.push((target, depth + 1, catch_levels.clone()));
4792 }
4793 worklist.push((next, depth, catch_levels));
4794 }
4795 // `ret` goes back to a `gosub`; nothing here follows it.
4796 Opcode::Ret
4797 | Opcode::Return
4798 | Opcode::ReturnUndef
4799 | Opcode::Throw
4800 | Opcode::ThrowError => {}
4801 _ => worklist.push((next, depth, catch_levels)),
4802 }
4803 }
4804 max_depth
4805}
4806
4807/// Record the stack depth on entry to `pc`, keeping the deeper value if the
4808/// instruction is reachable more than once.
4809fn force_depth(depth_at: &mut [u16], pc: usize, depth: u32) {
4810 let clamped = depth.min(u16::MAX as u32 - 1) as u16;
4811 if depth_at[pc] == u16::MAX || depth_at[pc] < clamped {
4812 depth_at[pc] = clamped;
4813 }
4814}
4815
4816fn read_u16(code: &[u8], at: usize) -> u16 {
4817 let mut value = 0u16;
4818 for i in 0..2 {
4819 value = (value << 8) | code.get(at + i).copied().unwrap_or(0) as u16;
4820 }
4821 value
4822}
4823
4824/// The absolute target of a jump instruction, if it has one.
4825fn jump_target_of(code: &[u8], pc: usize, op: Opcode) -> Option<usize> {
4826 let info = op.info();
4827 let position = pc + 1;
4828 match info.format {
4829 crate::opcode::OpFormat::Label8 => {
4830 let offset = *code.get(position)? as i8 as i64;
4831 Some((position as i64 + offset) as usize)
4832 }
4833 crate::opcode::OpFormat::Label16 => {
4834 let offset = read_u16(code, position) as i16 as i64;
4835 Some((position as i64 + offset) as usize)
4836 }
4837 crate::opcode::OpFormat::Label => {
4838 let mut offset = 0i32;
4839 for i in 0..4 {
4840 offset = (offset << 8) | *code.get(position + i).unwrap_or(&0) as i32;
4841 }
4842 Some((position as i64 + offset as i64) as usize)
4843 }
4844 _ => None,
4845 }
4846}
4847
4848fn choose_short_form(op: Opcode, operands: &[Op]) -> Opcode {
4849 use Opcode::*;
4850 match (op, operands.first()) {
4851 (PushI32, Some(Op::Int(value))) if (-1..=7).contains(value) => {
4852 op.short_form(*value as u32).unwrap_or(op)
4853 }
4854 (PushConst, Some(Op::Const(index))) if *index < 256 => Opcode::PushConst8,
4855 (Fclosure, Some(Op::Const(index))) if *index < 256 => Opcode::Fclosure8,
4856 (GetLoc | PutLoc | SetLoc, Some(Op::Slot(Slot::Loc(index))))
4857 | (GetArg | PutArg | SetArg, Some(Op::Slot(Slot::Arg(index))))
4858 | (GetVarRef | PutVarRef | SetVarRef, Some(Op::Slot(Slot::VarRef(index))))
4859 // A declared global is reached through its reference cell, so it shares
4860 // the `var_ref` encodings, short forms included.
4861 | (GetVarRef | PutVarRef | SetVarRef, Some(Op::Slot(Slot::GlobalDecl(index)))) => {
4862 op.short_form(*index).unwrap_or(op)
4863 }
4864 (Call, Some(Op::Int(count))) if (0..=3).contains(count) => {
4865 op.short_form(*count as u32).unwrap_or(op)
4866 }
4867 (IfFalse, _) => IfFalse8,
4868 (IfTrue, _) => IfTrue8,
4869 (Goto, _) => Goto8,
4870 _ => op,
4871 }
4872}
4873
4874fn encode_operands(
4875 code: &mut Vec<u8>,
4876 op: Opcode,
4877 operands: &[Op],
4878 position: usize,
4879 offsets: &[usize],
4880) {
4881 use crate::opcode::OpFormat::*;
4882 let info = op.info();
4883 let write_slot = |code: &mut Vec<u8>, slot: Slot| {
4884 let index = match slot {
4885 Slot::Arg(i)
4886 | Slot::Loc(i)
4887 | Slot::VarRef(i)
4888 | Slot::Global(i)
4889 | Slot::GlobalDecl(i) => i,
4890 };
4891 code.extend_from_slice(&(index as u16).to_be_bytes());
4892 };
4893 match info.format {
4894 None | NoneInt | NoneLoc | NoneArg | NoneVarRef | Npopx => {}
4895 U8 | Const8 => {
4896 if let Some(value) = operands.first().and_then(operand_uint) {
4897 code.push(value as u8);
4898 }
4899 }
4900 // The narrow slot forms (`inc_loc8` and friends) take a slot operand just
4901 // like their wide counterparts, only one byte wide.
4902 Loc8 => {
4903 if let Some(Op::Slot(slot)) = operands.first() {
4904 let index = match slot {
4905 Slot::Arg(i)
4906 | Slot::Loc(i)
4907 | Slot::VarRef(i)
4908 | Slot::Global(i)
4909 | Slot::GlobalDecl(i) => *i,
4910 };
4911 code.push(index as u8);
4912 }
4913 }
4914 I8 => {
4915 if let Some(value) = operands.first().and_then(operand_int) {
4916 code.push(value as i8 as u8);
4917 }
4918 }
4919 U16 | Npop => {
4920 if let Some(value) = operands.first().and_then(operand_int) {
4921 code.extend_from_slice(&(value as u16).to_be_bytes());
4922 }
4923 }
4924 I16 => {
4925 if let Some(value) = operands.first().and_then(operand_int) {
4926 code.extend_from_slice(&(value as i16 as u16).to_be_bytes());
4927 }
4928 }
4929 I32 => {
4930 if let Some(value) = operands.first().and_then(operand_int) {
4931 code.extend_from_slice(&value.to_be_bytes());
4932 }
4933 }
4934 U32 | Const => {
4935 if let Some(value) = operands.first().and_then(operand_uint) {
4936 code.extend_from_slice(&value.to_be_bytes());
4937 }
4938 }
4939 Loc | Arg | VarRef => {
4940 if let Some(Op::Slot(slot)) = operands.first() {
4941 write_slot(code, *slot);
4942 }
4943 }
4944 Atom | AtomU8 | AtomU16 | AtomLabelU8 | AtomLabelU16 => {
4945 if let Some(Op::AtomId(index)) = operands.first() {
4946 code.extend_from_slice(&index.to_be_bytes());
4947 }
4948 // The trailing immediate means different things per format, and the
4949 // atom forms that carry a *label* have to resolve it like any other
4950 // jump, so they cannot share the `U8`/`U16` arms above.
4951 match info.format {
4952 AtomU8 | AtomLabelU8 => {
4953 if let Some(value) = operands.get(1).and_then(operand_uint) {
4954 code.push(value as u8);
4955 }
4956 }
4957 AtomU16 | AtomLabelU16 => {
4958 if let Some(value) = operands.get(1).and_then(operand_uint) {
4959 code.extend_from_slice(&(value as u16).to_be_bytes());
4960 }
4961 }
4962 _ => {}
4963 }
4964 }
4965 NpopU16 => {
4966 for operand in operands.iter().take(2) {
4967 if let Some(value) = operand_uint(operand) {
4968 code.extend_from_slice(&(value as u16).to_be_bytes());
4969 }
4970 }
4971 }
4972 Label | Label8 | Label16 | LabelU16 => {
4973 if let Some(Op::Label(label)) = operands.first() {
4974 // Labels were already remapped to kept-instruction indices.
4975 let Some(&target) = offsets.get(label.0 as usize) else {
4976 debug_assert!(false, "label {} is past the end", label.0);
4977 return;
4978 };
4979 let relative = target as i64 - (position as i64 + 1);
4980 match info.format {
4981 Label8 => code.push(relative as i8 as u8),
4982 Label16 => code.extend_from_slice(&(relative as i16 as u16).to_be_bytes()),
4983 // `label_u16` stores the target followed by an unrelated u16.
4984 LabelU16 => {
4985 code.extend_from_slice(&(relative as i32).to_be_bytes());
4986 if let Some(value) = operands.get(1).and_then(operand_uint) {
4987 code.extend_from_slice(&(value as u16).to_be_bytes());
4988 }
4989 }
4990 _ => code.extend_from_slice(&(relative as i32).to_be_bytes()),
4991 }
4992 }
4993 }
4994 }
4995}
4996
4997fn operand_int(op: &Op) -> Option<i32> {
4998 match op {
4999 Op::Int(value) => Some(*value),
5000 _ => None,
5001 }
5002}
5003
5004fn operand_uint(op: &Op) -> Option<u32> {
5005 match op {
5006 Op::Const(value) | Op::AtomId(value) => Some(*value),
5007 Op::Int(value) => Some(*value as u32),
5008 _ => None,
5009 }
5010}
5011
5012/// Disassemble a compiled function.
5013pub fn disassemble(function: &CompiledFunction) -> String {
5014 disasm::disassemble_program(function)
5015}