Skip to main content

lemma/evaluation/
branch_semantics.rs

1//! Single source of truth for branch and veto decision semantics.
2//!
3//! The tree evaluator consults [`condition_outcome`] for piecewise unless-arm
4//! conditions and logical operands (`and` / `or`). One rule: a vetoed condition
5//! propagates its veto; a `true` boolean is [`BranchOutcome::Taken`]; a `false`
6//! boolean is [`BranchOutcome::NotTaken`]. Connectives interpret those outcomes
7//! via their absorbing / identity literals; this module does not.
8
9use crate::computation::OperationResult;
10use crate::planning::semantics::ValueKind;
11
12/// Outcome of inspecting a branch condition or a boolean operand.
13#[derive(Debug, Clone)]
14pub enum BranchOutcome {
15    /// The boolean was `true`.
16    Taken,
17    /// The boolean was `false`.
18    NotTaken,
19    /// This result becomes the value of the enclosing computation (vetoes
20    /// that propagate).
21    Propagate(OperationResult),
22}
23
24/// Read the boolean out of a non-vetoed result. Planning guarantees boolean
25/// operands in these positions; anything else is a compiler bug and crashes.
26fn boolean_value(result: &OperationResult, context: &str) -> bool {
27    match result {
28        OperationResult::Value(literal) => match &literal.value {
29            ValueKind::Boolean(boolean) => *boolean,
30            other => panic!("BUG: {context} expected a boolean, got {other:?}"),
31        },
32        OperationResult::Veto(veto) => {
33            panic!("BUG: {context} inspected for a boolean while vetoed: {veto}")
34        }
35    }
36}
37
38/// How a piecewise unless-arm condition or a logical operand decides.
39///
40/// A vetoed condition propagates its veto as the enclosing result. A `true`
41/// boolean is [`BranchOutcome::Taken`]; a `false` boolean is
42/// [`BranchOutcome::NotTaken`].
43pub fn condition_outcome(condition: &OperationResult) -> BranchOutcome {
44    if condition.vetoed() {
45        return BranchOutcome::Propagate(condition.clone());
46    }
47    if boolean_value(condition, "branch condition") {
48        BranchOutcome::Taken
49    } else {
50        BranchOutcome::NotTaken
51    }
52}
53
54/// Where the Piecewise arm scan stopped. Arm 0 is the default; unless arms
55/// `1..arm_count` are scanned from the highest index down, like the evaluator.
56#[derive(Debug, Clone, Copy, PartialEq, Eq)]
57pub enum PiecewiseDecision {
58    /// Arm `arm` wins: every condition above it was `NotTaken`.
59    Taken { arm: usize },
60    /// Every unless condition was `NotTaken`; the default body wins.
61    Default,
62    /// The scan stopped at `arm`: its condition is not a settled boolean
63    /// (not evaluated yet, or vetoed). Conditions above it were `NotTaken`.
64    Undecided { arm: usize },
65}
66
67/// Scan unless-arm conditions high to low. `outcome(arm)` reports the
68/// condition's decision, or `None` when there is none to read.
69pub fn piecewise_decision(
70    arm_count: usize,
71    mut outcome: impl FnMut(usize) -> Option<BranchOutcome>,
72) -> PiecewiseDecision {
73    assert!(arm_count > 0, "BUG: empty piecewise");
74    for arm in (1..arm_count).rev() {
75        match outcome(arm) {
76            Some(BranchOutcome::Taken) => return PiecewiseDecision::Taken { arm },
77            Some(BranchOutcome::NotTaken) => continue,
78            Some(BranchOutcome::Propagate(_)) | None => {
79                return PiecewiseDecision::Undecided { arm };
80            }
81        }
82    }
83    PiecewiseDecision::Default
84}
85
86/// An arm [`open_arms`] reaches: its condition is read, and its body when `body`.
87#[derive(Debug, Clone, Copy, PartialEq, Eq)]
88pub struct OpenArm {
89    pub arm: usize,
90    pub body: bool,
91}
92
93/// The arms some completion of the missing data can still reach, scanned like the
94/// evaluator: from the last `unless` to the default (arm 0). A false condition goes on, a
95/// true one ends the scan with its body, a vetoed one ends it. A condition that misses
96/// data, or has no outcome yet, leaves its body and the arms under it open.
97pub fn open_arms(
98    arm_count: usize,
99    mut outcome: impl FnMut(usize) -> Option<BranchOutcome>,
100) -> Vec<OpenArm> {
101    assert!(arm_count > 0, "BUG: empty piecewise");
102    let mut open = Vec::new();
103    for arm in (1..arm_count).rev() {
104        let (body, last) = match outcome(arm) {
105            Some(BranchOutcome::Taken) => (true, true),
106            Some(BranchOutcome::NotTaken) => (false, false),
107            Some(BranchOutcome::Propagate(veto)) if !veto.is_missing_data() => (false, true),
108            Some(BranchOutcome::Propagate(_)) | None => (true, false),
109        };
110        open.push(OpenArm { arm, body });
111        if last {
112            return open;
113        }
114    }
115    open.push(OpenArm { arm: 0, body: true });
116    open
117}
118
119#[cfg(test)]
120mod tests {
121    use super::*;
122    use crate::computation::VetoType;
123
124    fn outcome_from(
125        list: &[Option<BranchOutcome>],
126    ) -> impl FnMut(usize) -> Option<BranchOutcome> + '_ {
127        move |arm| list[arm].clone()
128    }
129
130    #[test]
131    fn piecewise_decision_default_when_all_not_taken() {
132        let outcomes = [
133            None,
134            Some(BranchOutcome::NotTaken),
135            Some(BranchOutcome::NotTaken),
136        ];
137        assert_eq!(
138            piecewise_decision(3, outcome_from(&outcomes)),
139            PiecewiseDecision::Default
140        );
141    }
142
143    #[test]
144    fn piecewise_decision_highest_taken_wins() {
145        let outcomes = [None, Some(BranchOutcome::Taken), Some(BranchOutcome::Taken)];
146        assert_eq!(
147            piecewise_decision(3, outcome_from(&outcomes)),
148            PiecewiseDecision::Taken { arm: 2 }
149        );
150    }
151
152    #[test]
153    fn piecewise_decision_stops_at_unfilled_condition() {
154        let outcomes = [
155            None,
156            Some(BranchOutcome::Taken),
157            None,
158            Some(BranchOutcome::NotTaken),
159        ];
160        assert_eq!(
161            piecewise_decision(4, outcome_from(&outcomes)),
162            PiecewiseDecision::Undecided { arm: 2 }
163        );
164    }
165
166    #[test]
167    fn piecewise_decision_stops_at_vetoed_condition() {
168        let veto = OperationResult::Veto(VetoType::computation("no"));
169        let outcomes = [
170            None,
171            Some(BranchOutcome::Taken),
172            Some(BranchOutcome::Propagate(veto)),
173        ];
174        assert_eq!(
175            piecewise_decision(3, outcome_from(&outcomes)),
176            PiecewiseDecision::Undecided { arm: 2 }
177        );
178    }
179    use crate::planning::semantics::{DataPath, LiteralValue};
180
181    fn boolean(value: bool) -> OperationResult {
182        OperationResult::from_literal(LiteralValue::from_bool(value))
183    }
184
185    fn user_veto() -> OperationResult {
186        OperationResult::Veto(VetoType::UserDefined {
187            message: Some("blocked".to_string()),
188        })
189    }
190
191    fn missing_data_veto() -> OperationResult {
192        OperationResult::Veto(VetoType::missing_data(
193            DataPath::new(vec![], "x".to_string()),
194            None,
195        ))
196    }
197
198    #[test]
199    fn propagates_any_veto() {
200        assert!(matches!(
201            condition_outcome(&user_veto()),
202            BranchOutcome::Propagate(_)
203        ));
204        assert!(matches!(
205            condition_outcome(&missing_data_veto()),
206            BranchOutcome::Propagate(_)
207        ));
208    }
209
210    #[test]
211    fn boolean_decides_when_not_vetoed() {
212        assert!(matches!(
213            condition_outcome(&boolean(true)),
214            BranchOutcome::Taken
215        ));
216        assert!(matches!(
217            condition_outcome(&boolean(false)),
218            BranchOutcome::NotTaken
219        ));
220    }
221}