elixcee 0.33.0

Emulate and execute Excel VBA macros at high speed — without Microsoft Excel
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
//! Property-based workbook test runner (Milestone B5a): the `test-workbook`
//! subcommand runs a macro against a starting `.xlsx`/`.ods` workbook many
//! times with generated boundary-value inputs, checking each run for
//! panics, runtime errors, timeouts, and Excel error values in a result
//! range. Every case starts from a completely fresh `Vm` and a fresh read
//! of the workbook file — no cell, variable, MsgBox-log, or deadline state
//! survives from one case to the next.
//!
//! **Known limitation, not fixed in this phase**: `RANDARRAY`/`Rnd`'s PRNG
//! (`src/formula/eval.rs`) is a *thread-local*, not a `Vm` field, so a fresh
//! `Vm` per case does not reset it — draws continue across cases on the
//! same thread. `--seed`/`--case` replay is only guaranteed to reproduce
//! identical *input generation* (which boundary value gets written where),
//! not VBA-visible randomness for a macro that calls `RANDARRAY`/`Rnd`.
//! Neither `boundary_numeric` nor `boundary_string` (the only strategies in
//! this phase) invoke any VBA-side randomness, so this doesn't bite v1.
//!
//! The TOML fixture format is parsed by a hand-rolled, deliberately
//! minimal subset parser (`parse_fixture` below) rather than a real TOML
//! dependency — `toml` is a `[dev-dependencies]`-only crate (added for
//! `tests/blackbox.rs`), and pulling it into the release binary would
//! reverse the project's zero-new-runtime-dependency principle (the same
//! one Milestone B2 invoked to reject a TOML project manifest). This
//! parser only supports what the fixture schema below needs: flat
//! `key = value` lines and `[[inputs]]`/`[[assertions]]` array-of-tables —
//! same scope-limiting philosophy as `reader.rs`'s minimal XML parser. Any
//! construct outside that subset (inline tables, multi-line strings,
//! dotted keys, trailing junk after a value) is a hard parse error, not a
//! silent skip — a silently-misparsed fixture that still "runs" would
//! produce a confusing green result instead of a clear failure.

use crate::diagnostics::{json_string, variant_to_json};
use crate::parser::ast::Program;
use crate::vm::{
    CellContent, HiddenCellsObservation, ResolutionFailureKind, Variant, Vm, parse_sheet_range_addr,
};
use std::collections::HashMap;
use std::time::{Duration, Instant};

// ── Fixture schema ────────────────────────────────────────────────────────────

pub struct Fixture {
    pub name: String,
    pub workbook: String,
    pub vba_files: Vec<String>,
    pub macro_name: String,
    pub cases: u64,
    pub seed: u64,
    pub timeout_secs: u64,
    pub inputs: Vec<InputSpec>,
    pub assertions: Vec<AssertionSpec>,
}

pub struct InputSpec {
    pub range: String,
    pub strategy: String,
}

pub struct AssertionSpec {
    pub range: String,
    pub rule: String,
}

// ── Minimal TOML-subset parser ────────────────────────────────────────────────

enum TomlValue {
    Str(String),
    Int(i64),
    StrArray(Vec<String>),
}

enum Section {
    None,
    Inputs,
    Assertions,
}

pub fn parse_fixture(text: &str) -> Result<Fixture, String> {
    let mut top: HashMap<String, TomlValue> = HashMap::new();
    let mut inputs: Vec<HashMap<String, TomlValue>> = Vec::new();
    let mut assertions: Vec<HashMap<String, TomlValue>> = Vec::new();
    let mut section = Section::None;

    for (i, raw_line) in text.lines().enumerate() {
        let line_no = i + 1;
        let line = raw_line.trim();
        if line.is_empty() || line.starts_with('#') {
            continue;
        }

        if let Some(name) = line.strip_prefix("[[").and_then(|r| r.strip_suffix("]]")) {
            match name.trim() {
                "inputs" => {
                    inputs.push(HashMap::new());
                    section = Section::Inputs;
                }
                "assertions" => {
                    assertions.push(HashMap::new());
                    section = Section::Assertions;
                }
                other => return Err(format!("line {}: unknown section '[[{}]]'", line_no, other)),
            }
            continue;
        }
        if line.starts_with('[') {
            return Err(format!(
                "line {}: unsupported TOML construct (only [[inputs]]/[[assertions]] sections are supported): {}",
                line_no, line
            ));
        }

        let Some(eq_pos) = line.find('=') else {
            return Err(format!(
                "line {}: expected 'key = value', got: {}",
                line_no, line
            ));
        };
        let key = line[..eq_pos].trim();
        if key.is_empty() || key.contains('.') || key.contains(char::is_whitespace) {
            return Err(format!(
                "line {}: unsupported key syntax: '{}'",
                line_no, key
            ));
        }
        let value = parse_toml_value(line[eq_pos + 1..].trim(), line_no)?;

        match section {
            Section::None => {
                top.insert(key.to_string(), value);
            }
            Section::Inputs => {
                inputs
                    .last_mut()
                    .expect("section entered via [[inputs]]")
                    .insert(key.to_string(), value);
            }
            Section::Assertions => {
                assertions
                    .last_mut()
                    .expect("section entered via [[assertions]]")
                    .insert(key.to_string(), value);
            }
        }
    }

    let name = require_str(&top, "name", "fixture")?;
    let workbook = require_str(&top, "workbook", "fixture")?;
    let vba_files = require_str_array(&top, "vba_files", "fixture")?;
    let macro_name = require_str(&top, "macro", "fixture")?;
    let cases = require_int(&top, "cases", "fixture")?;
    let seed = require_int(&top, "seed", "fixture")?;
    let timeout_secs = optional_int(&top, "timeout_secs", "fixture", 10)?;

    if inputs.is_empty() {
        return Err("fixture: at least one [[inputs]] entry is required".to_string());
    }
    if assertions.is_empty() {
        return Err("fixture: at least one [[assertions]] entry is required".to_string());
    }

    let inputs = inputs
        .iter()
        .map(|m| {
            Ok(InputSpec {
                range: require_str(m, "range", "[[inputs]]")?,
                strategy: require_str(m, "strategy", "[[inputs]]")?,
            })
        })
        .collect::<Result<Vec<_>, String>>()?;
    let assertions = assertions
        .iter()
        .map(|m| {
            Ok(AssertionSpec {
                range: require_str(m, "range", "[[assertions]]")?,
                rule: require_str(m, "rule", "[[assertions]]")?,
            })
        })
        .collect::<Result<Vec<_>, String>>()?;

    Ok(Fixture {
        name,
        workbook,
        vba_files,
        macro_name,
        cases,
        seed,
        timeout_secs,
        inputs,
        assertions,
    })
}

fn parse_toml_value(s: &str, line_no: usize) -> Result<TomlValue, String> {
    if let Some(inner) = s.strip_prefix('"').and_then(|r| r.strip_suffix('"')) {
        return Ok(TomlValue::Str(unescape_toml_string(inner, line_no)?));
    }
    if let Some(inner) = s.strip_prefix('[').and_then(|r| r.strip_suffix(']')) {
        let mut items = Vec::new();
        for part in split_top_level_commas(inner) {
            let part = part.trim();
            if part.is_empty() {
                continue;
            }
            match parse_toml_value(part, line_no)? {
                TomlValue::Str(s) => items.push(s),
                _ => return Err(format!("line {}: array elements must be strings", line_no)),
            }
        }
        return Ok(TomlValue::StrArray(items));
    }
    if let Ok(n) = s.parse::<i64>() {
        return Ok(TomlValue::Int(n));
    }
    Err(format!(
        "line {}: unsupported value syntax: '{}'",
        line_no, s
    ))
}

fn split_top_level_commas(s: &str) -> Vec<&str> {
    let mut parts = Vec::new();
    let mut in_quote = false;
    let mut start = 0;
    for (i, c) in s.char_indices() {
        match c {
            '"' => in_quote = !in_quote,
            ',' if !in_quote => {
                parts.push(&s[start..i]);
                start = i + 1;
            }
            _ => {}
        }
    }
    parts.push(&s[start..]);
    parts
}

fn unescape_toml_string(s: &str, line_no: usize) -> Result<String, String> {
    let mut out = String::with_capacity(s.len());
    let mut chars = s.chars();
    while let Some(c) = chars.next() {
        if c != '\\' {
            out.push(c);
            continue;
        }
        match chars.next() {
            Some('"') => out.push('"'),
            Some('\\') => out.push('\\'),
            Some('n') => out.push('\n'),
            Some('t') => out.push('\t'),
            Some('r') => out.push('\r'),
            other => {
                return Err(format!(
                    "line {}: unsupported escape sequence '\\{:?}'",
                    line_no, other
                ));
            }
        }
    }
    Ok(out)
}

fn require_str(
    map: &HashMap<String, TomlValue>,
    key: &str,
    context: &str,
) -> Result<String, String> {
    match map.get(key) {
        Some(TomlValue::Str(s)) => Ok(s.clone()),
        Some(_) => Err(format!("{}: '{}' must be a string", context, key)),
        None => Err(format!("{}: missing required field '{}'", context, key)),
    }
}

fn require_str_array(
    map: &HashMap<String, TomlValue>,
    key: &str,
    context: &str,
) -> Result<Vec<String>, String> {
    match map.get(key) {
        Some(TomlValue::StrArray(v)) => Ok(v.clone()),
        Some(_) => Err(format!(
            "{}: '{}' must be an array of strings",
            context, key
        )),
        None => Err(format!("{}: missing required field '{}'", context, key)),
    }
}

fn require_int(map: &HashMap<String, TomlValue>, key: &str, context: &str) -> Result<u64, String> {
    match map.get(key) {
        Some(TomlValue::Int(n)) if *n >= 0 => Ok(*n as u64),
        Some(TomlValue::Int(_)) => Err(format!("{}: '{}' must not be negative", context, key)),
        Some(_) => Err(format!("{}: '{}' must be an integer", context, key)),
        None => Err(format!("{}: missing required field '{}'", context, key)),
    }
}

fn optional_int(
    map: &HashMap<String, TomlValue>,
    key: &str,
    context: &str,
    default: u64,
) -> Result<u64, String> {
    match map.get(key) {
        Some(_) => require_int(map, key, context),
        None => Ok(default),
    }
}

// ── Seeded case generator ─────────────────────────────────────────────────────

/// Independent from `formula/eval.rs`'s thread-local xorshift64 (same core
/// algorithm, copied) — this one is explicitly seeded so case generation is
/// fully deterministic, unlike the thread-local RNG behind `RANDARRAY`.
struct CaseRng {
    state: u64,
}

impl CaseRng {
    fn new(seed: u64) -> Self {
        CaseRng {
            state: if seed == 0 {
                0x9E37_79B9_7F4A_7C15
            } else {
                seed
            },
        }
    }

    fn next_u64(&mut self) -> u64 {
        let mut s = self.state;
        s ^= s << 13;
        s ^= s >> 7;
        s ^= s << 17;
        self.state = s;
        s
    }
}

/// Derives a per-case seed so `--case N` always reproduces the same draws
/// whether run inside the full `cases` loop or standalone.
fn case_seed(base_seed: u64, case_index: u64) -> u64 {
    base_seed
        .wrapping_add(case_index)
        .wrapping_mul(0x9E37_79B9_7F4A_7C15)
}

// ── Strategies (v1: two, splitting the roadmap's 8 boundary values along the
// numeric/string divide implied by "boundary_numeric" itself) ────────────────

fn boundary_numeric_pool() -> Vec<Variant> {
    vec![
        Variant::Empty,
        Variant::Integer(0),
        Variant::Integer(1),
        Variant::Integer(-1),
        // Chosen over i64::MAX/MIN: these sit just past VBA's classic
        // Integer/Long overflow boundaries, which is where realistic
        // spreadsheet-macro bugs actually show up.
        Variant::Integer(999_999_999),
        Variant::Integer(-999_999_999),
    ]
}

fn boundary_string_pool() -> Vec<Variant> {
    vec![
        Variant::Str(String::new()),
        Variant::Str("test".to_string()),
        Variant::Str("a".repeat(1000)),
    ]
}

fn resolve_strategy(name: &str) -> Result<Vec<Variant>, String> {
    match name {
        "boundary_numeric" => Ok(boundary_numeric_pool()),
        "boundary_string" => Ok(boundary_string_pool()),
        other => Err(format!("unknown strategy '{}'", other)),
    }
}

fn col_to_letters(mut col: u32) -> String {
    let mut bytes = Vec::new();
    while col > 0 {
        col -= 1;
        bytes.push(b'A' + (col % 26) as u8);
        col /= 26;
    }
    bytes.reverse();
    String::from_utf8(bytes).unwrap()
}

// ── Execution ─────────────────────────────────────────────────────────────────

#[derive(Clone)]
pub struct InputUsed {
    pub address: String,
    pub value: Variant,
}

pub struct FailureDetail {
    pub rule: String,
    pub address: Option<String>,
    pub actual: Option<String>,
    pub message: Option<String>,
}

pub enum FixtureResult {
    Passed {
        seed: u64,
        cases_run: u64,
        /// See `Failed.hidden_cells`'s doc comment (Milestone B7b) — the
        /// same observation, computed the same way, just also threaded
        /// through the success variant since it isn't failure-gated.
        hidden_cells: Option<Box<HiddenCellsObservation>>,
    },
    Failed {
        seed: u64,
        case_index: u64,
        inputs_used: Vec<InputUsed>,
        failure: FailureDetail,
        /// The VM's classified resolution failure, if any, captured via
        /// `Vm::take_resolution_failure()` right after the macro call fails
        /// (Milestone B6d) — `None` for a panic/timeout, and also `None` for
        /// a runtime error that isn't one of `diagnose`'s classified kinds
        /// (most aren't: only structural ones like `SheetProtected` or
        /// genuinely input-dependent ones like `ArrayIndexOutOfBounds` set
        /// this side channel). `test-workbook`'s own `to_json`/`to_plain_text`
        /// ignore this field entirely — it exists for `diagnose-workbook` to
        /// enrich the same failure with root-cause evidence. `Box`ed:
        /// `ResolutionFailureKind`'s largest variants (several `String`s/
        /// `Vec`s) made this field big enough that clippy's
        /// `large_enum_variant` flagged the size gap against `Passed`.
        resolution_kind: Option<Box<ResolutionFailureKind>>,
        /// The `RANGE_CONTAINS_HIDDEN_CELLS` observation, if any, captured
        /// via `Vm::hidden_cells_observation()` right after the macro call
        /// (Milestone B7b) — unconditionally, regardless of `Ok`/`Err`,
        /// since it isn't a failure. `test-workbook`'s own `to_json`/
        /// `to_plain_text` ignore this field too; `diagnose-workbook`
        /// enriches with it. `Box`ed for the same `large_enum_variant`
        /// reason as `resolution_kind`.
        hidden_cells: Option<Box<HiddenCellsObservation>>,
    },
}

/// Runs `fixture` against `programs` (already parsed once, outside this
/// function — the AST is immutable and safe to reuse across cases). Each
/// case: derives its seed, builds a fresh `Vm`, reloads `workbook_path`
/// from scratch, writes generated input values, runs the macro under a
/// wall-clock deadline and `catch_unwind`, then checks assertions — fully
/// independent of every other case. Stops at the first failing case
/// (fail-fast, matching `proptest`'s own convention and keeping this
/// subcommand's "exactly one JSON object per invocation" contract).
///
/// `strict` sets `Vm::strict_resolution` before the macro call (Milestone
/// B6d) — `test-workbook` itself always passes `false` (unchanged lenient
/// behavior); `diagnose-workbook` passes `true` to also catch
/// `WorksheetNotFound`/`WorkbookNotFound`-style failures across generated
/// cases, matching `diagnose`'s own strict posture. Set only after inputs
/// are written: `ensure_sheet`'s auto-vivify is what strict mode disables,
/// and by then every input sheet already exists.
pub fn run_fixture(
    fixture: &Fixture,
    programs: &[(String, Program)],
    workbook_path: &str,
    seed_override: Option<u64>,
    case_override: Option<u64>,
    cases_override: Option<u64>,
    strict: bool,
) -> Result<FixtureResult, String> {
    let base_seed = seed_override.unwrap_or(fixture.seed);
    let input_pools: Vec<Vec<Variant>> = fixture
        .inputs
        .iter()
        .map(|i| resolve_strategy(&i.strategy))
        .collect::<Result<_, _>>()?;

    // `cases_override` (`--cases`, Milestone B6d) overrides the fixture's
    // declared case *count*; `case_override` (`--case`) replays one specific
    // index and takes precedence, same as `--seed` overriding `fixture.seed`.
    let case_indices: Vec<u64> = match case_override {
        Some(n) => vec![n],
        None => (0..cases_override.unwrap_or(fixture.cases)).collect(),
    };
    let cases_run = case_indices.len() as u64;
    // Milestone B7b: carries the last case's observation forward for the
    // final `Passed` result if every case passes. Structurally identical
    // across cases (workbook layout + macro text, not drawn values), so
    // which case's copy actually "wins" doesn't matter in practice.
    let mut last_hidden_cells: Option<Box<HiddenCellsObservation>> = None;

    for case_index in case_indices {
        let seed = case_seed(base_seed, case_index);
        let mut rng = CaseRng::new(seed);

        let mut vm = Vm::new();
        vm.load_workbook_file(workbook_path)
            .map_err(|e| format!("failed to load workbook: {}", e))?;

        let mut inputs_used = Vec::new();
        // [[inputs]] in TOML declaration order, cells row-major within each
        // range — draw order must be pinned for --case replay to reproduce
        // the exact same values every time.
        for (spec, pool) in fixture.inputs.iter().zip(input_pools.iter()) {
            let (sheet, (r1, c1), (r2, c2)) = parse_sheet_range_addr(&spec.range, &vm.active_sheet)
                .ok_or_else(|| format!("invalid range '{}'", spec.range))?;
            vm.ensure_sheet(&sheet);
            let prev_active = vm.active_sheet.clone();
            vm.active_sheet = sheet.clone();
            for r in r1..=r2 {
                for c in c1..=c2 {
                    let value = pool[(rng.next_u64() as usize) % pool.len()].clone();
                    let address = format!("{}!{}{}", sheet, col_to_letters(c), r);
                    vm.cells_mut().insert(
                        (r, c),
                        CellContent {
                            formula: None,
                            value: value.clone(),
                        },
                    );
                    inputs_used.push(InputUsed { address, value });
                }
            }
            vm.active_sheet = prev_active;
        }

        vm.deadline = Some(Instant::now() + Duration::from_secs(fixture.timeout_secs));
        vm.strict_resolution = strict;

        let run_result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
            if programs.len() == 1 {
                vm.run_sub(&programs[0].1, &fixture.macro_name)
            } else {
                vm.run_sub_multi(programs, &fixture.macro_name)
            }
        }));

        let hidden_cells = vm.hidden_cells_observation().map(Box::new);

        match run_result {
            Err(_panic) => {
                return Ok(FixtureResult::Failed {
                    seed: base_seed,
                    case_index,
                    inputs_used,
                    failure: FailureDetail {
                        rule: "no_panic".to_string(),
                        address: None,
                        actual: None,
                        message: Some("macro execution panicked".to_string()),
                    },
                    resolution_kind: None,
                    hidden_cells,
                });
            }
            Ok(Err(e)) => {
                let rule = if e.starts_with("TIMEOUT:") {
                    "no_timeout"
                } else {
                    "no_runtime_error"
                };
                let resolution_kind = vm.take_resolution_failure().map(Box::new);
                return Ok(FixtureResult::Failed {
                    seed: base_seed,
                    case_index,
                    inputs_used,
                    failure: FailureDetail {
                        rule: rule.to_string(),
                        address: None,
                        actual: None,
                        message: Some(e),
                    },
                    resolution_kind,
                    hidden_cells,
                });
            }
            Ok(Ok(())) => {}
        }

        for spec in &fixture.assertions {
            match spec.rule.as_str() {
                "no_excel_errors" => {
                    let (sheet, (r1, c1), (r2, c2)) =
                        parse_sheet_range_addr(&spec.range, &vm.active_sheet)
                            .ok_or_else(|| format!("invalid range '{}'", spec.range))?;
                    // A missing sheet is a fixture/config problem (typo, or
                    // the macro genuinely didn't produce the expected
                    // sheet) — hard error rather than silently treating
                    // "sheet doesn't exist" as "no errors found".
                    let cells = vm.get_sheet_cells(&sheet).ok_or_else(|| {
                        format!(
                            "assertion range '{}': sheet '{}' does not exist",
                            spec.range, sheet
                        )
                    })?;
                    for r in r1..=r2 {
                        for c in c1..=c2 {
                            if let Some(content) = cells.get(&(r, c))
                                && let Variant::Error(e) = &content.value
                            {
                                return Ok(FixtureResult::Failed {
                                    seed: base_seed,
                                    case_index,
                                    inputs_used,
                                    failure: FailureDetail {
                                        rule: "no_excel_errors".to_string(),
                                        address: Some(format!(
                                            "{}!{}{}",
                                            sheet,
                                            col_to_letters(c),
                                            r
                                        )),
                                        actual: Some(e.as_str().to_string()),
                                        message: None,
                                    },
                                    resolution_kind: None,
                                    hidden_cells: hidden_cells.clone(),
                                });
                            }
                        }
                    }
                }
                other => return Err(format!("unknown assertion rule '{}'", other)),
            }
        }

        last_hidden_cells = hidden_cells;
    }

    Ok(FixtureResult::Passed {
        seed: base_seed,
        cases_run,
        hidden_cells: last_hidden_cells,
    })
}

// ── Output ────────────────────────────────────────────────────────────────────

pub fn to_json(result: &FixtureResult) -> String {
    match result {
        FixtureResult::Passed {
            seed, cases_run, ..
        } => {
            format!(
                "{{\"schema_version\":1,\"ok\":true,\"seed\":{},\"cases_run\":{}}}",
                seed, cases_run
            )
        }
        FixtureResult::Failed {
            seed,
            case_index,
            inputs_used,
            failure,
            ..
        } => {
            let inputs_json: Vec<String> = inputs_used
                .iter()
                .map(|iu| {
                    format!(
                        "{{\"address\":{},\"value\":{}}}",
                        json_string(&iu.address),
                        variant_to_json(&iu.value)
                    )
                })
                .collect();
            let mut fields = vec![format!("\"rule\":{}", json_string(&failure.rule))];
            if let Some(a) = &failure.address {
                fields.push(format!("\"address\":{}", json_string(a)));
            }
            if let Some(a) = &failure.actual {
                fields.push(format!("\"actual\":{}", json_string(a)));
            }
            if let Some(m) = &failure.message {
                fields.push(format!("\"message\":{}", json_string(m)));
            }
            format!(
                "{{\"schema_version\":1,\"ok\":false,\"seed\":{},\"case_index\":{},\"inputs\":[{}],\"failure\":{{{}}}}}",
                seed,
                case_index,
                inputs_json.join(","),
                fields.join(",")
            )
        }
    }
}

fn display_variant(v: &Variant) -> String {
    match v {
        Variant::Empty => "(empty)".to_string(),
        other => other.to_string(),
    }
}

pub fn to_plain_text(result: &FixtureResult) -> String {
    match result {
        FixtureResult::Passed {
            seed, cases_run, ..
        } => {
            format!("ok: {} case(s) passed (seed {})", cases_run, seed)
        }
        FixtureResult::Failed {
            seed,
            case_index,
            inputs_used,
            failure,
            ..
        } => {
            let mut line = format!(
                "FAIL: case {} (seed {}) - {}",
                case_index, seed, failure.rule
            );
            if let Some(a) = &failure.address {
                line.push_str(&format!(" at {}", a));
            }
            if let Some(a) = &failure.actual {
                line.push_str(&format!(": {}", a));
            }
            if let Some(m) = &failure.message {
                line.push_str(&format!(": {}", m));
            }
            for iu in inputs_used {
                line.push_str(&format!(
                    "\n  {} = {}",
                    iu.address,
                    display_variant(&iu.value)
                ));
            }
            line
        }
    }
}

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

    const EXAMPLE_FIXTURE: &str = r#"
name = "order calculation"
workbook = "fixtures/orders.xlsx"
vba_files = ["Main.bas"]
macro = "Main.Process"
cases = 100
seed = 42

[[inputs]]
range = "Input!B2:B10"
strategy = "boundary_numeric"

[[assertions]]
range = "Result!A1:F100"
rule = "no_excel_errors"
"#;

    #[test]
    fn parse_fixture_round_trips_the_example_schema() {
        let f = parse_fixture(EXAMPLE_FIXTURE).unwrap();
        assert_eq!(f.name, "order calculation");
        assert_eq!(f.workbook, "fixtures/orders.xlsx");
        assert_eq!(f.vba_files, vec!["Main.bas".to_string()]);
        assert_eq!(f.macro_name, "Main.Process");
        assert_eq!(f.cases, 100);
        assert_eq!(f.seed, 42);
        assert_eq!(f.timeout_secs, 10); // default, not specified in the example
        assert_eq!(f.inputs.len(), 1);
        assert_eq!(f.inputs[0].range, "Input!B2:B10");
        assert_eq!(f.inputs[0].strategy, "boundary_numeric");
        assert_eq!(f.assertions.len(), 1);
        assert_eq!(f.assertions[0].range, "Result!A1:F100");
        assert_eq!(f.assertions[0].rule, "no_excel_errors");
    }

    #[test]
    fn parse_fixture_honors_an_explicit_timeout_secs() {
        // Inserted before any [[section]] — a key = value line after a
        // [[inputs]]/[[assertions]] header belongs to that table entry,
        // not to the top-level fixture (matches real TOML semantics).
        let text = EXAMPLE_FIXTURE.replacen("seed = 42\n", "seed = 42\ntimeout_secs = 5\n", 1);
        assert_eq!(parse_fixture(&text).unwrap().timeout_secs, 5);
    }

    #[test]
    fn parse_fixture_rejects_a_dotted_key() {
        let text = "name = \"x\"\nworkbook = \"w.xlsx\"\nvba_files = [\"a.bas\"]\nmacro = \"Main\"\ncases = 1\nseed = 1\na.b = 1\n[[inputs]]\nrange = \"A1\"\nstrategy = \"boundary_numeric\"\n[[assertions]]\nrange = \"A1\"\nrule = \"no_excel_errors\"\n";
        assert!(parse_fixture(text).is_err());
    }

    #[test]
    fn parse_fixture_rejects_an_inline_table() {
        let text = "x = { a = 1 }\n";
        assert!(parse_fixture(text).is_err());
    }

    #[test]
    fn parse_fixture_rejects_an_unknown_section() {
        let text = "[[bogus]]\nfoo = \"bar\"\n";
        assert!(parse_fixture(text).is_err());
    }

    #[test]
    fn parse_fixture_requires_at_least_one_input_and_assertion() {
        let no_inputs = "name = \"x\"\nworkbook = \"w.xlsx\"\nvba_files = [\"a.bas\"]\nmacro = \"Main\"\ncases = 1\nseed = 1\n[[assertions]]\nrange = \"A1\"\nrule = \"no_excel_errors\"\n";
        assert!(parse_fixture(no_inputs).is_err());
    }

    #[test]
    fn case_rng_is_deterministic_for_the_same_seed() {
        let mut a = CaseRng::new(42);
        let mut b = CaseRng::new(42);
        let seq_a: Vec<u64> = (0..10).map(|_| a.next_u64()).collect();
        let seq_b: Vec<u64> = (0..10).map(|_| b.next_u64()).collect();
        assert_eq!(seq_a, seq_b);
    }

    #[test]
    fn case_rng_differs_for_different_seeds() {
        let mut a = CaseRng::new(1);
        let mut b = CaseRng::new(2);
        assert_ne!(a.next_u64(), b.next_u64());
    }

    #[test]
    fn case_seed_is_deterministic_and_case_specific() {
        assert_eq!(case_seed(42, 17), case_seed(42, 17));
        assert_ne!(case_seed(42, 17), case_seed(42, 18));
    }

    #[test]
    fn boundary_numeric_pool_has_the_documented_values() {
        let pool = boundary_numeric_pool();
        assert!(pool.contains(&Variant::Empty));
        assert!(pool.contains(&Variant::Integer(0)));
        assert!(pool.contains(&Variant::Integer(1)));
        assert!(pool.contains(&Variant::Integer(-1)));
        assert!(pool.contains(&Variant::Integer(999_999_999)));
        assert!(pool.contains(&Variant::Integer(-999_999_999)));
    }

    #[test]
    fn boundary_string_pool_has_the_documented_values() {
        let pool = boundary_string_pool();
        assert!(pool.contains(&Variant::Str(String::new())));
        assert!(pool.contains(&Variant::Str("test".to_string())));
        assert!(
            pool.iter()
                .any(|v| matches!(v, Variant::Str(s) if s.len() == 1000))
        );
    }

    #[test]
    fn resolve_strategy_rejects_an_unknown_name() {
        assert!(resolve_strategy("bogus").is_err());
    }

    fn build_workbook_fixture(path: &str) {
        let vm = Vm::new();
        crate::save_workbook(&vm, path).unwrap();
    }

    /// `Main` writes `=100/B2` as a real formula (not raw VBA division,
    /// which raises a hard VBA runtime error rather than producing a
    /// stored Excel error value) into A1 — a deterministic way to make
    /// `no_excel_errors` fire exactly when the drawn input is `0` (one of
    /// `boundary_numeric`'s pool values), so the test doesn't depend on
    /// guessing which case number draws which value. Both cells live on
    /// the same (default) sheet to avoid needing cross-sheet `Range()`
    /// addressing inside the VBA macro itself — the fixture's own
    /// `Sheet!Range` parsing (exercised via `Input!B2`/`Result!A1` below)
    /// is a separate, already-covered code path.
    const DIVIDE_MACRO: &str = "Sub Main()\n    Range(\"A1\").Formula = \"=100/B2\"\nEnd Sub\n";

    #[test]
    fn run_fixture_reports_no_excel_errors_with_case_index_and_replays_identically() {
        let path = std::env::temp_dir().join("elixcee_testworkbook_divide.xlsx");
        build_workbook_fixture(path.to_str().unwrap());
        let program = parser::parse(DIVIDE_MACRO).unwrap();
        let programs = vec![("main".to_string(), program)];

        let fixture = Fixture {
            name: "divide".to_string(),
            workbook: path.to_str().unwrap().to_string(),
            vba_files: vec![],
            macro_name: "Main".to_string(),
            cases: 50,
            seed: 7,
            timeout_secs: 5,
            inputs: vec![InputSpec {
                range: "Sheet1!B2".to_string(),
                strategy: "boundary_numeric".to_string(),
            }],
            assertions: vec![AssertionSpec {
                range: "Sheet1!A1".to_string(),
                rule: "no_excel_errors".to_string(),
            }],
        };

        let result = run_fixture(
            &fixture,
            &programs,
            &fixture.workbook,
            None,
            None,
            None,
            false,
        )
        .unwrap();
        let (seed, case_index, inputs_used) = match &result {
            FixtureResult::Failed {
                seed,
                case_index,
                inputs_used,
                failure,
                ..
            } => {
                assert_eq!(failure.rule, "no_excel_errors");
                assert_eq!(failure.address.as_deref(), Some("sheet1!A1"));
                assert_eq!(failure.actual.as_deref(), Some("#DIV/0!"));
                (*seed, *case_index, inputs_used.clone())
            }
            FixtureResult::Passed { .. } => {
                panic!("expected a division-by-zero failure across 50 cases")
            }
        };

        // Replaying the exact failing case in isolation must reproduce the
        // identical failure and identical drawn input.
        let replay = run_fixture(
            &fixture,
            &programs,
            &fixture.workbook,
            Some(seed),
            Some(case_index),
            None,
            false,
        )
        .unwrap();
        match replay {
            FixtureResult::Failed {
                case_index: replay_case,
                inputs_used: replay_inputs,
                failure,
                ..
            } => {
                assert_eq!(replay_case, case_index);
                assert_eq!(failure.actual.as_deref(), Some("#DIV/0!"));
                assert_eq!(replay_inputs[0].value, inputs_used[0].value);
                assert_eq!(replay_inputs[0].address, inputs_used[0].address);
            }
            FixtureResult::Passed { .. } => {
                panic!("replay of a failing case must fail identically")
            }
        }
    }

    #[test]
    fn run_fixture_passes_when_the_macro_never_divides_by_a_drawn_zero() {
        let path = std::env::temp_dir().join("elixcee_testworkbook_noop.xlsx");
        build_workbook_fixture(path.to_str().unwrap());
        let program = parser::parse("Sub Main()\n    Cells(1, 1).Value = 1\nEnd Sub\n").unwrap();
        let programs = vec![("main".to_string(), program)];

        let fixture = Fixture {
            name: "noop".to_string(),
            workbook: path.to_str().unwrap().to_string(),
            vba_files: vec![],
            macro_name: "Main".to_string(),
            cases: 20,
            seed: 1,
            timeout_secs: 5,
            inputs: vec![InputSpec {
                range: "Sheet1!B2".to_string(),
                strategy: "boundary_numeric".to_string(),
            }],
            assertions: vec![AssertionSpec {
                range: "Sheet1!A1".to_string(),
                rule: "no_excel_errors".to_string(),
            }],
        };

        let result = run_fixture(
            &fixture,
            &programs,
            &fixture.workbook,
            None,
            None,
            None,
            false,
        )
        .unwrap();
        match result {
            FixtureResult::Passed { cases_run, .. } => assert_eq!(cases_run, 20),
            FixtureResult::Failed { .. } => {
                panic!("a macro that never divides should never fail no_excel_errors")
            }
        }
    }

    // ── Milestone B6d: resolution_kind capture + strict flag ────────────────

    #[test]
    fn run_fixture_captures_a_structural_resolution_failure_even_when_not_strict() {
        // SheetProtected is an unconditional hard error in every mode
        // (Milestone B6c) — not gated behind `strict_resolution` — so this
        // must be classified even at `test-workbook`'s own default (false).
        let path = std::env::temp_dir().join("elixcee_testworkbook_protected.xlsx");
        build_workbook_fixture(path.to_str().unwrap());
        let program = parser::parse(
            "Sub Main()\n    Sheets(\"sheet1\").Protect\n    Cells(1, 1).Value = 1\nEnd Sub\n",
        )
        .unwrap();
        let programs = vec![("main".to_string(), program)];

        let fixture = Fixture {
            name: "protected".to_string(),
            workbook: path.to_str().unwrap().to_string(),
            vba_files: vec![],
            macro_name: "Main".to_string(),
            cases: 1,
            seed: 1,
            timeout_secs: 5,
            inputs: vec![],
            assertions: vec![],
        };

        let result = run_fixture(
            &fixture,
            &programs,
            &fixture.workbook,
            None,
            None,
            None,
            false,
        )
        .unwrap();
        match result {
            FixtureResult::Failed {
                resolution_kind: Some(kind),
                ..
            } => match *kind {
                ResolutionFailureKind::SheetProtected { sheet } => assert_eq!(sheet, "sheet1"),
                other => panic!("expected SheetProtected, got {:?}", other),
            },
            _ => panic!("expected a classified SheetProtected failure"),
        }
    }

    #[test]
    fn run_fixture_with_strict_true_classifies_a_missing_worksheet_reference() {
        // Same macro, same workbook, only `strict` differs: non-strict
        // silently reads Empty from a nonexistent sheet (no failure);
        // strict classifies it as WorksheetNotFound — proving the `strict`
        // parameter actually changes behavior, not just a passthrough flag.
        let path = std::env::temp_dir().join("elixcee_testworkbook_strict.xlsx");
        build_workbook_fixture(path.to_str().unwrap());
        let program = parser::parse(
            "Sub Main()\n    Dim x As Variant\n    x = Sheets(\"DoesNotExist\").Range(\"A1\").Value\nEnd Sub\n",
        )
        .unwrap();
        let programs = vec![("main".to_string(), program)];

        let fixture = Fixture {
            name: "strict-check".to_string(),
            workbook: path.to_str().unwrap().to_string(),
            vba_files: vec![],
            macro_name: "Main".to_string(),
            cases: 1,
            seed: 1,
            timeout_secs: 5,
            inputs: vec![],
            assertions: vec![],
        };

        let lenient = run_fixture(
            &fixture,
            &programs,
            &fixture.workbook,
            None,
            None,
            None,
            false,
        )
        .unwrap();
        assert!(matches!(lenient, FixtureResult::Passed { .. }));

        let strict = run_fixture(
            &fixture,
            &programs,
            &fixture.workbook,
            None,
            None,
            None,
            true,
        )
        .unwrap();
        match strict {
            FixtureResult::Failed {
                resolution_kind: Some(kind),
                ..
            } if matches!(*kind, ResolutionFailureKind::WorksheetNotFound(_)) => {}
            _ => panic!("expected WorksheetNotFound to be classified under strict mode"),
        }
    }

    #[test]
    fn run_fixture_with_cases_override_runs_fewer_cases_than_the_fixture_declares() {
        let path = std::env::temp_dir().join("elixcee_testworkbook_cases_override.xlsx");
        build_workbook_fixture(path.to_str().unwrap());
        let program = parser::parse("Sub Main()\n    Cells(1, 1).Value = 1\nEnd Sub\n").unwrap();
        let programs = vec![("main".to_string(), program)];

        let fixture = Fixture {
            name: "cases-override".to_string(),
            workbook: path.to_str().unwrap().to_string(),
            vba_files: vec![],
            macro_name: "Main".to_string(),
            cases: 20,
            seed: 1,
            timeout_secs: 5,
            inputs: vec![InputSpec {
                range: "Sheet1!B2".to_string(),
                strategy: "boundary_numeric".to_string(),
            }],
            assertions: vec![AssertionSpec {
                range: "Sheet1!A1".to_string(),
                rule: "no_excel_errors".to_string(),
            }],
        };

        let result = run_fixture(
            &fixture,
            &programs,
            &fixture.workbook,
            None,
            None,
            Some(5),
            false,
        )
        .unwrap();
        match result {
            FixtureResult::Passed { cases_run, .. } => assert_eq!(cases_run, 5),
            FixtureResult::Failed { .. } => panic!("unexpected failure"),
        }
    }

    #[test]
    fn to_json_success_shape() {
        let json = to_json(&FixtureResult::Passed {
            seed: 42,
            cases_run: 100,
            hidden_cells: None,
        });
        assert!(json.contains("\"ok\":true"));
        assert!(json.contains("\"seed\":42"));
        assert!(json.contains("\"cases_run\":100"));
    }

    #[test]
    fn to_json_failure_shape_matches_the_documented_contract() {
        let result = FixtureResult::Failed {
            seed: 42,
            case_index: 17,
            inputs_used: vec![InputUsed {
                address: "Input!B2".to_string(),
                value: Variant::Integer(-1),
            }],
            failure: FailureDetail {
                rule: "no_excel_errors".to_string(),
                address: Some("Result!C8".to_string()),
                actual: Some("#DIV/0!".to_string()),
                message: None,
            },
            resolution_kind: None,
            hidden_cells: None,
        };
        let json = to_json(&result);
        assert!(json.contains("\"ok\":false"));
        assert!(json.contains("\"case_index\":17"));
        assert!(json.contains("\"address\":\"Input!B2\""));
        assert!(json.contains("\"value\":-1"));
        assert!(json.contains("\"rule\":\"no_excel_errors\""));
        assert!(json.contains("\"address\":\"Result!C8\""));
        assert!(json.contains("\"actual\":\"#DIV/0!\""));
    }
}