Skip to main content

egui_pop_model/
when.rs

1//! `when` clauses: where a command applies or a key binds, over named
2//! context keys (in the manner of VS Code's `when` clauses).
3//!
4//! Grammar: `key` (true when the key is set and not `false` or empty),
5//! `key == 'text'`, `key != 'text'`, `!expr`, `a && b`, `a || b`,
6//! parentheses. `&&` binds tighter than `||`.
7//!
8//! Each key of a [`WhenContext`] has a depth: 0 for application-wide
9//! keys, more for keys set by scopes nearer the focus (ADR 0007).
10//!
11//! ```
12//! use egui_pop_model::when::{When, WhenContext};
13//!
14//! let cx = WhenContext::new().flag("listFocus", true).with("view", "editor");
15//! let w = When::parse("listFocus && view == 'editor'").unwrap();
16//! assert!(w.eval(&cx));
17//! assert_eq!(w.specificity(), 2);
18//! ```
19
20use std::collections::BTreeMap;
21
22use serde::Serialize;
23
24/// The current context: focus, view, selection... as named values, each
25/// at the depth of the scope that set it.
26#[derive(Clone, Debug, Default, PartialEq, Serialize)]
27pub struct WhenContext(BTreeMap<String, (String, u32)>);
28
29impl WhenContext {
30    pub fn new() -> Self {
31        Self::default()
32    }
33
34    /// Sets a boolean key at depth 0.
35    pub fn flag(mut self, key: &str, on: bool) -> Self {
36        self.set(key, if on { "true" } else { "false" });
37        self
38    }
39
40    /// Sets a key at depth 0.
41    pub fn with(mut self, key: &str, value: &str) -> Self {
42        self.set(key, value);
43        self
44    }
45
46    /// Sets a key at depth 0.
47    pub fn set(&mut self, key: &str, value: &str) {
48        self.set_at(key, value, 0);
49    }
50
51    /// Sets a key at a depth; a deeper scope setting the same key wins.
52    pub fn set_at(&mut self, key: &str, value: &str, depth: u32) {
53        self.0.insert(key.into(), (value.into(), depth));
54    }
55
56    /// Sets a boolean key at a depth.
57    pub fn flag_at(&mut self, key: &str, on: bool, depth: u32) {
58        self.set_at(key, if on { "true" } else { "false" }, depth);
59    }
60
61    fn truthy(&self, key: &str) -> bool {
62        self.0
63            .get(key)
64            .is_some_and(|(v, _)| !v.is_empty() && v != "false")
65    }
66
67    pub fn get(&self, key: &str) -> &str {
68        self.0.get(key).map_or("", |(v, _)| v.as_str())
69    }
70
71    /// The depth a key was set at, if set.
72    pub fn depth_of(&self, key: &str) -> Option<u32> {
73        self.0.get(key).map(|(_, d)| *d)
74    }
75
76    /// Every key, its value and depth.
77    pub fn iter(&self) -> impl Iterator<Item = (&str, &str, u32)> {
78        self.0
79            .iter()
80            .map(|(k, (v, d))| (k.as_str(), v.as_str(), *d))
81    }
82}
83
84/// A parsed expression.
85#[derive(Clone, Debug, PartialEq)]
86pub enum When {
87    Always,
88    Key(String),
89    Eq(String, String),
90    Ne(String, String),
91    Not(Box<When>),
92    And(Box<When>, Box<When>),
93    Or(Box<When>, Box<When>),
94}
95
96#[derive(Clone, Debug, PartialEq)]
97enum Token {
98    Ident(String),
99    Text(String),
100    Not,
101    And,
102    Or,
103    Eq,
104    Ne,
105    Open,
106    Close,
107}
108
109fn tokens(src: &str) -> Result<Vec<Token>, String> {
110    let mut out = Vec::new();
111    let mut chars = src.chars().peekable();
112    while let Some(&c) = chars.peek() {
113        match c {
114            ' ' | '\t' => {
115                chars.next();
116            }
117            '(' => {
118                chars.next();
119                out.push(Token::Open);
120            }
121            ')' => {
122                chars.next();
123                out.push(Token::Close);
124            }
125            '!' => {
126                chars.next();
127                if chars.peek() == Some(&'=') {
128                    chars.next();
129                    out.push(Token::Ne);
130                } else {
131                    out.push(Token::Not);
132                }
133            }
134            '=' | '&' | '|' => {
135                chars.next();
136                if chars.next() != Some(c) {
137                    return Err(format!("`{c}` must be doubled in `{src}`"));
138                }
139                out.push(match c {
140                    '=' => Token::Eq,
141                    '&' => Token::And,
142                    _ => Token::Or,
143                });
144            }
145            '\'' | '"' => {
146                chars.next();
147                let mut text = String::new();
148                loop {
149                    match chars.next() {
150                        Some(q) if q == c => break,
151                        Some(ch) => text.push(ch),
152                        None => return Err(format!("unclosed text in `{src}`")),
153                    }
154                }
155                out.push(Token::Text(text));
156            }
157            c if c.is_alphanumeric() || c == '_' || c == '.' => {
158                let mut ident = String::new();
159                while let Some(&c) = chars.peek() {
160                    if c.is_alphanumeric() || c == '_' || c == '.' {
161                        ident.push(c);
162                        chars.next();
163                    } else {
164                        break;
165                    }
166                }
167                out.push(Token::Ident(ident));
168            }
169            other => return Err(format!("unexpected `{other}` in `{src}`")),
170        }
171    }
172    Ok(out)
173}
174
175struct Parser {
176    tokens: Vec<Token>,
177    at: usize,
178}
179
180impl Parser {
181    fn peek(&self) -> Option<&Token> {
182        self.tokens.get(self.at)
183    }
184
185    fn next(&mut self) -> Option<Token> {
186        let t = self.tokens.get(self.at).cloned();
187        self.at += 1;
188        t
189    }
190
191    fn or(&mut self) -> Result<When, String> {
192        let mut left = self.and()?;
193        while self.peek() == Some(&Token::Or) {
194            self.next();
195            left = When::Or(Box::new(left), Box::new(self.and()?));
196        }
197        Ok(left)
198    }
199
200    fn and(&mut self) -> Result<When, String> {
201        let mut left = self.unary()?;
202        while self.peek() == Some(&Token::And) {
203            self.next();
204            left = When::And(Box::new(left), Box::new(self.unary()?));
205        }
206        Ok(left)
207    }
208
209    fn unary(&mut self) -> Result<When, String> {
210        match self.next() {
211            Some(Token::Not) => Ok(When::Not(Box::new(self.unary()?))),
212            Some(Token::Open) => {
213                let inner = self.or()?;
214                match self.next() {
215                    Some(Token::Close) => Ok(inner),
216                    _ => Err("missing `)`".into()),
217                }
218            }
219            Some(Token::Ident(key)) => match self.peek() {
220                Some(Token::Eq) | Some(Token::Ne) => {
221                    let eq = self.next() == Some(Token::Eq);
222                    match self.next() {
223                        Some(Token::Text(t)) | Some(Token::Ident(t)) => Ok(if eq {
224                            When::Eq(key, t)
225                        } else {
226                            When::Ne(key, t)
227                        }),
228                        _ => Err(format!("`{key}` compared to nothing")),
229                    }
230                }
231                _ => Ok(When::Key(key)),
232            },
233            other => Err(format!("unexpected {other:?}")),
234        }
235    }
236}
237
238impl When {
239    /// Parses an expression; an empty one always applies.
240    pub fn parse(src: &str) -> Result<When, String> {
241        let tokens = tokens(src)?;
242        if tokens.is_empty() {
243            return Ok(When::Always);
244        }
245        let mut p = Parser { tokens, at: 0 };
246        let w = p.or()?;
247        if p.at != p.tokens.len() {
248            return Err(format!("trailing tokens in `{src}`"));
249        }
250        Ok(w)
251    }
252
253    pub fn eval(&self, cx: &WhenContext) -> bool {
254        match self {
255            When::Always => true,
256            When::Key(k) => cx.truthy(k),
257            When::Eq(k, v) => cx.get(k) == v,
258            When::Ne(k, v) => cx.get(k) != v,
259            When::Not(w) => !w.eval(cx),
260            When::And(a, b) => a.eval(cx) && b.eval(cx),
261            When::Or(a, b) => a.eval(cx) || b.eval(cx),
262        }
263    }
264
265    /// How specific the expression is: the number of keys it tests. Among
266    /// bindings of one layer and depth, the most specific wins.
267    pub fn specificity(&self) -> usize {
268        match self {
269            When::Always => 0,
270            When::Key(_) | When::Eq(..) | When::Ne(..) => 1,
271            When::Not(w) => w.specificity(),
272            When::And(a, b) | When::Or(a, b) => a.specificity() + b.specificity(),
273        }
274    }
275
276    /// The keys the expression tests.
277    pub fn keys(&self) -> Vec<&str> {
278        match self {
279            When::Always => vec![],
280            When::Key(k) | When::Eq(k, _) | When::Ne(k, _) => vec![k.as_str()],
281            When::Not(w) => w.keys(),
282            When::And(a, b) | When::Or(a, b) => {
283                let mut v = a.keys();
284                v.extend(b.keys());
285                v
286            }
287        }
288    }
289
290    /// Whether no context makes both expressions hold (`view == 'a'`
291    /// and `view == 'b'`, `listFocus` and `!listFocus`): two bindings of
292    /// one key under such clauses never compete. Conservative: `false`
293    /// when it cannot tell.
294    pub fn excludes(&self, other: &When) -> bool {
295        let (Some(a), Some(b)) = (dnf(self, false), dnf(other, false)) else {
296            return false;
297        };
298        a.iter().all(|x| {
299            b.iter()
300                .all(|y| x.iter().any(|l| y.iter().any(|m| l.contradicts(m))))
301        })
302    }
303
304    /// How deep in the focus chain the expression applies: the deepest
305    /// depth among the keys it tests that are set (0 when none is).
306    pub fn depth(&self, cx: &WhenContext) -> u32 {
307        self.keys()
308            .into_iter()
309            .filter_map(|k| cx.depth_of(k))
310            .max()
311            .unwrap_or(0)
312    }
313}
314
315/// One test of a key, as the disjunctive form holds it.
316#[derive(Clone, Debug, PartialEq)]
317enum Lit {
318    Truthy(String),
319    Falsy(String),
320    Eq(String, String),
321    Ne(String, String),
322}
323
324impl Lit {
325    fn contradicts(&self, other: &Lit) -> bool {
326        let truthy = |v: &str| !v.is_empty() && v != "false";
327        let one = |a: &Lit, b: &Lit| match (a, b) {
328            (Lit::Truthy(k), Lit::Falsy(j)) => k == j,
329            (Lit::Eq(k, v), Lit::Eq(j, w)) => k == j && v != w,
330            (Lit::Eq(k, v), Lit::Ne(j, w)) => k == j && v == w,
331            (Lit::Eq(k, v), Lit::Falsy(j)) => k == j && truthy(v),
332            (Lit::Eq(k, v), Lit::Truthy(j)) => k == j && !truthy(v),
333            _ => false,
334        };
335        one(self, other) || one(other, self)
336    }
337}
338
339/// The largest disjunctive form [`When::excludes`] works through.
340const DNF_LIMIT: usize = 64;
341
342/// The expression (negated when `neg`) as alternatives of conjunctions;
343/// `None` past [`DNF_LIMIT`] terms.
344fn dnf(w: &When, neg: bool) -> Option<Vec<Vec<Lit>>> {
345    let cross = |a: Vec<Vec<Lit>>, b: Vec<Vec<Lit>>| -> Option<Vec<Vec<Lit>>> {
346        if a.len() * b.len() > DNF_LIMIT {
347            return None;
348        }
349        Some(
350            a.iter()
351                .flat_map(|x| {
352                    b.iter().map(move |y| {
353                        let mut t = x.clone();
354                        t.extend(y.iter().cloned());
355                        t
356                    })
357                })
358                .collect(),
359        )
360    };
361    let union = |mut a: Vec<Vec<Lit>>, b: Vec<Vec<Lit>>| {
362        a.extend(b);
363        (a.len() <= DNF_LIMIT).then_some(a)
364    };
365    match (w, neg) {
366        (When::Always, false) => Some(vec![vec![]]),
367        (When::Always, true) => Some(vec![]),
368        (When::Key(k), false) => Some(vec![vec![Lit::Truthy(k.clone())]]),
369        (When::Key(k), true) => Some(vec![vec![Lit::Falsy(k.clone())]]),
370        (When::Eq(k, v), false) | (When::Ne(k, v), true) => {
371            Some(vec![vec![Lit::Eq(k.clone(), v.clone())]])
372        }
373        (When::Ne(k, v), false) | (When::Eq(k, v), true) => {
374            Some(vec![vec![Lit::Ne(k.clone(), v.clone())]])
375        }
376        (When::Not(x), n) => dnf(x, !n),
377        (When::And(a, b), false) | (When::Or(a, b), true) => cross(dnf(a, neg)?, dnf(b, neg)?),
378        (When::Or(a, b), false) | (When::And(a, b), true) => union(dnf(a, neg)?, dnf(b, neg)?),
379    }
380}
381
382#[cfg(test)]
383mod tests {
384    use super::*;
385
386    #[test]
387    fn clauses_that_never_hold_together_exclude_each_other() {
388        let p = |s: &str| When::parse(s).unwrap();
389        assert!(p("view == 'a'").excludes(&p("view == 'b'")));
390        assert!(p("listFocus").excludes(&p("!listFocus")));
391        assert!(p("view == 'a' && x").excludes(&p("view != 'a'")));
392        assert!(p("mode == 'edit' || mode == 'draw'").excludes(&p("mode == 'view'")));
393        assert!(p("!(a || b)").excludes(&p("b")));
394        assert!(!p("a").excludes(&p("b")));
395        assert!(!p("").excludes(&p("a")), "always holds with a");
396        assert!(!p("a || c").excludes(&p("!a")));
397    }
398
399    #[test]
400    fn expressions_evaluate_against_the_context() {
401        let cx = WhenContext::new()
402            .flag("listFocus", true)
403            .flag("textInputFocus", false)
404            .with("view", "editor");
405        for (src, expected) in [
406            ("", true),
407            ("listFocus", true),
408            ("textInputFocus", false),
409            ("!textInputFocus", true),
410            ("listFocus && !textInputFocus", true),
411            ("view == 'editor'", true),
412            ("view != editor", false),
413            ("canvasFocus || view == 'editor'", true),
414            ("(canvasFocus || listFocus) && view == \"browser\"", false),
415            ("missing", false),
416        ] {
417            assert_eq!(When::parse(src).unwrap().eval(&cx), expected, "{src}");
418        }
419    }
420
421    #[test]
422    fn mistakes_are_named() {
423        for bad in ["a & b", "(a", "a ==", "a b", "'open"] {
424            assert!(When::parse(bad).is_err(), "{bad}");
425        }
426        assert_eq!(When::parse("a && !b || c").unwrap().specificity(), 3);
427    }
428
429    #[test]
430    fn depth_is_the_deepest_key_tested() {
431        let mut cx = WhenContext::new().flag("app", true);
432        cx.flag_at("dialogFocus", true, 1);
433        cx.flag_at("textInputFocus", true, 2);
434        assert_eq!(When::parse("app").unwrap().depth(&cx), 0);
435        assert_eq!(When::parse("dialogFocus && app").unwrap().depth(&cx), 1);
436        assert_eq!(When::parse("textInputFocus").unwrap().depth(&cx), 2);
437        assert_eq!(When::parse("").unwrap().depth(&cx), 0);
438        assert_eq!(When::parse("unset").unwrap().depth(&cx), 0);
439    }
440}