quickjs-pure 0.14.0

Embeddable JavaScript engine written in pure Rust (QuickJS-compatible)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
//! The instruction stream the interpreter actually runs.
//!
//! Bytecode is a compact variable-length encoding, and decoding it costs a table
//! lookup, a width switch and a bounds check **per instruction**. At ten nanoseconds
//! per instruction that was a visible share of the budget, and it is work that never
//! changes its answer: a function's bytecode is immutable once compiled.
//!
//! So it is decoded once, into a fixed-width record. [`Insn`] is twenty bytes —
//! opcode, three operands, and the byte offset it came from — which is small enough
//! that a loop's whole body sits in a couple of cache lines, and it turns the
//! interpreter's `pc` into an index. The third operand exists for exactly one fusion
//! ([`Fused::LtLocImmJump`] needs a slot, a bound *and* a target); it is zero
//! everywhere else. Everything the old `decode` computed per
//! instruction is computed here instead:
//!
//! * operands are unpacked from their 1/2/4-byte big-endian fields;
//! * jump operands are resolved from the encoded relative offset to an **index** into
//!   this same array, so `goto` becomes an assignment rather than arithmetic;
//! * the byte offset is kept, because that is what a stack trace reports and what the
//!   line table is keyed by.
//!
//! This is not a peephole pass and not a superinstruction compiler: the instruction
//! sequence is exactly the reference's, one record per bytecode instruction, and the
//! 422-case disassembly diff still compares that bytecode byte for byte.

use js_compile::{OpFormat, Opcode};

/// One decoded instruction.
///
/// `a` and `b` are the two operands: a slot index, a constant-pool index, an atom, an
/// immediate — or, for a jump, the index of the target instruction.
#[derive(Clone, Copy, Debug)]
pub struct Insn {
    /// The opcode.
    pub op: Opcode,
    /// A fused form of this instruction **and the next few**, when they match a pattern
    /// worth collapsing. [`Fused::None`] means "run `op` as it is".
    ///
    /// The fused form is a shorthand for a sequence the bytecode still contains: the
    /// dispatcher runs one record and skips the rest, so the bytecode, the disassembly
    /// and every jump target are unchanged. This is the one optimisation that reduces
    /// the *number* of dispatches rather than their cost, which is why it is worth the
    /// extra pass.
    pub fused: Fused,
    /// First operand, or a jump target as an instruction index.
    pub a: u32,
    /// Second operand.
    pub b: u32,
    /// Third operand, used only by fusions that need a slot, an immediate **and** a jump
    /// target at once (currently [`Fused::LtLocImmJump`]).
    pub imm: u32,
    /// Where this instruction started in the bytecode, for stack traces and the line
    /// table. (`pc` is an index, and no longer answers that question.)
    pub offset: u32,
}

/// A fused instruction, and how many records it stands for.
///
/// Only shapes that cannot throw are fused, because `at` — the offset a stack trace
/// reports — names the *first* instruction of the group. A fused `x += 1` that raised
/// would blame the wrong column; a fused `x += 1` on integers cannot raise.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Fused {
    /// Not fused: run `Insn::op`.
    None,
    /// `x += k` for an integer `k`: `get_loc x; push k; add; put_loc x`.
    ///
    /// Four dispatches become one, and this is the most common four-instruction group
    /// in JavaScript — `i += 1`, `total += n`, every accumulator in every loop.
    AddImmLoc,
    /// `x += "literal"`: `get_loc x; push_atom_value atom; add; put_loc x`.
    ///
    /// The same group with a string constant instead of an integer, and it exists for one
    /// reason beyond dispatch: the reference's `OP_add_loc` hands the *variable's own*
    /// string to `JS_ConcatStringInPlace`, so `text += "abc"` in a loop grows one buffer
    /// instead of building a new string per iteration. Reproducing it needs the group
    /// fused, because only then is the variable's one handle the only handle — through
    /// `get_loc` alone it has already been cloned once.
    AddAtomLoc,
    /// `x += y`: `get_loc x; get_loc y; add; put_loc x`.
    ///
    /// The same, with the other operand also a local. `a` is `(x << 16) | y`, like
    /// [`Fused::LtLocArgJump`].
    AddLocLoc,
    /// `x += y` where `y` is an argument: `get_loc x; get_arg y; add; put_loc x`.
    ///
    /// Separate from [`Fused::AddLocLoc`] rather than a flag bit, because the two read
    /// different arrays and a bit would make every reader of the operand check it.
    AddArgLoc,
    /// `x++` and the value is dropped: `get_loc x; post_inc; put_loc x; drop`.
    PostIncLoc,
    /// `x = k`: `push k; put_loc x`.
    StoreImm,
    /// `if (!(x < arg)) goto target` — a loop's header: `get_loc x; get_arg arg; lt;
    /// if_false target`.
    ///
    /// The condition is the one instruction group that runs on *every* iteration of
    /// every loop, so collapsing it is worth the packed operands: `a` is
    /// `(x << 16) | arg`, `b` is the target instruction index.
    LtLocArgJump,
    /// `if (!(x < k)) goto target` — a loop header whose bound is a **literal**:
    /// `get_loc x; push k; lt; if_false target`.
    ///
    /// [`Fused::LtLocArgJump`] covers `for (var i = 0; i < n; i++)`, where the bound is a
    /// parameter. This covers `for (var i = 0; i < 1000; i++)`, where it is an immediate —
    /// measured as a 40% slowdown against the reference when it did not fuse at all, since
    /// the header is four dispatches on every iteration. `a` is the slot, `b` is the
    /// target instruction index, `imm` is the bound.
    LtLocImmJump,
}

impl Insn {
    /// How many bytecode instructions this record replaces.
    pub fn width(&self) -> usize {
        match self.fused {
            Fused::None => 1,
            Fused::AddImmLoc
            | Fused::AddAtomLoc
            | Fused::AddLocLoc
            | Fused::AddArgLoc
            | Fused::PostIncLoc
            | Fused::LtLocArgJump
            | Fused::LtLocImmJump => 4,
            Fused::StoreImm => 2,
        }
    }
}

/// Sentinal for "no instruction starts at this byte offset".
const UNMAPPED: u32 = u32::MAX;

/// Decode `code` into an instruction array.
///
/// A byte that is not a valid opcode stops the walk, and the instructions up to that
/// point are kept: running off the end of a function is a normal return, so the
/// truncation can never be reached by a well-formed program and it keeps a corrupted
/// blob from being a panic in the decoder.
pub fn predecode(code: &[u8]) -> Vec<Insn> {
    let mut insns = Vec::with_capacity(code.len() / 2 + 1);
    let mut offsets = Vec::with_capacity(code.len() + 1);
    let mut pc = 0;
    while pc < code.len() {
        let Some((op, a, b, next)) = decode(code, pc) else {
            break;
        };
        offsets.push(pc);
        insns.push(Insn {
            op,
            fused: Fused::None,
            imm: 0,
            a,
            b,
            offset: pc as u32,
        });
        pc = next;
    }
    // A label may point one past the last instruction — `break` at the end of a block
    // lands there — so the table has an entry for the end of the code, answering
    // `insns.len()`, which the interpreter reads as "past the end, return undefined".
    offsets.push(code.len());

    // Byte offset → instruction index, for resolving jumps.
    let mut index_of = vec![UNMAPPED; code.len() + 1];
    for (index, offset) in offsets.iter().enumerate() {
        index_of[*offset] = index as u32;
    }

    // Implicit operands, filled in so that a handler is a plain operand read rather than
    // a second `match` on the opcode. `get_loc0` means slot 0 whatever its operand byte
    // says, and `push_3` means the integer 3.
    for insn in &mut insns {
        if let Some(value) = implicit_operand(insn.op) {
            insn.a = value;
        }
    }

    for insn in &mut insns {
        let format = insn.op.info().format;
        if !format.is_label() {
            continue;
        }
        // Which operand holds the target depends on the encoding: the single-label
        // formats carry it in `a`, and the two that pair an atom or a value with a
        // label carry it after it.
        let target = match format {
            OpFormat::AtomLabelU8 | OpFormat::AtomLabelU16 => &mut insn.b,
            _ => &mut insn.a,
        };
        *target = resolve(&index_of, *target);
    }

    // Fusion runs **last**, because it reads resolved jump targets: `if_false` holds a
    // byte offset until the loop above turns it into an index, and a fusion that captured
    // the offset would jump to an instruction number equal to a byte count. That is
    // exactly the bug this ordering fixes — it made `dispatch:arith` answer `NaN`.
    fuse(&mut insns);
    insns
}

/// The operand an opcode encodes in its own number, or `None` if it has a real one.
///
/// `get_loc0`…`get_loc3`, `get_arg0`…`3`, `put_*`, `set_*`, `push_0`…`push_7` and
/// `push_minus1` all carry their operand in the opcode. Writing it into `a` at decode
/// time removes a `match` from the hot path of every local-variable access.
fn implicit_operand(op: Opcode) -> Option<u32> {
    use Opcode::*;
    Some(match op {
        GetLoc0 | PutLoc0 | SetLoc0 | GetArg0 | PutArg0 | SetArg0 | GetVarRef0 | PutVarRef0
        | SetVarRef0 => 0,
        GetLoc1 | PutLoc1 | SetLoc1 | GetArg1 | PutArg1 | SetArg1 | GetVarRef1 | PutVarRef1
        | SetVarRef1 => 1,
        GetLoc2 | PutLoc2 | SetLoc2 | GetArg2 | PutArg2 | SetArg2 | GetVarRef2 | PutVarRef2
        | SetVarRef2 => 2,
        GetLoc3 | PutLoc3 | SetLoc3 | GetArg3 | PutArg3 | SetArg3 | GetVarRef3 | PutVarRef3
        | SetVarRef3 => 3,
        PushMinus1 => u32::MAX,
        Push0 => 0,
        Push1 => 1,
        Push2 => 2,
        Push3 => 3,
        Push4 => 4,
        Push5 => 5,
        Push6 => 6,
        Push7 => 7,
        _ => return None,
    })
}

/// The integer a constant-pushing opcode pushes, for the fusions below.
fn pushed_int(op: Opcode, a: u32) -> Option<i32> {
    use Opcode::*;
    Some(match op {
        PushMinus1 => -1,
        Push0 => 0,
        Push1 => 1,
        Push2 => 2,
        Push3 => 3,
        Push4 => 4,
        Push5 => 5,
        Push6 => 6,
        Push7 => 7,
        PushI8 | PushI16 | PushI32 => a as i32,
        _ => return None,
    })
}

/// The local slot an opcode **reads**, when it is one of the `get_loc` family.
fn load_slot(op: Opcode, a: u32) -> Option<u32> {
    use Opcode::*;
    match op {
        GetLoc | GetLoc8 | GetLoc0 | GetLoc1 | GetLoc2 | GetLoc3 => Some(a),
        _ => None,
    }
}

/// The local slot an opcode **writes**, when it is one of the `put_loc` family.
///
/// Kept separate from [`load_slot`], and that separation is not cosmetic. A single
/// "local slot" helper accepted `get_loc` where the pattern meant `put_loc`, so
/// `push_0; get_loc0` fused into "store 0 into slot 0": it dropped the pushed argument
/// *and* overwrote the local. `str.slice(0, p)` then called `p`, which is a **wrong
/// answer** rather than a crash — and the compiler, the unit tests and the bytecode diff
/// were all blind to it. Only the differential suite against the reference caught it.
fn store_slot(op: Opcode, a: u32) -> Option<u32> {
    use Opcode::*;
    match op {
        PutLoc | PutLoc8 | PutLoc0 | PutLoc1 | PutLoc2 | PutLoc3 => Some(a),
        _ => None,
    }
}

/// Collapse the hot instruction groups.
///
/// Each pattern is matched over consecutive records, the *same* slot on both ends, and
/// only where nothing in the group can throw. The jump-target resolution above is done
/// before this runs, and the jump-target *resolution table* is untouched: a fused
/// record still starts at its first instruction's offset, so a jump into the middle of
/// a group is impossible — the compiler never emits one, and if it did, the record is
/// consumed from its start either way.
fn fuse(insns: &mut [Insn]) {
    let mut index = 0;
    while index < insns.len() {
        let width = fused_at(&insns[index..]);
        match width {
            Some((fused, a, b, imm, span)) => {
                let insn = &mut insns[index];
                insn.fused = fused;
                insn.a = a;
                insn.b = b;
                insn.imm = imm;
                index += span;
            }
            None => index += 1,
        }
    }
}

/// The argument slot an opcode reads, when it is one of the `get_arg` family.
fn arg_slot(op: Opcode, a: u32) -> Option<u32> {
    use Opcode::*;
    match op {
        GetArg | GetArg0 | GetArg1 | GetArg2 | GetArg3 => Some(a),
        _ => None,
    }
}

/// The target of an `if_false`, when that is what `insn` is.
///
/// Its operand is already an instruction index — the label-resolution pass above ran
/// first — so this is a read, not a conversion.
fn false_branch_target(insn: &Insn) -> Option<u32> {
    use Opcode::*;
    match insn.op {
        IfFalse | IfFalse8 => Some(insn.a),
        _ => None,
    }
}

/// The fusion starting at `rest[0]`, as `(kind, operand a, operand b, span)`.
fn fused_at(rest: &[Insn]) -> Option<(Fused, u32, u32, u32, usize)> {
    // `x = k`: `push k; put_loc x`.
    if let Some(value) = pushed_int(rest[0].op, rest[0].a)
        && let Some(store) = rest.get(1)
        && let Some(slot) = store_slot(store.op, store.a)
    {
        return Some((Fused::StoreImm, slot, value as u32, 0, 2));
    }
    // The rest start from a read of the same local they write.
    let slot = load_slot(rest[0].op, rest[0].a)?;
    // `x += k`: `get_loc x; push k; add; put_loc x`.
    if let Some(value) = rest.get(1).and_then(|insn| pushed_int(insn.op, insn.a))
        && let (Some(add), Some(store)) = (rest.get(2), rest.get(3))
        && add.op == Opcode::Add
        && store_slot(store.op, store.a) == Some(slot)
    {
        return Some((Fused::AddImmLoc, slot, value as u32, 0, 4));
    }
    // `x += "literal"`: `get_loc x; push_atom_value atom; add; put_loc x`.
    if let (Some(pushed), Some(add), Some(store)) = (rest.get(1), rest.get(2), rest.get(3))
        && pushed.op == Opcode::PushAtomValue
        && add.op == Opcode::Add
        && store_slot(store.op, store.a) == Some(slot)
    {
        return Some((Fused::AddAtomLoc, slot, pushed.a, 0, 4));
    }
    // `x += y`: `get_loc x; get_loc y; add; put_loc x`.
    if let (Some(second), Some(add), Some(store)) = (rest.get(1), rest.get(2), rest.get(3))
        && let Some(source) = load_slot(second.op, second.a)
        && add.op == Opcode::Add
        && store_slot(store.op, store.a) == Some(slot)
        && slot < 0x10000
        && source < 0x10000
    {
        return Some((Fused::AddLocLoc, (slot << 16) | source, 0, 0, 4));
    }
    // `x += y` where `y` is an argument: `get_loc x; get_arg y; add; put_loc x`.
    if let (Some(second), Some(add), Some(store)) = (rest.get(1), rest.get(2), rest.get(3))
        && let Some(source) = arg_slot(second.op, second.a)
        && add.op == Opcode::Add
        && store_slot(store.op, store.a) == Some(slot)
        && slot < 0x10000
        && source < 0x10000
    {
        return Some((Fused::AddArgLoc, (slot << 16) | source, 0, 0, 4));
    }
    // A loop header: `get_loc x; get_arg arg; lt; if_false target`. Both slots have to
    // fit in 16 bits, which the `Loc`/`Arg` encodings guarantee — and a slot beyond that
    // simply does not fuse.
    if let (Some(second), Some(cmp), Some(branch)) = (rest.get(1), rest.get(2), rest.get(3))
        && let Some(arg) = arg_slot(second.op, second.a)
        && cmp.op == Opcode::Lt
        && let Some(target) = false_branch_target(branch)
        && slot < 0x10000
        && arg < 0x10000
    {
        return Some((Fused::LtLocArgJump, (slot << 16) | arg, target, 0, 4));
    }
    // A loop header whose bound is an integer literal: `get_loc x; push k; lt;
    // if_false target`. Same shape as `LtLocArgJump`, but the second operand is a
    // constant instead of an argument, so the bound goes in `imm` and `a` carries only
    // the slot.
    if let (Some(bound), Some(cmp), Some(branch)) = (rest.get(1), rest.get(2), rest.get(3))
        && let Some(imm) = pushed_int(bound.op, bound.a)
        && cmp.op == Opcode::Lt
        && let Some(target) = false_branch_target(branch)
        && slot < 0x10000
    {
        return Some((Fused::LtLocImmJump, slot, target, imm as u32, 4));
    }
    // `x++` as a statement: `get_loc x; post_inc; put_loc x; drop`.
    if let (Some(inc), Some(store), Some(drop)) = (rest.get(1), rest.get(2), rest.get(3))
        && inc.op == Opcode::PostInc
        && store_slot(store.op, store.a) == Some(slot)
        && drop.op == Opcode::Drop
    {
        return Some((Fused::PostIncLoc, slot, 0, 0, 4));
    }
    None
}

/// Map a byte offset to an instruction index.
///
/// An offset with no instruction at it keeps its old meaning — "past the end of the
/// code" — as the index of the end. Anything else would be a jump into the middle of
/// an instruction, which the compiler cannot emit; it is treated as the end so that a
/// corrupted stream stops rather than reading nonsense, and `pc >= insns.len()` then
/// reports a normal return.
fn resolve(index_of: &[u32], offset: u32) -> u32 {
    match index_of.get(offset as usize) {
        Some(&index) if index != UNMAPPED => index,
        // The last entry is the end-of-code marker, so this is `insns.len()`.
        _ => index_of.last().copied().unwrap_or(0),
    }
}

/// Decode the instruction at `pc` into `(opcode, operand a, operand b, next pc)`.
///
/// Jump operands are resolved to absolute byte offsets here, because the encoding
/// stores them relative to the byte after the opcode and every use site would
/// otherwise repeat that arithmetic.
///
/// Only [`predecode`] calls this now; the interpreter works from [`Insn`] and never
/// looks at the bytes.
fn decode(code: &[u8], pc: usize) -> Option<(Opcode, u32, u32, usize)> {
    let op = Opcode::from_u8(*code.get(pc)?)?;
    let info = op.info();
    let base = pc + 1;
    let read_u8 = |offset: usize| -> u32 { code.get(base + offset).copied().unwrap_or(0) as u32 };
    let read_u16 = |offset: usize| -> u32 {
        let mut value = 0u32;
        for index in 0..2 {
            value = (value << 8) | code.get(base + offset + index).copied().unwrap_or(0) as u32;
        }
        value
    };
    let read_u32 = |offset: usize| -> u32 {
        let mut value = 0u32;
        for index in 0..4 {
            value = (value << 8) | code.get(base + offset + index).copied().unwrap_or(0) as u32;
        }
        value
    };
    let jump = |offset: usize, width: usize| -> u32 {
        let raw = match width {
            1 => read_u8(offset) as u8 as i8 as i64,
            2 => read_u16(offset) as u16 as i16 as i64,
            _ => read_u32(offset) as i32 as i64,
        };
        (base as i64 + raw) as u32
    };
    let (a, b) = match info.format {
        OpFormat::None
        | OpFormat::NoneInt
        | OpFormat::NoneLoc
        | OpFormat::NoneArg
        | OpFormat::NoneVarRef
        | OpFormat::Npopx => (0, 0),
        OpFormat::U8 | OpFormat::Loc8 | OpFormat::Const8 => (read_u8(0), 0),
        OpFormat::I8 => (read_u8(0) as u8 as i8 as i32 as u32, 0),
        OpFormat::Label8 => (jump(0, 1), 0),
        OpFormat::U16 | OpFormat::Npop | OpFormat::Loc | OpFormat::Arg | OpFormat::VarRef => {
            (read_u16(0), 0)
        }
        OpFormat::I16 => (read_u16(0) as u16 as i16 as i32 as u32, 0),
        OpFormat::Label16 => (jump(0, 2), 0),
        OpFormat::NpopU16 => (read_u16(0), read_u16(2)),
        OpFormat::U32 | OpFormat::Const | OpFormat::Atom => (read_u32(0), 0),
        OpFormat::I32 | OpFormat::Label => (
            if info.format == OpFormat::Label {
                jump(0, 4)
            } else {
                read_u32(0) as i32 as u32
            },
            0,
        ),
        // `atom_u8` / `atom_u16` pair an atom with a small value, and the two
        // `atom_label` formats pair an atom with a **label** — the layout is atom, then
        // label, then the value (see the reference's `OP_FMT_atom_label_u8`). The old
        // decoder read the label's first bytes as if they were the value, which was
        // unobservable only because no opcode with these formats is implemented yet:
        // they are `with_get_var` and friends, plus `scope_make_ref`.
        OpFormat::AtomU8 => (read_u32(0), read_u8(4)),
        OpFormat::AtomU16 | OpFormat::LabelU16 => (read_u32(0), read_u16(4)),
        OpFormat::AtomLabelU8 => (read_u32(0), jump(4, 4)),
        OpFormat::AtomLabelU16 => (read_u32(0), jump(4, 4)),
    };
    Some((op, a, b, pc + info.size as usize))
}

#[cfg(test)]
mod tests {
    use super::*;

    /// A hand-assembled `goto8` over a `push_1`.
    ///
    /// `goto8 <label>` is two bytes; the label is relative to the byte after the
    /// instruction. `push_1` is one byte. So jumping to the instruction after
    /// `push_1` from offset 0 means an offset of 1.
    #[test]
    fn a_jump_operand_becomes_an_index() {
        let goto8 = Opcode::Goto8 as u8;
        let push1 = Opcode::Push1 as u8;
        let code = [goto8, 1, push1];
        let insns = predecode(&code);
        assert_eq!(insns.len(), 2);
        assert_eq!(insns[0].op, Opcode::Goto8);
        assert_eq!(insns[0].a, 1, "the jump target is the second instruction");
        assert_eq!(insns[0].offset, 0);
        assert_eq!(insns[1].op, Opcode::Push1);
        assert_eq!(insns[1].offset, 2);
    }

    /// A jump past the last instruction lands on the end index, which the interpreter
    /// reads as "return undefined" — that is what `break` at the end of a block emits.
    ///
    /// `goto8` at offset 0 is two bytes long and its offset is relative to the byte
    /// after it, so `1` names byte 2, which is the end of the code.
    #[test]
    fn a_jump_past_the_end_lands_on_the_end() {
        let code = [Opcode::Goto8 as u8, 1];
        let insns = predecode(&code);
        assert_eq!(insns.len(), 1);
        assert_eq!(insns[0].a as usize, insns.len());
    }

    /// A backward jump resolves to the instruction it names, which is how a loop closes.
    #[test]
    fn a_backward_jump_resolves() {
        // `push_1` then `goto8 -2`: the instruction starts at byte 1, its offset is
        // relative to byte 2, so `-2` names byte 0.
        let code = [Opcode::Push1 as u8, Opcode::Goto8 as u8, 0xFE];
        let insns = predecode(&code);
        assert_eq!(insns.len(), 2);
        assert_eq!(insns[1].op, Opcode::Goto8);
        assert_eq!(insns[1].a, 0);
    }

    /// An operand that is not a jump keeps its value, so a slot index is not mistaken
    /// for a target.
    #[test]
    fn a_plain_operand_is_untouched() {
        let code = [Opcode::GetLoc8 as u8, 7, Opcode::Push1 as u8];
        let insns = predecode(&code);
        assert_eq!(insns[0].a, 7);
    }

    /// Truncated or corrupt bytecode stops the walk instead of panicking.
    #[test]
    fn an_unknown_opcode_ends_the_array() {
        let code = [Opcode::Push1 as u8, 0xFF, Opcode::Push1 as u8];
        let insns = predecode(&code);
        assert_eq!(insns.len(), 1);
        assert_eq!(insns[0].op, Opcode::Push1);
    }

    /// Decode the first function in `source` and hand back its records.
    ///
    /// Compiling rather than hand-assembling means the patterns under test are the ones
    /// the real compiler emits, not the ones this file imagines it emits.
    fn compiled(source: &str) -> Vec<Insn> {
        let program = js_parse::parse_script(source).expect("parses");
        let code = js_compile::compile_script(&program).expect("compiles");
        let js_compile::bytecode::Constant::Function(first) = &code.cpool[0] else {
            panic!("the script's first constant is the function");
        };
        predecode(&first.code)
    }

    /// The three fusions a counting loop is made of, all at once.
    #[test]
    fn a_counting_loop_fuses_its_header_body_and_increment() {
        let insns =
            compiled("function f(n){ var t = 0; for (var i = 0; i < n; i++) t += 1; return t }");
        let fused: Vec<Fused> = insns
            .iter()
            .filter(|insn| insn.fused != Fused::None)
            .map(|insn| insn.fused)
            .collect();
        assert_eq!(
            fused,
            vec![
                Fused::StoreImm,
                Fused::StoreImm,
                Fused::LtLocArgJump,
                Fused::AddImmLoc,
                Fused::PostIncLoc
            ],
            "header, body and increment each collapse into one dispatch"
        );
    }

    /// A counting loop whose bound is a **literal** fuses its header too.
    ///
    /// This is the shape `for (var i = 0; i < 60000000; i++)` compiles to, and it used to
    /// fuse nothing at the header: `LtLocArgJump` only matches a bound that is an
    /// argument. Measured on `huge.js`, that difference alone was 2.72 s against 1.16 s.
    #[test]
    fn a_loop_header_with_a_literal_bound_fuses() {
        let insns = compiled(
            "function f(){ var t = 0; for (var i = 0; i < 60000000; i++) t += 1; return t }",
        );
        let header = insns
            .iter()
            .find(|insn| insn.fused == Fused::LtLocImmJump)
            .expect("`get_loc; push_i32; lt; if_false` fuses with a literal bound");
        assert_eq!(header.a, 1, "the counter's slot");
        assert_eq!(header.imm, 60_000_000, "the bound, kept in `imm`");
        assert_eq!(header.width(), 4, "four dispatches become one");
    }

    /// A small literal bound fuses the same way, and `imm` still carries it.
    #[test]
    fn a_loop_header_with_a_small_literal_bound_fuses() {
        let insns =
            compiled("function f(){ var t = 0; for (var i = 0; i < 7; i++) t += 1; return t }");
        let header = insns
            .iter()
            .find(|insn| insn.fused == Fused::LtLocImmJump)
            .expect("`push_7` counts as an integer literal");
        assert_eq!(header.imm, 7);
    }

    /// A store fusion must name the slot the `put_loc` named, and the value the `push`
    /// pushed.
    #[test]
    fn a_store_keeps_its_slot_and_value() {
        // Hand-assembled so the operand is unambiguous: `push_7; put_loc0` is two bytes,
        // and the trailing `push_1` proves the fusion stopped where the pattern ended.
        let insns = predecode(&[
            Opcode::Push7 as u8,
            Opcode::PutLoc0 as u8,
            Opcode::Push1 as u8,
        ]);
        let store = insns
            .iter()
            .find(|insn| insn.fused == Fused::StoreImm)
            .expect("`push_7; put_loc0` fuses");
        assert_eq!(insns.len(), 3, "the third instruction keeps its own record");
        assert_eq!(store.a, 0, "slot of the local");
        assert_eq!(store.b, 7, "the pushed integer");
        assert_eq!(store.width(), 2);
    }

    /// `t += "abc"` and `s += t` fuse, and carry the operands the append needs.
    #[test]
    fn an_append_into_a_local_fuses() {
        let atom = compiled(
            r#"function f(n){ var t = ""; for (var i = 0; i < n; i++) t += "abc"; return t.length }"#,
        );
        let fused = atom
            .iter()
            .find(|insn| insn.fused == Fused::AddAtomLoc)
            .expect("`get_loc; push_atom_value; add; put_loc` fuses");
        assert_eq!(fused.a, 0, "the slot being appended to");
        assert_eq!(fused.width(), 4);

        let local = compiled(
            "function f(n){ var t = '', c = 'x'; for (var i = 0; i < n; i++) t += c; return t.length }",
        );
        let fused = local
            .iter()
            .find(|insn| insn.fused == Fused::AddLocLoc)
            .expect("`get_loc; get_loc; add; put_loc` fuses");
        assert_eq!(fused.a >> 16, 0, "the slot being appended to");

        // An argument on the right is a different read and a different fusion: `t += a`
        // appears in every `join`-style loop and reads `args`, not `locals`.
        let arg = compiled(
            "function f(n, a){ var t = ''; for (var i = 0; i < n; i++) t += a; return t.length }",
        );
        let fused = arg
            .iter()
            .find(|insn| insn.fused == Fused::AddArgLoc)
            .expect("`get_loc; get_arg; add; put_loc` fuses");
        assert_eq!(fused.a >> 16, 0, "the slot being appended to");
        assert_eq!(fused.a & 0xFFFF, 1, "`a` is the second argument");
    }

    /// `push k; get_loc x` is **not** a store.
    ///
    /// An earlier version asked one helper for "the local slot" without saying whether it
    /// was being read or written, so this sequence — a pushed argument followed by a read,
    /// as in `str.slice(0, p)` — fused into "store 0 into slot 0". The pushed argument was
    /// dropped and the local was clobbered: a wrong answer, invisible to the compiler, the
    /// unit tests and the bytecode diff. Only the differential suite caught it.
    #[test]
    fn a_push_followed_by_a_read_does_not_fuse() {
        let insns = compiled("function f(p, str){ return str.slice(0, p) }");
        for insn in &insns {
            assert_ne!(
                insn.fused,
                Fused::StoreImm,
                "`push; get_loc` must not become a store"
            );
        }
        assert!(
            insns.iter().any(|insn| insn.op == Opcode::GetArg0),
            "the read of `p` is still its own instruction"
        );
    }

    /// `x += 1` fuses only when the read and the write name the same local.
    #[test]
    fn an_add_needs_the_same_slot_on_both_ends() {
        let same = compiled("function f(n){ var t = 0; t += n; return t }");
        assert!(
            same.iter().all(|insn| insn.fused != Fused::AddImmLoc),
            "`t += n` pushes an argument, not an immediate"
        );
        let different = compiled("function f(){ var t = 0, k = 0; t = k + 1; return t }");
        assert!(
            different.iter().all(|insn| insn.fused != Fused::AddImmLoc),
            "`t = k + 1` reads `k` and writes `t`"
        );
    }

    /// A loop header's packed operands survive: the local, the argument, and the target
    /// as an instruction index — not as the byte offset the encoding stores.
    #[test]
    fn a_loop_header_carries_a_resolved_target() {
        let insns =
            compiled("function f(n){ var t = 0; for (var i = 0; i < n; i++) t += 1; return t }");
        let header = insns
            .iter()
            .find(|insn| insn.fused == Fused::LtLocArgJump)
            .expect("the loop header fuses");
        let local = header.a >> 16;
        let arg = header.a & 0xFFFF;
        assert_eq!(local, 1, "`i` is local slot 1");
        assert_eq!(arg, 0, "`n` is argument slot 0");
        let target = header.b as usize;
        assert!(
            target < insns.len(),
            "the target is an index into this array"
        );
        assert_eq!(
            insns[target].op,
            Opcode::GetLoc0,
            "the target is `return t`, the first instruction after the loop"
        );
    }

    /// Fusion leaves the record array alone: same length, same offsets, and each fused
    /// record still names the byte its first instruction came from. That is what keeps a
    /// stack trace and the line table pointing at the right place.
    #[test]
    fn fusion_keeps_offsets_and_count() {
        let unfused: Vec<u32> =
            compiled("function f(n){ var t = 0; for (var i = 0; i < n; i++) t += 1; return t }")
                .iter()
                .map(|insn| insn.offset)
                .collect();
        let insns =
            compiled("function f(n){ var t = 0; for (var i = 0; i < n; i++) t += 1; return t }");
        assert_eq!(
            insns.iter().map(|insn| insn.offset).collect::<Vec<_>>(),
            unfused,
            "fusion must not renumber or drop records"
        );
        for pair in insns.windows(2) {
            assert!(
                pair[0].offset < pair[1].offset,
                "offsets stay in byte order"
            );
        }
        for (index, insn) in insns.iter().enumerate() {
            assert!(
                index + insn.width() <= insns.len(),
                "a fused record's span stays inside the array"
            );
        }
    }

    /// Every opcode's record says where its bytes started, which is what a stack trace
    /// and the line table read.
    #[test]
    fn offsets_walk_the_encodings() {
        let code = [Opcode::Push1 as u8, Opcode::Push2 as u8, Opcode::Drop as u8];
        let insns = predecode(&code);
        assert_eq!(
            insns.iter().map(|insn| insn.offset).collect::<Vec<_>>(),
            vec![0, 1, 2]
        );
    }
}