Skip to main content

bynk_check/
entailment.rs

1//! Predicate entailment over the closed refinement vocabulary (#2802).
2//!
3//! One engine answers "does the sender's conjunction of predicates guarantee
4//! this receiver predicate?" for both consumers that ask it: the checker's
5//! cross-context argument and return matching
6//! ([`crate::checker`]'s `refinements_match`) and the deploy-gate classifier
7//! ([`crate::contract_compat`]). The two used to hold separate notions
8//! (set-equality here, entailment there), so the compiler rejected a program
9//! the gate called compatible.
10//!
11//! Predicates arrive in their canonical text (`contract::canon_pred_set`),
12//! so `NonEmpty` is already `MinLength(1)` and `InRange` bounds are values, not
13//! lexemes. The engine is **sound but incomplete**: it models an `Int` as
14//! unbounded, so it never concludes something only the safe-integer limit would
15//! give. `Matches` is entailed only by an identical `Matches` (regex-language
16//! inclusion is not attempted); a `Matches` on the sender is otherwise ignored,
17//! so `Matches(p) && MaxLength(4)` still entails `MaxLength(8)`.
18
19use std::cmp::Ordering;
20
21#[derive(Clone, Copy)]
22struct Interval<T> {
23    lo: Option<(T, bool)>,
24    hi: Option<(T, bool)>,
25}
26
27impl<T: PartialOrd + Copy> Interval<T> {
28    const ALL: Self = Interval { lo: None, hi: None };
29
30    fn intersect(self, o: Self) -> Self {
31        Interval {
32            lo: tighter(self.lo, o.lo, Ordering::Greater),
33            hi: tighter(self.hi, o.hi, Ordering::Less),
34        }
35    }
36
37    /// Every value of `self` lies in `outer`.
38    fn within(self, outer: Self) -> bool {
39        let lo_ok = match (self.lo, outer.lo) {
40            (_, None) => true,
41            (None, Some(_)) => false,
42            (Some((s, so)), Some((o, oo))) => match s.partial_cmp(&o) {
43                Some(Ordering::Greater) => true,
44                Some(Ordering::Equal) => so || !oo,
45                _ => false,
46            },
47        };
48        let hi_ok = match (self.hi, outer.hi) {
49            (_, None) => true,
50            (None, Some(_)) => false,
51            (Some((s, so)), Some((o, oo))) => match s.partial_cmp(&o) {
52                Some(Ordering::Less) => true,
53                Some(Ordering::Equal) => so || !oo,
54                _ => false,
55            },
56        };
57        lo_ok && hi_ok
58    }
59}
60
61/// The tighter of two bounds; `want` is `Greater` for lower bounds.
62fn tighter<T: PartialOrd + Copy>(
63    a: Option<(T, bool)>,
64    b: Option<(T, bool)>,
65    want: Ordering,
66) -> Option<(T, bool)> {
67    match (a, b) {
68        (None, x) | (x, None) => x,
69        (Some((av, ao)), Some((bv, bo))) => match av.partial_cmp(&bv) {
70            Some(o) if o == want => Some((av, ao)),
71            Some(Ordering::Equal) => Some((av, ao || bo)),
72            _ => Some((bv, bo)),
73        },
74    }
75}
76
77/// `args` of `Name(a, b)`, split on the top-level comma.
78fn pred_args<'a>(p: &'a str, name: &str) -> Option<Vec<&'a str>> {
79    let inner = p.strip_prefix(name)?.strip_prefix('(')?.strip_suffix(')')?;
80    Some(inner.split(", ").collect())
81}
82
83fn closed<T>(lo: T, hi: T) -> Interval<T> {
84    Interval {
85        lo: Some((lo, false)),
86        hi: Some((hi, false)),
87    }
88}
89
90/// A predicate as a bound on the numeric domain (`Int`, `Float` or `Decimal`) or
91/// the length domain.
92enum Domain<'a> {
93    Int(Interval<i128>),
94    Float(Interval<f64>),
95    Decimal(Interval<Dec<'a>>),
96    Length(Interval<i128>),
97}
98
99/// A canonical decimal bound (`-1.5`, `0`), compared by value and independent of
100/// scale (`1.2 == 1.20`).
101#[derive(Clone, Copy)]
102struct Dec<'a>(&'a str);
103
104impl Dec<'_> {
105    /// The coefficient (the digits with the point removed) and the scale.
106    fn parts(&self) -> (String, u32) {
107        match self.0.split_once('.') {
108            Some((int, frac)) => (format!("{int}{frac}"), frac.len() as u32),
109            None => (self.0.to_string(), 0),
110        }
111    }
112}
113
114impl PartialEq for Dec<'_> {
115    fn eq(&self, o: &Self) -> bool {
116        self.partial_cmp(o) == Some(Ordering::Equal)
117    }
118}
119
120impl PartialOrd for Dec<'_> {
121    fn partial_cmp(&self, o: &Self) -> Option<Ordering> {
122        let ((ac, asc), (bc, bsc)) = (self.parts(), o.parts());
123        Some(bynk_syntax::decimal::cmp(&ac, asc, &bc, bsc))
124    }
125}
126
127/// A canonical decimal bound is digits, an optional leading `-` and an optional
128/// point, with at least one digit.
129fn dec(text: &str) -> Option<Dec<'_>> {
130    let digits = text.strip_prefix('-').unwrap_or(text);
131    let ok = digits.bytes().any(|b| b.is_ascii_digit())
132        && digits.bytes().all(|b| b.is_ascii_digit() || b == b'.')
133        && digits.bytes().filter(|&b| b == b'.').count() <= 1;
134    ok.then_some(Dec(text))
135}
136
137fn domain<'a>(base: &str, p: &'a str) -> Option<Domain<'a>> {
138    let int_pred = || -> Option<Interval<i128>> {
139        Some(match p {
140            "Positive" => Interval {
141                lo: Some((1, false)),
142                hi: None,
143            },
144            "NonNegative" => Interval {
145                lo: Some((0, false)),
146                hi: None,
147            },
148            _ => {
149                let a = pred_args(p, "InRange")?;
150                closed(a.first()?.parse().ok()?, a.get(1)?.parse().ok()?)
151            }
152        })
153    };
154    let float_pred = || -> Option<Interval<f64>> {
155        Some(match p {
156            "Positive" => Interval {
157                lo: Some((0.0, true)),
158                hi: None,
159            },
160            "NonNegative" => Interval {
161                lo: Some((0.0, false)),
162                hi: None,
163            },
164            _ => {
165                let a = pred_args(p, "InRangeF")?;
166                closed(a.first()?.parse().ok()?, a.get(1)?.parse().ok()?)
167            }
168        })
169    };
170    let dec_pred = || -> Option<Interval<Dec<'a>>> {
171        Some(match p {
172            "Positive" => Interval {
173                lo: Some((dec("0")?, true)),
174                hi: None,
175            },
176            "NonNegative" => Interval {
177                lo: Some((dec("0")?, false)),
178                hi: None,
179            },
180            _ => {
181                let a = pred_args(p, "InRangeD")?;
182                closed(dec(a.first()?)?, dec(a.get(1)?)?)
183            }
184        })
185    };
186    if let Some(a) = pred_args(p, "MinLength") {
187        return Some(Domain::Length(Interval {
188            lo: Some((a.first()?.parse().ok()?, false)),
189            hi: None,
190        }));
191    }
192    if let Some(a) = pred_args(p, "MaxLength") {
193        return Some(Domain::Length(Interval {
194            lo: None,
195            hi: Some((a.first()?.parse().ok()?, false)),
196        }));
197    }
198    // #2867: `IsoDate` is exactly ten characters, so it entails every length
199    // bound `Length(10)` does. Nothing but `IsoDate` itself entails `IsoDate`.
200    if p == "IsoDate" {
201        return Some(Domain::Length(closed(10, 10)));
202    }
203    // #3873: `* * * * *` is the shortest valid schedule, so `Cron` entails every
204    // length bound `MinLength(9)` does. Nothing but `Cron` itself entails `Cron`.
205    if p == "Cron" {
206        return Some(Domain::Length(Interval {
207            lo: Some((9, false)),
208            hi: None,
209        }));
210    }
211    if let Some(a) = pred_args(p, "Length") {
212        let n = a.first()?.parse().ok()?;
213        return Some(Domain::Length(closed(n, n)));
214    }
215    match base {
216        "Int" => int_pred().map(Domain::Int),
217        "Float" => float_pred().map(Domain::Float),
218        "Decimal" => dec_pred().map(Domain::Decimal),
219        _ => None,
220    }
221}
222
223/// Does the conjunction `sender` guarantee the predicate `q`?
224pub fn entailed(base: &str, sender: &[String], q: &str) -> bool {
225    if sender.iter().any(|p| p == q) {
226        return true;
227    }
228    // #2867: being a date is more than being ten characters long, so only `IsoDate` itself
229    // satisfies `IsoDate` (it is still *sent* as `Length(10)` below).
230    if q == "IsoDate" || q == "Cron" {
231        return false;
232    }
233    let Some(want) = domain(base, q) else {
234        // `Matches`, or a predicate this version cannot reason about: only an
235        // identical predicate satisfies it.
236        return false;
237    };
238    let given = sender.iter().filter_map(|p| domain(base, p));
239    match want {
240        Domain::Int(w) => {
241            let mut have = Interval::ALL;
242            for d in given {
243                if let Domain::Int(i) = d {
244                    have = have.intersect(i);
245                }
246            }
247            have.within(w)
248        }
249        Domain::Float(w) => {
250            let mut have = Interval::ALL;
251            for d in given {
252                if let Domain::Float(i) = d {
253                    have = have.intersect(i);
254                }
255            }
256            have.within(w)
257        }
258        Domain::Decimal(w) => {
259            let mut have = Interval::ALL;
260            for d in given {
261                if let Domain::Decimal(i) = d {
262                    have = have.intersect(i);
263                }
264            }
265            have.within(w)
266        }
267        Domain::Length(w) => {
268            let mut have = Interval::ALL;
269            for d in given {
270                if let Domain::Length(i) = d {
271                    have = have.intersect(i);
272                }
273            }
274            have.within(w)
275        }
276    }
277}
278
279/// The receiver predicates the sender's conjunction does not guarantee; empty
280/// when the sender is admissible where the receiver is expected.
281pub fn unmet<'a>(base: &str, sender: &[String], receiver: &'a [String]) -> Vec<&'a String> {
282    receiver
283        .iter()
284        .filter(|q| !entailed(base, sender, q))
285        .collect()
286}
287
288#[cfg(test)]
289mod tests {
290    use super::*;
291
292    fn s(v: &[&str]) -> Vec<String> {
293        v.iter().map(|x| x.to_string()).collect()
294    }
295
296    #[test]
297    fn decimal_bounds_compare_by_value_not_scale() {
298        // `canon_predicate` drops trailing zeros, so scales differ between sides.
299        assert!(entailed(
300            "Decimal",
301            &s(&["InRangeD(0.5, 1)"]),
302            "InRangeD(0, 2)"
303        ));
304        assert!(entailed(
305            "Decimal",
306            &s(&["InRangeD(1.2, 1.2)"]),
307            "InRangeD(1.20, 1.3)"
308        ));
309        assert!(!entailed(
310            "Decimal",
311            &s(&["InRangeD(0, 2)"]),
312            "InRangeD(0.5, 1)"
313        ));
314        assert!(!entailed(
315            "Decimal",
316            &s(&["InRangeD(-1.5, 2)"]),
317            "InRangeD(-1, 2)"
318        ));
319    }
320
321    #[test]
322    fn decimal_sign_predicates() {
323        assert!(entailed("Decimal", &s(&["Positive"]), "NonNegative"));
324        assert!(!entailed("Decimal", &s(&["NonNegative"]), "Positive"));
325        assert!(entailed("Decimal", &s(&["InRangeD(0.01, 5)"]), "Positive"));
326        assert!(!entailed("Decimal", &s(&["InRangeD(0, 5)"]), "Positive"));
327        assert!(!entailed("Decimal", &s(&["Positive"]), "InRangeD(0, 5)"));
328    }
329
330    #[test]
331    fn matches_is_entailed_only_by_the_identical_pattern() {
332        let m = "Matches(\"[a-z]+\")";
333        assert!(entailed("String", &s(&[m]), m));
334        assert!(!entailed("String", &s(&["Matches(\"[a-z0-9]+\")"]), m));
335        // A sender's `Matches` is ignored for other receiver predicates.
336        assert!(entailed("String", &s(&[m, "MaxLength(4)"]), "MaxLength(8)"));
337        assert!(!entailed("String", &s(&[m]), "MaxLength(8)"));
338        // #2867
339        assert!(!entailed("String", &s(&["Length(10)"]), "IsoDate"));
340        assert!(entailed("String", &s(&["IsoDate"]), "IsoDate"));
341        assert!(entailed("String", &s(&["IsoDate"]), "MaxLength(12)"));
342        assert!(!entailed("String", &s(&["IsoDate"]), "MaxLength(9)"));
343        // #3873: only `Cron` entails `Cron`, and it entails `MinLength(1..=9)`.
344        assert!(entailed("String", &s(&["Cron"]), "Cron"));
345        assert!(!entailed("String", &s(&["MinLength(9)"]), "Cron"));
346        assert!(entailed("String", &s(&["Cron"]), "MinLength(9)"));
347        assert!(entailed("String", &s(&["Cron"]), "MinLength(1)"));
348        assert!(!entailed("String", &s(&["Cron"]), "MinLength(10)"));
349        assert!(!entailed("String", &s(&["Cron"]), "MaxLength(20)"));
350    }
351
352    #[test]
353    fn float_positive_is_open_at_zero() {
354        assert!(entailed("Float", &s(&["Positive"]), "NonNegative"));
355        assert!(!entailed("Float", &s(&["NonNegative"]), "Positive"));
356        assert!(entailed(
357            "Float",
358            &s(&["InRangeF(0.5, 1)"]),
359            "InRangeF(0, 2)"
360        ));
361    }
362}