lemma-engine 0.11.4

A pure, declarative language for business rules.
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
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
//! Computation of one normal-form cell from values already evaluated: arithmetic,
//! comparison, conversion and the settling of dynamic unit scales. Nothing here
//! evaluates an operand, spawns work or decides what to evaluate next; that control
//! stays with the walk ([`crate::evaluation::tree`]), which hands these functions the
//! operand values it gathered and the context it reads in.

use crate::computation::arithmetic::divisive_operation_results;
use crate::computation::bigint::BigInt;
use crate::computation::datetime::{
    compute_date_calendar, compute_date_relative, evaluate_past_future_range,
};
use crate::computation::measure_math::{integer_rounding, step_rounding};
use crate::computation::range::{check_containment, ordered_endpoints};
use crate::computation::rational::{
    checked_mul, checked_pow_integer, rational_one, rational_zero, RationalInteger,
};
use crate::computation::{
    arithmetic_operation, comparison_operation, convert_unit_operand, OperationResult, VetoType,
};
use crate::evaluation::branch_semantics::{condition_outcome, BranchOutcome};
use crate::evaluation::expression::{evaluate_mathematical_operator, resolve_data_path_value};
use crate::evaluation::list_ops;
use crate::evaluation::tree::RowBody;
use crate::evaluation::{CurrentRow, EvaluationContext};
use crate::parsing::ast::{ConversionTypeKind, LogicalConnective};
use crate::planning::execution_plan::{validate_value_against_type, ExecutionPlan, TargetForce};
use crate::planning::instance_list::InstanceListSource;
use crate::planning::instance_list::KeyIndex;
use crate::planning::normalize::{LeafKind, NormalFormId, NormalFormKind};
use crate::planning::semantics::{
    primitive_boolean_arc, primitive_number_arc, typed_literal_from_bound, ArithmeticComputation,
    BoundValueKind, ComparisonComputation, DataPath, InstanceKey, LemmaType, LiteralValue,
    RangeBound, ReferenceEnd, ReferenceTarget, RowBinding, ScaleTarget, SemanticConversionTarget,
    SemanticDateTime, TypedLiteral, ValueKind,
};
use crate::planning::semantics::{KeyField, ListValue};
use std::collections::HashMap;
use std::sync::Arc;

/// Factor of a resolved unit-scale target: missing/veto pass through, `<= 0` is
/// a computation veto, otherwise the number.
fn resolved_scale_factor(
    scale: &ScaleTarget,
    plan: &ExecutionPlan,
    ctx: &EvaluationContext,
) -> Result<RationalInteger, OperationResult> {
    assert!(
        plan.holds_scale_target(scale),
        "BUG: scale target '{scale}' resolved on a plan of '{}', which does not hold it",
        plan.spec_name
    );
    match resolve_stored_target(&scale.target, plan, ctx) {
        OperationResult::Veto(veto) => Err(OperationResult::Veto(veto)),
        OperationResult::Value(bound) => {
            let ValueKind::Number(factor) = &bound.value else {
                panic!(
                    "BUG: unit scale target resolved to {} after planning required number",
                    bound.value
                );
            };
            if !factor.numer_is_positive() {
                return Err(OperationResult::Veto(VetoType::computation(
                    "unit conversion factor must be greater than zero",
                )));
            }
            Ok(factor.clone())
        }
    }
}

/// Effective conversion factor of a dynamic measure unit:
/// `coefficient * Π settled(t_i)^e_i`.
pub(crate) fn composed_unit_scale_factor(
    unit: &crate::literals::MeasureUnit,
    plan: &ExecutionPlan,
    ctx: &EvaluationContext,
) -> Result<RationalInteger, OperationResult> {
    let factors = unit.resolved_scale_factors();
    if factors.is_empty() {
        panic!(
            "BUG: composed_unit_scale_factor on unit '{}' with no scale factors",
            unit.name
        );
    }
    let mut product = unit.scale_coefficient();
    for (target, exponent) in factors {
        let settled = resolved_scale_factor(target, plan, ctx)?;
        let raised = if *exponent == 1 {
            settled
        } else {
            checked_pow_integer(&settled, &BigInt::from_i64(i64::from(*exponent))).map_err(
                |failure| OperationResult::Veto(VetoType::computation(failure.to_string())),
            )?
        };
        product = checked_mul(&product, &raised)
            .map_err(|failure| OperationResult::Veto(VetoType::computation(failure.to_string())))?;
    }
    Ok(product)
}

fn measure_unit_on_type<'a>(
    lemma_type: &'a LemmaType,
    unit_name: &str,
) -> &'a crate::literals::MeasureUnit {
    let units = lemma_type.measure_units_table().unwrap_or_else(|| {
        panic!(
            "BUG: measure unit lookup on non-measure type '{}'",
            lemma_type.name()
        )
    });
    units.get(unit_name).unwrap_or_else(|_| {
        panic!(
            "BUG: unknown unit '{unit_name}' on measure type '{}'",
            lemma_type.name()
        )
    })
}

enum ScaleNodeType<'a> {
    Borrowed(&'a LemmaType),
    Shared(Arc<LemmaType>),
}

impl ScaleNodeType<'_> {
    fn get(&self) -> &LemmaType {
        match self {
            Self::Borrowed(lemma_type) => lemma_type,
            Self::Shared(lemma_type) => lemma_type.as_ref(),
        }
    }

    fn into_arc(self) -> Arc<LemmaType> {
        match self {
            Self::Borrowed(lemma_type) => Arc::new(lemma_type.clone()),
            Self::Shared(lemma_type) => lemma_type,
        }
    }
}

enum ScaleTask<'a> {
    Visit {
        value: ValueKind,
        lemma_type: ScaleNodeType<'a>,
        binding: Option<Arc<str>>,
    },
    AssembleRange {
        lemma_type: Arc<LemmaType>,
        binding: Option<Arc<str>>,
    },
    AssembleList {
        lemma_type: Arc<LemmaType>,
        binding: Option<Arc<str>>,
        rows: usize,
    },
}

fn scale_value(
    value: ValueKind,
    lemma_type: &LemmaType,
    binding: Option<Arc<str>>,
    plan: &ExecutionPlan,
    ctx: &EvaluationContext,
) -> OperationResult {
    let mut tasks = vec![ScaleTask::Visit {
        value,
        lemma_type: ScaleNodeType::Borrowed(lemma_type),
        binding: binding.clone(),
    }];
    let mut done: Vec<TypedLiteral> = Vec::new();
    let mut root_unit = binding;
    while let Some(task) = tasks.pop() {
        match task {
            ScaleTask::Visit {
                value,
                lemma_type,
                binding,
            } => match value {
                ValueKind::UnscaledMeasure { magnitude, unit } => {
                    let holding = lemma_type.get();
                    if holding.unit_scale_factors(&unit).is_empty() {
                        panic!(
                            "BUG: unscaled measure unit '{unit}' on '{}' has no scale factors",
                            holding.name()
                        );
                    }
                    if tasks.is_empty() && done.is_empty() {
                        root_unit = Some(Arc::clone(&unit));
                    }
                    let measure_unit = measure_unit_on_type(holding, &unit);
                    match composed_unit_scale_factor_for_settle(
                        measure_unit,
                        &unit,
                        holding,
                        plan,
                        ctx,
                    ) {
                        Err(veto) => return veto,
                        Ok(factor) => match checked_mul(&magnitude, &factor) {
                            Ok(canonical) => done.push(TypedLiteral {
                                value: ValueKind::Measure(canonical),
                                lemma_type: lemma_type.into_arc(),
                            }),
                            Err(failure) => {
                                return OperationResult::Veto(VetoType::computation(
                                    failure.to_string(),
                                ));
                            }
                        },
                    }
                }
                ValueKind::Range(left, right) => {
                    let lemma_type = lemma_type.into_arc();
                    tasks.push(ScaleTask::AssembleRange {
                        lemma_type: Arc::clone(&lemma_type),
                        binding,
                    });
                    let right = *right;
                    let left = *left;
                    tasks.push(ScaleTask::Visit {
                        value: right.value,
                        lemma_type: ScaleNodeType::Shared(right.lemma_type),
                        binding: None,
                    });
                    tasks.push(ScaleTask::Visit {
                        value: left.value,
                        lemma_type: ScaleNodeType::Shared(left.lemma_type),
                        binding: None,
                    });
                }
                ValueKind::List(rows) => {
                    let lemma_type = lemma_type.into_arc();
                    let count = rows.len();
                    tasks.push(ScaleTask::AssembleList {
                        lemma_type,
                        binding,
                        rows: count,
                    });
                    for row in rows.iter().rev() {
                        let row = row.into_owned();
                        tasks.push(ScaleTask::Visit {
                            value: row.value,
                            lemma_type: ScaleNodeType::Shared(row.lemma_type),
                            binding: None,
                        });
                    }
                }
                other => done.push(TypedLiteral {
                    value: other,
                    lemma_type: lemma_type.into_arc(),
                }),
            },
            ScaleTask::AssembleRange {
                lemma_type,
                binding,
            } => {
                let right = done
                    .pop()
                    .expect("BUG: scaled range missing right endpoint");
                let left = done.pop().expect("BUG: scaled range missing left endpoint");
                if tasks.is_empty() && done.is_empty() {
                    root_unit = binding;
                }
                done.push(TypedLiteral {
                    value: ValueKind::Range(Box::new(left), Box::new(right)),
                    lemma_type,
                });
            }
            ScaleTask::AssembleList {
                lemma_type,
                binding,
                rows,
            } => {
                let mut scaled = Vec::with_capacity(rows);
                for _ in 0..rows {
                    scaled.push(done.pop().expect("BUG: scaled list missing a row"));
                }
                scaled.reverse();
                if tasks.is_empty() && done.is_empty() {
                    root_unit = binding;
                }
                done.push(TypedLiteral {
                    value: ValueKind::List(scaled.into()),
                    lemma_type,
                });
            }
        }
    }
    let result = done.pop().expect("BUG: scale walk leaves one result");
    OperationResult::from_bound(BoundValueKind {
        value: result.value,
        unit: root_unit,
        instance_factors: None,
    })
}

/// `bound` with every unscaled measure scaled. The scales were evaluated before the
/// rule or row leaf that reads it (`scale_dependencies`). Factors the value already
/// carried stay on the settled result.
pub(crate) fn settle_stored(
    bound: BoundValueKind,
    lemma_type: &LemmaType,
    plan: &ExecutionPlan,
    ctx: &EvaluationContext,
) -> OperationResult {
    if !bound.value.has_unscaled_measure() {
        return OperationResult::from_bound(bound);
    }
    let carried = bound.instance_factors.clone();
    match scale_value(bound.value, lemma_type, bound.unit, plan, ctx) {
        OperationResult::Value(mut settled) => {
            if settled.instance_factors.is_none() {
                settled.instance_factors = carried;
            }
            OperationResult::from_bound(settled)
        }
        other => other,
    }
}

/// Dynamic unit a conversion needs to settle, if any.
pub(crate) fn conversion_dynamic_unit<'a>(
    target: &'a SemanticConversionTarget,
    source_type: &'a LemmaType,
) -> Option<(String, &'a LemmaType)> {
    match target {
        SemanticConversionTarget::Unit {
            unit_name,
            owning_type,
        } if owning_type.unit_is_dynamic(unit_name) => {
            if owning_type.unit_scale_factors(unit_name).is_empty() {
                panic!(
                    "BUG: dynamic unit '{unit_name}' on '{}' has no scale factors",
                    owning_type.name()
                );
            }
            Some((unit_name.clone(), owning_type.as_ref()))
        }
        SemanticConversionTarget::Type(ConversionTypeKind::Number) if source_type.is_measure() => {
            let unit = source_type.measure_runtime_signature().into_iter().next()?;
            if source_type.unit_is_dynamic(&unit.0) {
                if source_type.unit_scale_factors(&unit.0).is_empty() {
                    panic!(
                        "BUG: dynamic unit '{}' on '{}' has no scale factors",
                        unit.0,
                        source_type.name()
                    );
                }
                Some((unit.0, source_type))
            } else {
                None
            }
        }
        _ => None,
    }
}

/// `converted`, a value converted into `unit` at `factor`: the factors it carries from
/// its instance give `unit` that factor, so it shows in the unit it was converted to.
fn converted_at(
    converted: OperationResult,
    unit: &str,
    factor: &RationalInteger,
) -> OperationResult {
    let OperationResult::Value(mut bound) = converted else {
        return converted;
    };
    if let Some(carried) = &bound.instance_factors {
        if carried.get(unit) != Some(factor) {
            bound.instance_factors = Some(Arc::new(carried.with_factor(unit, factor)));
        }
    }
    OperationResult::from_bound(bound)
}

/// Factor for a dynamic conversion: prefer a factor the operand already carries from
/// its instance (row / uses read). Otherwise resolve every scale factor on this plan,
/// or through the row stack for bare targets. A scale that is not forcible here and
/// not carried is a computation veto — not a missing data_leaf panic.
pub(crate) fn conversion_dynamic_factor(
    bound: &BoundValueKind,
    unit_name: &str,
    holding: &LemmaType,
    plan: &ExecutionPlan,
    ctx: &EvaluationContext,
) -> Result<RationalInteger, OperationResult> {
    let measure_unit = measure_unit_on_type(holding, unit_name);
    let factors = measure_unit.resolved_scale_factors();
    if factors.is_empty() {
        panic!("BUG: conversion_dynamic_factor on unit '{unit_name}' with no scale factors");
    }
    // A target unit whose scale resolves in this plan (this spec's own unit, or a `uses`
    // import's) names that scale, whatever row the value came from.
    let all_in_plan = factors
        .iter()
        .all(|(target, _)| plan.holds_scale_target(target));
    if all_in_plan {
        for (target, _) in factors {
            assert!(
                unforced_target(target, plan, ctx).is_none(),
                "BUG: conversion scale {target:?} read before its scale dependency was evaluated"
            );
        }
        return composed_unit_scale_factor(measure_unit, plan, ctx);
    }
    // A unit in a row's own coordinates (`lines.Type.unit`) scales as the row the value
    // was read from.
    if let Some(factors) = bound.instance_factors.as_ref() {
        if let Some(factor) = factors.get(unit_name) {
            return Ok(factor.clone());
        }
        if let Some(veto) = factors.unsettled(unit_name) {
            return Err(OperationResult::Veto(veto.clone()));
        }
    }
    let all_bare = factors.iter().all(|(scale, _)| match &scale.target {
        ReferenceTarget::Data(path) => path.segments.is_empty(),
        ReferenceTarget::Rule(path) => path.segments.is_empty(),
    });
    let in_rows = factors
        .iter()
        .all(|(target, _)| bare_target_row(target, plan, ctx).is_some());
    let all_settle = factors.iter().all(|(target, _)| {
        plan.holds_scale_target(target) || bare_target_row(target, plan, ctx).is_some()
    });
    if (all_bare && all_settle) || in_rows {
        return composed_unit_scale_factor_for_settle(measure_unit, unit_name, holding, plan, ctx);
    }
    Err(OperationResult::Veto(VetoType::computation(format!(
        "no conversion factor is known for unit '{unit_name}'"
    ))))
}

/// Factors of the units declared on `lemma_type`, as settled in `ctx`: a vetoed or
/// missing scale has no entry. The rule or row leaf that produced a value of this
/// type evaluated these scales first. The type carries the coordinates of the plan
/// that holds it (`uses` hops already prefixed). A bare target resolves only when
/// this plan declares the measure family (or the target is otherwise a cell of this
/// plan). Callers merge [`BoundValueKind::instance_factors`] on top when a value was
/// read from a row.
pub(crate) fn runtime_scale_factors_for(
    lemma_type: &LemmaType,
    plan: &ExecutionPlan,
    ctx: &EvaluationContext,
) -> HashMap<String, RationalInteger> {
    runtime_scales_for(lemma_type, plan, ctx).0
}

/// [`runtime_scale_factors_for`], with the units whose factor this plan reads but could
/// not settle, and why: missing data or a veto.
pub(crate) fn runtime_scales_for(
    lemma_type: &LemmaType,
    plan: &ExecutionPlan,
    ctx: &EvaluationContext,
) -> (
    HashMap<String, RationalInteger>,
    std::collections::BTreeMap<String, VetoType>,
) {
    let mut out = HashMap::new();
    let mut unsettled = std::collections::BTreeMap::new();
    let Some(units) = lemma_type.measure_units_table() else {
        return (out, unsettled);
    };
    let family_declared_here = lemma_type.held_measure_family().is_some_and(|family| {
        family.spec == plan.spec_name
            && family.repository.as_deref() == plan.identity.repository.as_deref()
    });
    for unit in units.iter() {
        match &unit.scale {
            crate::literals::UnitScale::Literal(factor) => {
                out.insert(unit.name.clone(), factor.clone());
            }
            crate::literals::UnitScale::Reference { factors, .. } => {
                if factors.is_empty() {
                    panic!(
                        "BUG: dynamic unit '{}' on '{}' has empty scale factors after planning",
                        unit.name,
                        lemma_type.name()
                    );
                }
                let all_forcible = factors.iter().all(|(target, _)| {
                    let bare = match &target.target {
                        ReferenceTarget::Data(path) => path.segments.is_empty(),
                        ReferenceTarget::Rule(path) => path.segments.is_empty(),
                    };
                    if bare && !family_declared_here && !plan.holds_scale_target(target) {
                        return false;
                    }
                    // A scale this evaluation did not reach has no factor here yet.
                    plan.holds_scale_target(target) && unforced_target(target, plan, ctx).is_none()
                });
                if !all_forcible {
                    continue;
                }
                match composed_unit_scale_factor(unit, plan, ctx) {
                    Ok(factor) => {
                        out.insert(unit.name.clone(), factor);
                    }
                    Err(OperationResult::Veto(veto)) => {
                        unsettled.insert(unit.name.clone(), veto);
                    }
                    Err(OperationResult::Value(_)) => {
                        unreachable!("BUG: a unit scale failure is a veto")
                    }
                }
            }
            crate::literals::UnitScale::Compound { .. }
            | crate::literals::UnitScale::Unresolved { .. } => {
                panic!(
                    "BUG: unit '{}' on '{}' never went through scale resolution",
                    unit.name,
                    lemma_type.name()
                );
            }
        }
    }
    (out, unsettled)
}

/// Effective conversion factor for settling an unscaled measure: each scale factor
/// settles on this plan when local here; otherwise the innermost row on the stack
/// whose template holds a bare target (per-row literal in a list argument).
fn composed_unit_scale_factor_for_settle(
    unit: &crate::literals::MeasureUnit,
    unit_name: &str,
    holding: &LemmaType,
    plan: &ExecutionPlan,
    ctx: &EvaluationContext,
) -> Result<RationalInteger, OperationResult> {
    let factors = unit.resolved_scale_factors();
    if factors.is_empty() {
        panic!(
            "BUG: composed_unit_scale_factor_for_settle on unit '{unit_name}' with no scale factors"
        );
    }
    let mut product = unit.scale_coefficient();
    for (target, exponent) in factors {
        let settled = settled_scale_factor_for_target(target, unit_name, holding, plan, ctx)?;
        let raised = if *exponent == 1 {
            settled
        } else {
            checked_pow_integer(&settled, &BigInt::from_i64(i64::from(*exponent))).map_err(
                |failure| OperationResult::Veto(VetoType::computation(failure.to_string())),
            )?
        };
        product = checked_mul(&product, &raised)
            .map_err(|failure| OperationResult::Veto(VetoType::computation(failure.to_string())))?;
    }
    Ok(product)
}

fn settled_scale_factor_for_target(
    target: &ScaleTarget,
    unit_name: &str,
    holding: &LemmaType,
    plan: &ExecutionPlan,
    ctx: &EvaluationContext,
) -> Result<RationalInteger, OperationResult> {
    if plan.holds_scale_target(target) {
        assert!(
            unforced_target(target, plan, ctx).is_none(),
            "BUG: scale of unit '{unit_name}' on '{}' read before its scale dependency was evaluated",
            holding.name()
        );
        return resolved_scale_factor(target, plan, ctx);
    }
    if let Some((key, template)) = bare_target_row(target, plan, ctx) {
        if ctx.owner_row.as_ref() == Some(key) {
            assert!(
                unforced_target(target, template, ctx).is_none(),
                "BUG: scale of unit '{unit_name}' on '{}' read before its scale dependency was evaluated",
                holding.name()
            );
            return resolved_scale_factor(target, template, ctx);
        }
        let caches = ctx.caches.row_contexts.borrow();
        let row_ctx = caches.get(key).unwrap_or_else(|| {
            panic!(
                "BUG: bare scale target '{target}' of a row-typed value settled before the row context was built; list per-row paths must spawn an empty RowScope first"
            )
        });
        assert!(
            unforced_target(target, template, row_ctx).is_none(),
            "BUG: scale of unit '{unit_name}' on '{}' read before its scale dependency was evaluated",
            holding.name()
        );
        return resolved_scale_factor(target, template, row_ctx);
    }
    assert!(
        unforced_target(target, plan, ctx).is_none(),
        "BUG: scale of unit '{unit_name}' on '{}' read before its scale dependency was evaluated",
        holding.name()
    );
    resolved_scale_factor(target, plan, ctx)
}

/// The innermost list row on the stack whose template holds scale target `target`, when
/// `target` is not a target of `plan` itself: a unit of the rows written in a list
/// argument settles in that row.
pub(crate) fn bare_target_row<'p, 'c>(
    target: &ScaleTarget,
    plan: &'p ExecutionPlan,
    ctx: &'c EvaluationContext,
) -> Option<(&'c InstanceKey, &'p ExecutionPlan)> {
    if plan.holds_scale_target(target) {
        return None;
    }
    ctx.row_stack.iter().rev().find_map(|row| {
        let CurrentRow::Instance { key, .. } = row else {
            return None;
        };
        let template = plan.row_template(&key.row.identity);
        template
            .holds_scale_target(target)
            .then_some((key, template))
    })
}

/// Display factors for a settled value: instance factors from a row or uses read
/// override the type lookup for those unit names.
pub(crate) fn display_scale_factors(
    bound: Option<&BoundValueKind>,
    lemma_type: &LemmaType,
    plan: &ExecutionPlan,
    ctx: &EvaluationContext,
) -> HashMap<String, RationalInteger> {
    let mut factors = runtime_scale_factors_for(lemma_type, plan, ctx);
    if let Some(instance) = bound.and_then(|bound| bound.instance_factors.as_ref()) {
        for (unit, factor) in instance.iter() {
            factors.insert(unit.clone(), factor.clone());
        }
    }
    factors
}

/// What `target` still needs evaluated in `ctx` over `plan`, its owner, before it
/// resolves: the rule or member it ends at, or the slot of `ctx`'s own row it names, when
/// that slot is itself bound to what no read of the row resolved yet. `None` when it
/// resolves as is.
pub(crate) fn unforced_target(
    scale: &ScaleTarget,
    plan: &ExecutionPlan,
    ctx: &EvaluationContext,
) -> Option<RowBody> {
    unforced_reference(&scale.target, plan, ctx)
}

/// The work that evaluates `target` itself, `None` when it resolves as is: what a
/// deferred row binding ends at. A value its data's type bounds at other than 0 in a
/// dynamic unit first needs the sizes of that type ([`bounded_unscaled`]).
pub(crate) fn unforced_reference(
    target: &ReferenceTarget,
    plan: &ExecutionPlan,
    ctx: &EvaluationContext,
) -> Option<RowBody> {
    if let ReferenceTarget::Data(path) = target {
        if let Some((held, _)) = bounded_unscaled(path, plan, ctx) {
            for scale in plan.data_scale_targets(held) {
                if let Some(force) = unevaluated(&scale.target, plan, ctx) {
                    return Some(force);
                }
            }
        }
    }
    unevaluated(target, plan, ctx)
}

/// The work that evaluates `target` itself, `None` when it resolves as is.
fn unevaluated(
    target: &ReferenceTarget,
    plan: &ExecutionPlan,
    ctx: &EvaluationContext,
) -> Option<RowBody> {
    match plan.target_force(target) {
        Some(TargetForce::Member(cell)) => ctx.values[cell.index()]
            .is_none()
            .then_some(RowBody::Member(cell)),
        Some(TargetForce::Rule(index)) => ctx.rule_values[index.index()]
            .is_none()
            .then_some(RowBody::Rule(index)),
        None => {
            let ReferenceTarget::Data(path) = target else {
                return None;
            };
            let row = ctx.owner_row.as_ref()?;
            let slot = plan.data.get_index_of(path)?;
            if !matches!(
                ctx.caches.binding(row, plan, slot).as_deref(),
                Some(RowBinding::Deferred { .. })
            ) {
                return None;
            }
            let leaf = *plan.data_leaf.get(path)?;
            ctx.values[leaf.index()]
                .is_none()
                .then_some(RowBody::Leaf(leaf))
        }
    }
}

/// Rule 6: the data `path` reads its value from, and that value, while it is still
/// written in a dynamic unit the data's type bounds at other than 0: a copy of it checks
/// the bound with the sizes of the instance the type belongs to.
pub(crate) fn bounded_unscaled<'a>(
    path: &'a DataPath,
    plan: &'a ExecutionPlan,
    ctx: &'a EvaluationContext,
) -> Option<(&'a DataPath, &'a BoundValueKind)> {
    let held = match plan.reference_ends.get(path) {
        Some(ReferenceEnd::Promptable(end)) => end,
        Some(ReferenceEnd::Rule(_)) | None => path,
    };
    let leaf = plan.data_leaf.get(held)?;
    let bound = ctx.values[leaf.index()].as_ref()?.value()?;
    if !bound.value.has_unscaled_measure() {
        return None;
    }
    let held_type = plan.data.get(held)?.schema_type()?;
    crate::planning::fill::bounded_at_other_than_zero(held_type).then_some((held, bound))
}

pub(crate) fn resolve_stored_target(
    target: &ReferenceTarget,
    plan: &ExecutionPlan,
    ctx: &EvaluationContext,
) -> OperationResult {
    if let Some(&cell) = plan.member_targets.get(target) {
        return ctx.values[cell.index()]
            .clone()
            .expect("BUG: member target resolved before its cell was evaluated");
    }
    match target {
        ReferenceTarget::Rule(rule) => ctx.rule_value(plan, rule).clone(),
        ReferenceTarget::Data(path) => resolve_stored_data_target(path, plan, ctx),
    }
}

pub(crate) fn resolve_stored_data_target(
    path: &DataPath,
    plan: &ExecutionPlan,
    ctx: &EvaluationContext,
) -> OperationResult {
    if let Some(slot) = ctx.data_slot(plan, path) {
        return slot.clone();
    }
    match plan.reference_ends.get(path) {
        Some(ReferenceEnd::Rule(_)) => resolve_data_path_value(path, plan, ctx),
        Some(ReferenceEnd::Promptable(end)) => {
            if let Some(slot) = ctx.data_slot(plan, end) {
                return slot.clone();
            }
            if let Some(nested_source) = plan.instance_lists.get(end) {
                return stored_list(end, nested_source, ctx);
            }
            resolve_data_path_value(path, plan, ctx)
        }
        None => {
            if let Some(nested_source) = plan.instance_lists.get(path) {
                return stored_list(path, nested_source, ctx);
            }
            resolve_data_path_value(path, plan, ctx)
        }
    }
}

/// The stored list at `path`, its rows owned by `ctx.owner_row`. Its store's index
/// serves it unless a key field of a row is supplied, or written by a plan above.
pub(crate) fn stored_list(
    path: &DataPath,
    source: &InstanceListSource,
    ctx: &EvaluationContext,
) -> OperationResult {
    // Rows a plan above fills the list with (`-> with items: a, b`).
    let mut list = match ctx.caches.list_above(ctx.owner_row.as_ref(), path) {
        Some(rows) => {
            ListValue::stored_rows(rows, ctx.owner_row.clone(), Arc::clone(&source.row_type))
        }
        None => source.list(ctx.owner_row.clone()),
    };
    // A supplied key field the store's index does not hold.
    if ctx.caches.supplied.is_key_supplied(&ctx.owner_row, path)
        || ctx.caches.is_rekeyed_above(ctx.owner_row.as_ref(), path)
    {
        list = list.unindexed();
    }
    OperationResult::from_literal(LiteralValue {
        value: ValueKind::List(list),
    })
}

pub(crate) fn binary_arithmetic_result(
    left: &OperationResult,
    left_type: &Arc<LemmaType>,
    right: &OperationResult,
    right_type: &Arc<LemmaType>,
    op: ArithmeticComputation,
    plan: &ExecutionPlan,
) -> OperationResult {
    arithmetic_operation(
        borrow_value(left, "left operand"),
        left_type,
        &op,
        borrow_value(right, "right operand"),
        right_type,
        &plan.signature_index,
    )
}

/// Value of the one-operand cell `id` from its operand's value. A vetoed operand is
/// the cell's value, except for `is veto`, which reads it.
pub(crate) fn unary(
    id: NormalFormId,
    value: OperationResult,
    plan: &ExecutionPlan,
    ctx: &EvaluationContext,
) -> OperationResult {
    let kind = &plan.normal_form(id).kind;
    if let NormalFormKind::ResultIsVeto(_) = kind {
        return OperationResult::from_literal(LiteralValue::from_bool(value.vetoed()));
    }
    if value.vetoed() {
        return value;
    }
    match kind {
        NormalFormKind::Negate(inner) => {
            let zero = OperationResult::from_literal(LiteralValue::number(rational_zero()));
            binary_arithmetic_result(
                &zero,
                primitive_number_arc(),
                &value,
                plan.result_type(*inner),
                ArithmeticComputation::Subtract,
                plan,
            )
        }
        NormalFormKind::Reciprocal(inner) => {
            let one = OperationResult::from_literal(LiteralValue::number(rational_one()));
            binary_arithmetic_result(
                &one,
                primitive_number_arc(),
                &value,
                plan.result_type(*inner),
                ArithmeticComputation::Divide,
                plan,
            )
        }
        NormalFormKind::Not(inner) => {
            let false_lit = OperationResult::from_literal(LiteralValue::from_bool(false));
            comparison_operation(
                &borrow_value(&value, "not operand").value,
                plan.result_type(*inner),
                &ComparisonComputation::Is,
                &borrow_value(&false_lit, "not operand").value,
                primitive_boolean_arc(),
            )
        }
        NormalFormKind::MathOp(op, _) => evaluate_mathematical_operator(
            op,
            borrow_value(&value, "operand"),
            plan.result_type(id),
        ),
        NormalFormKind::StepRounding(mode, _, None) => {
            integer_rounding(*mode, borrow_value(&value, "rounded operand"))
        }
        NormalFormKind::UnitConversion(inner, target) => {
            let source_type = plan.result_type(*inner).as_ref();
            // Source unscaled dynamic magnitudes must settle before any cast —
            // including `as <literal-unit>`, which has no conversion_dynamic_unit.
            let value = match value {
                OperationResult::Value(bound) if bound.value.has_unscaled_measure() => {
                    settle_stored(bound, source_type, plan, ctx)
                }
                other => other,
            };
            if value.vetoed() {
                return value;
            }
            let bound = borrow_value(&value, "conversion operand");
            match conversion_dynamic_unit(target, source_type) {
                Some((unit_name, holding)) => {
                    match conversion_dynamic_factor(bound, &unit_name, holding, plan, ctx) {
                        Err(veto) => veto,
                        Ok(factor) => {
                            let converted =
                                convert_unit_operand(bound, source_type, target, Some(&factor));
                            converted_at(converted, &unit_name, &factor)
                        }
                    }
                }
                None => convert_unit_operand(bound, source_type, target, None),
            }
        }
        NormalFormKind::DateRelative(kind, _) => {
            let date = match &borrow_value(&value, "date operand").value {
                ValueKind::Date(dt) => dt,
                other => panic!("BUG: date-relative operand expected date, got {other:?}"),
            };
            compute_date_relative(kind, date, now_date(ctx))
        }
        NormalFormKind::DateCalendar(kind, unit, _) => {
            let date = match &borrow_value(&value, "date operand").value {
                ValueKind::Date(dt) => dt,
                other => panic!("BUG: date-calendar operand expected date, got {other:?}"),
            };
            compute_date_calendar(kind, unit, date, now_date(ctx))
        }
        NormalFormKind::RangeBound(bound, inner) => {
            let range_literal = borrow_value(&value, "range operand");
            let ValueKind::Range(left, right) = &range_literal.value else {
                panic!(
                    "BUG: lower/upper expected a range value, got {:?}",
                    range_literal.value
                )
            };
            let endpoint_type = plan
                .result_type(*inner)
                .specifications
                .element_from_range()
                .map(|element| Arc::new(LemmaType::primitive(element)))
                .expect("BUG: lower/upper requires a range result type");
            match ordered_endpoints(&left.value, &right.value, &endpoint_type) {
                Ok((lo, hi)) => {
                    let picked = match bound {
                        RangeBound::Lower => lo,
                        RangeBound::Upper => hi,
                    };
                    let chosen = if std::ptr::eq(picked, &left.value) {
                        left.as_ref()
                    } else {
                        right.as_ref()
                    };
                    let unit = chosen.lemma_type.unit().map(Arc::<str>::from);
                    OperationResult::from_bound(BoundValueKind::with_binding(
                        chosen.value.clone(),
                        unit,
                    ))
                }
                Err(veto) => OperationResult::Veto(veto),
            }
        }
        NormalFormKind::PastFutureRange(kind, inner) => evaluate_past_future_range(
            kind,
            &borrow_value(&value, "offset operand").to_literal(),
            plan.result_type(*inner),
            now_date(ctx),
        ),
        other => panic!("BUG: {other:?} is not a one-operand cell"),
    }
}

/// Value of the two-operand cell `id`. `right` is `None` when `left` is a definitive
/// veto: that veto is the value. A missing-data `left` still reads `right`, and a
/// definitive veto there wins (for `/` and `%` the divisor's veto rules apply).
pub(crate) fn binary(
    id: NormalFormId,
    left: &OperationResult,
    right: Option<&OperationResult>,
    plan: &ExecutionPlan,
) -> OperationResult {
    let Some(right) = right else {
        assert!(
            left.vetoed() && !left.is_missing_data(),
            "BUG: a binary cell skips its right operand only after a definitive left veto"
        );
        return left.clone();
    };
    let kind = &plan.normal_form(id).kind;
    let (left_id, right_id) = match kind {
        NormalFormKind::Subtract(l, r)
        | NormalFormKind::Power(l, r)
        | NormalFormKind::Divide(l, r)
        | NormalFormKind::Modulo(l, r)
        | NormalFormKind::Comparison(l, _, r)
        | NormalFormKind::StepRounding(_, l, Some(r))
        | NormalFormKind::RangeLiteral(l, r)
        | NormalFormKind::RangeContainment(l, r) => (*l, *r),
        other => panic!("BUG: {other:?} is not a two-operand cell"),
    };
    let (left_type, right_type) = (plan.result_type(left_id), plan.result_type(right_id));
    if let NormalFormKind::Divide(..) | NormalFormKind::Modulo(..) = kind {
        if right.vetoed() && !right.is_missing_data() {
            return right.clone();
        }
        if right.is_missing_data() {
            return if left.is_missing_data() {
                left.clone()
            } else {
                right.clone()
            };
        }
        let op = match kind {
            NormalFormKind::Divide(..) => ArithmeticComputation::Divide,
            _ => ArithmeticComputation::Modulo,
        };
        return divisive_operation_results(
            left,
            left_type,
            &op,
            right,
            right_type,
            &plan.signature_index,
        );
    }
    if left.vetoed() {
        if right.vetoed() && !right.is_missing_data() {
            return right.clone();
        }
        return left.clone();
    }
    if right.vetoed() {
        return right.clone();
    }
    match kind {
        NormalFormKind::Subtract(..) => binary_arithmetic_result(
            left,
            left_type,
            right,
            right_type,
            ArithmeticComputation::Subtract,
            plan,
        ),
        NormalFormKind::Power(..) => binary_arithmetic_result(
            left,
            left_type,
            right,
            right_type,
            ArithmeticComputation::Power,
            plan,
        ),
        NormalFormKind::Comparison(_, op, _) => comparison_operation(
            &borrow_value(left, "left operand").value,
            left_type,
            op,
            &borrow_value(right, "right operand").value,
            right_type,
        ),
        NormalFormKind::StepRounding(mode, ..) => step_rounding(
            *mode,
            borrow_value(left, "rounded operand"),
            borrow_value(right, "rounding step"),
            plan.result_type(id),
        ),
        NormalFormKind::RangeLiteral(..) => {
            let left_typed =
                typed_literal_from_bound(borrow_value(left, "left endpoint"), left_type);
            let right_typed =
                typed_literal_from_bound(borrow_value(right, "right endpoint"), right_type);
            OperationResult::from_literal(LiteralValue::range(left_typed, right_typed))
        }
        NormalFormKind::RangeContainment(..) => {
            let range_literal = borrow_value(right, "range operand");
            let ValueKind::Range(range_left, range_right) = &range_literal.value else {
                panic!(
                    "BUG: range containment expected range operand, got {:?}",
                    range_literal.value
                )
            };
            let endpoint_type = right_type
                .specifications
                .element_from_range()
                .map(|element| Arc::new(LemmaType::primitive(element)))
                .expect("BUG: range containment requires a range result type");
            check_containment(
                &borrow_value(left, "value operand").value,
                left_type,
                &range_left.value,
                &range_right.value,
                &endpoint_type,
            )
        }
        _ => unreachable!("BUG: two-operand kinds are matched above"),
    }
}

pub(crate) fn borrow_value<'a>(result: &'a OperationResult, operand: &str) -> &'a BoundValueKind {
    match result {
        OperationResult::Value(v) => v,
        OperationResult::Veto(_) => panic!("BUG: {operand} passed veto check but has no value"),
    }
}

pub(crate) fn now_date(ctx: &EvaluationContext) -> &SemanticDateTime {
    match &ctx.now().value {
        ValueKind::Date(dt) => dt,
        other => panic!("BUG: context.now() must be a date, got {other:?}"),
    }
}

/// Whether an n-ary fold's value is fixed: a definitive veto. Later operands no longer
/// change it.
pub(crate) fn fold_settled(veto: Option<&OperationResult>) -> bool {
    veto.is_some_and(|veto| !veto.is_missing_data())
}

/// Combine operand `index` (value `result`) of the n-ary `+` / `*` cell `id` into the
/// running `acc` and `veto`. A missing-data veto is kept while later operands are
/// combined: a definitive veto replaces it, and a divisor after it may still give a
/// definitive veto (zero). Progressive accumulator types come from the cell's
/// `fold_types`.
pub(crate) fn fold_term(
    acc: &mut Option<OperationResult>,
    veto: &mut Option<OperationResult>,
    id: NormalFormId,
    index: usize,
    result: OperationResult,
    plan: &ExecutionPlan,
) {
    let cell = plan.normal_form(id);
    let (terms, direct_op, inverse_op) = match &cell.kind {
        NormalFormKind::Sum(terms) => (
            terms,
            ArithmeticComputation::Add,
            ArithmeticComputation::Subtract,
        ),
        NormalFormKind::Product(terms) => (
            terms,
            ArithmeticComputation::Multiply,
            ArithmeticComputation::Divide,
        ),
        other => panic!("BUG: {other:?} is not an n-ary fold"),
    };
    let fold_types = &cell.fold_types;
    assert_eq!(
        fold_types.len(),
        terms.len(),
        "BUG: Sum/Product fold_types length must match terms"
    );
    let term = terms[index];
    let child = term.operand;
    if let Some(settled) = veto.as_ref() {
        if settled.is_missing_data() && !result.vetoed() && term.inverse {
            let combined = divisive_operation_results(
                settled,
                &fold_types[index - 1],
                &inverse_op,
                &result,
                plan.result_type(child),
                &plan.signature_index,
            );
            if combined.vetoed() && !combined.is_missing_data() {
                *veto = Some(combined);
            }
            return;
        }
        if settled.is_missing_data() && result.vetoed() && !result.is_missing_data() {
            *veto = Some(result);
        }
        return;
    }
    if result.vetoed() {
        *veto = Some(result);
        return;
    }
    *acc = Some(match acc.take() {
        None => result,
        Some(left) => {
            // left type = fold_types[index-1]; next left (if any) = fold_types[index].
            let op = if term.inverse { inverse_op } else { direct_op };
            let combined = if matches!(
                op,
                ArithmeticComputation::Divide | ArithmeticComputation::Modulo
            ) {
                divisive_operation_results(
                    &left,
                    &fold_types[index - 1],
                    &op,
                    &result,
                    plan.result_type(child),
                    &plan.signature_index,
                )
            } else {
                binary_arithmetic_result(
                    &left,
                    &fold_types[index - 1],
                    &result,
                    plan.result_type(child),
                    op,
                    plan,
                )
            };
            if combined.vetoed() {
                *veto = Some(combined);
                return;
            }
            combined
        }
    });
}

/// Value of a finished n-ary fold: its veto, else its accumulated value.
pub(crate) fn fold_result(
    acc: Option<OperationResult>,
    veto: Option<OperationResult>,
) -> OperationResult {
    veto.or(acc)
        .expect("BUG: n-ary arithmetic produced neither value nor veto after evaluating children")
}

/// Read one operand `result` of a `connective`. The absorbing literal (`true` for `or`,
/// `false` for `and`) decides regardless of position: `Some(value)`. Without one, the
/// first missing or vetoed operand in source order is kept in `veto` while later
/// operands are read, so a later absorbing literal can still decide.
pub(crate) fn logical_operand(
    connective: LogicalConnective,
    veto: &mut Option<OperationResult>,
    result: OperationResult,
) -> Option<OperationResult> {
    let absorbing = connective.absorbing_operand();
    match condition_outcome(&result) {
        BranchOutcome::Taken if absorbing => {
            Some(OperationResult::from_literal(LiteralValue::from_bool(true)))
        }
        BranchOutcome::NotTaken if !absorbing => Some(OperationResult::from_literal(
            LiteralValue::from_bool(false),
        )),
        BranchOutcome::Propagate(propagated) => {
            veto.get_or_insert(propagated);
            None
        }
        BranchOutcome::Taken | BranchOutcome::NotTaken => None,
    }
}

/// Value of a `connective` whose operands were all read without an absorbing one: the
/// kept veto, else the identity literal (`false` for `or`, `true` for `and`).
pub(crate) fn logical_result(
    connective: LogicalConnective,
    veto: Option<OperationResult>,
) -> OperationResult {
    veto.unwrap_or_else(|| {
        OperationResult::from_literal(LiteralValue::from_bool(!connective.absorbing_operand()))
    })
}

/// The row of `rows` whose key values are `wanted`, through `index`.
pub(crate) fn find_keyed(
    rows: &ListValue,
    index: &KeyIndex,
    fields: &[KeyField],
    wanted: &[TypedLiteral],
) -> OperationResult {
    match index.probe(wanted) {
        Ok(Some(position)) => OperationResult::from_literal(
            rows.get(position)
                .expect("BUG: index position is a row of the list")
                .to_literal(),
        ),
        Ok(None) => list_ops::no_row_with_key(fields, wanted),
        Err(veto) => veto,
    }
}

pub(crate) fn first_operand(values: &[OperationResult]) -> OperationResult {
    values
        .first()
        .cloned()
        .expect("BUG: command operand collected before use")
}

pub(crate) fn options_rule_blocker(
    plan: &ExecutionPlan,
    ctx: &EvaluationContext,
    path: &DataPath,
) -> Option<OperationResult> {
    let rule_path = plan.options_rule_of(path)?;
    let index = plan.rule_index(&rule_path);
    let result = ctx.rule_values.get(index.index())?.as_ref()?;
    match result.value().map(|bound| &bound.value) {
        Some(crate::planning::semantics::ValueKind::List(_)) => None,
        _ => Some(result.clone()),
    }
}

fn check_data_options(
    id: NormalFormId,
    slot: OperationResult,
    plan: &ExecutionPlan,
    ctx: &EvaluationContext,
) -> OperationResult {
    if slot.vetoed() || slot.is_missing_data() {
        return slot;
    }
    let path = match &plan.normal_form(id).kind {
        NormalFormKind::Leaf(LeafKind::DataPath(path)) => path,
        other => panic!("BUG: options check on {other:?}"),
    };
    let lemma_type = plan
        .data
        .get(path)
        .and_then(|definition| definition.schema_type())
        .expect("BUG: options check on data without a type");
    let rule_index = plan
        .options_rule_of(path)
        .map(|rule_path| plan.rule_index(&rule_path));
    let rule_result = rule_index.map(|index| {
        ctx.rule_values[index.index()]
            .as_ref()
            .expect("BUG: options rule checked before it was evaluated")
    });
    if let Some(rule_result) = rule_result {
        if rule_result.vetoed() || rule_result.is_missing_data() {
            return rule_result.clone();
        }
    }
    let Some(slot_bound) = slot.value() else {
        return slot;
    };
    let rule_rows = match rule_result {
        Some(rule_result) => match rule_result.value().map(|bound| &bound.value) {
            Some(ValueKind::List(rows)) => Some(rows),
            _ => {
                return OperationResult::Veto(VetoType::computation(
                    "options rule did not return a list".to_string(),
                ));
            }
        },
        None => None,
    };
    let scales = display_scale_factors(Some(slot_bound), lemma_type, plan, ctx);
    match lemma_type.explain_disallowed(&slot_bound.value, rule_rows, Some(&scales)) {
        None => slot,
        Some(message) => OperationResult::Veto(VetoType::computation(message)),
    }
}

/// Value of the literal cell `id`, its unscaled dynamic magnitudes settled.
pub(crate) fn literal(
    id: NormalFormId,
    plan: &ExecutionPlan,
    ctx: &EvaluationContext,
) -> OperationResult {
    let NormalFormKind::Leaf(LeafKind::Literal(literal)) = &plan.normal_form(id).kind else {
        panic!("BUG: cell {} is not a literal", id.index());
    };
    let lemma_type = plan.result_type(id).as_ref();
    let unit = lemma_type.unit().map(Arc::<str>::from);
    let bound = BoundValueKind::with_binding(literal.value.clone(), unit);
    settle_stored(bound, lemma_type, plan, ctx)
}

/// Value of the data cell `id` whose slot holds `slot`: its dynamic magnitudes settled,
/// checked against its type, and against its options (and their rule, evaluated
/// already) when it has runtime options. A veto or missing data is the value.
pub(crate) fn stored_data_leaf(
    id: NormalFormId,
    slot: OperationResult,
    plan: &ExecutionPlan,
    ctx: &EvaluationContext,
) -> OperationResult {
    let NormalFormKind::Leaf(LeafKind::DataPath(path)) = &plan.normal_form(id).kind else {
        panic!("BUG: cell {} is not a data leaf", id.index());
    };
    let lemma_type = plan
        .data
        .get(path)
        .and_then(|definition| definition.schema_type());
    let slot = match (slot, lemma_type) {
        (OperationResult::Value(bound), Some(lemma_type)) => {
            settle_stored(bound, lemma_type, plan, ctx)
        }
        (slot, _) => slot,
    };
    if slot.vetoed() || slot.is_missing_data() {
        return slot;
    }
    if let (Some(lemma_type), Some(bound)) = (lemma_type, slot.value()) {
        let scales = display_scale_factors(Some(bound), lemma_type, plan, ctx);
        if let Err(msg) = validate_value_against_type(
            lemma_type,
            &bound.to_literal(),
            &plan.resolved_types.unit_index,
            Some(&scales),
        ) {
            return OperationResult::Veto(VetoType::computation(msg));
        }
    }
    if lemma_type.is_some_and(|schema| schema.needs_runtime_option_check()) {
        return check_data_options(id, slot, plan, ctx);
    }
    slot
}