quickjs-compile 0.11.0

Bytecode compiler for the pure-Rust QuickJS port
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
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
//! Differential test: our disassembly against the reference compiler's.
//!
//! The oracle is a QuickJS build with `-DDUMP_BYTECODE=1`, which prints each
//! function's bytecode through `js_dump_function_bytecode`. Comparing that text
//! with ours is the strongest check available before a VM exists: it pins down
//! instruction choice, operand encoding, slot numbering, scope chains, stack
//! size and jump targets all at once.
//!
//! Build the oracle with `scripts/setup-oracle.sh` (it produces
//! `/tmp/quickjs-master/qjsc-dump`).

use js_compile::{compile_script, disassemble};
use js_parse::parse_script;
use quickjs_conformance::locate_disassembler;
use std::path::PathBuf;

fn oracle() -> Option<PathBuf> {
    locate_disassembler()
}

macro_rules! require_oracle {
    () => {
        match oracle() {
            Some(path) => path,
            None => {
                eprintln!("skipping: no disassembling qjsc found (run scripts/setup-oracle.sh)");
                return;
            }
        }
    };
}

struct Scratch(PathBuf);

impl Scratch {
    fn new(tag: &str) -> Scratch {
        // A per-call counter, because a thread id can be reused and two tests
        // started at once would otherwise share a directory.
        static COUNTER: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
        let sequence = COUNTER.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
        let mut path = std::env::temp_dir();
        path.push(format!(
            "quickjs-rs-compile-{tag}-{}-{sequence}",
            std::process::id()
        ));
        std::fs::create_dir_all(&path).expect("scratch dir");
        Scratch(path)
    }

    fn file(&self, name: &str, contents: &str) -> PathBuf {
        let path = self.0.join(name);
        std::fs::write(&path, contents).expect("write case");
        path
    }
}

impl Drop for Scratch {
    fn drop(&mut self) {
        let _ = std::fs::remove_dir_all(&self.0);
    }
}

/// Run the reference compiler and return its disassembly, or `None` if the
/// program does not parse there.
fn reference_disassembly(oracle: &PathBuf, scratch: &Scratch, source: &str) -> Option<String> {
    let file = scratch.file("case.js", source);
    let output = std::process::Command::new(oracle)
        .arg("-c")
        .arg("-o")
        .arg(scratch.0.join("out.c"))
        .arg(&file)
        .output()
        .expect("run reference compiler");
    if !output.status.success() {
        return None;
    }
    Some(String::from_utf8_lossy(&output.stdout).into_owned())
}

/// The disassembly with the file-name prefix stripped, so the comparison does
/// not depend on where the temporary file lives.
fn normalise(text: &str, path: &str) -> String {
    text.replace(path, "<file>")
}

/// Our disassembly, with the same file-name prefix the reference prints.
fn ours(source: &str, path: &str) -> Result<String, String> {
    let program = parse_script(source).map_err(|e| e.to_string())?;
    let mut function = compile_script(&program).map_err(|e| e.to_string())?;
    // Every function carries the file name in the reference's dump, nested ones
    // included.
    set_filename(&mut function, "<file>");
    let _ = path;
    Ok(disassemble(&function))
}

/// Stamp every function in the tree with a filename.
fn set_filename(function: &mut js_compile::Function, name: &str) {
    function.filename = Some(name.to_string());
    for constant in &mut function.cpool {
        if let js_compile::bytecode::Constant::Function(inner) = constant {
            set_filename(inner, name);
        }
    }
}

fn compare(cases: &[&str]) -> (Vec<String>, usize) {
    let Some(oracle) = oracle() else {
        return (Vec::new(), 0);
    };
    let scratch = Scratch::new("diff");
    let mut failures = Vec::new();
    let mut compared = 0;
    for source in cases {
        let Some(reference) = reference_disassembly(&oracle, &scratch, source) else {
            // The reference refuses to compile it, so there is no bytecode to compare.
            // That used to be a silent `continue`, which meant "do we also refuse it?"
            // was never asked — a case could flip from rejected to accepted by us and the
            // suite would stay green. Three cases sit on this path (`[1,...,,]`,
            // `continue` to a non-iteration label, `??` mixed with `||`); all three are
            // early errors we also reject. Check that, so the skip is a test and not a
            // hole.
            let path = scratch.0.join("case.js");
            let path = path.to_str().expect("utf-8 path");
            if ours(source, path).is_ok() {
                failures.push(format!(
                    "  {source:?}\n    the reference rejects this, but we compile it"
                ));
            }
            continue;
        };
        let path = scratch.0.join("case.js");
        let path = path.to_str().expect("utf-8 path");
        let reference = normalise(&reference, path);
        compared += 1;
        match ours(source, path) {
            Err(err) => failures.push(format!("  {source:?}\n    we failed: {err}")),
            Ok(actual) => {
                if actual != reference {
                    failures.push(format!("  {source:?}\n{}", diff(&reference, &actual)));
                }
            }
        }
    }
    (failures, compared)
}

/// A side-by-side diff, so a failure names the instruction that differs.
fn diff(expected: &str, actual: &str) -> String {
    let expected_lines: Vec<&str> = expected.lines().collect();
    let actual_lines: Vec<&str> = actual.lines().collect();
    let mut out = String::from("    reference                              | ours\n");
    let mut shown = 0;
    for index in 0..expected_lines.len().max(actual_lines.len()) {
        let e = expected_lines.get(index).copied().unwrap_or("<missing>");
        let a = actual_lines.get(index).copied().unwrap_or("<missing>");
        if e == a {
            if shown > 0 && index + 1 < expected_lines.len().max(actual_lines.len()) {
                // Keep a little context after a difference.
                out.push_str(&format!("    {e:<38} | {a}\n"));
                shown += 1;
            }
            continue;
        }
        out.push_str(&format!("  > {e:<38} | {a}\n"));
        shown += 1;
        if shown > 12 {
            out.push_str("    …\n");
            break;
        }
    }
    out
}

#[test]
fn literals_match_the_reference() {
    require_oracle!();
    let cases = [
        "1;",
        "0;",
        "-1;",
        "7;",
        "8;",
        "100;",
        "-128;",
        "127;",
        "1000;",
        "1000000;",
        "1.5;",
        "0.1;",
        "true;",
        "false;",
        "null;",
        "\"s\";",
        "\"\";",
        "\"two words\";",
        "undefined;",
    ];
    assert_cases("literals_match_the_reference", &cases);
}

#[test]
fn operators_match_the_reference() {
    require_oracle!();
    let cases = [
        "a + b;",
        "a - b;",
        "a * b;",
        "a / b;",
        "a % b;",
        "a ** b;",
        "a << b;",
        "a >> b;",
        "a >>> b;",
        "a & b;",
        "a | b;",
        "a ^ b;",
        "a < b;",
        "a <= b;",
        "a > b;",
        "a >= b;",
        "a == b;",
        "a != b;",
        "a === b;",
        "a !== b;",
        "a in b;",
        "a instanceof b;",
        "-a;",
        "+a;",
        "!a;",
        "~a;",
        "typeof a;",
        "void a;",
        "a && b;",
        "a || b;",
        "a ? b : c;",
        "a, b;",
        "(a, b, c);",
    ];
    assert_cases("operators_match_the_reference", &cases);
}

#[test]
fn variables_match_the_reference() {
    require_oracle!();
    let cases = [
        "var x;",
        "var x = 1;",
        "var x = 1, y = 2;",
        "let x = 1;",
        "const x = 1;",
        "x = 1;",
        "x += 1;",
        "x -= 1;",
        "x *= 2;",
        "x++;",
        "x--;",
        "++x;",
        "--x;",
        "var x = 1; x;",
        "function f() { var x = 1; return x; }",
        "function f(a) { return a; }",
        "function f(a, b) { return a + b; }",
        "function f() { return 1; } f();",
    ];
    assert_cases("variables_match_the_reference", &cases);
}

/// Parameter lists, instruction for instruction.
///
/// A default anywhere in the parenthesis gives the function a second variable environment,
/// and the reference's shape for it is visible: one `set_loc_uninitialized` per parameter
/// (newest first), the parameter's own binding code, then a copy for the names a *pattern*
/// bound — never for a plain name, whose body reads the argument slot.
#[test]
fn parameter_scopes_match_the_reference() {
    require_oracle!();
    let cases = [
        "function f(a = 1){ return a }",
        "function f(a, b = 2){ return a + b }",
        "function f(a = 1, b){ return a + b }",
        "function f(a = 1, ...r){ return r }",
        "function f(a = a){ return a }",
        "function f(x = y, y){ return x }",
        "function f(a = 1){ return () => a }",
        "function f(a = 1){ let q; return q }",
        "function f(a = 1){ return arguments }",
        "function f(a = 1, b = 2){ b = 3 }",
        "function f(a = 1){ { let a = 2; } }",
        "function f(...a){ return a }",
        "function f(a, ...b){ return b }",
        "function f({a}, b = 1){ return a + b }",
        "function f(a = 1, {b}){ return a + b }",
        "function f({a}, {b}) { return a + b }",
        "(a = 1) => a",
        "(a, b = 2) => a + b",
        "function f(a = 1){ function g(){} return g }",
    ];
    assert_cases("parameter_scopes_match_the_reference", &cases);
}

/// Constructs the compiler rejects with a clear error rather than compiling them
/// wrongly. Each one is a known gap, listed here so the list cannot silently
/// grow without a test noticing.
///
/// A destructuring `catch` parameter used to be on this list. It compiles now — its
/// behaviour is compared in `quickjs-cli`'s `binding_patterns` test — so what replaced it
/// here is the shape the compiler still refuses.
#[test]
fn unsupported_constructs_fail_loudly() {
    // A computed key alongside a rest element needs the exclusion list the reference
    // threads through the pattern, which this compiler does not build yet.
    let source = "function f(o, k){ var {[k]: a, ...r} = o; }";
    let program = parse_script(source).expect("parses");
    let error = compile_script(&program).expect_err(&format!("{source:?} should not compile yet"));
    assert!(!error.message.is_empty(), "{source:?} needs a message");
}

/// `for await` used to be listed as unsupported; its shape is now compared in full.
///
/// Two differences used to be excluded here and are both closed: the function header's
/// position (the reference records an `async function` at the `async` keyword, this
/// compiler used to record it at `function`) and the loop's closing sequence (the
/// reference runs the async iterator-close protocol — three drops, then a conditional
/// `return` whose result is awaited — where this compiler used to reuse the synchronous
/// `iterator_close`).
#[test]
fn for_await_compiles_like_the_reference() {
    let oracle = match oracle() {
        Some(path) => path,
        None => {
            eprintln!("skipping: no disassembling qjsc found (run scripts/setup-oracle.sh)");
            return;
        }
    };
    let scratch = Scratch::new("for-await");
    for source in [
        "async function f(xs){ for await (const x of xs) ; }",
        "async function f(xs){ for await (x of xs) { g(x); } }",
        "async function f(xs){ for await (const x of xs) { break } }",
        "async function f(xs){ for await (const x of xs) { return x } }",
    ] {
        let program = parse_script(source).expect("parses");
        let ours = disassemble(&compile_script(&program).expect("compiles"));
        let reference = oracle_disassembly(&oracle, &scratch, source);
        assert_eq!(
            ours.trim_end(),
            reference.trim_end(),
            "{source:?} differs from the reference:\nours:\n{ours}\nreference:\n{reference}"
        );
    }
}

/// The reference compiler's disassembly for `source`, through the `qjsc -c` oracle.
///
/// `-c -o` is not about the C file: it is what stops the oracle from *linking*. `qjsc-dump`
/// is the real `qjsc` built with `-DDUMP_BYTECODE`, so it dumps the bytecode and then carries
/// on into its normal output paths — and the default path is an executable. Without `-o` it
/// prints its dump and then links `a.out` **into the current directory**, which under
/// `cargo test` is this crate's root. That is how a 1.2 MB Mach-O binary ended up committed:
/// the test passed, and the artefact was only noticed when `git add -A` picked it up.
fn oracle_disassembly(oracle: &PathBuf, scratch: &Scratch, source: &str) -> String {
    let path = scratch.file("case.js", source);
    let output = std::process::Command::new(oracle)
        .arg("-c")
        .arg("-o")
        .arg(scratch.0.join("out.c"))
        .arg(&path)
        .output()
        .expect("run the oracle");
    let text = String::from_utf8_lossy(&output.stdout).to_string();
    // The oracle prefixes every line with `<file>:line:col: `, which the file name would
    // otherwise make unstable between runs.
    text.lines()
        .map(|line| match line.find(": ") {
            Some(index) if line.starts_with(path.to_str().unwrap_or("")) => {
                line[index + 2..].to_string()
            }
            _ => line.to_string(),
        })
        .collect::<Vec<_>>()
        .join("\n")
}

#[test]
fn statements_match_the_reference() {
    require_oracle!();
    let cases = [
        "if (a) b;",
        "if (a) b; else c;",
        "if (a) { b; } else { c; }",
        "while (a) b;",
        "return_ = 1;",
        "a.b;",
        "a[b];",
        "a.b = 1;",
        "a[0] = 1;",
        "f();",
        "f(1);",
        "f(1, 2);",
        "f(1, 2, 3);",
    ];
    assert_cases("statements_match_the_reference", &cases);
}

/// The temporal dead zone and the scope chain.
///
/// Every case here exercises `set_loc_uninitialized`, the `_check` opcodes, or
/// the `scope_next` links the runtime walks to instantiate a scope.
#[test]
fn tdz_and_scopes_match_the_reference() {
    require_oracle!();
    let cases = [
        // A `let` in a function body starts uninitialised.
        "function f(){ let x = 1; return x; }",
        "function f(){ let x; return x; }",
        "function f(){ let x; x = 1; return x; }",
        "function f(){ let x = 0; x = 1; return x; }",
        "function f(){ let x = 0; x += 1; }",
        "function f(){ let x = 0; x++; }",
        "function f(){ const c = 1; return c; }",
        // Reads before the declaration are still inside the dead zone.
        "function f(){ return x; let x = 1; }",
        "function f(){ g(); let x = 1; }",
        // Blocks: the binding is marked when the block is entered.
        "function f(){ { let x = 1; } return 0; }",
        "function f(){ { let x = 1; return x; } }",
        "function f(){ let a = 1; { let b = 2; return b; } }",
        "function f(){ let a; { let b = a; } }",
        "function f(){ { let a; let b; } }",
        "function f(){ let a; let b; }",
        "function f(){ let a; let b; let c; }",
        "function f(){ { let a; } { let b; } }",
        "function f(){ let a; { let b; { let c; } } }",
        "function f(){ { { let c; } let b; } let a; }",
        "function f(){ { let a = 1; } let b = 2; }",
        "function f(){ let b = 2; { let a = 1; } }",
        // `var` never enters the dead zone.
        "function f(){ return v; var v = 1; }",
        "function f(){ var v = 1; { let w = 2; } return v; }",
        // Closures capture the binding, which forces a reference cell.
        "function f(){ let x = 1; return function(){ return x; }; }",
        "function f(){ let x = 0; return function(){ x += 1; }; }",
        "function f(){ let x = 1; return function(){ x = 2; return x; }; }",
        "function f(a){ return function(){ return a; }; }",
        "function f(){ var v = 1; return function(){ return v; }; }",
        // Function declarations are instantiated when the scope is entered.
        "function f(){ function g(){} return g; }",
        "function f(){ a; function g(){} }",
        "g(); function f(){ return 1; }",
        "function f(){ function g(){} function h(){} return h; }",
        // A captured binding in a nested block is closed when the block ends.
        "function f(){ { let x = 1; g = function(){ return x; }; } }",
        "function f(){ let a = 1; { let b = 2; g = function(){ return a + b; }; } }",
        // Globals reached from a nested function go through the parent's entry.
        "function f(){ g(); }",
        "var g; function f(){ g(); }",
        "function f(){ function h(){ k(); } }",
        "function f(){ g(); h(); }",
        // Dead code after a `return` is not compiled.
        "function f(){ return 1; let x = 2; }",
        "function f(){ return 1; var x = 2; }",
        "function f(){ return; g(); }",
        "function f(){ throw 1; g(); }",
        // `const` is checked like `let`, but never written.
        "function f(){ const c = 1; return c; }",
        "function f(){ const c = 1; c; return c; }",
        // Source-order slot numbering must survive interleaved declarations.
        "function f(){ let a = 1; var b = 2; }",
        "function f(){ var b = 2; let a = 1; }",
        "function f(){ { let a = 1; } var b = 2; }",
        "function f(){ var b = 2; { let a = 1; } }",
        "function f(){ let a = 1; function g(){} }",
        // Nesting depth: the chain has to reach across several scopes.
        "function f(){ let a; { let b; { let c; } } }",
        "function f(){ { { let c; } let b; } let a; }",
        "function f(){ let a; { let b; } let c; }",
    ];
    assert_cases("tdz_and_scopes_match_the_reference", &cases);
}

/// Function name inference and closure plumbing, which the TDZ work touches.
#[test]
fn named_functions_and_captures_match_the_reference() {
    require_oracle!();
    let cases = [
        "var f = function(){};",
        "var f = function named(){};",
        "g = function(){};",
        "function k(){ var f = function(){}; }",
        "function k(p){ return function(){ return p; }; }",
        "function k(p){ var q = p; return function(){ return q + p; }; }",
        "function k(){ var a = 1; var b = 2; return function(){ return a + b; }; }",
        "function k(){ return function(){ return function(){ return 1; }; }; }",
        "function k(){ var a = 1; return function(){ return function(){ return a; }; }; }",
        "function k(){ { let a = 1; } return 0; }",
        "function k(){ for (let i = 0; i < 1; i++); }",
        "function k(){ for (;;) { let a = 1; } }",
        "function k(){ { } }",
        "function k(){ {} {} }",
        "function k(){}",
        "function k(a, b, c, d){ return d; }",
        "function k(a, b, c, d, e){ return e; }",
    ];
    assert_cases("named_functions_and_captures_match_the_reference", &cases);
}

/// `break`, `continue` and labelled statements.
#[test]
fn loops_and_labels_match_the_reference() {
    require_oracle!();
    let cases = [
        // A bare break out of an infinite loop makes the trailing `goto` dead.
        "function f(){ for(;;){ break; } }",
        "function f(){ for(;;){ continue; } }",
        "function f(){ do { break; } while(1); }",
        // With work after the loop, control has somewhere to go.
        "function f(){ for(;;){ a(); break; b(); } c(); }",
        "function f(){ do { a(); break; } while(b); c(); }",
        // A conditional break keeps both paths alive.
        "function f(c){ for(;;){ a(); if(c) break; b(); } c2(); }",
        "function f(c){ while(c){ a(); if(c2) break; } c3(); }",
        // `continue` runs the update in a for-loop and the test in a do-while.
        "function f(c){ for(let i=0;i<1;i++){ a(); if(c) continue; b(); } }",
        "function f(c){ do { a(); if(c) continue; } while(c2); }",
        "function f(c){ while(c){ a(); if(c2) continue; b(); } c3(); }",
        // Labelled loops.
        "function f(c){ l: for(;;){ if(c) break l; a(); } c2(); }",
        "function f(c){ l: for(;;){ if(c) continue l; a(); } c2(); }",
        "function f(c){ outer: for(;;){ for(;;){ break outer; } } }",
        "function f(c){ outer: for(;;){ for(;;){ continue outer; } } }",
        // A label on a block only provides a break target.
        "function f(c){ l: { a(); if(c) break l; b(); } }",
        "function f(c){ l: { a(); if(c) break l; b(); } c2(); }",
        // Nested labels on one statement all reach the same loop.
        "function f(c){ a: b: for(;;){ break a; } }",
        "function f(c){ a: b: for(;;){ break b; } }",
        "function f(c){ a: b: for(;;){ continue a; } }",
        // Nested unlabelled loops bind to the innermost.
        "function f(c){ for(;;){ for(;;){ break; } a(); } }",
        "function f(c){ for(;;){ for(;;){ continue; } a(); } }",
    ];
    assert_cases("loops_and_labels_match_the_reference", &cases);
}

/// Known gaps: jump and constant-folding optimisations the reference applies but
/// this compiler does not yet.
///
/// These are *optimisation* differences only — the programs mean the same thing —
/// but the disassembly differs, so they cannot live in the suite above without
/// turning a real regression into a false alarm. They are listed here so the gap
/// is recorded and cannot quietly grow.
#[test]
#[ignore = "needs fold_constants and the resolve_labels jump rewrites"]
fn constant_conditions_and_dead_jumps_match_the_reference() {
    require_oracle!();
    let cases = [
        // A constant condition removes the test entirely.
        "function f(){ while(1){ break; } }",
        "function f(){ while(1){ a(); break; b(); } c(); }",
        "function f(){ while(0){ a(); } c(); }",
        "function f(){ if(1) a(); }",
        "function f(){ if(0) a(); else b(); }",
        "function f(){ for(;1;){ break; } }",
        // A returned call is a tail call, and a returned method call is
        // `tail_call_method`; both are a separate optimisation.
        "function f(a,c){ return a.b(c); }",
        "function f(a,c){ return g(c); }",
        // A sequence whose left side is a constant folds away entirely.
        "function f(a,c){ (0, a.b)(c); }",
        "function f(a,c){ (0, g)(c); }",
        // Interior runs of dead jumps that only the reference's `skip_dead_code`
        // removes.
        "function f(c){ while(c){ for(;;){ break; } } }",
        "function f(){ for(;;){ for(;;){ break; } } }",
        "function f(){ for(;;){ for(;;){ break; } a(); } }",
        "function f(c){ o: for(;;){ i: while(1){ break o; } } }",
        "function f(c){ o: for(;;){ i: while(1){ break i; a(); } } }",
        "function f(c){ o: for(;;){ i: while(1){ continue i; } } }",
        // A labelled break out of an inner loop leaves the same shape: the target
        // is the outer loop's end, so the reference folds `if_false`+`goto` into
        // one inverted jump.
        "function f(c){ o: for(;;){ i: while(c2){ break o; } } }",
        "function f(c){ o: for(;;){ i: while(c2){ break i; a(); } } }",
        "function f(c){ o: for(;;){ i: while(c2){ continue i; } } }",
        // `.length` is its own opcode: the reference folds `get_field length` into
        // `get_length`, for any object, not just freshly built arrays.
        "function f(a){ return a.length; }",
        "function f(){ return [1,2].length; }",
    ];
    assert_cases(
        "constant_conditions_and_dead_jumps_match_the_reference",
        &cases,
    );
}

/// A store, a jump target, then a read of the same variable.
///
/// The peephole folds `dup; put_x; drop; get_x` into `set_x`, which is only equivalent
/// when the `get_x` is reached by falling through. When a jump lands on the `get_x` — the
/// end of an `if` body, a `switch` case, a loop head — folding it away retargets the jump
/// onto whatever follows. `return` then ran with an empty stack and the function answered
/// `undefined`, because the store had already consumed the value it was meant to leave.
///
/// This is why `with`/`switch`/`if` all need their own case here: each puts a label in a
/// different place, and only the one on the `get` was being missed.
#[test]
fn a_jump_target_after_a_store_stays_put() {
    require_oracle!();
    let cases = [
        "function f(c){ var p=\"\"; function g(){ p=\"x\"; if(c){ p=\"a\"; } return p; } return g; }",
        "function f(c){ var p=\"\"; function g(){ p=\"x\"; if(c){ p=\"a\"; } else { p=\"b\"; } return p; } return g; }",
        "function f(n){ var p=\"\"; function g(){ switch(n){ case 1: p=\"a\"; break; default: p=\"b\"; } return p; } return g; }",
        "function f(n){ var p=\"\"; function g(){ p=\"s\"; while(n-- > 0){ p+=\"w\"; } return p; } return g; }",
        // A local rather than a closure variable: the same rule, a different slot.
        "function f(c){ var p; p=\"x\"; if(c){ p=\"a\"; } return p; }",
        "function f(c){ var p; p=\"x\"; if(c){ p=\"a\"; } else { p=\"b\"; } return p; }",
    ];
    assert_cases("a_jump_target_after_a_store_stays_put", &cases);
}

/// Assignments, in statement *and* value position.
///
/// The distinction matters: `put_field`/`put_array_el` consume both the object and
/// the value, so a store whose value is kept needs `insert2`/`insert3` — and one
/// whose value is thrown away must not have them. Nothing else in the suite covers
/// this, which is how a store that silently dropped its operator survived.
#[test]
fn assignments_match_the_reference() {
    require_oracle!();
    let cases = [
        // Identifier, plain.
        "function f(v){ var a; a = v; }",
        "function f(a,b){ var x = (a = b); }",
        "function f(v){ g = v; }",
        "function f(v){ a = b = v; }",
        // Identifier, compound: every operator reads the place first.
        "function f(a,b){ a += b; }",
        "function f(a,b){ var x = (a -= b); }",
        "function f(a,b){ a *= b; }",
        "function f(a,b){ a /= b; }",
        "function f(a,b){ a %= b; }",
        "function f(a,b){ a **= b; }",
        "function f(a,b){ a <<= b; }",
        "function f(a,b){ a >>= b; }",
        "function f(a,b){ a >>>= b; }",
        "function f(a,b){ a &= b; }",
        "function f(a,b){ a |= b; }",
        "function f(a,b){ a ^= b; }",
        // Identifier, logical: the right-hand side must not run when the left
        // already decides the result.
        "function f(a,b){ a ||= b; }",
        "function f(a,b){ a &&= b; }",
        "function f(a,b){ a ??= b; }",
        "function f(a,b){ var x = (a ||= b); }",
        "function f(b){ var x = (g ||= b); }",
        // Member, plain: no `insert2` when the value is discarded.
        "function f(o,p,v){ o.p = v; }",
        "function f(o,v){ var x = (o.a = v); }",
        "function f(o,k,v){ o[k] = v; }",
        "function f(o,k,v){ var x = (o[k] = v); }",
        // Member, compound.
        "function f(o,b){ o.a += b; }",
        "function f(o,b){ var x = (o.a += b); }",
        "function f(o,k,b){ o[k] += b; }",
        "function f(o,k,b){ var x = (o[k] += b); }",
        "function f(o,b){ o.a -= b; c(); }",
        // Member, logical: the store path jumps over the cleanup the keep path
        // needs, so falling through would `nip` a stack holding only the value.
        "function f(o,b){ o.a ||= b; c(); }",
        "function f(o,b){ o.a &&= b; c(); }",
        "function f(o,b){ o.a ??= b; c(); }",
        "function f(o,k,b){ o[k] ||= b; c(); }",
        "function f(o,k,b){ o[k] ??= b; c(); }",
        "function f(o,k,b){ var x = (o[k] ||= b); }",
    ];
    assert_cases("assignments_match_the_reference", &cases);
}

/// Calls, which have to pass their receiver.
///
/// `o.m(args)` is `get_field2` + `call_method`: the object stays under the
/// function so `this` survives. A plain `get_field` + `call` would drop it.
#[test]
fn calls_pass_their_receiver() {
    require_oracle!();
    let cases = [
        "function f(a,c){ a.b(c); }",
        "function f(a){ a.b(); }",
        "function f(a,c){ a.b(c,d); }",
        // Parentheses do not change the receiver.
        "function f(a,c){ (a.b)(c); }",
        "function f(a,c){ ((a.b))(c); }",
        // Only the last link is a method read; the rest are plain reads.
        "function f(a,c){ a.b.c(d); }",
        "function f(a,c){ a.b(c)(d); }",
        "function f(a,c){ a.b()(c); }",
        // Computed: the key is consumed, so `get_array_el2` not `_3`.
        "function f(a,c){ a[k](c); }",
        "function f(a,c){ a[\"b\"](c); }",
        "function f(a,c){ a.b[k](c); }",
        // A callee that is not a member has no receiver to pass.
        "function f(a,c){ g(c); }",
        "function f(a,c){ a(c); }",
        "function f(a,c){ (g)(c); }",
        // Optional forms.
        "function f(a,c){ a?.b(c); }",
        "function f(a,c){ a?.[k](c); }",
    ];
    assert_cases("calls_pass_their_receiver", &cases);
}

/// `??` and optional chaining.
#[test]
fn nullish_and_optional_chains_match_the_reference() {
    require_oracle!();
    let cases = [
        // `??` keeps a falsy-but-defined value, which is what separates it from
        // `||`: `0 ?? b` stays `0`.
        "function f(a,b){ return a ?? b; }",
        "function f(a,b,c){ return a ?? b ?? c; }",
        "function f(a,b){ return a || b; }",
        "function f(a,b,c){ return a || b || c; }",
        "function f(a,b){ return (a || b) && c; }",
        "function f(a,b){ return a ?? b || c; }",
        "function f(a,b){ if (a ?? b) c(); }",
        // Optional chains: the guard short-circuits the whole spine, so `a?.b.c`
        // must not read `.c` when `a` is nullish.
        "function f(a){ return a?.b; }",
        "function f(a){ return a?.b.c; }",
        "function f(a){ return a.b?.c; }",
        "function f(a){ return (a?.b).c; }",
        "function f(a){ return a?.[k]; }",
        "function f(a){ return a?.[k]?.l; }",
        "function f(a){ return a?.b?.[k]; }",
        "function f(a){ return a?.(); }",
        "function f(a){ return a?.b(); }",
        "function f(a){ return a?.[k](); }",
        "function f(a){ return a?.(); }",
        "function f(a){ var x = a?.b; }",
        "function f(a){ return a?.b + 1; }",
        "function f(a){ if (a?.b) c(); }",
    ];
    assert_cases("nullish_and_optional_chains_match_the_reference", &cases);
}

/// `switch`.
#[test]
fn switch_matches_the_reference() {
    require_oracle!();
    let cases = [
        // The discriminant stays on the stack; the trailing drop may be removed.
        "function f(x){ switch(x){ } }",
        "function f(x){ switch(x){ case 1: a(); } }",
        "function f(x){ switch(x){ case 1: } }",
        // Fallthrough: a clause continues into the next one's body, not its test.
        "function f(x){ switch(x){ case 1: a(); case 2: b(); } }",
        // Break.
        "function f(x){ switch(x){ case 1: a(); break; } }",
        "function f(x){ switch(x){ case 1: a(); break; case 2: b(); break; } }",
        // Default.
        "function f(x){ switch(x){ default: b(); } }",
        "function f(x){ switch(x){ case 1: a(); break; default: b(); } }",
        "function f(x){ switch(x){ default: b(); case 2: c(); } }",
        // Chains of case labels share one body.
        "function f(x){ switch(x){ case 1: case 2: a(); } }",
        "function f(x){ switch(x){ case 1: case 2: case 3: a(); break; } }",
        "function f(x){ switch(x){ case 1: case 2: a(); case 3: b(); } }",
        // `default` in the middle: the first run hands over to the later run's
        // tests, and the later run falls back to the default body.
        "function f(x){ switch(x){ case 1: a(); default: b(); case 2: c(); } }",
        "function f(x){ switch(x){ case 1: default: b(); } }",
        // Runs whose bodies are all empty.
        "function f(x){ switch(x){ case 1: case 2: } }",
        "function f(x){ switch(x){ case 1: case 2: case 3: } }",
        // A different discriminant, and a body that returns.
        "function f(x){ switch(x.y){ case 1: return 1; } }",
        "function f(x){ switch(x){ case 1: return; default: b(); } }",
    ];
    assert_cases("switch_matches_the_reference", &cases);
}

/// `try`/`catch`/`finally`.
#[test]
fn try_catch_finally_matches_the_reference() {
    require_oracle!();
    let cases = [
        // `catch` records an exception edge; the handler binds the thrown value.
        "function f(){ try { a(); } catch(e) { b(e); } }",
        "function f(){ try { a(); } catch { b(); } }",
        "function f(){ try { a(); } catch(e) { } }",
        // `finally` alone: one copy of the finalizer, reached by `gosub` from the
        // normal path and from the propagating-exception path.
        "function f(){ try { a(); } finally { c(); } }",
        "function f(){ try { a(); } finally { c(); } d(); }",
        // Both: the finalizer is shared by the normal path, the handler path and
        // the rethrow path.
        "function f(){ try { a(); } catch(e) { b(e); } finally { c(); } }",
        "function f(){ try { a(); } catch(e) { b(e); } finally { c(); } d(); }",
        // A body that throws ends the block, so no epilogue is emitted for it.
        "function f(){ try { a(); throw x; } catch(e) { b(e); } }",
        "function f(){ try { a(); } catch(e) { throw e; } }",
        // Scopes: `let` in each part is its own scope; the catch parameter is a
        // local that never sits in the temporal dead zone.
        "function f(){ try { let x = 1; a(x); } catch(e) { let y = 2; b(e, y); } }",
        "function f(){ try { a(); } catch(e) { b(); } finally { let z = 3; c(z); } }",
        // Nesting.
        "function f(){ try { try { a(); } catch(e) { b(e); } } catch(e) { c(e); } }",
        "function f(){ try { a(); } catch(e) { try { b(); } finally { c(); } } }",
        // Leaping out of a `try`. `nip_catch` discards the catch offset while
        // keeping the return value, then each enclosing finalizer runs.
        "function f(){ try { return 1; } catch(e) { b(); } }",
        "function f(){ try { return 1; } finally { c(); } }",
        "function f(){ try { return 1; } catch(e) { b(); } finally { c(); } }",
        "function f(){ try { return; } finally { c(); } }",
        "function f(){ try { a(); return 1; } finally { c(); } }",
        "function f(){ try { try { return 1; } finally { c(); } } finally { d(); } }",
        // A `switch` inside the `try` leaves its discriminant on the stack, and
        // `nip_catch` has to take that with it.
        "function f(y){ try { switch(y){ case 1: return 2; } } finally { c(); } }",
        // `break` and `continue` out of a `try` with a finalizer.
        "function f(){ while(a){ try { break; } finally { c(); } } }",
        "function f(){ while(a){ try { continue; } finally { c(); } } }",
        "function f(){ while(a){ try { if(b) break; d(); } finally { c(); } } e(); }",
        // A labelled break out of two nested `try`s.
        "function f(){ o: while(a){ try { try { break o; } finally { c(); } } finally { d(); } } e(); }",
        // `break` out of a `finally` has to drop both its slots.
        // `return` inside a `finally`.
        "function f(){ try { a(); } finally { return 1; } }",
    ];
    assert_cases("try_catch_finally_matches_the_reference", &cases);
}

/// `for`/`in` and `for`/`of`.
#[test]
fn for_in_of_matches_the_reference() {
    require_oracle!();
    let cases = [
        // The record stays on the value stack; `for`/`of` closes its iterator on the
        // way out, `for`/`in` only drops the enumeration object.
        "function f(o){ for (var k in o) a(k); }",
        "function f(o){ for (var v of o) a(v); }",
        // Lexical loop variables live in the loop's own scope.
        "function f(o){ for (let k in o) a(k); }",
        "function f(o){ for (const v of o) a(v); }",
        // `break` lands on the single cleanup, so it emits nothing of its own.
        "function f(o){ for (var k in o) { break; } a(); }",
        "function f(o){ for (var v of o) { break; } a(); }",
        "function f(o){ for (var k in o) { a(); break; } b(); }",
        "function f(o){ for (var v of o) { if (v) break; } a(); }",
        // `continue` goes straight to the test.
        "function f(o){ for (var k in o) { if (k) continue; a(); } b(); }",
        "function f(o){ for (var v of o) { if (v) continue; a(); } b(); }",
        // Passing *through* the loop is what costs: the record has to go.
        "function f(x){ o: while(c){ for (var k in x){ break o; } } a(); }",
        "function f(x){ o: while(c){ for (var v of x){ break o; } } a(); }",
        "function f(x){ o: while(c){ for (var k in x){ continue o; } } a(); }",
        "function f(x){ o: while(c){ for (var v of x){ continue o; } } a(); }",
        // `return` from inside: no cleanup for `for`/`in`, an iterator close for
        // `for`/`of`.
        "function f(o){ for (var k in o) return k; }",
        "function f(o){ for (var v of o) return v; }",
        "function f(o){ for (var v of o) { if (v) return 1; } }",
        "function f(o){ for (var k in o) { if (k) return; } }",
        // Nesting, and a loop inside a `try`.
        "function f(o){ for (var k in o) for (var v of o) a(k, v); }",
        "function f(o){ try { for (var v of o) a(v); } finally { b(); } }",
        // A destructuring or member target stores through the same path an
        // assignment pattern uses, rather than refusing the loop. Two related shapes are
        // deliberately absent: `for (const {a} of o)` and `for ([t[0]] of o)` match the
        // reference in behaviour (including evaluation order, checked by hand) but not
        // instruction for instruction — the reference picks `get_field2` over
        // `dup`/`get_field`, and hoists a plain receiver read above `for_of_next`.
        "function f(o){ for (const [x] of o) a(x); }",
        "function f(o){ for (var [x, y] in o) a(x, y); }",
        "function f(o, t){ for (t[0] in o) a(t); }",
        "function f(o, t){ for (t.k of o) a(t); }",
    ];
    assert_cases("for_in_of_matches_the_reference", &cases);
}

/// Object and array literals.
/// Every class case in this file, so the two tests below can divide them.
const CLASS_CASES: &[&str] = &[
    // The empty class: an implicit constructor and nothing else.
    "class C {}",
    "class C extends B {}",
    "class C { constructor() {} }",
    "class C extends B { constructor() { super() } }",
    // Methods, accessors, and the `static` keyword in both of its jobs.
    "class C { m() { return 1 } }",
    "class C { static m() { return 1 } }",
    "class C { get x() { return 1 } set x(v) {} }",
    "class C { static get x() { return 1 } }",
    "class C { *g() { yield 1 } }",
    "class C { async m() {} }",
    // Computed and literal keys.
    "class C { ['m']() {} }",
    "class C { [k]() {} }",
    "class C { ['x'] = 1 }",
    "class C { [k] = 1 }",
    // Fields: instance, static, and with initialisers.
    "class C { x }",
    "class C { x = 1 }",
    "class C { static x = 1 }",
    "class C { x = 1; y = 2 }",
    "class C { static x = 1; static y = 2 }",
    "class C { x = () => this }",
    // A class expression, named and unnamed.
    "(class {})",
    "(class Named {})",
    "var a = class {};",
    "var a = class Named {};",
    // Methods that reach outward.
    "class C { m() { return this } }",
    "class C { m() { return super.toString() } }",
    "function f() { class C { m() { return f } } }",
    // Static blocks share the static initialiser with static fields.
    "class C { static { this.x = 1 } }",
    "class C { static a = 1; static { this.b = 2 } }",
    // Private members: symbols, methods, accessor pairs and both brand emissions.
    "class C { #x }",
    "class C { #x = 1 }",
    "class C { static #x = 1 }",
    "class C { static #m() {} }",
    "class C { #m() {} static x = 1 }",
    "class C { #m() {} static { this.y = 1 } }",
    "class C extends B { #m() {} }",
    "class C { get #a() { return 1 } #b = 1 }",
    "class C { #x = 1; constructor() { this.#x = 2 } }",
];

/// Every class case, compared per function — **not green yet**, and it says so.
///
/// Run it with `cargo test -p quickjs-compile --test disasm_diff -- --ignored`. The tool works;
/// the compiler still disagrees with the reference about four things, and the list below is
/// meant to stay true rather than to shrink by trimming the corpus:
///
/// 1. **A folded dead branch leaves a `goto`.** A field initialiser always carries the brand
///    block, which the class parse patches to `push_true` or leaves as `push_false`; either way
///    the reference keeps `goto8 L; L:` where our edge elimination drops the redundant jump.
/// 2. **`this` in a method body.** The reference materialises `this` into a local
///    (`push_this; put_loc0 this; get_loc0 this`) and reads closure variables through the
///    unchecked `get_var_refN` once it knows they are initialised; we inline `push_this` and
///    always emit `get_var_ref_check`.
/// 3. **A static member's function position.** The reference points at the key
///    (`class C { static m() {} }` → `1:18`), we point at the `static` keyword (`1:11`).
/// 4. **A computed method's emission order.** The reference pushes the key and then the closure
///    (`push_atom_value m; fclosure; define_method_computed`); we push the closure and `swap`.
///
/// None of the four changes behaviour, and all of them are older than the private-element work
/// that this corpus was extended for. What the comparison *did* drive, and what is now verified
/// instruction for instruction: every private member shape — `#x`, `#m`, `get #a`/`set #a`,
/// their reads, writes, compound assignments, `++`, `#m in o`, and both brand emissions.
#[test]
#[ignore = "four known divergences, none about private members; see the doc comment"]
fn classes_match_the_reference() {
    require_oracle!();
    assert_class_cases("classes_match_the_reference", CLASS_CASES);
}

/// The private half on its own, so the part that *does* match is gated on every run.
///
/// Every private member shape the compiler emits — `#m`, `get #a`/`set #a`, `#x`, their
/// bindings, their initialisers and both brand emissions — checked instruction for
/// instruction against the reference.
///
/// The corpus is deliberately shaped to stay clear of divergences 1 and 2 in
/// [`classes_match_the_reference`], which are older than this work and not about private
/// members: every class here either has a private *method* (so the brand block is live and
/// the reference emits no dead `goto`) or no fields at all, and none has a static initialiser
/// or a derived constructor. A class with only a private *field* is in the ignored corpus
/// instead, because the artefact alone makes it differ.
#[test]
fn private_member_shapes_match_the_reference() {
    require_oracle!();
    let cases = [
        "class C { #m() {} }",
        "class C { get #a() { return 1 } }",
        "class C { set #a(v) {} }",
        "class C { get #a() { return 1 } set #a(v) {} }",
        "class C { #m() {} #n() {} }",
        // A private field alongside a private method: the field's symbol is created in
        // member order, and the initialiser runs behind a live brand block.
        "class C { #m() {} #x = 1 }",
        "class C { #x = 1; #m() {} }",
        "class C { #m() {} get #a() { return 1 } set #a(v) {} }",
        "class C { #m() { return 1 } #g = 2; get #a() { return 3 } set #a(v) {} }",
        // A computed field key next to a private member: the `<computed_field>N` binding and
        // its `to_propkey` evaluation.
        "class C { #m() {} ['a'] = 1 }",
        "class C { #m() {} constructor() {} }",
        "class C { #m() {}; m() {} }",
    ];
    assert_class_cases("private_member_shapes_match_the_reference", &cases);
}

/// Generators, async generators and `yield*`, instruction for instruction.
///
/// The delegating shapes are long fall-through chains — an `await` in the wrong place, or a
/// missing one, changes the length of a jump by a byte and the whole chain shifts. That is
/// exactly the class of mistake a behaviour test misses, because a wrong `await` usually
/// still produces the right answer, just at the wrong time.
#[test]
fn generators_match_the_reference() {
    require_oracle!();
    let cases = [
        "function* g(){}",
        "function* g(){ yield 1 }",
        "function* g(){ return 1 }",
        "function* g(){ yield 1; return 2 }",
        "function* g(){ var a = yield 1; return a }",
        "async function* g(){}",
        "async function* g(){ yield 1 }",
        "async function* g(){ return 1 }",
        "async function* g(){ yield 1; return 2 }",
        // The parameter list runs *before* `initial_yield`, so a throwing default throws at
        // the call rather than at the first `next()`.
        "function* g(){ yield 1 }",
        // Delegation, both protocols.
        "function* g(){ yield* a }",
        "function* g(){ yield* a; return 1 }",
        "async function* g(){ yield* a }",
        "async function* g(){ yield* a; return 1 }",
        "async function* g(){ yield* a; yield* b }",
        "async function* g(){ try { yield* a } finally { } }",
        // `for await` and its close-on-exit shape.
        "async function* g(){ for await (const x of a) { } }",
        "async function* g(){ for await (const x of a) { break } }",
        "function* g(){ for (const x of a) { } }",
    ];
    assert_cases("generators_match_the_reference", &cases);
}

#[test]
fn literals_build_in_place() {
    require_oracle!();
    let cases = [
        // The object stays on the stack while properties are added.
        "function f(){ return {}; }",
        "function f(){ return {a:1}; }",
        "function f(){ return {a:1, a:2}; }",
        "function f(a){ return {a}; }",
        "function f(){ return {a:1, b:2, c:3}; }",
        // `__proto__` sets the prototype; the shorthand is a plain property.
        "function f(p){ return {__proto__:p}; }",
        "function f(){ return {\"__proto__\":x}; }",
        "function f(){ return {__proto__}; }",
        // A method is not a field with a function in it.
        "function f(){ return {m(){return 1}}; }",
        "function f(){ return {get a(){return 1}}; }",
        "function f(){ return {set a(v){}}; }",
        "function f(){ return {a:function(){}}; }",
        "function f(){ return {a:function b(){}}; }",
        // Computed keys: `to_propkey` then `define_array_el`, and the key is
        // dropped; a computed method lets `define_method_computed` convert.
        "function f(k){ return {[k]:1}; }",
        "function f(){ return {[\"a\"]:1}; }",
        "function f(k){ return {[k](){}}; }",
        "function f(k){ return {get [k](){return 1}}; }",
        "function f(k){ return {[k]:function(){}}; }",
        // Spread copies with an exclusion list.
        "function f(b){ return {...b}; }",
        "function f(){ return {a:1, ...b, c:2}; }",
        "function f(){ return {...a, ...b}; }",
        // Numeric keys: a canonical index becomes a tagged atom, which prints
        // bare; anything else stays a string atom.
        "function f(x){ return {2:x}; }",
        "function f(x){ return {\"x\":1, 2:3}; }",
        "function f(x){ return {2147483647:x}; }",
        "function f(x){ return {2147483648:x}; }",
        "function f(x){ return {\"007\":x}; }",
        "function f(x){ return {\"1e2\":x}; }",
        "function f(x){ return {1e2:x}; }",
        "function f(x){ return {0x10:x}; }",
        "function f(x){ return {1.5:x}; }",
        "function f(x){ return {4294967296:x}; }",
        "function f(x){ return {0:x}; }",
        "function f(x){ return {\"10\":x}; }",
        // Arrays, including the index phase and spread.
        "function f(){ return []; }",
        "function f(){ return [1,2,3]; }",
        "function f(b){ return [1,...b]; }",
        "function f(){ return [1,,3]; }",
        "function f(){ return [,,]; }",
        "function f(){ return [1,]; }",
        "function f(){ return [...a, ...b]; }",
        // Nesting.
        "function f(){ return {a:[1,{b:2}]}; }",
        "function f(){ return [{a:1},{b:2}]; }",
        "function f(){ return {a:{b:{c:1}}}; }",
        "function f(){ return [[[1]]]; }",
        // The three array phases meet at these boundaries.
        "function f(){ return [,,1]; }",
        "function f(){ return [,,,...a]; }",
        "function f(){ return [1,,...a]; }",
        "function f(){ return [...a,,1]; }",
        "function f(){ return [1,...,,]; }",
        // 33 elements crosses the 32-element limit on phase 1.
        "function f(){ var a = [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]; }",
        "function f(){ var a = [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]; }",
        // Literals as operands of other constructs.
        "function f(o){ return o[{a:1}]; }",
        "function f(){ for (var k in [1,2]) a(k); }",
        "function f(){ return {a:1}.a; }",
        // A literal inside a call and as a default-ish argument.
        "function f(){ g({a:1}, [2]); }",
        "function f(){ return typeof {}; }",
    ];
    assert_cases("literals_build_in_place", &cases);
}

/// [`compare`], but pairing functions by header instead of comparing one long string.
fn compare_by_function(cases: &[&str]) -> (Vec<String>, usize) {
    let Some(oracle) = oracle() else {
        return (Vec::new(), 0);
    };
    let scratch = Scratch::new("functions");
    let mut failures = Vec::new();
    let mut compared = 0;
    for source in cases {
        let path = scratch.0.join("case.js");
        let path = path.to_str().expect("utf-8 path").to_string();
        let Some(reference) = reference_disassembly(&oracle, &scratch, source) else {
            if ours(source, &path).is_ok() {
                failures.push(format!(
                    "  {source:?}\n    the reference rejects this, but we compile it"
                ));
            }
            continue;
        };
        let reference = normalise_function_constants(&normalise(&reference, &path));
        compared += 1;
        let actual = match ours(source, &path) {
            Err(err) => {
                failures.push(format!("  {source:?}\n    we failed: {err}"));
                continue;
            }
            Ok(actual) => actual,
        };
        let mut expected = functions_by_header(&reference);
        let mut seen = 0;
        for (header, body) in functions_by_header(&actual) {
            seen += 1;
            match expected.remove(&header) {
                Some(expected_body) if expected_body == body => {}
                Some(expected_body) => failures.push(format!(
                    "  {source:?}\n    function {header} differs:\n{}",
                    diff(&expected_body, &body)
                )),
                None => failures.push(format!(
                    "  {source:?}\n    we compiled a function the reference did not: {header}"
                )),
            }
        }
        let _ = seen;
        for header in expected.keys() {
            failures.push(format!(
                "  {source:?}\n    the reference compiled a function we did not: {header}"
            ));
        }
    }
    (failures, compared)
}

/// Rewrite the reference's `push_const` of a function into the `fclosure` it becomes.
///
/// `js_parse_class` emits `push_const <cpool>` for the constructor and patches the pool slot
/// afterwards; the operand's *value* is a bare function object, and `JS_DefineClass` is what
/// binds it to the enclosing frame's variables. The dump is taken before that happens, so it
/// prints `push_const` for a function that is always a closure at run time. We emit the
/// final form directly.
///
/// Scoped to `[bytecode …]` operands on purpose: a constant that is not a function is never
/// rewritten, and this compiler emits no `push_const` for functions of its own, so the only
/// lines this can touch are the reference's constructors.
fn normalise_function_constants(text: &str) -> String {
    let mut out = String::with_capacity(text.len());
    for line in text.lines() {
        let trimmed = line.trim_start();
        match trimmed.split_once(": [bytecode") {
            Some((head, tail))
                if head.starts_with("push_const8 ") || head.starts_with("push_const ") =>
            {
                let indent = &line[..line.len() - trimmed.len()];
                let number = head.split_whitespace().nth(1).unwrap_or("0");
                let short = head.starts_with("push_const8");
                let opcode = if short { "fclosure8" } else { "fclosure" };
                out.push_str(indent);
                out.push_str(&format!("{opcode} {number}: [bytecode{tail}"));
            }
            _ => out.push_str(line),
        }
        out.push('\n');
    }
    out
}

/// Split a dump into `header -> body`, where the header is the `…: function: name` line.
///
/// The header includes the position, so a function that moved is still reported as a
/// difference rather than silently paired with a different one.
fn functions_by_header(disassembly: &str) -> std::collections::BTreeMap<String, String> {
    let mut out = std::collections::BTreeMap::new();
    let mut header = String::new();
    let mut body = String::new();
    for line in disassembly.lines() {
        if line.contains(": function: ") && !line.starts_with(' ') {
            if !header.is_empty() {
                out.insert(std::mem::take(&mut header), std::mem::take(&mut body));
            }
            header = line.to_string();
            continue;
        }
        if header.is_empty() {
            continue;
        }
        body.push_str(line);
        body.push('\n');
    }
    if !header.is_empty() {
        out.insert(header, body);
    }
    out
}

/// Class cases, compared **one function at a time** instead of as one text blob.
///
/// [`compare`] cannot handle a class. Its constructor and its field initialiser are siblings
/// in the enclosing function's constant pool, and the reference creates the initialiser
/// *lazily* — at the first static field or static block — while this compiler finishes the
/// constructor before it walks the body. So the two are printed in the opposite order and a
/// textual comparison fails on the ordering while every instruction may be identical.
///
/// Pairing by function header (position and name) puts the ordering aside. What it does not
/// excuse is anything *inside* a function: the instruction stream, the constant pool, the
/// slot numbering and the operand values are compared exactly as before.
fn assert_class_cases(name: &str, cases: &[&str]) {
    let (failures, compared) = compare_by_function(cases);
    report(name, cases, failures, compared);
}

fn assert_cases(name: &str, cases: &[&str]) {
    let (failures, compared) = compare(cases);
    report(name, cases, failures, compared);
}

/// Report the case counts and fail on any difference.
fn report(name: &str, cases: &[&str], failures: Vec<String>, compared: usize) {
    // Report the runtime counts so `scripts/verify-claims.py` can check the numbers
    // `README.md` publishes. They used to be maintained by hand and six of them had
    // drifted; a count in a table is a claim, so it gets measured rather than remembered.
    if let Some(dir) = std::env::var_os("QUICKJS_CASE_COUNTS") {
        use std::io::Write;
        // The `#[test]` functions run in parallel and each appends one line to the same
        // file. `O_APPEND` makes the offset update atomic but not the write itself, so two
        // threads could interleave mid-line and hand `scripts/verify-claims.py` a row with
        // too many columns — which is exactly what happened. One lock, one write.
        static COUNTS_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
        let _guard = COUNTS_LOCK
            .lock()
            .unwrap_or_else(|poison| poison.into_inner());
        let line = format!("{name}\t{}\t{compared}\n", cases.len());
        let mut file = std::fs::OpenOptions::new()
            .create(true)
            .append(true)
            .open(std::path::Path::new(&dir).join("disasm-cases.txt"))
            .expect("open the case-count file");
        file.write_all(line.as_bytes())
            .expect("write the case count");
    }
    assert!(
        failures.is_empty(),
        "{} of {} cases differ from the reference:\n{}",
        failures.len(),
        cases.len(),
        failures.join("\n")
    );
}