fusevm 0.26.7

Language-agnostic bytecode VM with fused superinstructions and a 3-tier Cranelift JIT (linear/block/tracing)
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
//! Exhaustive interpreter-vs-native differential matrix.
//!
//! fusevm has no external reference implementation — its parity contract is
//! internal: for one `Chunk`, the interpreter, the linear/block JIT, and the
//! AOT compiler must produce the *same* `Value`, variant included. A tier
//! divergence is a silent wrong answer in every frontend at once.
//!
//! `tests/jit_fuzz.rs` random-walks JIT-friendly loops; this file is the
//! complementary axis — every native-lowerable op crossed with the operand
//! edges that break naive lowerings: `0`, `-1`, `i64::MIN`, `i64::MAX`,
//! `-0.0`, non-integral floats, and shift counts at/over the word width.
//!
//! The comparison is on the `Value` *variant*, not on numeric equality:
//! `Int(0)` where the interpreter answers `Float(0.5)` is exactly the class of
//! bug this file exists to catch, and a float-tolerant comparator would let it
//! through.

#![cfg(feature = "jit")]

use fusevm::{Chunk, ChunkBuilder, JitCompiler, Op, VMResult, Value, VM};

/// One operand, as the op sequence that pushes it.
#[derive(Clone, Debug)]
struct Operand {
    label: &'static str,
    push: Vec<Op>,
}

fn int(label: &'static str, n: i64) -> Operand {
    Operand {
        label,
        push: vec![Op::LoadInt(n)],
    }
}

fn float(label: &'static str, f: f64) -> Operand {
    Operand {
        label,
        push: vec![Op::LoadFloat(f)],
    }
}

/// Integer operand edges. These are the values that separate a correct
/// lowering from a plausible one.
fn int_operands() -> Vec<Operand> {
    vec![
        int("0", 0),
        int("1", 1),
        int("2", 2),
        int("-1", -1),
        int("-2", -2),
        int("3", 3),
        int("7", 7),
        int("63", 63),
        int("64", 64),
        int("65", 65),
        int("i64::MIN", i64::MIN),
        int("i64::MAX", i64::MAX),
        // Past 2^53 an `i64` no longer round-trips through `f64`. Any lowering
        // that reaches a float register — or any interpreter path that does —
        // starts answering a *different integer*.
        int("2^53+1", (1i64 << 53) + 1),
        int("i64::MAX-1", i64::MAX - 1),
        int("i64::MIN+1", i64::MIN + 1),
    ]
}

/// Float operand edges, including the signed zero that a naive
/// `f as i64` round-trip collapses.
fn float_operands() -> Vec<Operand> {
    vec![
        float("0.0", 0.0),
        float("-0.0", -0.0),
        float("1.0", 1.0),
        float("-1.0", -1.0),
        float("0.5", 0.5),
        float("-2.5", -2.5),
        float("3.0", 3.0),
        float("1e18", 1e18),
        float("-1e18", -1e18),
        // Past `i64::MAX` as an f64. This is the edge that separates
        // Cranelift's `fcvt_to_sint` (traps — an illegal instruction in
        // JIT-compiled code) from `fcvt_to_sint_sat` (saturates, which is what
        // Rust's `f as i64` and so `Value::to_int` do). `1e18` is inside the
        // range and cannot tell them apart.
        float("1e30", 1e30),
        float("-1e30", -1e30),
    ]
}

/// Booleans, and the comparisons that produce them. `Value::Bool` is not a
/// native number — the interpreter coerces it through `to_float`, so `true + 1`
/// is `Float(2.0)`, not `Int(2)` — which makes it the operand kind most likely
/// to be folded into an integer by a native tier.
fn bool_operands() -> Vec<Operand> {
    vec![
        Operand {
            label: "true",
            push: vec![Op::LoadTrue],
        },
        Operand {
            label: "false",
            push: vec![Op::LoadFalse],
        },
        Operand {
            label: "(1<2)",
            push: vec![Op::LoadInt(1), Op::LoadInt(2), Op::NumLt],
        },
        Operand {
            label: "(1>2)",
            push: vec![Op::LoadInt(1), Op::LoadInt(2), Op::NumGt],
        },
        Operand {
            label: "!0",
            push: vec![Op::LoadInt(0), Op::LogNot],
        },
    ]
}

fn mixed_operands() -> Vec<Operand> {
    let mut v = int_operands();
    v.extend(float_operands());
    v
}

/// Every operand kind the linear tier can see, booleans included.
fn all_operands() -> Vec<Operand> {
    let mut v = mixed_operands();
    v.extend(bool_operands());
    v
}

fn chunk_for(a: &Operand, b: Option<&Operand>, op: &Op) -> Chunk {
    let mut bd = ChunkBuilder::new();
    for o in &a.push {
        bd.emit(o.clone(), 1);
    }
    if let Some(b) = b {
        for o in &b.push {
            bd.emit(o.clone(), 1);
        }
    }
    bd.emit(op.clone(), 1);
    bd.build()
}

/// Interpret `chunk` and return the value left on top, or `None` for an error.
fn interp(chunk: &Chunk) -> Option<Value> {
    let mut vm = VM::new(chunk.clone());
    match vm.run() {
        VMResult::Ok(v) => Some(v),
        VMResult::Halted => vm.stack.last().cloned(),
        VMResult::Error(_) => None,
    }
}

/// Bit-exact `Value` comparison. `Float` compares on raw bits so `-0.0` and
/// `NaN` are distinguished — the JIT is required to reproduce them exactly.
fn same(a: &Value, b: &Value) -> bool {
    match (a, b) {
        (Value::Float(x), Value::Float(y)) => {
            x.to_bits() == y.to_bits() || (x.is_nan() && y.is_nan())
        }
        _ => a == b,
    }
}

fn describe(v: &Option<Value>) -> String {
    match v {
        None => "<error>".to_string(),
        Some(Value::Float(f)) => format!("Float({f:?} bits={:#x})", f.to_bits()),
        Some(other) => format!("{other:?}"),
    }
}

/// Cross `ops` with the operand matrix and report every case where the linear
/// JIT accepted the chunk but disagreed with the interpreter.
fn diff_binary(ops: &[Op], operands: &[Operand]) -> Vec<String> {
    let jit = JitCompiler::new();
    let mut diffs = Vec::new();
    for op in ops {
        for a in operands {
            for b in operands {
                let chunk = chunk_for(a, Some(b), op);
                let Some(native) = jit.try_run_linear(&chunk, &[]) else {
                    continue; // declined — not a divergence
                };
                let expected = interp(&chunk);
                if !expected.as_ref().is_some_and(|e| same(e, &native)) {
                    diffs.push(format!(
                        "{:?}({}, {}): interp={} native={}",
                        op,
                        a.label,
                        b.label,
                        describe(&expected),
                        describe(&Some(native))
                    ));
                }
            }
        }
    }
    diffs
}

fn diff_unary(ops: &[Op], operands: &[Operand]) -> Vec<String> {
    let jit = JitCompiler::new();
    let mut diffs = Vec::new();
    for op in ops {
        for a in operands {
            let chunk = chunk_for(a, None, op);
            let Some(native) = jit.try_run_linear(&chunk, &[]) else {
                continue;
            };
            let expected = interp(&chunk);
            if !expected.as_ref().is_some_and(|e| same(e, &native)) {
                diffs.push(format!(
                    "{:?}({}): interp={} native={}",
                    op,
                    a.label,
                    describe(&expected),
                    describe(&Some(native))
                ));
            }
        }
    }
    diffs
}

fn assert_no_diffs(what: &str, diffs: Vec<String>) {
    if !diffs.is_empty() {
        for d in &diffs {
            eprintln!("TIER DIVERGENCE {what}: {d}");
        }
        panic!("{} interpreter/JIT divergence(s) in {what}", diffs.len());
    }
}

#[test]
fn linear_jit_matches_interpreter_on_arithmetic() {
    assert_no_diffs(
        "arithmetic",
        diff_binary(
            &[Op::Add, Op::Sub, Op::Mul, Op::Div, Op::Mod, Op::Pow],
            &mixed_operands(),
        ),
    );
}

#[test]
fn linear_jit_matches_interpreter_on_bitwise_and_shifts() {
    assert_no_diffs(
        "bitwise",
        diff_binary(
            &[Op::BitAnd, Op::BitOr, Op::BitXor, Op::Shl, Op::Shr],
            &mixed_operands(),
        ),
    );
}

#[test]
fn linear_jit_matches_interpreter_on_comparisons() {
    assert_no_diffs(
        "comparison",
        diff_binary(
            &[
                Op::NumEq,
                Op::NumNe,
                Op::NumLt,
                Op::NumGt,
                Op::NumLe,
                Op::NumGe,
                Op::Spaceship,
            ],
            &mixed_operands(),
        ),
    );
}

#[test]
fn linear_jit_matches_interpreter_on_int_intrinsics() {
    assert_no_diffs(
        "int intrinsics",
        diff_binary(&[Op::GcdInt, Op::LcmInt], &int_operands()),
    );
}

#[test]
fn linear_jit_matches_interpreter_on_unary_ops() {
    assert_no_diffs(
        "unary",
        diff_unary(
            &[
                Op::Negate,
                Op::Inc,
                Op::Dec,
                Op::BitNot,
                Op::LogNot,
                Op::AbsInt,
                Op::TruncInt,
                Op::RubyTruthy,
            ],
            &mixed_operands(),
        ),
    );
}

/// The boolean axis: a `Value::Bool` reaching a native op, and a `Value::Bool`
/// coming back out of one. Both directions were wrong before the linear tier
/// grew a boolean cell kind — `Op::NumLt` handed back `Int(1)` where the
/// interpreter and the AOT tier both answer `Bool(true)`, and `true + 1`
/// folded to `Int(2)` where both answer `Float(2.0)`.
#[test]
fn linear_jit_matches_interpreter_on_boolean_operands() {
    let mut diffs = diff_binary(
        &[
            Op::Add,
            Op::Sub,
            Op::Mul,
            Op::Div,
            Op::Mod,
            Op::Pow,
            Op::BitAnd,
            Op::BitOr,
            Op::BitXor,
            Op::Shl,
            Op::Shr,
            Op::NumEq,
            Op::NumLt,
            Op::Spaceship,
            Op::GcdInt,
            Op::LcmInt,
        ],
        &all_operands(),
    );
    diffs.extend(diff_unary(
        &[
            Op::Negate,
            Op::Inc,
            Op::Dec,
            Op::BitNot,
            Op::LogNot,
            Op::AbsInt,
            Op::TruncInt,
            Op::SqrtFloat,
            Op::AwkInt,
            Op::AwkMkbool,
        ],
        &all_operands(),
    ));
    assert_no_diffs("boolean operands", diffs);
}

#[test]
fn linear_jit_matches_interpreter_on_float_intrinsics() {
    assert_no_diffs(
        "float intrinsics",
        diff_unary(
            &[
                Op::SqrtFloat,
                Op::AbsFloat,
                Op::TruncFloat,
                Op::RoundFloat,
                Op::SinFloat,
                Op::CosFloat,
                Op::ExpFloat,
                Op::LogFloat,
                Op::Log2Float,
                Op::Log10Float,
            ],
            &mixed_operands(),
        ),
    );
}

// ── AOT tier ──
//
// `src/aot.rs` is a *separate* compiler from `src/jit.rs` with its own kind
// lattice and its own lowering of every op, so linear-tier agreement says
// nothing about it. `Op::GcdInt` is the proof: the linear tier saturated the
// unrepresentable `gcd(0, i64::MIN)` magnitude at `i64::MAX` while the
// interpreter and the AOT compiler both wrapped it to a *negative* gcd.

/// Cross `ops` with the operand matrix through the AOT compiler.
#[cfg(feature = "aot")]
fn diff_aot(ops: &[Op], operands: &[Operand], binary: bool) -> Vec<String> {
    let mut diffs = Vec::new();
    for op in ops {
        for a in operands {
            let bs: Vec<Option<&Operand>> = if binary {
                operands.iter().map(Some).collect()
            } else {
                vec![None]
            };
            for b in bs {
                let chunk = chunk_for(a, b, op);
                let native = match fusevm::aot::run_chunk_native(&chunk, |_| {}) {
                    Ok(VMResult::Ok(v)) => Some(v),
                    Ok(VMResult::Error(_)) | Err(_) => None,
                    Ok(VMResult::Halted) => continue,
                };
                let expected = interp(&chunk);
                let agree = match (&expected, &native) {
                    (Some(e), Some(n)) => same(e, n),
                    (None, None) => true,
                    _ => false,
                };
                if !agree {
                    diffs.push(format!(
                        "{:?}({}{}): interp={} aot={}",
                        op,
                        a.label,
                        b.map(|b| format!(", {}", b.label)).unwrap_or_default(),
                        describe(&expected),
                        describe(&native)
                    ));
                }
            }
        }
    }
    diffs
}

#[cfg(feature = "aot")]
#[test]
fn aot_matches_interpreter_on_int_intrinsics() {
    assert_no_diffs(
        "aot int intrinsics",
        diff_aot(&[Op::GcdInt, Op::LcmInt], &int_operands(), true),
    );
}

#[cfg(feature = "aot")]
#[test]
fn aot_matches_interpreter_on_unary_ops() {
    assert_no_diffs(
        "aot unary",
        diff_aot(
            &[
                Op::Negate,
                Op::Inc,
                Op::Dec,
                Op::BitNot,
                Op::LogNot,
                Op::AbsInt,
                Op::TruncInt,
            ],
            &all_operands(),
            false,
        ),
    );
}

#[cfg(feature = "aot")]
#[test]
fn aot_matches_interpreter_on_arithmetic_and_bitwise() {
    assert_no_diffs(
        "aot arithmetic",
        diff_aot(
            &[
                Op::Add,
                Op::Sub,
                Op::Mul,
                Op::Div,
                Op::Mod,
                Op::Pow,
                Op::BitAnd,
                Op::BitOr,
                Op::BitXor,
                Op::Shl,
                Op::Shr,
            ],
            &all_operands(),
            true,
        ),
    );
}

#[cfg(feature = "aot")]
#[test]
fn aot_matches_interpreter_on_comparisons() {
    assert_no_diffs(
        "aot comparison",
        diff_aot(
            &[
                Op::NumEq,
                Op::NumNe,
                Op::NumLt,
                Op::NumGt,
                Op::NumLe,
                Op::NumGe,
                Op::Spaceship,
            ],
            &all_operands(),
            true,
        ),
    );
}

// ── Block tier ──
//
// The third compiler. `src/jit.rs`'s block path (`build_block_function`) has
// its own slot model and its own `Op::SetSlot`/`Op::GetSlot` lowering, and it
// *warms up*: `block_threshold` defaults to 1, so a chunk runs on the
// interpreter once and in native code forever after. A block/interpreter
// disagreement is therefore not a static wrong answer but a `Value` that
// changes on the second call of the same `Chunk` on the same `VM` —
// `VM::run` boxes the block result directly (`src/vm.rs`, `BlockNum::Int(n)
// => Value::Int(n)`), so nothing downstream re-derives the kind.
//
// The block return channel is numeric (`BlockNum`), so an interpreter `Bool`
// is compared against `Int(0|1)` here. That leniency is NOT a judgement that
// the kind does not matter — see `block_jit_preserves_boolean_result_kind`
// below, which asserts the strict contract and is `#[ignore]`d because the
// block tier does not meet it yet.

/// Run `chunk` through the block JIT eagerly and describe the result.
fn block(chunk: &Chunk) -> Option<fusevm::BlockNum> {
    let jit = JitCompiler::new();
    let mut slots = vec![0i64; 8];
    let kinds = vec![fusevm::SlotKind::Int; 8];
    jit.try_run_block_eager_typed_kinded(chunk, &mut slots, &kinds)
}

/// A block-tier chunk needs a frame so the slot ops are legal.
fn block_chunk_for(a: &Operand, b: Option<&Operand>, op: &Op) -> Chunk {
    let mut bd = ChunkBuilder::new();
    bd.emit(Op::PushFrame, 1);
    for o in &a.push {
        bd.emit(o.clone(), 1);
    }
    if let Some(b) = b {
        for o in &b.push {
            bd.emit(o.clone(), 1);
        }
    }
    bd.emit(op.clone(), 1);
    bd.build()
}

fn describe_block(v: &Option<fusevm::BlockNum>) -> String {
    match v {
        None => "<declined>".to_string(),
        Some(fusevm::BlockNum::Int(n)) => format!("Int({n})"),
        Some(fusevm::BlockNum::Float(f)) => format!("Float({f:?} bits={:#x})", f.to_bits()),
        Some(fusevm::BlockNum::Bool(b)) => format!("Bool({b})"),
    }
}

/// Declining is always correct — the caller falls back to the interpreter.
/// Answering differently is not.
///
/// There is still deliberately no `Bool`-answers-`Int` arm, and that is the
/// load-bearing part of this function: accepting `Bool(true)` against
/// `BlockNum::Int(1)` is exactly what let the old flattening go unnoticed. A
/// boolean result must arrive as `BlockNum::Bool` or not at all.
///
/// What changed is that arriving is now allowed. The tier no longer has to
/// decline a chunk whose result is a `Value::Bool`: `BlockNum::Bool` carries
/// the kind out, so a comparison at the end of a chunk compiles and answers
/// with the kind the interpreter would. Every other escape route for a boolean
/// is still refused — see `bool_is_consumed_in_place` and
/// `bool_is_chunk_result` in `src/jit.rs`.
fn block_agrees(expected: &Option<Value>, got: &Option<fusevm::BlockNum>) -> bool {
    match (expected, got) {
        (_, None) => true,
        (Some(Value::Int(a)), Some(fusevm::BlockNum::Int(b))) => a == b,
        (Some(Value::Bool(a)), Some(fusevm::BlockNum::Bool(b))) => a == b,
        (Some(Value::Float(a)), Some(fusevm::BlockNum::Float(b))) => {
            a.to_bits() == b.to_bits() || (a.is_nan() && b.is_nan())
        }
        _ => false,
    }
}

fn diff_block(ops: &[Op], operands: &[Operand], binary: bool) -> Vec<String> {
    let mut diffs = Vec::new();
    for op in ops {
        for a in operands {
            let bs: Vec<Option<&Operand>> = if binary {
                operands.iter().map(Some).collect()
            } else {
                vec![None]
            };
            for b in bs {
                let chunk = block_chunk_for(a, b, op);
                let got = block(&chunk);
                let expected = interp(&chunk_for(a, b, op));
                if !block_agrees(&expected, &got) {
                    diffs.push(format!(
                        "{:?}({}{}): interp={} block={}",
                        op,
                        a.label,
                        b.map(|b| format!(", {}", b.label)).unwrap_or_default(),
                        describe(&expected),
                        describe_block(&got)
                    ));
                }
            }
        }
    }
    diffs
}

#[test]
fn block_jit_matches_interpreter_on_unary_ops() {
    assert_no_diffs(
        "block unary",
        diff_block(
            &[
                Op::Negate,
                Op::Inc,
                Op::Dec,
                Op::BitNot,
                Op::LogNot,
                Op::AbsInt,
                Op::TruncInt,
                Op::AbsFloat,
                Op::CeilFloat,
                Op::FloorFloat,
                Op::TruncFloat,
                Op::RoundFloat,
                Op::SqrtFloat,
            ],
            &mixed_operands(),
            false,
        ),
    );
}

#[test]
fn block_jit_matches_interpreter_on_transcendentals() {
    assert_no_diffs(
        "block transcendentals",
        diff_block(
            &[
                Op::SinFloat,
                Op::CosFloat,
                Op::TanFloat,
                Op::AsinFloat,
                Op::AcosFloat,
                Op::AtanFloat,
                Op::SinhFloat,
                Op::CoshFloat,
                Op::TanhFloat,
                Op::ExpFloat,
                Op::LogFloat,
                Op::Log2Float,
                Op::Log10Float,
                Op::AwkSin,
                Op::AwkCos,
                Op::AwkExp,
                Op::AwkMkbool,
            ],
            &mixed_operands(),
            false,
        ),
    );
}

#[test]
fn block_jit_matches_interpreter_on_arithmetic_and_bitwise() {
    assert_no_diffs(
        "block arithmetic",
        diff_block(
            &[
                Op::Add,
                Op::Sub,
                Op::Mul,
                Op::Div,
                Op::Mod,
                Op::Pow,
                Op::PowFloat,
                Op::BitAnd,
                Op::BitOr,
                Op::BitXor,
                Op::Shl,
                Op::Shr,
            ],
            &mixed_operands(),
            true,
        ),
    );
}

#[test]
fn block_jit_matches_interpreter_on_comparisons_and_int_intrinsics() {
    assert_no_diffs(
        "block comparison",
        diff_block(
            &[
                Op::NumEq,
                Op::NumNe,
                Op::NumLt,
                Op::NumGt,
                Op::NumLe,
                Op::NumGe,
                Op::Spaceship,
                Op::GcdInt,
                Op::LcmInt,
                Op::Atan2Float,
                Op::AwkAtan2,
            ],
            &mixed_operands(),
            true,
        ),
    );
}

// ── `Op::AwkInt` is host-dispatched and must never be lowered natively ──
//
// `VM::run` sends it to `AwkHost::int`, an overridable trait method whose
// implementations disagree on the result *variant*: the default
// (`awk_host::awk_int`) answers `Int(3)` for `int(3.7)`, while a frontend that
// models awk numbers as `f64` answers `Float(3.0)`. Native code sees neither,
// so no lowering is right for every host.

/// An `AwkHost` that models awk numbers as `f64` — `int()` is always a Float.
struct FloatIntHost;
impl fusevm::AwkHost for FloatIntHost {
    fn int(&mut self, x: &Value) -> Value {
        Value::Float(x.to_float().trunc())
    }
}

fn awk_int_chunk(push: Op, salt: i64) -> Chunk {
    let mut b = ChunkBuilder::new();
    b.emit(Op::PushFrame, 1);
    // Unique padding: the block cache is keyed on `chunk.op_hash`, so two
    // cases built from the same ops share a cache entry and the second one
    // never gets a cold (interpreter) run.
    b.emit(Op::LoadInt(salt), 1);
    b.emit(Op::Pop, 1);
    b.emit(push, 1);
    b.emit(Op::AwkInt, 1);
    b.build()
}

/// The regression this pins: the answer must not depend on how many times the
/// chunk has run. Before the fix, `int(3.7)` was `Int(3)` on the first call
/// and `Float(3.0)` on every call after, because the block JIT compiled a
/// kind-preserving `trunc` behind the interpreter's back.
#[test]
fn awk_int_answer_is_stable_across_block_warmup() {
    let mut salt = 7_000_000;
    for push in [
        Op::LoadFloat(3.7),
        Op::LoadFloat(-2.5),
        Op::LoadFloat(0.5),
        Op::LoadInt(2),
        Op::LoadInt((1i64 << 53) + 1),
        Op::LoadInt(i64::MAX - 1),
        Op::LoadInt(i64::MIN + 1),
    ] {
        for use_host in [false, true] {
            salt += 1;
            let chunk = awk_int_chunk(push.clone(), salt);
            let mut answers = Vec::new();
            for _ in 0..4 {
                let mut vm = VM::new(chunk.clone());
                if use_host {
                    vm.set_awk_host(Box::new(FloatIntHost));
                }
                vm.enable_tracing_jit();
                answers.push(describe(&match vm.run() {
                    VMResult::Ok(v) => Some(v),
                    _ => None,
                }));
            }
            assert!(
                answers.windows(2).all(|w| w[0] == w[1]),
                "AwkInt({push:?}) host={use_host} changed answer across block warmup: {answers:?}"
            );
        }
    }
}

/// And the answer must be the *host's*, since the host is what the op
/// dispatches to. With a host that models awk numbers as `f64`, `int()` is a
/// `Float` for every operand — including integer ones, where the old native
/// lowering returned the operand unchanged as an `Int`.
#[test]
fn awk_int_honours_a_registered_host_for_every_operand() {
    let mut salt = 7_500_000;
    for push in [
        Op::LoadFloat(3.7),
        Op::LoadFloat(-2.5),
        Op::LoadInt(0),
        Op::LoadInt(2),
        Op::LoadInt(-2),
        Op::LoadInt((1i64 << 53) + 1),
        Op::LoadInt(i64::MAX),
    ] {
        salt += 1;
        let chunk = awk_int_chunk(push.clone(), salt);
        for call in 1..=3 {
            let mut vm = VM::new(chunk.clone());
            vm.set_awk_host(Box::new(FloatIntHost));
            vm.enable_tracing_jit();
            match vm.run() {
                VMResult::Ok(Value::Float(_)) => {}
                other => panic!(
                    "AwkInt({push:?}) call #{call}: host returns Float for every operand, \
                     got {other:?}"
                ),
            }
        }
    }
}

/// The value error that survived past `2^53` even when the variant matched:
/// the default host truncates *through an `f64`*, native code never left the
/// integer register, and the two answered different integers.
#[test]
fn awk_int_matches_the_default_host_past_2_pow_53() {
    let mut salt = 7_900_000;
    for (n, want) in [
        ((1i64 << 53) + 1, 9_007_199_254_740_992i64),
        (i64::MAX - 1, i64::MAX),
        (i64::MIN + 1, i64::MIN),
    ] {
        salt += 1;
        let chunk = awk_int_chunk(Op::LoadInt(n), salt);
        for call in 1..=3 {
            let mut vm = VM::new(chunk.clone());
            vm.enable_tracing_jit();
            match vm.run() {
                VMResult::Ok(Value::Int(got)) => assert_eq!(
                    got, want,
                    "int({n}) call #{call}: default host answers {want}"
                ),
                other => panic!("int({n}) call #{call}: expected Int({want}), got {other:?}"),
            }
        }
    }
}

// ── Traps: native code must not execute an illegal instruction where the
//    interpreter returns a value ──

/// `Op::Inc`/`Op::Dec` on a float operand. The interpreter is
/// `Value::Int(v.to_int().wrapping_add(1))` and `Value::to_int` saturates
/// (Rust `f as i64`), so `Inc(1e30)` is `Int(i64::MIN)`. The block tier used
/// Cranelift's *trapping* `fcvt_to_sint` and died with SIGILL instead — and
/// nothing guarded it, because `is_block_eligible_op` rejects `Inc`/`Dec`
/// only under `strict_numeric()`, which is not the default.
#[test]
fn block_jit_inc_dec_saturate_instead_of_trapping_on_huge_floats() {
    for (op, f, want) in [
        (Op::Inc, 1e30f64, i64::MIN),
        (Op::Inc, -1e30f64, i64::MIN + 1),
        (Op::Dec, 1e30f64, i64::MAX - 1),
        (Op::Dec, -1e30f64, i64::MAX),
    ] {
        let mut b = ChunkBuilder::new();
        b.emit(Op::PushFrame, 1);
        b.emit(Op::LoadFloat(f), 1);
        b.emit(op.clone(), 1);
        let chunk = b.build();
        let expected = interp(&chunk);
        assert_eq!(
            expected,
            Some(Value::Int(want)),
            "interpreter reference for {op:?}({f})"
        );
        // Reaching this line at all is half the assertion: before the fix the
        // process died here with SIGILL and the test binary never reported.
        match block(&chunk) {
            None => {}
            Some(fusevm::BlockNum::Int(got)) => assert_eq!(
                got, want,
                "{op:?}({f}): block must saturate like Value::to_int"
            ),
            other => panic!("{op:?}({f}): expected Int({want}), got {other:?}"),
        }
    }
}

/// `Op::SetSlot` of a float into a slot the caller declared `SlotKind::Int`.
/// Memory-backed and register-promoted slots are both raw `i64`, so the value
/// cannot survive; the block tier truncated it through the trapping
/// conversion. `x = 3.5` into a slot that entered the chunk holding an integer
/// read back as `Int(3)` once warm, and `x = 1e30` was a SIGILL.
#[test]
fn block_jit_declines_storing_a_float_into_an_int_kinded_slot() {
    for f in [3.5f64, -2.5, 1e30, -1e30, 0.5] {
        let mut b = ChunkBuilder::new();
        b.emit(Op::PushFrame, 1);
        b.emit(Op::LoadFloat(f), 1);
        b.emit(Op::SetSlot(0), 1);
        b.emit(Op::GetSlot(0), 1);
        let chunk = b.build();
        assert_eq!(
            block(&chunk),
            None,
            "storing {f} into an Int-kinded slot has no correct i64 lowering; \
             the block tier must decline so the interpreter runs it"
        );
    }
}

/// End-to-end through `VM::run`: the same shape a frontend actually emits for
/// `x = 3.5` when `x` entered the chunk holding an integer. The float must
/// survive every call, not just the cold one.
#[test]
fn float_assignment_to_an_int_slot_survives_block_warmup() {
    let mut b = ChunkBuilder::new();
    b.emit(Op::LoadFloat(3.5), 1);
    b.emit(Op::SetSlot(0), 1);
    b.emit(Op::GetSlot(0), 1);
    let chunk = b.build();
    for call in 1..=4 {
        let mut vm = VM::new(chunk.clone());
        vm.frames.last_mut().unwrap().slots.push(Value::Int(0));
        vm.enable_tracing_jit();
        match vm.run() {
            VMResult::Ok(Value::Float(got)) => assert_eq!(got, 3.5, "call #{call}"),
            other => panic!("call #{call}: expected Float(3.5), got {other:?}"),
        }
    }
}

// ── The block/tracing lattice has no boolean kind, so it must decline ──
//
// `JitTy` is Int-or-Float and `BlockNum` is Int-or-Float, so a `Value::Bool`
// has nowhere to live. `VM::run` boxes `BlockNum::Int(n)` as `Value::Int(n)`,
// so every boolean-valued block-eligible chunk changed variant on its second
// call: `1 < 2` was `Bool(true)` cold and `Int(1)` warm, and `Bool(false)`
// stringifies as `""` where `Int(0)` stringifies as `"0"`. A `Bool` *operand*
// was the same gap in the other direction — `true + 1` is `Float(2.0)` on the
// interpreter (booleans coerce through `to_float`) and was `Int(2)` in the
// block tier.
//
// The linear tier solved this with a `Cell::ConstB`/`Cell::DynB`, and the AOT
// tier with a `Kind::Bool`. Widening this lattice would touch every `JitTy`
// match plus the public `BlockNum`, so instead the tier now *declines* any
// chunk where a boolean outlives the op that produced it
// (`bool_is_consumed_in_place` in `src/jit.rs`) and the interpreter runs it.
// Declining is always a correct answer; flattening to `Int` was not.
#[test]
fn block_jit_preserves_boolean_result_kind() {
    let mut diffs = Vec::new();
    for (label, ops) in [
        ("1 < 2", vec![Op::LoadInt(1), Op::LoadInt(2), Op::NumLt]),
        ("1 > 2", vec![Op::LoadInt(1), Op::LoadInt(2), Op::NumGt]),
        ("1 == 1", vec![Op::LoadInt(1), Op::LoadInt(1), Op::NumEq]),
        ("LoadTrue", vec![Op::LoadTrue]),
        ("LoadFalse", vec![Op::LoadFalse]),
        ("!0", vec![Op::LoadInt(0), Op::LogNot]),
        ("true + 1", vec![Op::LoadTrue, Op::LoadInt(1), Op::Add]),
    ] {
        let mut b = ChunkBuilder::new();
        for o in &ops {
            b.emit(o.clone(), 1);
        }
        let chunk = b.build();
        let mut answers = Vec::new();
        for _ in 0..3 {
            let mut vm = VM::new(chunk.clone());
            vm.enable_tracing_jit();
            answers.push(describe(&match vm.run() {
                VMResult::Ok(v) => Some(v),
                _ => None,
            }));
        }
        if !answers.windows(2).all(|w| w[0] == w[1]) {
            diffs.push(format!("{label}: {answers:?}"));
        }
    }
    assert_no_diffs("block boolean kind", diffs);
}

// ── Tracing tier ──
//
// The fourth compiler, and the one this file could not see at all until now:
// every harness above drives `try_run_linear` / `try_run_block_*` /
// `run_chunk_native`, and a trace anchors only on a **conditional backward
// branch**. The whole corpus above is straight-line, so no chunk in it ever
// closed a trace — the tracing tier was scoring agreement it had never been
// asked a single question about.
//
// It was not agreeing. With the op under test inside a hot loop, 252 of the
// 589 compiling combinations disagreed with the interpreter, and the failures
// were not confined to the variant: a boolean stored into a float-kinded slot
// came back as a *bit pattern*, so `0 + true` answered `Float(5e-324)` (the
// bits of `1`) and `0 - true` answered `NaN` (the bits of `-1`) where the
// interpreter answers `Float(1.0)` / `Float(-1.0)`.

/// Wrap `a OP b` in a hot do-while loop so the op is recorded into a trace,
/// and hand the computed value back through a slot.
///
/// ```text
///   LoadInt(salt); Pop            // unique op_hash per case
///   LoadInt(0); SetSlot(0)
/// anchor:
///   PreIncSlotVoid(0)             // loop counter
///   <push a> <push b> OP SetSlot(1)
///   GetSlot(0) LoadInt(200) NumLt JumpIfTrue(anchor)
///   GetSlot(1)                    // the value under test
/// ```
fn trace_chunk_for(a: &Operand, b: Option<&Operand>, op: &Op, salt: i64) -> (Chunk, usize) {
    let mut bd = ChunkBuilder::new();
    bd.emit(Op::LoadInt(salt), 1);
    bd.emit(Op::Pop, 1);
    bd.emit(Op::LoadInt(0), 1);
    bd.emit(Op::SetSlot(0), 1);
    let anchor = bd.current_pos();
    bd.emit(Op::PreIncSlotVoid(0), 1);
    for o in &a.push {
        bd.emit(o.clone(), 1);
    }
    if let Some(b) = b {
        for o in &b.push {
            bd.emit(o.clone(), 1);
        }
    }
    bd.emit(op.clone(), 1);
    bd.emit(Op::SetSlot(1), 1);
    bd.emit(Op::GetSlot(0), 1);
    bd.emit(Op::LoadInt(200), 1);
    bd.emit(Op::NumLt, 1);
    let jmp = bd.emit(Op::JumpIfTrue(0), 1);
    bd.patch_jump(jmp, anchor);
    bd.emit(Op::GetSlot(1), 1);
    (bd.build(), anchor)
}

/// Run `chunk` with the given slot count, optionally with the tracing JIT on.
fn run_with_slots(chunk: &Chunk, tracing: bool) -> Option<Value> {
    let mut vm = VM::new(chunk.clone());
    if tracing {
        vm.enable_tracing_jit();
    }
    let frame = vm.frames.last_mut().unwrap();
    while frame.slots.len() < 4 {
        frame.slots.push(Value::Int(0));
    }
    match vm.run() {
        VMResult::Ok(v) => Some(v),
        VMResult::Halted => vm.stack.last().cloned(),
        VMResult::Error(_) => None,
    }
}

/// Cross `ops` with `operands` through the tracing tier.
///
/// Returns `(diffs, compiled)`. A case whose trace never compiled is SKIPPED,
/// not scored — but `compiled` is reported so a caller can refuse to pass on an
/// empty corpus. The reference is always the interpreter running the *same*
/// chunk with tracing off, never the traced answer.
fn diff_trace(ops: &[Op], operands: &[Operand], binary: bool, salt0: i64) -> (Vec<String>, usize) {
    let jit = JitCompiler::new();
    let mut diffs = Vec::new();
    let mut compiled = 0usize;
    let mut salt = salt0;
    for op in ops {
        for a in operands {
            let bs: Vec<Option<&Operand>> = if binary {
                operands.iter().map(Some).collect()
            } else {
                vec![None]
            };
            for b in bs {
                salt += 1;
                let (chunk, anchor) = trace_chunk_for(a, b, op, salt);
                let traced = run_with_slots(&chunk, true);
                if !jit.trace_is_compiled(&chunk, anchor) {
                    continue; // never reached the tier — not evidence of agreement
                }
                compiled += 1;
                let expected = run_with_slots(&chunk, false);
                let agree = match (&expected, &traced) {
                    (Some(e), Some(t)) => same(e, t),
                    (None, None) => true,
                    _ => false,
                };
                if !agree {
                    diffs.push(format!(
                        "{:?}({}{}): interp={} trace={}",
                        op,
                        a.label,
                        b.map(|b| format!(", {}", b.label)).unwrap_or_default(),
                        describe(&expected),
                        describe(&traced)
                    ));
                }
            }
        }
    }
    (diffs, compiled)
}

fn assert_trace_clean(what: &str, (diffs, compiled): (Vec<String>, usize)) {
    assert!(
        compiled > 0,
        "{what}: no case in this corpus ever compiled a trace, so a clean run \
         proves nothing. A trace anchors only on a conditional backward branch \
         — check the loop shape before trusting this test."
    );
    assert_no_diffs(what, diffs);
}

#[test]
fn tracing_jit_matches_interpreter_on_arithmetic_and_bitwise() {
    assert_trace_clean(
        "trace arithmetic",
        diff_trace(
            &[
                Op::Add,
                Op::Sub,
                Op::Mul,
                Op::Div,
                Op::Mod,
                Op::Pow,
                Op::BitAnd,
                Op::BitOr,
                Op::BitXor,
                Op::Shl,
                Op::Shr,
            ],
            &all_operands(),
            true,
            1_000_000,
        ),
    );
}

#[test]
fn tracing_jit_matches_interpreter_on_comparisons_and_int_intrinsics() {
    assert_trace_clean(
        "trace comparison",
        diff_trace(
            &[
                Op::NumEq,
                Op::NumNe,
                Op::NumLt,
                Op::NumGt,
                Op::NumLe,
                Op::NumGe,
                Op::Spaceship,
                Op::GcdInt,
                Op::LcmInt,
            ],
            &all_operands(),
            true,
            2_000_000,
        ),
    );
}

#[test]
fn tracing_jit_matches_interpreter_on_unary_ops() {
    assert_trace_clean(
        "trace unary",
        diff_trace(
            &[
                Op::Negate,
                Op::Inc,
                Op::Dec,
                Op::BitNot,
                Op::LogNot,
                Op::AbsInt,
                Op::TruncInt,
                Op::AbsFloat,
                Op::CeilFloat,
                Op::FloorFloat,
                Op::TruncFloat,
                Op::RoundFloat,
                Op::SqrtFloat,
            ],
            &all_operands(),
            false,
            3_000_000,
        ),
    );
}