ccalc-engine 0.47.0

Core computation engine for ccalc: tokenizer, parser, AST evaluator, and memory cells
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
//! Bytecode VM executor.
//!
//! [`vm_exec`] runs a compiled [`Chunk`] against a mutable [`Env`], producing
//! identical observable behaviour to the tree-walking interpreter while
//! eliminating per-statement `exec_stmts` call overhead.

use ndarray::Array2;
use num_complex::Complex;

use super::{Chunk, IterState, Opcode};
use crate::env::{Env, Value};
use crate::eval::{
    Base, Expr, FormatMode, Op, current_func_name, eval_with_io, global_set, is_global,
    is_persistent, persistent_save, set_display_ctx,
};
use crate::exec::{Signal, print_value};
use crate::io::IoContext;

// ── Entry point ───────────────────────────────────────────────────────────────

/// Execute a compiled [`Chunk`] against `env`.
///
/// Returns `Ok(None)` on normal completion, `Ok(Some(Signal::*))` when a
/// `break`/`continue`/`return` escapes the block, or `Err(msg)` on runtime
/// error.  The result is identical to what `exec_stmts` would have produced for
/// the same statement block.
pub fn vm_exec(
    chunk: &Chunk,
    env: &mut Env,
    io: &mut IoContext,
    fmt: &FormatMode,
    base: Base,
    compact: bool,
) -> Result<Option<Signal>, String> {
    // Propagate display settings to eval.rs so EvalExpr / fn-call paths work.
    set_display_ctx(fmt, base, compact);

    // ── Init slot-local variables from env (one-time cost per chunk entry) ───
    let mut locals: Vec<Value> = chunk
        .slot_names
        .iter()
        .map(|name| env.get(name.as_str()).cloned().unwrap_or(Value::Void))
        .collect();

    let mut stack: Vec<Value> = Vec::with_capacity(8);
    let mut iters: Vec<IterState> = Vec::new();
    let mut ip: usize = 0;

    // Annotate a runtime error with a source line number if one is recorded.
    macro_rules! at_line {
        ($result:expr) => {
            $result.map_err(|e: String| {
                let line = chunk.lines.get(ip).copied().unwrap_or(0);
                if line == 0 || e.contains("near line") {
                    e
                } else {
                    format!("{e} near line {line}")
                }
            })?
        };
    }

    while ip < chunk.code.len() {
        let instr = &chunk.code[ip];
        match instr.op {
            // ── Constants & variables ─────────────────────────────────────────
            Opcode::PushConst => {
                let v = chunk.consts[instr.u16_arg() as usize].clone();
                stack.push(v);
                ip += 1;
            }

            Opcode::LoadVar => {
                let name = &chunk.names[instr.u16_arg() as usize];
                // Fast path: variable already in env (covers most iterations).
                let v = if let Some(existing) = env.get(name.as_str()) {
                    existing.clone()
                } else {
                    // Slow path: may be a built-in constant (pi, e, inf, nan, …).
                    at_line!(eval_with_io(&Expr::Var(name.clone()), env, io))
                };
                stack.push(v);
                ip += 1;
            }

            Opcode::StoreVar => {
                let name_idx = instr.u16_at(0) as usize;
                let silent = instr.u8_at(2) != 0;
                let val = stack.pop().unwrap();
                let name = &chunk.names[name_idx];
                env.insert(name.clone(), val.clone());
                // Mirror to the global store when declared global in this scope.
                if is_global(name) {
                    global_set(name, val.clone());
                }
                // Write-through for persistent vars.
                if is_persistent(name) {
                    persistent_save(&current_func_name(), name, val.clone());
                }
                if !silent && !matches!(val, Value::Void) {
                    print_value(Some(name), &val, fmt, base, compact);
                }
                ip += 1;
            }

            Opcode::UpdateAns => {
                // Peek (no pop) — ans is updated even for silent expr stmts.
                let v = stack.last().unwrap().clone();
                env.insert("ans".to_string(), v);
                ip += 1;
            }

            Opcode::Pop => {
                stack.pop();
                ip += 1;
            }

            Opcode::Print => {
                let v = stack.pop().unwrap();
                if !matches!(v, Value::Void) {
                    print_value(None, &v, fmt, base, compact);
                }
                ip += 1;
            }

            // ── Slot-local variables ──────────────────────────────────────────
            Opcode::LoadSlot => {
                let slot = instr.u16_arg() as usize;
                stack.push(locals[slot].clone());
                ip += 1;
            }

            Opcode::StoreSlot => {
                let slot = instr.u16_at(0) as usize;
                let silent = instr.u8_at(2) != 0;
                let val = stack.pop().unwrap();
                locals[slot] = val.clone();
                if !silent && !matches!(val, Value::Void) {
                    print_value(Some(&chunk.slot_names[slot]), &val, fmt, base, compact);
                }
                ip += 1;
            }

            // ── Arithmetic ────────────────────────────────────────────────────
            Opcode::Add => {
                let b = stack.pop().unwrap();
                let a = stack.pop().unwrap();
                stack.push(at_line!(vm_binop(a, Op::Add, b, env, io)));
                ip += 1;
            }
            Opcode::Sub => {
                let b = stack.pop().unwrap();
                let a = stack.pop().unwrap();
                stack.push(at_line!(vm_binop(a, Op::Sub, b, env, io)));
                ip += 1;
            }
            Opcode::Mul => {
                let b = stack.pop().unwrap();
                let a = stack.pop().unwrap();
                stack.push(at_line!(vm_binop(a, Op::Mul, b, env, io)));
                ip += 1;
            }
            Opcode::Div => {
                let b = stack.pop().unwrap();
                let a = stack.pop().unwrap();
                stack.push(at_line!(vm_binop(a, Op::Div, b, env, io)));
                ip += 1;
            }
            Opcode::Pow => {
                let b = stack.pop().unwrap();
                let a = stack.pop().unwrap();
                stack.push(at_line!(vm_binop(a, Op::Pow, b, env, io)));
                ip += 1;
            }
            Opcode::ElemMul => {
                let b = stack.pop().unwrap();
                let a = stack.pop().unwrap();
                stack.push(at_line!(vm_binop(a, Op::ElemMul, b, env, io)));
                ip += 1;
            }
            Opcode::ElemDiv => {
                let b = stack.pop().unwrap();
                let a = stack.pop().unwrap();
                stack.push(at_line!(vm_binop(a, Op::ElemDiv, b, env, io)));
                ip += 1;
            }
            Opcode::ElemPow => {
                let b = stack.pop().unwrap();
                let a = stack.pop().unwrap();
                stack.push(at_line!(vm_binop(a, Op::ElemPow, b, env, io)));
                ip += 1;
            }
            Opcode::Neg => {
                let a = stack.pop().unwrap();
                stack.push(at_line!(vm_neg(a, env, io)));
                ip += 1;
            }

            // ── Comparison / logical ──────────────────────────────────────────
            Opcode::Eq => {
                let b = stack.pop().unwrap();
                let a = stack.pop().unwrap();
                stack.push(at_line!(vm_binop(a, Op::Eq, b, env, io)));
                ip += 1;
            }
            Opcode::Ne => {
                let b = stack.pop().unwrap();
                let a = stack.pop().unwrap();
                stack.push(at_line!(vm_binop(a, Op::NotEq, b, env, io)));
                ip += 1;
            }
            Opcode::Lt => {
                let b = stack.pop().unwrap();
                let a = stack.pop().unwrap();
                stack.push(at_line!(vm_binop(a, Op::Lt, b, env, io)));
                ip += 1;
            }
            Opcode::Le => {
                let b = stack.pop().unwrap();
                let a = stack.pop().unwrap();
                stack.push(at_line!(vm_binop(a, Op::LtEq, b, env, io)));
                ip += 1;
            }
            Opcode::Gt => {
                let b = stack.pop().unwrap();
                let a = stack.pop().unwrap();
                stack.push(at_line!(vm_binop(a, Op::Gt, b, env, io)));
                ip += 1;
            }
            Opcode::Ge => {
                let b = stack.pop().unwrap();
                let a = stack.pop().unwrap();
                stack.push(at_line!(vm_binop(a, Op::GtEq, b, env, io)));
                ip += 1;
            }
            Opcode::And => {
                let b = stack.pop().unwrap();
                let a = stack.pop().unwrap();
                stack.push(at_line!(vm_binop(a, Op::And, b, env, io)));
                ip += 1;
            }
            Opcode::Or => {
                let b = stack.pop().unwrap();
                let a = stack.pop().unwrap();
                stack.push(at_line!(vm_binop(a, Op::Or, b, env, io)));
                ip += 1;
            }
            Opcode::Not => {
                let a = stack.pop().unwrap();
                let result = match &a {
                    Value::Scalar(n) => Value::Scalar(if *n == 0.0 { 1.0 } else { 0.0 }),
                    _ => {
                        // Fall back via eval_with_io for complex / matrix NOT.
                        let idx = env.len(); // use len as a unique key to avoid collision
                        let tmp_key = format!("__vm_not_{idx}__");
                        env.insert(tmp_key.clone(), a);
                        let result = eval_with_io(
                            &Expr::UnaryNot(Box::new(Expr::Var(tmp_key.clone()))),
                            env,
                            io,
                        )?;
                        env.remove(&tmp_key);
                        result
                    }
                };
                stack.push(result);
                ip += 1;
            }

            // ── Control flow ──────────────────────────────────────────────────
            Opcode::Jump => {
                let off = instr.i32_arg();
                ip = (ip as isize + 1 + off as isize) as usize;
            }
            Opcode::JumpFalsy => {
                let off = instr.i32_arg();
                let v = stack.pop().unwrap();
                if !is_truthy(&v) {
                    ip = (ip as isize + 1 + off as isize) as usize;
                } else {
                    ip += 1;
                }
            }
            Opcode::JumpTruthy => {
                let off = instr.i32_arg();
                let v = stack.pop().unwrap();
                if is_truthy(&v) {
                    ip = (ip as isize + 1 + off as isize) as usize;
                } else {
                    ip += 1;
                }
            }

            // ── For-loop iteration ────────────────────────────────────────────
            Opcode::PushIter => {
                let range_val = stack.pop().unwrap();
                iters.push(at_line!(IterState::from_value(range_val)));
                ip += 1;
            }
            Opcode::IterNext => {
                let var_idx = instr.u16_at(0) as usize;
                let exit_off = instr.i32_at(2);
                match iters.last_mut().unwrap().next_val() {
                    Some(val) => {
                        env.insert(chunk.names[var_idx].clone(), val);
                        ip += 1;
                    }
                    None => {
                        iters.pop();
                        ip = (ip as isize + 1 + exit_off as isize) as usize;
                    }
                }
            }
            Opcode::PopIter => {
                iters.pop();
                ip += 1;
            }
            Opcode::IterNextSlot => {
                let slot = instr.u16_at(0) as usize;
                let exit_off = instr.i32_at(2);
                match iters.last_mut().unwrap().next_val() {
                    Some(val) => {
                        locals[slot] = val;
                        ip += 1;
                    }
                    None => {
                        iters.pop();
                        ip = (ip as isize + 1 + exit_off as isize) as usize;
                    }
                }
            }

            // ── Native builtin call ───────────────────────────────────────────
            Opcode::CallBuiltin => {
                let name_idx = instr.u16_at(0) as usize;
                let argc = instr.u8_at(2) as usize;
                // Pop argc args; rightmost arg is on top — reverse to get call order.
                let mut args: Vec<Value> = (0..argc).map(|_| stack.pop().unwrap()).collect();
                args.reverse();
                let result = at_line!(crate::eval::call_builtin(
                    &chunk.names[name_idx],
                    &args,
                    env,
                    Some(&mut *io),
                ));
                stack.push(result);
                ip += 1;
            }

            // ── Deferred expression evaluation ────────────────────────────────
            Opcode::EvalExpr => {
                let expr_idx = instr.u16_arg() as usize;
                let val = at_line!(eval_with_io(&chunk.exprs[expr_idx], env, io));
                stack.push(val);
                ip += 1;
            }

            // ── Indexed assignment: A(i, j) = v ──────────────────────────────
            Opcode::IndexSetOp => {
                let name_idx = instr.u16_at(0) as usize;
                let iset_idx = instr.u16_at(2) as usize;
                let silent = instr.u8_at(4) != 0;
                let rhs = stack.pop().unwrap();
                let name = &chunk.names[name_idx];
                let indices = &chunk.index_sets[iset_idx];

                // Refresh persistent var before partial update.
                if is_persistent(name) {
                    let func = current_func_name();
                    if let Some(fresh) = crate::eval::persistent_load(&func, name) {
                        env.insert(name.clone(), fresh);
                    }
                }

                at_line!(crate::exec::exec_index_set(name, indices, rhs, env, io));

                // Write-through for persistent vars.
                if is_persistent(name)
                    && let Some(val) = env.get(name)
                {
                    crate::eval::persistent_save(&current_func_name(), name, val.clone());
                }
                if is_global(name)
                    && let Some(val) = env.get(name)
                {
                    global_set(name, val.clone());
                }
                if !silent && let Some(val) = env.get(name) {
                    print_value(Some(name), val, fmt, base, compact);
                }
                ip += 1;
            }

            // ── Function definition ───────────────────────────────────────────
            Opcode::DefineFunc => {
                let name_idx = instr.u16_at(0) as usize;
                let const_idx = instr.u16_at(2) as usize;
                let func = chunk.consts[const_idx].clone();
                env.insert(chunk.names[name_idx].clone(), func);
                ip += 1;
            }

            // ── Function control ──────────────────────────────────────────────
            Opcode::Return => {
                sync_locals(chunk, &locals, env);
                return Ok(Some(Signal::Return));
            }
        }
    }

    // ── Sync slot-local variables back to env on normal exit ─────────────────
    sync_locals(chunk, &locals, env);
    Ok(None)
}

// ── Arithmetic helpers ────────────────────────────────────────────────────────

/// Evaluate a binary operation on two [`Value`]s.
///
/// Fast path for `Scalar op Scalar`; falls back to `eval_with_io` for all
/// other type combinations to reuse the existing semantics without duplication.
fn vm_binop(
    a: Value,
    op: Op,
    b: Value,
    env: &mut Env,
    io: &mut IoContext,
) -> Result<Value, String> {
    // ── Scalar × Scalar fast path ─────────────────────────────────────────────
    if let (Value::Scalar(fa), Value::Scalar(fb)) = (&a, &b) {
        let fa = *fa;
        let fb = *fb;
        let result = match op {
            Op::Add => fa + fb,
            Op::Sub => fa - fb,
            Op::Mul => fa * fb,
            Op::Div => fa / fb,
            Op::Pow | Op::ElemPow => fa.powf(fb),
            Op::ElemMul => fa * fb,
            Op::ElemDiv => fa / fb,
            Op::Eq => {
                if fa == fb {
                    1.0
                } else {
                    0.0
                }
            }
            Op::NotEq => {
                if fa != fb {
                    1.0
                } else {
                    0.0
                }
            }
            Op::Lt => {
                if fa < fb {
                    1.0
                } else {
                    0.0
                }
            }
            Op::LtEq => {
                if fa <= fb {
                    1.0
                } else {
                    0.0
                }
            }
            Op::Gt => {
                if fa > fb {
                    1.0
                } else {
                    0.0
                }
            }
            Op::GtEq => {
                if fa >= fb {
                    1.0
                } else {
                    0.0
                }
            }
            Op::And => {
                if fa != 0.0 && fb != 0.0 {
                    1.0
                } else {
                    0.0
                }
            }
            Op::Or => {
                if fa != 0.0 || fb != 0.0 {
                    1.0
                } else {
                    0.0
                }
            }
            Op::ElemAnd => {
                if fa != 0.0 && fb != 0.0 {
                    1.0
                } else {
                    0.0
                }
            }
            Op::ElemOr => {
                if fa != 0.0 || fb != 0.0 {
                    1.0
                } else {
                    0.0
                }
            }
            Op::LDiv => fb / fa,
        };
        return Ok(Value::Scalar(result));
    }

    // ── Complex × Complex / Scalar×Complex fast path ──────────────────────────
    if matches!(
        (&a, &b),
        (
            Value::Complex(..) | Value::Scalar(_),
            Value::Complex(..) | Value::Scalar(_)
        )
    ) {
        let (are, aim) = to_complex_parts(&a);
        let (bre, bim) = to_complex_parts(&b);
        let result: Option<(f64, f64)> = match op {
            Op::Add => Some((are + bre, aim + bim)),
            Op::Sub => Some((are - bre, aim - bim)),
            Op::Mul | Op::ElemMul => Some((are * bre - aim * bim, are * bim + aim * bre)),
            Op::Div | Op::ElemDiv => {
                let denom = bre * bre + bim * bim;
                Some((
                    (are * bre + aim * bim) / denom,
                    (aim * bre - are * bim) / denom,
                ))
            }
            Op::Pow | Op::ElemPow => {
                // Use num_complex for correct branch-cut behaviour.
                let base = Complex::new(are, aim);
                let r = if bim == 0.0 {
                    // Real exponent — use powi for integer exponents (exact, no FP error).
                    if bre.fract() == 0.0 && bre.abs() <= i32::MAX as f64 {
                        base.powi(bre as i32)
                    } else {
                        base.powf(bre)
                    }
                } else {
                    base.powc(Complex::new(bre, bim))
                };
                Some((r.re, r.im))
            }
            Op::Eq => {
                return Ok(Value::Scalar(if are == bre && aim == bim {
                    1.0
                } else {
                    0.0
                }));
            }
            Op::NotEq => {
                return Ok(Value::Scalar(if are != bre || aim != bim {
                    1.0
                } else {
                    0.0
                }));
            }
            _ => None,
        };
        if let Some((re, im)) = result {
            return Ok(if im == 0.0 {
                Value::Scalar(re)
            } else {
                Value::Complex(re, im)
            });
        }
    }

    // ── Scalar × Matrix / Matrix × Scalar broadcast ───────────────────────────
    if let (Value::Scalar(s), Value::Matrix(m)) | (Value::Matrix(m), Value::Scalar(s)) = (&a, &b) {
        let s = *s;
        let result_mat = match op {
            Op::Add | Op::ElemMul => {
                // commutative
                if matches!(a, Value::Scalar(_)) {
                    m.mapv(|x| match op {
                        Op::Add => s + x,
                        _ => s * x,
                    })
                } else {
                    m.mapv(|x| match op {
                        Op::Add => x + s,
                        _ => x * s,
                    })
                }
            }
            Op::Sub => {
                if matches!(a, Value::Scalar(_)) {
                    m.mapv(|x| s - x)
                } else {
                    m.mapv(|x| x - s)
                }
            }
            Op::Mul => {
                // Scalar * Matrix or Matrix * Scalar → broadcast
                m.mapv(|x| x * s)
            }
            Op::Div => {
                if matches!(a, Value::Scalar(_)) {
                    m.mapv(|x| s / x)
                } else {
                    m.mapv(|x| x / s)
                }
            }
            Op::ElemDiv => {
                if matches!(a, Value::Scalar(_)) {
                    m.mapv(|x| s / x)
                } else {
                    m.mapv(|x| x / s)
                }
            }
            Op::Pow | Op::ElemPow => {
                if matches!(a, Value::Scalar(_)) {
                    m.mapv(|x| s.powf(x))
                } else {
                    m.mapv(|x| x.powf(s))
                }
            }
            _ => {
                // Comparison: element-wise
                m.mapv(|x| {
                    let (fa, fb) = if matches!(a, Value::Scalar(_)) {
                        (s, x)
                    } else {
                        (x, s)
                    };
                    match op {
                        Op::Eq => {
                            if fa == fb {
                                1.0
                            } else {
                                0.0
                            }
                        }
                        Op::NotEq => {
                            if fa != fb {
                                1.0
                            } else {
                                0.0
                            }
                        }
                        Op::Lt => {
                            if fa < fb {
                                1.0
                            } else {
                                0.0
                            }
                        }
                        Op::LtEq => {
                            if fa <= fb {
                                1.0
                            } else {
                                0.0
                            }
                        }
                        Op::Gt => {
                            if fa > fb {
                                1.0
                            } else {
                                0.0
                            }
                        }
                        Op::GtEq => {
                            if fa >= fb {
                                1.0
                            } else {
                                0.0
                            }
                        }
                        Op::And => {
                            if fa != 0.0 && fb != 0.0 {
                                1.0
                            } else {
                                0.0
                            }
                        }
                        Op::Or => {
                            if fa != 0.0 || fb != 0.0 {
                                1.0
                            } else {
                                0.0
                            }
                        }
                        _ => unreachable!(),
                    }
                })
            }
        };
        return Ok(Value::Matrix(Box::new(result_mat)));
    }

    // ── Matrix × Matrix ────────────────────────────────────────────────────────
    if let (Value::Matrix(ma), Value::Matrix(mb)) = (&a, &b) {
        match op {
            Op::Add => return Ok(Value::Matrix(Box::new(&**ma + &**mb))),
            Op::Sub => return Ok(Value::Matrix(Box::new(&**ma - &**mb))),
            Op::ElemMul => return Ok(Value::Matrix(Box::new(&**ma * &**mb))),
            Op::ElemDiv => return Ok(Value::Matrix(Box::new(&**ma / &**mb))),
            Op::ElemPow => {
                return Ok(Value::Matrix(Box::new(ma.mapv(|_| 0.0))));
            }
            Op::Mul => {
                // Matrix product
                if ma.ncols() != mb.nrows() {
                    return Err(format!(
                        "Matrix dimensions mismatch for *: {}×{} vs {}×{}",
                        ma.nrows(),
                        ma.ncols(),
                        mb.nrows(),
                        mb.ncols()
                    ));
                }
                return Ok(Value::Matrix(Box::new(ma.dot(&**mb))));
            }
            _ => {} // fall through to eval_with_io for other ops
        }
        // Element-wise pow needs special handling (zip).
        if matches!(op, Op::ElemPow) {
            let mut result = Array2::<f64>::zeros(ma.raw_dim());
            for ((r, &av), &bv) in result.iter_mut().zip(ma.iter()).zip(mb.iter()) {
                *r = av.powf(bv);
            }
            return Ok(Value::Matrix(Box::new(result)));
        }
        // Comparison element-wise.
        let result = ndarray::Zip::from(&**ma)
            .and(&**mb)
            .map_collect(|&av, &bv| {
                let t = match op {
                    Op::Eq => av == bv,
                    Op::NotEq => av != bv,
                    Op::Lt => av < bv,
                    Op::LtEq => av <= bv,
                    Op::Gt => av > bv,
                    Op::GtEq => av >= bv,
                    Op::And => av != 0.0 && bv != 0.0,
                    Op::Or => av != 0.0 || bv != 0.0,
                    _ => return 0.0,
                };
                if t { 1.0 } else { 0.0 }
            });
        return Ok(Value::Matrix(Box::new(result)));
    }

    // ── String concatenation (`+` on StringObj) ───────────────────────────────
    if let (Op::Add, Value::StringObj(sa), Value::StringObj(sb)) = (&op, &a, &b) {
        return Ok(Value::StringObj(format!("{sa}{sb}")));
    }

    // ── General fallback: delegate to eval_with_io via temporary env entries ───
    // This handles ComplexMatrix, Str arithmetic, and any remaining combinations.
    vm_binop_fallback(a, op, b, env, io)
}

/// Fallback: evaluate `a op b` by inserting values into a temporary scope and
/// calling `eval_with_io` on a constructed `BinOp` expression.
fn vm_binop_fallback(
    a: Value,
    op: Op,
    b: Value,
    env: &mut Env,
    io: &mut IoContext,
) -> Result<Value, String> {
    let key_a = "__vm_op_a__".to_string();
    let key_b = "__vm_op_b__".to_string();
    let saved_a = env.get(&key_a).cloned();
    let saved_b = env.get(&key_b).cloned();
    env.insert(key_a.clone(), a);
    env.insert(key_b.clone(), b);
    let result = eval_with_io(
        &Expr::BinOp(
            Box::new(Expr::Var(key_a.clone())),
            op,
            Box::new(Expr::Var(key_b.clone())),
        ),
        env,
        io,
    );
    // Restore env to its previous state.
    match saved_a {
        Some(v) => {
            env.insert(key_a, v);
        }
        None => {
            env.remove("__vm_op_a__");
        }
    }
    match saved_b {
        Some(v) => {
            env.insert(key_b, v);
        }
        None => {
            env.remove("__vm_op_b__");
        }
    }
    result
}

/// Negate a [`Value`].  Fast path for `Scalar`; fallback via `eval_with_io` for others.
fn vm_neg(a: Value, env: &mut Env, io: &mut IoContext) -> Result<Value, String> {
    match &a {
        Value::Scalar(f) => return Ok(Value::Scalar(-f)),
        Value::Complex(re, im) => return Ok(Value::Complex(-re, -im)),
        Value::Matrix(m) => return Ok(Value::Matrix(Box::new(m.mapv(|x| -x)))),
        _ => {}
    }
    let key = "__vm_neg__".to_string();
    let saved = env.get(&key).cloned();
    env.insert(key.clone(), a);
    let result = eval_with_io(&Expr::UnaryMinus(Box::new(Expr::Var(key.clone()))), env, io);
    match saved {
        Some(v) => {
            env.insert(key, v);
        }
        None => {
            env.remove("__vm_neg__");
        }
    }
    result
}

// ── Truthiness ────────────────────────────────────────────────────────────────

/// Returns `true` if `val` is truthy under MATLAB `if`/`while` semantics.
///
/// Mirrors the `is_truthy` function in `exec.rs`.
fn is_truthy(val: &Value) -> bool {
    match val {
        Value::Scalar(n) => *n != 0.0 && !n.is_nan(),
        Value::Matrix(m) => m.iter().all(|&x| x != 0.0 && !x.is_nan()),
        Value::Complex(re, im) => *re != 0.0 || *im != 0.0,
        Value::ComplexMatrix(m) => m.iter().all(|c: &Complex<f64>| c.re != 0.0 || c.im != 0.0),
        Value::Str(s) | Value::StringObj(s) => !s.is_empty(),
        Value::Void => false,
        Value::Lambda(_) | Value::Function(_) | Value::Tuple(_) => true,
        Value::Cell(v) => !v.is_empty(),
        Value::Struct(_) | Value::StructArray(_) => true,
        Value::DateTime(ts) => !ts.is_nan(),
        Value::Duration(s) => *s != 0.0,
        Value::DateTimeArray(v) | Value::DurationArray(v) => !v.is_empty(),
        Value::Map(m) => !m.is_empty(),
    }
}

// ── Slot sync ─────────────────────────────────────────────────────────────────

/// Copy non-Void slot values back to `env`.
///
/// Called at every exit path of `vm_exec` (normal completion and `return`),
/// so that slot-optimised variables are visible to callers that read from `env`.
fn sync_locals(chunk: &Chunk, locals: &[Value], env: &mut Env) {
    for (slot, name) in chunk.slot_names.iter().enumerate() {
        if !matches!(locals[slot], Value::Void) {
            env.insert(name.clone(), locals[slot].clone());
        }
    }
}

// ── Complex helpers ───────────────────────────────────────────────────────────

fn to_complex_parts(v: &Value) -> (f64, f64) {
    match v {
        Value::Scalar(f) => (*f, 0.0),
        Value::Complex(re, im) => (*re, *im),
        _ => (f64::NAN, 0.0),
    }
}