formualizer-eval 0.8.3

High-performance Arrow-backed Excel formula engine with dependency graph and incremental recalculation
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
use super::producer::{AxisProjection, DirtyProjectionRule, SpanReadSummary};
use super::region_index::{AxisRange, Region};
use super::runtime::{FormulaSpan, PlacementDomain};
use crate::SheetId;

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum StructuralOp {
    InsertRows {
        sheet_id: SheetId,
        before: u32,
        count: u32,
    },
    DeleteRows {
        sheet_id: SheetId,
        start: u32,
        count: u32,
    },
    InsertColumns {
        sheet_id: SheetId,
        before: u32,
        count: u32,
    },
    DeleteColumns {
        sheet_id: SheetId,
        start: u32,
        count: u32,
    },
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum AxisShiftCase {
    OtherSheet,
    EntirelyBelow,
    EntirelyAboveShift { delta: i64 },
    Straddles,
    DeleteFullyContains,
}

#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) enum SpanShiftPlan {
    NoOp,
    Shift {
        row_delta: i64,
        col_delta: i64,
        origin_row_delta: i64,
        origin_col_delta: i64,
        /// The op displaces the target of at least one absolute-anchored
        /// read. Origin relocation cannot repoint absolute references, so
        /// the apply site must rewrite the template AST through the shared
        /// `ReferenceAdjuster` (issue #168). Whenever this is set the origin
        /// deltas equal the result deltas: a full-AST rewrite shifts the
        /// template's displaced relative references too, and moving the
        /// origin with the block exactly cancels that for stationary
        /// relative reads while composing correctly with shifted ones —
        /// replicating per-cell adjustment semantics.
        rewrite_absolute_reads: bool,
    },
    /// A mid-domain insert straddles the span's result domain. The apply site
    /// may split the domain at the insert boundary into an unshifted upper
    /// half and a shifted lower half, re-derive each half's read summary, and
    /// re-classify each half; it must fall back to demoting the whole span
    /// when either half does not classify cleanly.
    Split,
    Demote {
        reason: SpanDemoteReason,
    },
    Remove,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum SpanDemoteReason {
    ReadRegionStraddles,
    OriginNotShiftedButReadRegionShifts,
    DeletePartiallyOverlaps,
    /// The template mixes relative reads whose targets the op displaces
    /// with relative reads whose targets stay put. No origin choice can
    /// satisfy both, and (unlike absolute reads) a template rewrite for
    /// relative references is deferred, so the span demotes.
    MixedReadRegionShift,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum AxisKindForOp {
    Row,
    Col,
}

impl StructuralOp {
    pub(crate) fn sheet_id(self) -> SheetId {
        match self {
            Self::InsertRows { sheet_id, .. }
            | Self::DeleteRows { sheet_id, .. }
            | Self::InsertColumns { sheet_id, .. }
            | Self::DeleteColumns { sheet_id, .. } => sheet_id,
        }
    }

    pub(crate) fn count(self) -> u32 {
        match self {
            Self::InsertRows { count, .. }
            | Self::DeleteRows { count, .. }
            | Self::InsertColumns { count, .. }
            | Self::DeleteColumns { count, .. } => count,
        }
    }

    pub(crate) fn axis_shift_delta(self) -> (i64, i64) {
        match self {
            Self::InsertRows { count, .. } => (i64::from(count), 0),
            Self::DeleteRows { count, .. } => (-i64::from(count), 0),
            Self::InsertColumns { count, .. } => (0, i64::from(count)),
            Self::DeleteColumns { count, .. } => (0, -i64::from(count)),
        }
    }

    pub(crate) fn classify_axis(self, axis: AxisRange) -> AxisShiftCase {
        let (min, max) = axis.query_bounds();
        match self {
            Self::InsertRows { before, count, .. } | Self::InsertColumns { before, count, .. } => {
                if max < before {
                    AxisShiftCase::EntirelyBelow
                } else if min >= before {
                    AxisShiftCase::EntirelyAboveShift {
                        delta: i64::from(count),
                    }
                } else {
                    AxisShiftCase::Straddles
                }
            }
            Self::DeleteRows { start, count, .. } | Self::DeleteColumns { start, count, .. } => {
                let end = start.saturating_add(count);
                if max < start {
                    AxisShiftCase::EntirelyBelow
                } else if min >= end {
                    AxisShiftCase::EntirelyAboveShift {
                        delta: -i64::from(count),
                    }
                } else if min >= start && max < end {
                    AxisShiftCase::DeleteFullyContains
                } else {
                    AxisShiftCase::Straddles
                }
            }
        }
    }

    pub(crate) fn classify_region(self, region: Region) -> AxisShiftCase {
        if region.sheet_id() != self.sheet_id() {
            return AxisShiftCase::OtherSheet;
        }
        let (rows, cols) = region.axis_ranges();
        match self.axis_kind() {
            AxisKindForOp::Row => self.classify_axis(rows),
            AxisKindForOp::Col => self.classify_axis(cols),
        }
    }

    fn axis_kind(self) -> AxisKindForOp {
        match self {
            Self::InsertRows { .. } | Self::DeleteRows { .. } => AxisKindForOp::Row,
            Self::InsertColumns { .. } | Self::DeleteColumns { .. } => AxisKindForOp::Col,
        }
    }

    fn is_delete(self) -> bool {
        matches!(self, Self::DeleteRows { .. } | Self::DeleteColumns { .. })
    }
}

/// The anchor kinds a dirty-projection rule uses on the op's axis:
/// `(has_relative, has_absolute)`. Relative bounds are relocated by the
/// span's origin choice; absolute bounds can only be repointed by a template
/// AST rewrite. Bounds on the other axis are unaffected by the op.
///
/// `WholeResult` is a test-only rule with no axis information; it is treated
/// as relative to preserve the legacy region-level classification.
fn rule_axis_bound_kinds(rule: DirtyProjectionRule, axis: AxisKindForOp) -> (bool, bool) {
    fn is_abs(projection: AxisProjection) -> bool {
        matches!(projection, AxisProjection::Absolute { .. })
    }
    fn kinds(bounds: &[AxisProjection]) -> (bool, bool) {
        let has_absolute = bounds.iter().copied().any(is_abs);
        let has_relative = bounds.iter().copied().any(|bound| !is_abs(bound));
        (has_relative, has_absolute)
    }
    match (rule, axis) {
        (DirtyProjectionRule::AffineCell { row, .. }, AxisKindForOp::Row) => kinds(&[row]),
        (DirtyProjectionRule::AffineCell { col, .. }, AxisKindForOp::Col) => kinds(&[col]),
        (
            DirtyProjectionRule::AffineRange {
                row_start, row_end, ..
            },
            AxisKindForOp::Row,
        ) => kinds(&[row_start, row_end]),
        (
            DirtyProjectionRule::AffineRange {
                col_start, col_end, ..
            },
            AxisKindForOp::Col,
        ) => kinds(&[col_start, col_end]),
        (DirtyProjectionRule::WholeColumnRange { col_start, col_end }, AxisKindForOp::Col) => {
            kinds(&[col_start, col_end])
        }
        // A whole-column read has no row bounds to displace; row-op regions
        // for it are whole-axis and classify as straddles before this check.
        (DirtyProjectionRule::WholeColumnRange { .. }, AxisKindForOp::Row) => (true, false),
        (DirtyProjectionRule::WholeResult, _) => (true, false),
    }
}

/// Whether the op displaces the target of any absolute-anchored read in the
/// summary. Used by the delete-compaction path (which never reaches
/// `classify_span_for_op`'s read partition because the result-region
/// straddle is classified first): compaction projects read REGIONS through
/// the delete but keeps the template AST, so a displaced absolute read must
/// force a demote to the per-cell path where the shared adjuster repoints
/// the reference (issue #168).
pub(crate) fn summary_has_displaced_absolute_read(
    read_summary: &SpanReadSummary,
    op: StructuralOp,
) -> bool {
    read_summary.dependencies.iter().any(|dependency| {
        matches!(
            op.classify_region(dependency.read_region),
            AxisShiftCase::EntirelyAboveShift { .. }
        ) && rule_axis_bound_kinds(dependency.projection, op.axis_kind()).1
    })
}

/// Relative-anchored bounds of `rule` on the op axis, as authored-frame
/// offsets from the template origin. Returns `None` when the rule carries no
/// usable axis information (`WholeResult`), which callers must treat as
/// unverifiable.
fn rule_relative_offsets_on_op_axis(
    rule: DirtyProjectionRule,
    axis: AxisKindForOp,
) -> Option<[Option<i64>; 2]> {
    fn offset(projection: AxisProjection) -> Option<i64> {
        match projection {
            AxisProjection::Relative { offset } => Some(offset),
            AxisProjection::Absolute { .. } => None,
        }
    }
    match (rule, axis) {
        (DirtyProjectionRule::AffineCell { row, .. }, AxisKindForOp::Row) => {
            Some([offset(row), None])
        }
        (DirtyProjectionRule::AffineCell { col, .. }, AxisKindForOp::Col) => {
            Some([offset(col), None])
        }
        (
            DirtyProjectionRule::AffineRange {
                row_start, row_end, ..
            },
            AxisKindForOp::Row,
        ) => Some([offset(row_start), offset(row_end)]),
        (
            DirtyProjectionRule::AffineRange {
                col_start, col_end, ..
            },
            AxisKindForOp::Col,
        ) => Some([offset(col_start), offset(col_end)]),
        (DirtyProjectionRule::WholeColumnRange { col_start, col_end }, AxisKindForOp::Col) => {
            Some([offset(col_start), offset(col_end)])
        }
        // A whole-column read has no row bounds; row-op regions for it are
        // whole-axis and classify as straddles before rewrite planning.
        (DirtyProjectionRule::WholeColumnRange { .. }, AxisKindForOp::Row) => Some([None, None]),
        (DirtyProjectionRule::WholeResult, _) => None,
    }
}

/// FRAME INVARIANT (issue #168 rewrite arm). A template's AST authoring
/// frame and its `origin_{row,col}` fields may legitimately diverge:
/// `intern_shifted_origin_clone` reuses the source `ast_id` with a new
/// origin, the mixed-read fast path shifts a domain while pinning the origin
/// (`origin_delta: 0`), and split lower halves keep the original anchor
/// while their domain starts at the split boundary. Evaluation only
/// guarantees that `authored_coord + (placement - origin)` names the right
/// cell for placements IN THE DOMAIN — the authored coordinates themselves
/// need not lie inside the read regions.
///
/// The shared `ReferenceAdjuster` relocates by AUTHORED coordinate, so a
/// whole-template rewrite is only equivalent to per-cell adjustment when
/// every relative-anchored bound on the op axis classifies against the op
/// boundary exactly the way its read region does (displaced ⟺ displaced,
/// stationary ⟺ stationary, and never inside a deleted band). When the
/// frames disagree — e.g. a split lower half whose stale origin sits below a
/// later insert point that displaces its reads — the rewrite would shear
/// every relative read by the op count. This check refuses those rewrites
/// (the caller demotes, which is correct via the per-cell adjuster).
///
/// Absolute bounds need no check: their authored coordinate IS the read
/// region coordinate. Cross-sheet reads are refused outright: the adjuster
/// relocates by coordinate without honoring the reference's sheet, so their
/// frame cannot be verified here.
pub(crate) fn rewrite_frame_is_sound(
    read_summary: &SpanReadSummary,
    origin_row: u32,
    origin_col: u32,
    op: StructuralOp,
) -> bool {
    let axis = op.axis_kind();
    // Template origins are 1-based; regions and op boundaries are 0-based.
    let origin_axis0 = match axis {
        AxisKindForOp::Row => i64::from(origin_row) - 1,
        AxisKindForOp::Col => i64::from(origin_col) - 1,
    };
    for dependency in &read_summary.dependencies {
        let region_displaced = match op.classify_region(dependency.read_region) {
            AxisShiftCase::EntirelyBelow => false,
            AxisShiftCase::EntirelyAboveShift { .. } => true,
            AxisShiftCase::OtherSheet
            | AxisShiftCase::Straddles
            | AxisShiftCase::DeleteFullyContains => return false,
        };
        let Some(offsets) = rule_relative_offsets_on_op_axis(dependency.projection, axis) else {
            return false;
        };
        for offset in offsets.into_iter().flatten() {
            let authored0 = origin_axis0 + offset;
            if authored0 < 0 {
                return false;
            }
            let authored_displaced = match op {
                StructuralOp::InsertRows { before, .. }
                | StructuralOp::InsertColumns { before, .. } => authored0 >= i64::from(before),
                StructuralOp::DeleteRows { start, count, .. }
                | StructuralOp::DeleteColumns { start, count, .. } => {
                    let start = i64::from(start);
                    let end = start + i64::from(count);
                    if authored0 >= start && authored0 < end {
                        // The authored coordinate would become #REF! while
                        // the read region is uniformly intact.
                        return false;
                    }
                    authored0 >= end
                }
            };
            if authored_displaced != region_displaced {
                return false;
            }
        }
    }
    true
}

pub(crate) fn classify_span_for_op(
    span: &FormulaSpan,
    read_summary: Option<&SpanReadSummary>,
    op: StructuralOp,
) -> SpanShiftPlan {
    let result_region = Region::from_domain(span.result_region.domain());
    let result_case = if span.sheet_id == op.sheet_id() {
        op.classify_region(result_region)
    } else {
        AxisShiftCase::OtherSheet
    };

    let (row_delta, col_delta) = match result_case {
        AxisShiftCase::OtherSheet | AxisShiftCase::EntirelyBelow => (0, 0),
        AxisShiftCase::EntirelyAboveShift { .. } => op.axis_shift_delta(),
        AxisShiftCase::DeleteFullyContains => return SpanShiftPlan::Remove,
        AxisShiftCase::Straddles => {
            return if op.is_delete() {
                SpanShiftPlan::Demote {
                    reason: SpanDemoteReason::DeletePartiallyOverlaps,
                }
            } else {
                SpanShiftPlan::Split
            };
        }
    };
    let result_shifts = row_delta != 0 || col_delta != 0;

    // Partition read dependencies by (displaced-by-op × anchor kind on the
    // op axis). Stationary absolute reads impose no constraint: the AST
    // coordinate already points at the unmoved target and origin relocation
    // never touches absolute references.
    let mut saw_shifting_relative = false;
    let mut saw_stationary_relative = false;
    let mut saw_displaced_absolute = false;
    if let Some(read_summary) = read_summary {
        for dependency in &read_summary.dependencies {
            let (has_relative, has_absolute) =
                rule_axis_bound_kinds(dependency.projection, op.axis_kind());
            match op.classify_region(dependency.read_region) {
                AxisShiftCase::OtherSheet | AxisShiftCase::EntirelyBelow => {
                    if has_relative {
                        saw_stationary_relative = true;
                    }
                }
                AxisShiftCase::EntirelyAboveShift { .. } => {
                    if has_relative {
                        saw_shifting_relative = true;
                    }
                    if has_absolute {
                        saw_displaced_absolute = true;
                    }
                }
                AxisShiftCase::Straddles | AxisShiftCase::DeleteFullyContains => {
                    return SpanShiftPlan::Demote {
                        reason: SpanDemoteReason::ReadRegionStraddles,
                    };
                }
            }
        }
    }

    if !result_shifts {
        // The span itself does not move. Any displaced read target (relative
        // or absolute) would require per-read relocation that origin choice
        // cannot express for a stationary span; demote conservatively.
        return if saw_shifting_relative || saw_displaced_absolute {
            SpanShiftPlan::Demote {
                reason: SpanDemoteReason::OriginNotShiftedButReadRegionShifts,
            }
        } else {
            SpanShiftPlan::NoOp
        };
    }

    if saw_displaced_absolute {
        // A displaced absolute read needs a template AST rewrite (issue
        // #168). The rewrite runs the shared `ReferenceAdjuster` over the
        // whole template, which also relocates displaced relative reads and
        // leaves stationary ones alone — so pairing it with an origin that
        // moves with the block is correct for every read kind (see the
        // `rewrite_absolute_reads` field docs).
        return SpanShiftPlan::Shift {
            row_delta,
            col_delta,
            origin_row_delta: row_delta,
            origin_col_delta: col_delta,
            rewrite_absolute_reads: true,
        };
    }

    match (saw_shifting_relative, saw_stationary_relative) {
        // Mixed relative kinds: no origin choice satisfies both, and the
        // relative-rewrite upgrade is deferred.
        (true, true) => SpanShiftPlan::Demote {
            reason: SpanDemoteReason::MixedReadRegionShift,
        },
        // All displaced reads are relative and move with the block: keep the
        // origin stationary so evaluated relative references shift with the
        // placements. Stationary absolute reads (e.g. the flagship `$F$1`)
        // are untouched by the origin and stay correct — this is the P2.5
        // mixed-read fast path.
        (true, false) => SpanShiftPlan::Shift {
            row_delta,
            col_delta,
            origin_row_delta: 0,
            origin_col_delta: 0,
            rewrite_absolute_reads: false,
        },
        // No displaced reads at all: move the origin with the block so
        // stationary relative reads keep pointing at their unmoved targets.
        (false, _) => SpanShiftPlan::Shift {
            row_delta,
            col_delta,
            origin_row_delta: row_delta,
            origin_col_delta: col_delta,
            rewrite_absolute_reads: false,
        },
    }
}

fn split_axis_at(min: u32, max: u32, before: u32) -> Option<((u32, u32), (u32, u32))> {
    if min < before && before <= max {
        Some(((min, before - 1), (before, max)))
    } else {
        None
    }
}

/// Split `domain` at an insert boundary into (upper, lower) halves in the
/// PRE-insert coordinate frame: the upper half is untouched by the insert,
/// the lower half starts at the insert boundary and shifts by the insert
/// count. Sibling of the delete-compaction domain surgery in
/// `demote_spans_for_structural_op_impl` (deliberately not merged: compaction
/// yields one domain, splitting yields two). Returns None whenever the domain
/// cannot be split cleanly along the insert axis; callers fall back to
/// demoting the whole span.
pub(crate) fn split_domain_at(
    domain: &PlacementDomain,
    op: StructuralOp,
) -> Option<(PlacementDomain, PlacementDomain)> {
    if domain.sheet_id() != op.sheet_id() {
        return None;
    }
    match (domain, op) {
        (
            PlacementDomain::RowRun {
                sheet_id,
                row_start,
                row_end,
                col,
            },
            StructuralOp::InsertRows { before, .. },
        ) => {
            let ((upper_start, upper_end), (lower_start, lower_end)) =
                split_axis_at(*row_start, *row_end, before)?;
            Some((
                PlacementDomain::row_run(*sheet_id, upper_start, upper_end, *col),
                PlacementDomain::row_run(*sheet_id, lower_start, lower_end, *col),
            ))
        }
        (
            PlacementDomain::Rect {
                sheet_id,
                row_start,
                row_end,
                col_start,
                col_end,
            },
            StructuralOp::InsertRows { before, .. },
        ) => {
            let ((upper_start, upper_end), (lower_start, lower_end)) =
                split_axis_at(*row_start, *row_end, before)?;
            Some((
                PlacementDomain::rect(*sheet_id, upper_start, upper_end, *col_start, *col_end),
                PlacementDomain::rect(*sheet_id, lower_start, lower_end, *col_start, *col_end),
            ))
        }
        (
            PlacementDomain::ColRun {
                sheet_id,
                row,
                col_start,
                col_end,
            },
            StructuralOp::InsertColumns { before, .. },
        ) => {
            let ((upper_start, upper_end), (lower_start, lower_end)) =
                split_axis_at(*col_start, *col_end, before)?;
            Some((
                PlacementDomain::col_run(*sheet_id, *row, upper_start, upper_end),
                PlacementDomain::col_run(*sheet_id, *row, lower_start, lower_end),
            ))
        }
        (
            PlacementDomain::Rect {
                sheet_id,
                row_start,
                row_end,
                col_start,
                col_end,
            },
            StructuralOp::InsertColumns { before, .. },
        ) => {
            let ((upper_start, upper_end), (lower_start, lower_end)) =
                split_axis_at(*col_start, *col_end, before)?;
            Some((
                PlacementDomain::rect(*sheet_id, *row_start, *row_end, upper_start, upper_end),
                PlacementDomain::rect(*sheet_id, *row_start, *row_end, lower_start, lower_end),
            ))
        }
        _ => None,
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::formula_plane::ids::FormulaTemplateId;
    use crate::formula_plane::producer::{DirtyProjectionRule, SpanReadDependency};
    use crate::formula_plane::runtime::{
        FormulaSpan, FormulaSpanId, PlacementDomain, ResultRegion, SpanAstRelocation, SpanState,
    };

    fn span(domain: PlacementDomain) -> FormulaSpan {
        FormulaSpan {
            id: FormulaSpanId(0),
            generation: 0,
            sheet_id: domain.sheet_id(),
            template_id: FormulaTemplateId(0),
            ast_relocation: SpanAstRelocation {
                ast_id: crate::engine::arena::AstNodeId::from_u32(0),
                anchor_row: 1,
                anchor_col: 1,
            },
            result_region: ResultRegion::scalar_cells(domain.clone()),
            domain,
            intrinsic_mask_id: None,
            read_summary_id: None,
            binding_set_id: None,
            is_constant_result: false,
            state: SpanState::Active,
            version: 0,
        }
    }

    fn summary(read_regions: Vec<Region>) -> SpanReadSummary {
        SpanReadSummary {
            result_region: Region::point(0, 0, 0),
            dependencies: read_regions
                .into_iter()
                .map(|read_region| SpanReadDependency {
                    read_region,
                    projection: DirtyProjectionRule::WholeResult,
                })
                .collect(),
        }
    }

    #[test]
    fn classify_axis_insert_columns_covers_each_axis_range_kind() {
        let op = StructuralOp::InsertColumns {
            sheet_id: 0,
            before: 5,
            count: 2,
        };
        assert_eq!(
            op.classify_axis(AxisRange::Point(4)),
            AxisShiftCase::EntirelyBelow
        );
        assert_eq!(
            op.classify_axis(AxisRange::Point(5)),
            AxisShiftCase::EntirelyAboveShift { delta: 2 }
        );
        assert_eq!(
            op.classify_axis(AxisRange::Span(2, 6)),
            AxisShiftCase::Straddles
        );
        assert_eq!(
            op.classify_axis(AxisRange::From(5)),
            AxisShiftCase::EntirelyAboveShift { delta: 2 }
        );
        assert_eq!(
            op.classify_axis(AxisRange::To(4)),
            AxisShiftCase::EntirelyBelow
        );
        assert_eq!(op.classify_axis(AxisRange::All), AxisShiftCase::Straddles);
    }

    #[test]
    fn classify_axis_insert_before_zero_shifts_all_axis_range_kinds() {
        let op = StructuralOp::InsertRows {
            sheet_id: 0,
            before: 0,
            count: 5,
        };
        for axis in [
            AxisRange::Point(0),
            AxisRange::Span(0, 7),
            AxisRange::From(0),
            AxisRange::To(7),
            AxisRange::All,
        ] {
            assert_eq!(
                op.classify_axis(axis),
                AxisShiftCase::EntirelyAboveShift { delta: 5 }
            );
        }
    }

    #[test]
    fn classify_axis_delete_columns_covers_below_above_full_and_partial() {
        let op = StructuralOp::DeleteColumns {
            sheet_id: 0,
            start: 5,
            count: 3,
        };
        assert_eq!(
            op.classify_axis(AxisRange::Span(0, 4)),
            AxisShiftCase::EntirelyBelow
        );
        assert_eq!(
            op.classify_axis(AxisRange::Point(8)),
            AxisShiftCase::EntirelyAboveShift { delta: -3 }
        );
        assert_eq!(
            op.classify_axis(AxisRange::Span(5, 7)),
            AxisShiftCase::DeleteFullyContains
        );
        assert_eq!(
            op.classify_axis(AxisRange::Span(4, 5)),
            AxisShiftCase::Straddles
        );
        assert_eq!(
            op.classify_axis(AxisRange::From(8)),
            AxisShiftCase::EntirelyAboveShift { delta: -3 }
        );
        assert_eq!(op.classify_axis(AxisRange::All), AxisShiftCase::Straddles);
    }

    #[test]
    fn classify_region_uses_only_affected_axis_and_sheet() {
        let op = StructuralOp::InsertColumns {
            sheet_id: 7,
            before: 3,
            count: 1,
        };
        assert_eq!(
            op.classify_region(Region::rect(7, 0, 9, 0, 2)),
            AxisShiftCase::EntirelyBelow
        );
        assert_eq!(
            op.classify_region(Region::rect(7, 0, 9, 3, 6)),
            AxisShiftCase::EntirelyAboveShift { delta: 1 }
        );
        assert_eq!(
            op.classify_region(Region::rect(7, 0, 9, 2, 3)),
            AxisShiftCase::Straddles
        );
        assert_eq!(
            op.classify_region(Region::rect(8, 0, 9, 3, 6)),
            AxisShiftCase::OtherSheet
        );
    }

    #[test]
    fn classify_span_case3_origin_moves_when_reads_stay_below_insert() {
        let s = span(PlacementDomain::col_run(0, 0, 2, 4));
        let rs = summary(vec![Region::point(0, 0, 0)]);
        let op = StructuralOp::InsertColumns {
            sheet_id: 0,
            before: 2,
            count: 1,
        };
        assert_eq!(
            classify_span_for_op(&s, Some(&rs), op),
            SpanShiftPlan::Shift {
                row_delta: 0,
                col_delta: 1,
                origin_row_delta: 0,
                origin_col_delta: 1,
                rewrite_absolute_reads: false,
            }
        );
    }

    #[test]
    fn classify_span_shifts_with_stationary_origin_when_reads_shift() {
        let s = span(PlacementDomain::col_run(0, 0, 2, 4));
        let rs = summary(vec![Region::point(0, 0, 2)]);
        let op = StructuralOp::InsertColumns {
            sheet_id: 0,
            before: 2,
            count: 1,
        };
        assert_eq!(
            classify_span_for_op(&s, Some(&rs), op),
            SpanShiftPlan::Shift {
                row_delta: 0,
                col_delta: 1,
                origin_row_delta: 0,
                origin_col_delta: 0,
                rewrite_absolute_reads: false,
            }
        );
    }

    #[test]
    fn classify_span_demotes_result_straddle_read_straddle_and_delete_overlap() {
        let insert = StructuralOp::InsertColumns {
            sheet_id: 0,
            before: 3,
            count: 1,
        };
        let result_straddle = span(PlacementDomain::col_run(0, 0, 2, 4));
        assert_eq!(
            classify_span_for_op(&result_straddle, None, insert),
            SpanShiftPlan::Split
        );

        let result_above = span(PlacementDomain::col_run(0, 0, 5, 7));
        let read_straddle = summary(vec![Region::row_interval(0, 0, 2, 4)]);
        assert_eq!(
            classify_span_for_op(&result_above, Some(&read_straddle), insert),
            SpanShiftPlan::Demote {
                reason: SpanDemoteReason::ReadRegionStraddles
            }
        );

        let delete = StructuralOp::DeleteColumns {
            sheet_id: 0,
            start: 3,
            count: 2,
        };
        assert_eq!(
            classify_span_for_op(&result_straddle, None, delete),
            SpanShiftPlan::Demote {
                reason: SpanDemoteReason::DeletePartiallyOverlaps
            }
        );
    }

    #[test]
    fn classify_span_returns_split_for_mid_domain_row_insert() {
        let s = span(PlacementDomain::row_run(0, 0, 99, 1));
        let op = StructuralOp::InsertRows {
            sheet_id: 0,
            before: 50,
            count: 2,
        };
        // Result-domain straddle on an insert is now a split candidate even
        // when reads would straddle: the apply site re-classifies each half
        // and falls back to demoting the whole span.
        assert_eq!(classify_span_for_op(&s, None, op), SpanShiftPlan::Split);
        let read_straddle = summary(vec![Region::col_interval(0, 0, 0, 99)]);
        assert_eq!(
            classify_span_for_op(&s, Some(&read_straddle), op),
            SpanShiftPlan::Split
        );
    }

    #[test]
    fn classify_span_remove_for_delete_fully_contains_result() {
        let s = span(PlacementDomain::col_run(0, 0, 3, 4));
        let op = StructuralOp::DeleteColumns {
            sheet_id: 0,
            start: 2,
            count: 5,
        };
        assert_eq!(classify_span_for_op(&s, None, op), SpanShiftPlan::Remove);
    }

    #[test]
    fn classify_rect_span_partial_row_and_column_deletes_demote_for_compaction_path() {
        let s = span(PlacementDomain::rect(0, 0, 9, 2, 3));
        let delete_rows = StructuralOp::DeleteRows {
            sheet_id: 0,
            start: 4,
            count: 2,
        };
        assert_eq!(
            classify_span_for_op(&s, None, delete_rows),
            SpanShiftPlan::Demote {
                reason: SpanDemoteReason::DeletePartiallyOverlaps
            }
        );

        let delete_columns = StructuralOp::DeleteColumns {
            sheet_id: 0,
            start: 2,
            count: 1,
        };
        assert_eq!(
            classify_span_for_op(&s, None, delete_columns),
            SpanShiftPlan::Demote {
                reason: SpanDemoteReason::DeletePartiallyOverlaps
            }
        );
    }

    #[test]
    fn split_domain_at_covers_row_and_column_axes() {
        // RowRun / row insert: rows [10, 99] split before row 40.
        assert_eq!(
            split_domain_at(
                &PlacementDomain::row_run(0, 10, 99, 2),
                StructuralOp::InsertRows {
                    sheet_id: 0,
                    before: 40,
                    count: 3,
                },
            ),
            Some((
                PlacementDomain::row_run(0, 10, 39, 2),
                PlacementDomain::row_run(0, 40, 99, 2),
            ))
        );
        // Rect / row insert keeps the column extent on both halves.
        assert_eq!(
            split_domain_at(
                &PlacementDomain::rect(0, 0, 99, 1, 3),
                StructuralOp::InsertRows {
                    sheet_id: 0,
                    before: 50,
                    count: 1,
                },
            ),
            Some((
                PlacementDomain::rect(0, 0, 49, 1, 3),
                PlacementDomain::rect(0, 50, 99, 1, 3),
            ))
        );
        // ColRun / column insert.
        assert_eq!(
            split_domain_at(
                &PlacementDomain::col_run(0, 5, 1, 100),
                StructuralOp::InsertColumns {
                    sheet_id: 0,
                    before: 49,
                    count: 2,
                },
            ),
            Some((
                PlacementDomain::col_run(0, 5, 1, 48),
                PlacementDomain::col_run(0, 5, 49, 100),
            ))
        );
        // Rect / column insert keeps the row extent on both halves.
        assert_eq!(
            split_domain_at(
                &PlacementDomain::rect(0, 0, 9, 2, 8),
                StructuralOp::InsertColumns {
                    sheet_id: 0,
                    before: 4,
                    count: 1,
                },
            ),
            Some((
                PlacementDomain::rect(0, 0, 9, 2, 3),
                PlacementDomain::rect(0, 0, 9, 4, 8),
            ))
        );
    }

    #[test]
    fn split_domain_at_rejects_non_straddling_and_cross_axis_cases() {
        let row_run = PlacementDomain::row_run(0, 10, 99, 2);
        // Boundary at/above the start or beyond the end is not a straddle.
        for before in [5, 10, 100, 200] {
            assert_eq!(
                split_domain_at(
                    &row_run,
                    StructuralOp::InsertRows {
                        sheet_id: 0,
                        before,
                        count: 1,
                    },
                ),
                None
            );
        }
        // A row insert cannot split a single-row ColRun; a column insert
        // cannot split a single-column RowRun; deletes never split.
        assert_eq!(
            split_domain_at(
                &PlacementDomain::col_run(0, 5, 1, 100),
                StructuralOp::InsertRows {
                    sheet_id: 0,
                    before: 5,
                    count: 1,
                },
            ),
            None
        );
        assert_eq!(
            split_domain_at(
                &row_run,
                StructuralOp::InsertColumns {
                    sheet_id: 0,
                    before: 2,
                    count: 1,
                },
            ),
            None
        );
        assert_eq!(
            split_domain_at(
                &row_run,
                StructuralOp::DeleteRows {
                    sheet_id: 0,
                    start: 40,
                    count: 1,
                },
            ),
            None
        );
        // Other-sheet ops never split.
        assert_eq!(
            split_domain_at(
                &row_run,
                StructuralOp::InsertRows {
                    sheet_id: 1,
                    before: 40,
                    count: 1,
                },
            ),
            None
        );
    }

    #[test]
    fn classify_span_routes_absolute_reads_to_rewrite_or_mixed_fast_path() {
        // Flagship shape (issue #168 / P2.5): a vertical run reading
        // relative inputs plus an absolute scalar `$F$1`.
        let s = span(PlacementDomain::row_run(0, 10, 99, 2));
        let relative_dep = SpanReadDependency {
            read_region: Region::col_interval(0, 0, 10, 99),
            projection: DirtyProjectionRule::AffineCell {
                row: AxisProjection::Relative { offset: 0 },
                col: AxisProjection::Relative { offset: -2 },
            },
        };
        let absolute_dep = SpanReadDependency {
            read_region: Region::point(0, 0, 5),
            projection: DirtyProjectionRule::AffineCell {
                row: AxisProjection::Absolute { index: 0 },
                col: AxisProjection::Absolute { index: 5 },
            },
        };
        let rs = SpanReadSummary {
            result_region: Region::col_interval(0, 2, 10, 99),
            dependencies: vec![relative_dep, absolute_dep],
        };

        // Insert above the absolute target: everything (span, relative
        // inputs, scalar target) shifts. The absolute read requires a
        // template AST rewrite, which pairs with an origin that moves with
        // the block.
        let insert_above_all = StructuralOp::InsertRows {
            sheet_id: 0,
            before: 0,
            count: 2,
        };
        assert_eq!(
            classify_span_for_op(&s, Some(&rs), insert_above_all),
            SpanShiftPlan::Shift {
                row_delta: 2,
                col_delta: 0,
                origin_row_delta: 2,
                origin_col_delta: 0,
                rewrite_absolute_reads: true,
            }
        );

        // Insert between the absolute target and the span: the scalar's
        // target is stationary (absolute reads impose no constraint), the
        // relative reads shift with the block — the P2.5 mixed-read fast
        // path: shift with a stationary origin, no rewrite, no demote.
        let insert_between = StructuralOp::InsertRows {
            sheet_id: 0,
            before: 5,
            count: 2,
        };
        assert_eq!(
            classify_span_for_op(&s, Some(&rs), insert_between),
            SpanShiftPlan::Shift {
                row_delta: 2,
                col_delta: 0,
                origin_row_delta: 0,
                origin_col_delta: 0,
                rewrite_absolute_reads: false,
            }
        );
    }

    #[test]
    fn classify_span_column_absolute_read_displaced_routes_to_rewrite() {
        // Column-axis mirror: a horizontal run reading `$A$1` under a
        // column insert that displaces column A.
        let s = span(PlacementDomain::col_run(0, 2, 10, 99));
        let absolute_dep = SpanReadDependency {
            read_region: Region::point(0, 0, 0),
            projection: DirtyProjectionRule::AffineCell {
                row: AxisProjection::Absolute { index: 0 },
                col: AxisProjection::Absolute { index: 0 },
            },
        };
        let relative_dep = SpanReadDependency {
            read_region: Region::row_interval(0, 0, 10, 99),
            projection: DirtyProjectionRule::AffineCell {
                row: AxisProjection::Relative { offset: -2 },
                col: AxisProjection::Relative { offset: 0 },
            },
        };
        let rs = SpanReadSummary {
            result_region: Region::row_interval(0, 2, 10, 99),
            dependencies: vec![absolute_dep, relative_dep],
        };
        let op = StructuralOp::InsertColumns {
            sheet_id: 0,
            before: 0,
            count: 2,
        };
        assert_eq!(
            classify_span_for_op(&s, Some(&rs), op),
            SpanShiftPlan::Shift {
                row_delta: 0,
                col_delta: 2,
                origin_row_delta: 0,
                origin_col_delta: 2,
                rewrite_absolute_reads: true,
            }
        );
    }

    #[test]
    fn classify_span_mixed_relative_reads_still_demote() {
        // One relative read shifts with the block, another relative read's
        // target stays put: no origin choice satisfies both and the
        // relative-rewrite upgrade is deferred, so the span demotes.
        // Span rows 50..=80 reading A{r} (shifts with the block) and a far
        // stationary relative read at rows 0..=5; the insert at row 20 sits
        // strictly between them so both classify uniformly.
        let s = span(PlacementDomain::row_run(0, 50, 80, 2));
        let shifting_rel = SpanReadDependency {
            read_region: Region::col_interval(0, 0, 50, 80),
            projection: DirtyProjectionRule::AffineCell {
                row: AxisProjection::Relative { offset: 0 },
                col: AxisProjection::Relative { offset: -2 },
            },
        };
        let stationary_rel = SpanReadDependency {
            read_region: Region::col_interval(0, 1, 0, 5),
            projection: DirtyProjectionRule::AffineCell {
                row: AxisProjection::Relative { offset: -50 },
                col: AxisProjection::Relative { offset: -1 },
            },
        };
        let rs = SpanReadSummary {
            result_region: Region::col_interval(0, 2, 50, 80),
            dependencies: vec![shifting_rel, stationary_rel],
        };
        let op = StructuralOp::InsertRows {
            sheet_id: 0,
            before: 20,
            count: 1,
        };
        assert_eq!(
            classify_span_for_op(&s, Some(&rs), op),
            SpanShiftPlan::Demote {
                reason: SpanDemoteReason::MixedReadRegionShift
            }
        );
    }

    #[test]
    fn rewrite_frame_soundness_matrix() {
        fn rel_cell_dep(
            read_region: Region,
            row_offset: i64,
            col_offset: i64,
        ) -> SpanReadDependency {
            SpanReadDependency {
                read_region,
                projection: DirtyProjectionRule::AffineCell {
                    row: AxisProjection::Relative { offset: row_offset },
                    col: AxisProjection::Relative { offset: col_offset },
                },
            }
        }
        fn summary_of(dependencies: Vec<SpanReadDependency>) -> SpanReadSummary {
            SpanReadSummary {
                result_region: Region::col_interval(0, 2, 50, 119),
                dependencies,
            }
        }
        let insert_rows = |before: u32| StructuralOp::InsertRows {
            sheet_id: 0,
            before,
            count: 3,
        };

        // Split-lower-half divergence (the #168 composition repro): domain
        // reads rows 50..119 but the stale origin authors A1 (row 0); an
        // insert at row 9 displaces the region while the authored coordinate
        // stays put — rewriting would shear relative reads.
        let displaced_region = summary_of(vec![rel_cell_dep(
            Region::col_interval(0, 0, 50, 119),
            0,
            -2,
        )]);
        assert!(!rewrite_frame_is_sound(
            &displaced_region,
            1,
            3,
            insert_rows(9)
        ));
        // Aligned frame (origin at the domain start): sound.
        assert!(rewrite_frame_is_sound(
            &displaced_region,
            51,
            3,
            insert_rows(9)
        ));

        // Column-axis mirror: relative column bound authored at
        // origin_col-1; the insert displaces the read region's column but
        // not the authored column.
        let displaced_col_region =
            summary_of(vec![rel_cell_dep(Region::row_interval(0, 10, 3, 3), 0, -1)]);
        let insert_cols = StructuralOp::InsertColumns {
            sheet_id: 0,
            before: 3,
            count: 1,
        };
        assert!(!rewrite_frame_is_sound(
            &displaced_col_region,
            11,
            4,
            insert_cols
        ));
        assert!(rewrite_frame_is_sound(
            &displaced_col_region,
            11,
            5,
            insert_cols
        ));

        // Spurious-stationary direction: the region is stationary but the
        // authored coordinate sits at/above the insert point (requires
        // origin > domain end, unreachable via engine ops today, covered
        // defensively).
        let stationary_region = summary_of(vec![rel_cell_dep(
            Region::col_interval(0, 0, 44, 54),
            0,
            -2,
        )]);
        assert!(!rewrite_frame_is_sound(
            &stationary_region,
            61,
            3,
            insert_rows(56)
        ));
        assert!(rewrite_frame_is_sound(
            &stationary_region,
            45,
            3,
            insert_rows(56)
        ));

        // Delete removing the authored coordinate while the region is
        // uniformly displaced.
        let delete = StructuralOp::DeleteRows {
            sheet_id: 0,
            start: 0,
            count: 1,
        };
        assert!(!rewrite_frame_is_sound(&displaced_region, 1, 3, delete));

        // Absolute-only dependencies carry their coordinate in the rule and
        // never need frame verification.
        let absolute_only = summary_of(vec![SpanReadDependency {
            read_region: Region::point(0, 29, 5),
            projection: DirtyProjectionRule::AffineCell {
                row: AxisProjection::Absolute { index: 29 },
                col: AxisProjection::Absolute { index: 5 },
            },
        }]);
        assert!(rewrite_frame_is_sound(&absolute_only, 1, 3, insert_rows(9)));

        // WholeResult rules have no axis information: unverifiable.
        let whole_result = summary_of(vec![SpanReadDependency {
            read_region: Region::col_interval(0, 0, 50, 119),
            projection: DirtyProjectionRule::WholeResult,
        }]);
        assert!(!rewrite_frame_is_sound(
            &whole_result,
            51,
            3,
            insert_rows(9)
        ));

        // Cross-sheet reads are refused: the shared adjuster relocates by
        // coordinate without honoring the reference's sheet.
        let cross_sheet = summary_of(vec![rel_cell_dep(
            Region::col_interval(1, 0, 50, 119),
            0,
            -2,
        )]);
        assert!(!rewrite_frame_is_sound(&cross_sheet, 51, 3, insert_rows(9)));
    }

    #[test]
    fn classify_span_cross_sheet_read_demotes_when_references_shift() {
        let s = span(PlacementDomain::col_run(1, 0, 3, 5));
        let rs = summary(vec![Region::point(0, 0, 4)]);
        let op = StructuralOp::InsertColumns {
            sheet_id: 0,
            before: 2,
            count: 1,
        };
        assert_eq!(
            classify_span_for_op(&s, Some(&rs), op),
            SpanShiftPlan::Demote {
                reason: SpanDemoteReason::OriginNotShiftedButReadRegionShifts
            }
        );
    }
}