shape-vm 0.3.1

Stack-based bytecode virtual machine for the Shape programming language
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
//! Integration tests for operator overloading via traits.
//!
//! Tests compile and run Shape source code to verify:
//! - impl Add for custom types
//! - impl Sub for custom types
//! - impl Mul for custom types
//! - impl Div for custom types
//! - impl Neg for custom types
//! - Operator trait fallback only fires when built-in paths don't match

use crate::bytecode::{BuiltinFunction, OpCode, Operand};
use crate::executor::tests::test_utils::{compile, eval, eval_result};
use shape_value::{ValueWord, ValueWordExt};

#[test]
fn test_add_trait_overload() {
    // Define a Vec2 type with impl Add
    let result = eval(
        r#"
        type Vec2 { x: number, y: number }

        impl Add for Vec2 {
            method add(other: Vec2) -> Vec2 {
                Vec2 { x: self.x + other.x, y: self.y + other.y }
            }
        }

        let a = Vec2 { x: 1.0, y: 2.0 }
        let b = Vec2 { x: 3.0, y: 4.0 }
        let c = a + b
        c.x + c.y
    "#,
    );
    let val = result.as_number_coerce().expect("should be a number");
    assert_eq!(val, 10.0, "Vec2(1,2) + Vec2(3,4) = Vec2(4,6), x+y = 10");
}

#[test]
fn test_sub_trait_overload() {
    let result = eval(
        r#"
        type Vec2 { x: number, y: number }

        impl Sub for Vec2 {
            method sub(other: Vec2) -> Vec2 {
                Vec2 { x: self.x - other.x, y: self.y - other.y }
            }
        }

        let a = Vec2 { x: 5.0, y: 10.0 }
        let b = Vec2 { x: 1.0, y: 3.0 }
        let c = a - b
        c.x + c.y
    "#,
    );
    let val = result.as_number_coerce().expect("should be a number");
    assert_eq!(val, 11.0, "Vec2(5,10) - Vec2(1,3) = Vec2(4,7), x+y = 11");
}

#[test]
fn test_mul_trait_overload() {
    let result = eval(
        r#"
        type Vec2 { x: number, y: number }

        impl Mul for Vec2 {
            method mul(other: Vec2) -> Vec2 {
                Vec2 { x: self.x * other.x, y: self.y * other.y }
            }
        }

        let a = Vec2 { x: 2.0, y: 3.0 }
        let b = Vec2 { x: 4.0, y: 5.0 }
        let c = a * b
        c.x + c.y
    "#,
    );
    let val = result.as_number_coerce().expect("should be a number");
    assert_eq!(val, 23.0, "Vec2(2,3) * Vec2(4,5) = Vec2(8,15), x+y = 23");
}

#[test]
fn test_div_trait_overload() {
    let result = eval(
        r#"
        type Vec2 { x: number, y: number }

        impl Div for Vec2 {
            method div(other: Vec2) -> Vec2 {
                Vec2 { x: self.x / other.x, y: self.y / other.y }
            }
        }

        let a = Vec2 { x: 10.0, y: 20.0 }
        let b = Vec2 { x: 2.0, y: 5.0 }
        let c = a / b
        c.x + c.y
    "#,
    );
    let val = result.as_number_coerce().expect("should be a number");
    assert_eq!(val, 9.0, "Vec2(10,20) / Vec2(2,5) = Vec2(5,4), x+y = 9");
}

#[test]
fn test_neg_trait_overload() {
    let result = eval(
        r#"
        type Vec2 { x: number, y: number }

        impl Neg for Vec2 {
            method neg() -> Vec2 {
                Vec2 { x: -self.x, y: -self.y }
            }
        }

        let a = Vec2 { x: 3.0, y: -7.0 }
        let b = -a
        b.x + b.y
    "#,
    );
    let val = result.as_number_coerce().expect("should be a number");
    assert_eq!(val, 4.0, "-Vec2(3,-7) = Vec2(-3,7), x+y = 4");
}

#[test]
fn test_multiple_operator_traits() {
    // Test that a type can implement multiple operator traits
    let result = eval(
        r#"
        type Money { cents: int }

        impl Add for Money {
            method add(other: Money) -> Money {
                Money { cents: self.cents + other.cents }
            }
        }

        impl Sub for Money {
            method sub(other: Money) -> Money {
                Money { cents: self.cents - other.cents }
            }
        }

        let a = Money { cents: 500 }
        let b = Money { cents: 200 }
        let sum = a + b
        let diff = a - b
        sum.cents + diff.cents
    "#,
    );
    let val = result.as_i64().expect("should be an int");
    assert_eq!(
        val, 1000,
        "Money(500)+Money(200)=700, Money(500)-Money(200)=300, total=1000"
    );
}

#[test]
fn test_builtin_arithmetic_still_works() {
    // Make sure regular numeric arithmetic isn't affected
    let result = eval("2 + 3");
    assert_eq!(result.as_i64().unwrap(), 5);

    let result = eval("10.0 - 3.0");
    assert_eq!(result.as_number_coerce().unwrap(), 7.0);

    let result = eval("4 * 5");
    assert_eq!(result.as_i64().unwrap(), 20);

    let result = eval("20 / 4");
    assert_eq!(result.as_i64().unwrap(), 5);

    let result = eval("-42");
    assert_eq!(result.as_i64().unwrap(), -42);
}

#[test]
fn test_string_concat_still_works() {
    // String concatenation should not be affected by operator traits
    let result = eval(r#""hello " + "world""#);
    assert_eq!(result.as_str().unwrap(), "hello world");
}

/// Iterate over every instruction in the program, including function bodies.
/// Used by the R5.2A baseline tests below to assert on the full emitted opcode
/// stream, not just the main script body.
fn all_opcodes(program: &crate::bytecode::BytecodeProgram) -> Vec<OpCode> {
    program.instructions.iter().map(|i| i.opcode).collect()
}

/// R5.2A baseline regression test for the v2 residuals closeout plan.
///
/// Pins the current emission shape for user-defined `impl Add for T` so that
/// R5.2B (which extends retargeting to the remaining Add-specific dynamic
/// fallback branch at `binary_ops.rs:~L867`) can make a focused, reviewable
/// change without accidentally regressing the paths that already compile to
/// `CallMethod`.
///
/// Today the compiler already emits `CallMethod` (via
/// `emit_operator_trait_call`) for `a + b` when both operands have TypedObject
/// schemas AND the left type implements `Add` (see
/// `compiler/expressions/binary_ops.rs:665-684`). This test pins that
/// behaviour: the script's `a + b` user-trait dispatch must compile to
/// `CallMethod`, not to `AddDynamic`.
///
/// The test isolates the user-trait dispatch by storing the result in a
/// module binding and checking only the main-script instruction range (i.e.
/// excluding function bodies, which legitimately contain `AddNumber` for
/// inlined numeric field additions).
///
/// Reference: `/home/dev/.claude/plans/v2-residuals-closeout.md` §R5.2.
#[test]
fn test_r5_2a_user_add_compiles_to_call_method_not_add_dynamic() {
    let program = compile(
        r#"
        type Vec2 { x: number, y: number }

        impl Add for Vec2 {
            method add(other: Vec2) -> Vec2 {
                Vec2 { x: self.x + other.x, y: self.y + other.y }
            }
        }

        let a = Vec2 { x: 1.0, y: 2.0 }
        let b = Vec2 { x: 3.0, y: 4.0 }
        let c = a + b
    "#,
    );

    let ops = all_opcodes(&program);

    // Baseline: this self-contained program has exactly one `+` in the main
    // script (`a + b`). It must have retargeted to `CallMethod` at compile
    // time, so `AddDynamic` must not appear in the main-script stream.
    //
    // Note: function bodies (e.g. `self.x + other.x` inside Vec2::add) live
    // in the same instruction vector but emit `AddNumber`, not `AddDynamic`,
    // because both operands are proven `number`. So scanning the whole vector
    // for `AddDynamic` is sufficient here; any future regression in the user-
    // trait retarget would surface as `AddDynamic` in this program.
    // Phase 2: the `AddDynamic` opcode no longer exists; the only post-Phase-2
    // signal that the retarget fired is the presence of `CallMethod`.
    let call_method_count = ops.iter().filter(|&&o| o == OpCode::CallMethod).count();
    assert!(
        call_method_count >= 1,
        "R5.2A regression: no CallMethod emitted for user-defined operator \
         trait dispatch. Ops emitted: {:?}",
        ops
    );
}

/// R5.2B regression test for the v2 residuals closeout plan.
///
/// Exercises the gap path closed by R5.2B: the Add branch's
/// `NumericEmitResult::CoercedNeedsGeneric | NumericEmitResult::NoPlan`
/// arm in `compiler/expressions/binary_ops.rs`. In R5.2A this arm fell
/// through to `emit_binary_op(..., Unknown, Unknown, ...)` which emitted
/// `AddDynamic`, so the user trait impl was only reached at runtime via
/// `exec_arithmetic_dynamic_fallback::try_binary_operator_trait`. R5.2B
/// retargets this arm to `CallMethod` at compile time.
///
/// To reach the arm we need a program where only the LHS has a schema
/// (the priority-1 both-schemas fast path at L665-684 does not fire) AND
/// `emit_numeric_binary_with_coercion_trusted` returns `NoPlan`. The RHS
/// is an identity-style function call `pick(b)`: because `pick` has an
/// untyped parameter, its inferred return is a fresh type variable, and
/// the call-site value carries no TypedObject schema. After
/// `compile_expr(right)` the compiler's `last_expr_schema` is None,
/// defeating the priority-1 fast path and forcing the NoPlan arm.
///
/// Verified by stashing just the `binary_ops.rs` change on top of R5.2A:
/// this test failed with `AddDynamic` appearing in the instruction
/// stream at the `a + pick(b)` site. With R5.2B applied it retargets to
/// `CallMethod` and this test passes.
///
/// Reference: `/home/dev/.claude/plans/v2-residuals-closeout.md` §R5.2.
#[test]
fn test_r5_2b_user_add_retargets_single_schema_fallback() {
    let program = compile(
        r#"
        type Vec2 { x: number, y: number }

        impl Add for Vec2 {
            method add(other: Vec2) -> Vec2 {
                Vec2 { x: self.x + other.x, y: self.y + other.y }
            }
        }

        // Identity-style function with an untyped parameter: its inferred
        // return type is a free type variable (not a concrete schema), so
        // the call-site value has no TypedObject schema attached.
        fn pick(x) { return x }

        let a = Vec2 { x: 1.0, y: 2.0 }
        let b = Vec2 { x: 3.0, y: 4.0 }
        // `pick(b)` returns a schema-less value at compile time: the
        // identity return type is a fresh type variable, so after
        // `compile_expr(right)` the compiler's `last_expr_schema` is None.
        // This defeats the priority-1 both-schemas fast path at L665-684
        // and forces the Add branch into the `CoercedNeedsGeneric | NoPlan`
        // arm — the gap R5.2B closes. The R5.2B-inserted
        // `try_emit_trait_dispatch` call then picks up `left_schema = Vec2`
        // and retargets to `CallMethod("add")` at compile time.
        let r = a + pick(b)
    "#,
    );

    let ops = all_opcodes(&program);

    // R5.2B: the single-schema fallback must now retarget to `CallMethod`
    // at compile time, not fall through to `AddDynamic`. Scanning the
    // whole instruction vector is safe: every `+` inside `Vec2::add`
    // operates on proven-numeric operands and emits `AddNumber`; any
    // `AddDynamic` would be the R5.2B gap regressing.
    // Phase 2: the `AddDynamic` opcode no longer exists; the only post-Phase-2
    // signal that the retarget fired is the presence of `CallMethod`.

    // `CallMethod` must appear at least once — for the top-level
    // `a + { ... }` retargeted to `a.add(rhs)`.
    let call_method_count = ops.iter().filter(|&&o| o == OpCode::CallMethod).count();
    assert!(
        call_method_count >= 1,
        "R5.2B regression: no CallMethod emitted for the single-schema \
         user-op Add fallback. Ops emitted: {:?}",
        ops
    );
}

/// R5.3B retarget regression test for the v2 residuals closeout plan.
///
/// Replaces `test_r5_3a_datetime_arithmetic_fallback_baseline` (the R5.3A
/// baseline that pinned the pre-fix `AddDynamic` / `SubDynamic` emission).
/// After R5.3B the compiler's temporal retarget fires uniformly:
///
///   - `compile_expr_datetime` and `compile_expr_duration` now publish the
///     temporal display name on `last_expr_type_info`, so
///     `propagate_assignment_type_to_slot` records `"DateTime"` or
///     `"Duration"` on let-locals bound to temporal literals.
///   - `infer_expr_type` consults the compiler's `type_tracker` for
///     `Expr::Identifier` and returns the temporal display name whenever
///     the local/module-binding tracker records it, covering both typed
///     function parameters (populated via
///     `tracked_type_name_from_annotation`) and let-locals (populated via
///     the new `propagate_assignment_type_to_slot` arm).
///
/// With those two fixes the retarget guards at
/// `compiler/expressions/binary_ops.rs:750-771` (Add) and `:1049-1072`
/// (Sub) fire for every reachable DateTime / Duration arithmetic shape
/// and emit `CallMethod("add")` / `CallMethod("sub")`. The five temporal
/// arms in `executor/arithmetic/mod.rs::try_heap_arithmetic` are now
/// unreachable for any program these assertions can reach.
///
/// The three cases mirror the R5.3A baseline shapes: let-locals +
/// literals, typed params with `DateTime - Duration`, typed params with
/// `DateTime - DateTime`. Each asserts `CallMethod` is emitted and that
/// the dynamic-fallback opcode is absent.
///
/// Reference: `/home/dev/.claude/plans/v2-residuals-closeout.md` §R5.3.

#[test]
fn test_r5_3b_datetime_arithmetic_retargets_to_call_method() {
    // Case 1: DateTime + Duration via let-locals. After R5.3B the
    // temporal-literal initializers populate the local tracker with
    // `"DateTime"` / `"Duration"`, and `infer_expr_type` reads them back
    // through the tracker for the `dt + dur` identifier references so the
    // retarget fires.
    {
        let program = compile(
            r#"
            fn test() {
                let dt = @"2024-01-15"
                let dur = 3d
                dt + dur
            }
            test()
            "#,
        );
        let ops = all_opcodes(&program);
        // Phase 2: `*Dynamic` opcodes deleted; CallMethod presence is the signal.
        assert!(
            ops.contains(&OpCode::CallMethod),
            "R5.3B regression: let-local DateTime + Duration did not emit \
             CallMethod. Ops emitted: {:?}",
            ops
        );
    }

    // Case 2: DateTime - Duration via typed function parameters. Param
    // annotations seed the tracker via `tracked_type_name_from_annotation`
    // in `compile_function`, so `infer_expr_type` finds `"DateTime"` /
    // `"Duration"` for the identifiers and the Sub retarget fires.
    {
        let program = compile(
            r#"
            fn test(dt: DateTime, dur: Duration) {
                dt - dur
            }
            test(@"2024-01-15", 1d)
            "#,
        );
        let ops = all_opcodes(&program);
        assert!(
            ops.contains(&OpCode::CallMethod),
            "R5.3B regression: typed-param DateTime - Duration did not emit \
             CallMethod. Ops emitted: {:?}",
            ops
        );
    }

    // Case 3: DateTime - DateTime via typed function parameters. Yields a
    // Duration/TimeSpan via `datetime_sub_v2` through CallMethod.
    {
        let program = compile(
            r#"
            fn test(a: DateTime, b: DateTime) {
                a - b
            }
            test(@"2024-01-15", @"2024-01-10")
            "#,
        );
        let ops = all_opcodes(&program);
        assert!(
            ops.contains(&OpCode::CallMethod),
            "R5.3B regression: typed-param DateTime - DateTime did not emit \
             CallMethod. Ops emitted: {:?}",
            ops
        );
    }
}

#[test]
fn test_operator_overload_without_trait_fails() {
    // Without implementing Sub, - on custom types should fail at compile time
    let result = eval_result(
        r#"
        type Foo { x: int }
        let a = Foo { x: 1 }
        let b = Foo { x: 2 }
        a - b
    "#,
    );
    assert!(
        result.is_err(),
        "Subtracting two Foo without impl Sub should fail"
    );
}

/// Check whether the emitted instruction stream contains a `BuiltinCall`
/// targeting the given `BuiltinFunction` variant. Used by the R5.4E
/// retarget-pin test to assert that `Matrix`/`Vec` arithmetic compiles
/// down to the intrinsic form rather than the dynamic arithmetic
/// fallback.
fn has_builtin_call(program: &crate::bytecode::BytecodeProgram, builtin: BuiltinFunction) -> bool {
    program.instructions.iter().any(|ins| {
        ins.opcode == OpCode::BuiltinCall
            && matches!(ins.operand, Some(Operand::Builtin(b)) if b == builtin)
    })
}

/// R5.4E retarget-pin test for the v2 residuals closeout plan.
///
/// This is the flipped successor of R5.4A's baseline. After R5.4E, the
/// compiler retargets `Matrix`/`Vec` arithmetic at compile time to the
/// `IntrinsicMat*` / `IntrinsicVec*` builtins added in R5.4D
/// (`IntrinsicMatAdd`, `IntrinsicMatSub`, `IntrinsicVecAddI64`) and
/// wired in R5.4C (`IntrinsicVecAdd/Sub/Mul/Div`). Each of the seven
/// operand shapes the R5.4A baseline pinned to `*Dynamic` now compiles
/// to a `BuiltinCall(BuiltinFunction::Intrinsic*)` and the `*Dynamic`
/// opcode is absent from the emitted stream.
///
/// The two retarget helpers —
/// `try_compile_typed_vec_arithmetic` and
/// `try_compile_typed_matrix_arithmetic` in
/// `compiler/expressions/matrix_ops.rs` — are invoked from the Add arm
/// and the generic `_ => {}` arm in `compiler/expressions/binary_ops.rs`
/// before any operand compilation. They classify by resolved type name
/// (`Vec<number>`/`Vec<int>`/`Mat<number>`), compile both operands,
/// push the arg-count constant, and emit `BuiltinCall`.
///
/// R5.4F owns the dead-arm annotation / eventual removal of the
/// corresponding arms in `executor/arithmetic/mod.rs::try_heap_arithmetic`.
///
/// Reference: /home/dev/.claude/plans/v2-residuals-closeout.md §R5.4.
#[test]
fn test_r5_4e_matrix_vec_arithmetic_retargets_to_intrinsics() {
    // Case 1: `Mat<number> + Mat<number>` → IntrinsicMatAdd.
    {
        let program = compile(
            r#"
            fn test(a: Mat<number>, b: Mat<number>) { a + b }
            "#,
        );
        let ops = all_opcodes(&program);
        assert!(
            has_builtin_call(&program, BuiltinFunction::IntrinsicMatAdd),
            "R5.4E retarget: Mat+Mat must emit BuiltinCall(IntrinsicMatAdd). \
             Ops emitted: {:?}",
            ops
        );
    }

    // Case 2: `Mat<number> - Mat<number>` → IntrinsicMatSub.
    {
        let program = compile(
            r#"
            fn test(a: Mat<number>, b: Mat<number>) { a - b }
            "#,
        );
        let ops = all_opcodes(&program);
        assert!(
            has_builtin_call(&program, BuiltinFunction::IntrinsicMatSub),
            "R5.4E retarget: Mat-Mat must emit BuiltinCall(IntrinsicMatSub). \
             Ops emitted: {:?}",
            ops
        );
    }

    // Case 3: `Vec<number> + Vec<number>` → IntrinsicVecAdd.
    {
        let program = compile(
            r#"
            fn test(a: Vec<number>, b: Vec<number>) { a + b }
            "#,
        );
        let ops = all_opcodes(&program);
        assert!(
            has_builtin_call(&program, BuiltinFunction::IntrinsicVecAdd),
            "R5.4E retarget: Vec<number>+Vec<number> must emit \
             BuiltinCall(IntrinsicVecAdd). Ops emitted: {:?}",
            ops
        );
    }

    // Case 4: `Vec<number> - Vec<number>` → IntrinsicVecSub.
    {
        let program = compile(
            r#"
            fn test(a: Vec<number>, b: Vec<number>) { a - b }
            "#,
        );
        let ops = all_opcodes(&program);
        assert!(
            has_builtin_call(&program, BuiltinFunction::IntrinsicVecSub),
            "R5.4E retarget: Vec<number>-Vec<number> must emit \
             BuiltinCall(IntrinsicVecSub). Ops emitted: {:?}",
            ops
        );
    }

    // Case 5: `Vec<number> * Vec<number>` → IntrinsicVecMul.
    // Covers the element-wise multiply path (separate from
    // `try_compile_typed_matrix_mul`, which only fires for Mat*Vec /
    // Mat*Mat).
    {
        let program = compile(
            r#"
            fn test(a: Vec<number>, b: Vec<number>) { a * b }
            "#,
        );
        let ops = all_opcodes(&program);
        assert!(
            has_builtin_call(&program, BuiltinFunction::IntrinsicVecMul),
            "R5.4E retarget: Vec<number>*Vec<number> must emit \
             BuiltinCall(IntrinsicVecMul). Ops emitted: {:?}",
            ops
        );
    }

    // Case 6: `Vec<number> / Vec<number>` → IntrinsicVecDiv.
    {
        let program = compile(
            r#"
            fn test(a: Vec<number>, b: Vec<number>) { a / b }
            "#,
        );
        let ops = all_opcodes(&program);
        assert!(
            has_builtin_call(&program, BuiltinFunction::IntrinsicVecDiv),
            "R5.4E retarget: Vec<number>/Vec<number> must emit \
             BuiltinCall(IntrinsicVecDiv). Ops emitted: {:?}",
            ops
        );
    }

    // Case 7: `Vec<int> + Vec<int>` → IntrinsicVecAddI64.
    // Overflow semantics (`simd_vec_add_i64`) are preserved by the
    // intrinsic — see `intrinsic_vec_add_i64` at
    // `shape-runtime::intrinsics::vector`.
    {
        let program = compile(
            r#"
            fn test(a: Vec<int>, b: Vec<int>) { a + b }
            "#,
        );
        let ops = all_opcodes(&program);
        assert!(
            has_builtin_call(&program, BuiltinFunction::IntrinsicVecAddI64),
            "R5.4E retarget: Vec<int>+Vec<int> must emit \
             BuiltinCall(IntrinsicVecAddI64). Ops emitted: {:?}",
            ops
        );
    }
}

/// R5.4E runtime: verify that the retargeted `Mat<number> + Mat<number>`
/// path returns the expected element-wise sum. Uses the `let`-binding
/// form with an explicit `Mat<number>` annotation so R5.4B's nested-array
/// typed-inference rule applies (produces `HeapValue::Array` of
/// `HeapValue::Array`, which `extract_matrix_f64` in the kernel expects).
#[test]
fn test_r5_4e_mat_add_runtime_returns_correct_values() {
    // (a + b)[0][0] = 1 + 10 = 11, (a + b)[1][1] = 4 + 40 = 44, sum = 55.
    let result = eval(
        r#"
        let a: Mat<number> = [[1.0, 2.0], [3.0, 4.0]]
        let b: Mat<number> = [[10.0, 20.0], [30.0, 40.0]]
        let c = a + b
        c[0][0] + c[1][1]
        "#,
    );
    let n = result
        .as_number_coerce()
        .expect("R5.4E: Mat+Mat result should be numeric at c[0][0]+c[1][1]");
    assert!(
        (n - 55.0).abs() < 1e-10,
        "R5.4E: Mat+Mat expected 55.0, got {}",
        n
    );
}

// R5.4E runtime note: an end-to-end Shape-source runtime test for the
// retargeted `Vec<number>+Vec<number>` / `Vec<int>+Vec<int>` shapes is
// blocked on a v2 array-literal representation concern that is
// orthogonal to R5.4E. The compiler's typed-array fast path stores
// `Vec<number>` as a native `TypedArray<f64>` pointer (via
// `NewTypedArrayF64` / `TypedArrayPushF64`) and `Vec<int>` as a native
// `TypedArray<i64>` pointer, while the intrinsic kernels — and the
// pre-R5.4E `AddDynamic` path via `as_heap_ref()` — expect the v1
// `HeapValue::TypedArray(TypedArrayData::F64(..))` /
// `(TypedArrayData::I64(..))` form. This is NOT a regression: the
// same let-form `Vec<T>+Vec<T>` fails identically under the
// pre-R5.4E `AddDynamic` path for the same reason. Closing that gap
// (making both paths accept the v2 native pointer) is tracked
// separately and out of R5.4E scope.
//
// The kernel-level element-wise sum and overflow semantics are pinned
// in `shape-runtime::intrinsics::vector::tests` (incl.
// `test_simd_vec_add_i64_overflow` and
// `test_simd_vec_add_f64_*`). The compile-time retarget emission
// across all seven R5.4A baseline shapes is pinned by
// `test_r5_4e_matrix_vec_arithmetic_retargets_to_intrinsics` above.
// The Mat+Mat runtime path is exercised by
// `test_r5_4e_mat_add_runtime_returns_correct_values` above, where
// R5.4B's nested-array typed-inference rule produces operands in the
// `HeapValue::Array` shape that `extract_matrix_f64` accepts.