Skip to main content

crisol_core/commands/
when.rs

1//! Context keys and the small `when` expression evaluated for each command.
2//!
3//! The language is intentionally small: identifiers, `!`, `&&`, `||`, and parentheses.
4//! A command is available when its `when` expression is true for the current
5//! [`WhenContext`]. An empty expression is always true.
6//!
7//! ```
8//! use crisol_core::commands::when;
9//! ```
10
11use std::collections::BTreeSet;
12use std::fmt;
13
14#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
15#[cfg_attr(feature = "serde", serde(transparent))]
16/// The keys a host can publish before drawing a frame.
17///
18/// The constants are the names the workbench itself uses; an application may add its
19/// own. Keys are case-sensitive and must be identifiers.
20#[derive(Clone, Debug, Default, PartialEq, Eq)]
21/// # Example
22///
23/// ```
24/// use crisol_core::commands::WhenContext;
25/// ```
26pub struct WhenContext {
27    keys: BTreeSet<String>,
28}
29
30impl WhenContext {
31    /// An empty context: every key is false.
32    pub fn new() -> Self {
33        Self::default()
34    }
35
36    /// Insert a key and return the context.
37    pub fn with(mut self, key: impl Into<String>) -> Self {
38        self.insert(key);
39        self
40    }
41
42    /// Insert a key.
43    pub fn insert(&mut self, key: impl Into<String>) {
44        self.keys.insert(key.into());
45    }
46
47    /// Remove a key.
48    pub fn remove(&mut self, key: &str) {
49        self.keys.remove(key);
50    }
51
52    /// Whether a key is set.
53    pub fn contains(&self, key: &str) -> bool {
54        self.keys.contains(key)
55    }
56
57    /// Clear every key.
58    pub fn clear(&mut self) {
59        self.keys.clear();
60    }
61
62    /// The set keys, sorted.
63    pub fn keys(&self) -> impl Iterator<Item = &str> {
64        self.keys.iter().map(String::as_str)
65    }
66}
67
68/// The standard context key for a focused text editor.
69/// # Example
70///
71/// ```
72/// use crisol_core::commands::EDITOR_FOCUS;
73/// ```
74pub const EDITOR_FOCUS: &str = "editorFocus";
75/// The standard context key for a non-empty selection.
76/// # Example
77///
78/// ```
79/// use crisol_core::commands::HAS_SELECTION;
80/// ```
81pub const HAS_SELECTION: &str = "hasSelection";
82/// The standard context key for an open modal.
83/// # Example
84///
85/// ```
86/// use crisol_core::commands::DIALOG_OPEN;
87/// ```
88pub const DIALOG_OPEN: &str = "dialogOpen";
89/// The standard context key for an open command palette.
90/// # Example
91///
92/// ```
93/// use crisol_core::commands::PALETTE_OPEN;
94/// ```
95pub const PALETTE_OPEN: &str = "paletteOpen";
96/// The standard context key for a read-only document.
97/// # Example
98///
99/// ```
100/// use crisol_core::commands::READ_ONLY;
101/// ```
102pub const READ_ONLY: &str = "readOnly";
103/// The standard context key for unsaved changes.
104/// # Example
105///
106/// ```
107/// use crisol_core::commands::DIRTY;
108/// ```
109pub const DIRTY: &str = "dirty";
110
111/// A parsed `when` expression.
112#[derive(Clone, Debug, Default, PartialEq, Eq)]
113/// # Example
114///
115/// ```
116/// use crisol_core::commands::When;
117/// ```
118pub struct When {
119    source: String,
120    expression: Option<Expression>,
121}
122
123impl When {
124    /// An expression that is always true.
125    pub fn always() -> Self {
126        Self::default()
127    }
128
129    /// Parse an expression. An empty or whitespace-only string is always true.
130    ///
131    /// # Errors
132    /// When a token or parenthesis is missing or unexpected.
133    pub fn parse(source: &str) -> Result<Self, WhenError> {
134        if source.trim().is_empty() {
135            return Ok(Self::always());
136        }
137        let mut parser = Parser::new(source)?;
138        let expression = parser.expression()?;
139        parser.expect_end()?;
140        Ok(Self {
141            source: source.to_owned(),
142            expression: Some(expression),
143        })
144    }
145
146    /// The source text, or an empty string for an always-true expression.
147    pub fn source(&self) -> &str {
148        &self.source
149    }
150
151    /// Whether the expression is always true.
152    pub fn is_always(&self) -> bool {
153        self.expression.is_none()
154    }
155
156    /// Evaluate the expression against `context`.
157    pub fn evaluate(&self, context: &WhenContext) -> bool {
158        self.expression
159            .as_ref()
160            .is_none_or(|expression| expression.evaluate(context))
161    }
162}
163
164impl fmt::Display for When {
165    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
166        formatter.write_str(&self.source)
167    }
168}
169
170#[derive(Clone, Debug, PartialEq, Eq)]
171enum Expression {
172    Key(String),
173    Not(Box<Self>),
174    And(Box<Self>, Box<Self>),
175    Or(Box<Self>, Box<Self>),
176}
177
178impl Expression {
179    fn evaluate(&self, context: &WhenContext) -> bool {
180        match self {
181            Self::Key(key) => context.contains(key),
182            Self::Not(inner) => !inner.evaluate(context),
183            Self::And(left, right) => left.evaluate(context) && right.evaluate(context),
184            Self::Or(left, right) => left.evaluate(context) || right.evaluate(context),
185        }
186    }
187}
188
189/// What went wrong while parsing a `when` expression.
190#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
191/// # Example
192///
193/// ```
194/// use crisol_core::commands::WhenError;
195/// ```
196#[error("{message} at byte {offset}")]
197pub struct WhenError {
198    message: String,
199    offset: usize,
200}
201
202impl WhenError {
203    /// A human-readable message.
204    pub fn message(&self) -> &str {
205        &self.message
206    }
207
208    /// The byte offset of the problem.
209    pub fn offset(&self) -> usize {
210        self.offset
211    }
212}
213
214struct Parser<'a> {
215    source: &'a str,
216    bytes: &'a [u8],
217    offset: usize,
218    depth: usize,
219}
220
221/// Deepest nesting of `!` and parentheses; the parser recurses.
222const MAX_DEPTH: usize = 64;
223
224impl<'a> Parser<'a> {
225    fn new(source: &'a str) -> Result<Self, WhenError> {
226        Ok(Self {
227            source,
228            bytes: source.as_bytes(),
229            offset: 0,
230            depth: 0,
231        })
232    }
233
234    fn expression(&mut self) -> Result<Expression, WhenError> {
235        let mut expression = self.term()?;
236        loop {
237            self.skip_whitespace();
238            if self.take("||") {
239                let right = self.term()?;
240                expression = Expression::Or(Box::new(expression), Box::new(right));
241            } else {
242                return Ok(expression);
243            }
244        }
245    }
246
247    fn term(&mut self) -> Result<Expression, WhenError> {
248        let mut expression = self.unary()?;
249        loop {
250            self.skip_whitespace();
251            if self.take("&&") {
252                let right = self.unary()?;
253                expression = Expression::And(Box::new(expression), Box::new(right));
254            } else {
255                return Ok(expression);
256            }
257        }
258    }
259
260    fn unary(&mut self) -> Result<Expression, WhenError> {
261        self.skip_whitespace();
262        if self.take("!") {
263            self.enter()?;
264            let inner = self.unary();
265            self.depth -= 1;
266            return Ok(Expression::Not(Box::new(inner?)));
267        }
268        if self.take("(") {
269            self.enter()?;
270            let expression = self.expression();
271            self.depth -= 1;
272            let expression = expression?;
273            self.skip_whitespace();
274            if !self.take(")") {
275                return Err(self.error("expected `)`"));
276            }
277            return Ok(expression);
278        }
279        let key = self.identifier()?;
280        Ok(Expression::Key(key))
281    }
282
283    fn enter(&mut self) -> Result<(), WhenError> {
284        if self.depth >= MAX_DEPTH {
285            return Err(self.error("the expression is nested too deeply"));
286        }
287        self.depth += 1;
288        Ok(())
289    }
290
291    fn identifier(&mut self) -> Result<String, WhenError> {
292        self.skip_whitespace();
293        let start = self.offset;
294        while let Some(byte) = self.bytes.get(self.offset) {
295            if byte.is_ascii_alphanumeric() || *byte == b'_' || *byte == b'.' || *byte == b'-' {
296                self.offset += 1;
297            } else {
298                break;
299            }
300        }
301        if self.offset == start {
302            return Err(self.error("expected a context key"));
303        }
304        Ok(self.source[start..self.offset].to_owned())
305    }
306
307    fn expect_end(&mut self) -> Result<(), WhenError> {
308        self.skip_whitespace();
309        if self.offset == self.bytes.len() {
310            Ok(())
311        } else {
312            Err(self.error("unexpected input after the expression"))
313        }
314    }
315
316    fn skip_whitespace(&mut self) {
317        while self.bytes.get(self.offset).is_some_and(u8::is_ascii_whitespace) {
318            self.offset += 1;
319        }
320    }
321
322    fn take(&mut self, text: &str) -> bool {
323        if self.source[self.offset..].starts_with(text) {
324            self.offset += text.len();
325            true
326        } else {
327            false
328        }
329    }
330
331    fn error(&self, message: &str) -> WhenError {
332        WhenError {
333            message: message.to_owned(),
334            offset: self.offset,
335        }
336    }
337}
338
339#[cfg(feature = "serde")]
340mod serde_impl {
341    use serde::{Deserialize, Deserializer, Serializer};
342
343    use super::When;
344
345    impl serde::Serialize for When {
346        fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
347            serializer.serialize_str(self.source())
348        }
349    }
350
351    impl<'de> Deserialize<'de> for When {
352        fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
353            let text = String::deserialize(deserializer)?;
354            Self::parse(&text).map_err(serde::de::Error::custom)
355        }
356    }
357}
358
359#[cfg(test)]
360mod tests {
361    use super::*;
362
363    fn context(keys: &[&str]) -> WhenContext {
364        let mut context = WhenContext::new();
365        for key in keys {
366            context.insert(*key);
367        }
368        context
369    }
370
371    #[test]
372    fn empty_is_always_true() {
373        let when = When::parse("").expect("empty");
374        assert!(when.is_always());
375        assert!(when.evaluate(&WhenContext::new()));
376    }
377
378    #[test]
379    fn keys_and_negation_follow_the_context() {
380        let when = When::parse("editorFocus && !dialogOpen").expect("expression");
381        assert!(when.evaluate(&context(&[EDITOR_FOCUS])));
382        assert!(!when.evaluate(&context(&[EDITOR_FOCUS, DIALOG_OPEN])));
383        assert!(!when.evaluate(&WhenContext::new()));
384    }
385
386    #[test]
387    fn precedence_is_not_then_and_then_or() {
388        let when = When::parse("!dialogOpen && editorFocus || hasSelection").expect("expression");
389        assert!(when.evaluate(&context(&[EDITOR_FOCUS])));
390        assert!(when.evaluate(&context(&[HAS_SELECTION])));
391        assert!(!when.evaluate(&context(&[EDITOR_FOCUS, DIALOG_OPEN])));
392        let grouped = When::parse("!(dialogOpen && editorFocus)").expect("grouped");
393        assert!(grouped.evaluate(&context(&[EDITOR_FOCUS])));
394    }
395
396    #[test]
397    fn errors_have_an_offset() {
398        let error = When::parse("editorFocus &&").expect_err("missing operand");
399        assert_eq!(error.offset(), 14);
400        assert!(When::parse("(editorFocus").is_err());
401        assert!(When::parse("editorFocus dialogOpen").is_err());
402    }
403
404    #[cfg(feature = "serde")]
405    #[test]
406    fn expressions_round_trip_through_json() {
407        let when = When::parse("editorFocus && !dialogOpen").expect("expression");
408        let json = serde_json::to_string(&when).expect("serialize");
409        assert_eq!(json, "\"editorFocus && !dialogOpen\"");
410        let back: When = serde_json::from_str(&json).expect("deserialize");
411        assert_eq!(back, when);
412    }
413}