crisol-core 1.3.0

Crisol core: an egui-free data model, themes, metrics, localization, commands, state, and storage.
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
//! Context keys and the small `when` expression evaluated for each command.
//!
//! The language is intentionally small: identifiers, `!`, `&&`, `||`, and parentheses.
//! A command is available when its `when` expression is true for the current
//! [`WhenContext`]. An empty expression is always true.
//!
//! ```
//! use crisol_core::commands::when;
//! ```

use std::collections::BTreeSet;
use std::fmt;

#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "serde", serde(transparent))]
/// The keys a host can publish before drawing a frame.
///
/// The constants are the names the workbench itself uses; an application may add its
/// own. Keys are case-sensitive and must be identifiers.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
/// # Example
///
/// ```
/// use crisol_core::commands::WhenContext;
/// ```
pub struct WhenContext {
    keys: BTreeSet<String>,
}

impl WhenContext {
    /// An empty context: every key is false.
    pub fn new() -> Self {
        Self::default()
    }

    /// Insert a key and return the context.
    pub fn with(mut self, key: impl Into<String>) -> Self {
        self.insert(key);
        self
    }

    /// Insert a key.
    pub fn insert(&mut self, key: impl Into<String>) {
        self.keys.insert(key.into());
    }

    /// Remove a key.
    pub fn remove(&mut self, key: &str) {
        self.keys.remove(key);
    }

    /// Whether a key is set.
    pub fn contains(&self, key: &str) -> bool {
        self.keys.contains(key)
    }

    /// Clear every key.
    pub fn clear(&mut self) {
        self.keys.clear();
    }

    /// The set keys, sorted.
    pub fn keys(&self) -> impl Iterator<Item = &str> {
        self.keys.iter().map(String::as_str)
    }
}

/// The standard context key for a focused text editor.
/// # Example
///
/// ```
/// use crisol_core::commands::EDITOR_FOCUS;
/// ```
pub const EDITOR_FOCUS: &str = "editorFocus";
/// The standard context key for a non-empty selection.
/// # Example
///
/// ```
/// use crisol_core::commands::HAS_SELECTION;
/// ```
pub const HAS_SELECTION: &str = "hasSelection";
/// The standard context key for an open modal.
/// # Example
///
/// ```
/// use crisol_core::commands::DIALOG_OPEN;
/// ```
pub const DIALOG_OPEN: &str = "dialogOpen";
/// The standard context key for an open command palette.
/// # Example
///
/// ```
/// use crisol_core::commands::PALETTE_OPEN;
/// ```
pub const PALETTE_OPEN: &str = "paletteOpen";
/// The standard context key for a read-only document.
/// # Example
///
/// ```
/// use crisol_core::commands::READ_ONLY;
/// ```
pub const READ_ONLY: &str = "readOnly";
/// The standard context key for unsaved changes.
/// # Example
///
/// ```
/// use crisol_core::commands::DIRTY;
/// ```
pub const DIRTY: &str = "dirty";

/// A parsed `when` expression.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
/// # Example
///
/// ```
/// use crisol_core::commands::When;
/// ```
pub struct When {
    source: String,
    expression: Option<Expression>,
}

impl When {
    /// An expression that is always true.
    pub fn always() -> Self {
        Self::default()
    }

    /// Parse an expression. An empty or whitespace-only string is always true.
    ///
    /// # Errors
    /// When a token or parenthesis is missing or unexpected.
    pub fn parse(source: &str) -> Result<Self, WhenError> {
        if source.trim().is_empty() {
            return Ok(Self::always());
        }
        let mut parser = Parser::new(source)?;
        let expression = parser.expression()?;
        parser.expect_end()?;
        Ok(Self {
            source: source.to_owned(),
            expression: Some(expression),
        })
    }

    /// The source text, or an empty string for an always-true expression.
    pub fn source(&self) -> &str {
        &self.source
    }

    /// Whether the expression is always true.
    pub fn is_always(&self) -> bool {
        self.expression.is_none()
    }

    /// Evaluate the expression against `context`.
    pub fn evaluate(&self, context: &WhenContext) -> bool {
        self.expression
            .as_ref()
            .is_none_or(|expression| expression.evaluate(context))
    }
}

impl fmt::Display for When {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str(&self.source)
    }
}

#[derive(Clone, Debug, PartialEq, Eq)]
enum Expression {
    Key(String),
    Not(Box<Self>),
    And(Box<Self>, Box<Self>),
    Or(Box<Self>, Box<Self>),
}

impl Expression {
    fn evaluate(&self, context: &WhenContext) -> bool {
        match self {
            Self::Key(key) => context.contains(key),
            Self::Not(inner) => !inner.evaluate(context),
            Self::And(left, right) => left.evaluate(context) && right.evaluate(context),
            Self::Or(left, right) => left.evaluate(context) || right.evaluate(context),
        }
    }
}

/// What went wrong while parsing a `when` expression.
#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
/// # Example
///
/// ```
/// use crisol_core::commands::WhenError;
/// ```
#[error("{message} at byte {offset}")]
pub struct WhenError {
    message: String,
    offset: usize,
}

impl WhenError {
    /// A human-readable message.
    pub fn message(&self) -> &str {
        &self.message
    }

    /// The byte offset of the problem.
    pub fn offset(&self) -> usize {
        self.offset
    }
}

struct Parser<'a> {
    source: &'a str,
    bytes: &'a [u8],
    offset: usize,
    depth: usize,
}

/// Deepest nesting of `!` and parentheses; the parser recurses.
const MAX_DEPTH: usize = 64;

impl<'a> Parser<'a> {
    fn new(source: &'a str) -> Result<Self, WhenError> {
        Ok(Self {
            source,
            bytes: source.as_bytes(),
            offset: 0,
            depth: 0,
        })
    }

    fn expression(&mut self) -> Result<Expression, WhenError> {
        let mut expression = self.term()?;
        loop {
            self.skip_whitespace();
            if self.take("||") {
                let right = self.term()?;
                expression = Expression::Or(Box::new(expression), Box::new(right));
            } else {
                return Ok(expression);
            }
        }
    }

    fn term(&mut self) -> Result<Expression, WhenError> {
        let mut expression = self.unary()?;
        loop {
            self.skip_whitespace();
            if self.take("&&") {
                let right = self.unary()?;
                expression = Expression::And(Box::new(expression), Box::new(right));
            } else {
                return Ok(expression);
            }
        }
    }

    fn unary(&mut self) -> Result<Expression, WhenError> {
        self.skip_whitespace();
        if self.take("!") {
            self.enter()?;
            let inner = self.unary();
            self.depth -= 1;
            return Ok(Expression::Not(Box::new(inner?)));
        }
        if self.take("(") {
            self.enter()?;
            let expression = self.expression();
            self.depth -= 1;
            let expression = expression?;
            self.skip_whitespace();
            if !self.take(")") {
                return Err(self.error("expected `)`"));
            }
            return Ok(expression);
        }
        let key = self.identifier()?;
        Ok(Expression::Key(key))
    }

    fn enter(&mut self) -> Result<(), WhenError> {
        if self.depth >= MAX_DEPTH {
            return Err(self.error("the expression is nested too deeply"));
        }
        self.depth += 1;
        Ok(())
    }

    fn identifier(&mut self) -> Result<String, WhenError> {
        self.skip_whitespace();
        let start = self.offset;
        while let Some(byte) = self.bytes.get(self.offset) {
            if byte.is_ascii_alphanumeric() || *byte == b'_' || *byte == b'.' || *byte == b'-' {
                self.offset += 1;
            } else {
                break;
            }
        }
        if self.offset == start {
            return Err(self.error("expected a context key"));
        }
        Ok(self.source[start..self.offset].to_owned())
    }

    fn expect_end(&mut self) -> Result<(), WhenError> {
        self.skip_whitespace();
        if self.offset == self.bytes.len() {
            Ok(())
        } else {
            Err(self.error("unexpected input after the expression"))
        }
    }

    fn skip_whitespace(&mut self) {
        while self.bytes.get(self.offset).is_some_and(u8::is_ascii_whitespace) {
            self.offset += 1;
        }
    }

    fn take(&mut self, text: &str) -> bool {
        if self.source[self.offset..].starts_with(text) {
            self.offset += text.len();
            true
        } else {
            false
        }
    }

    fn error(&self, message: &str) -> WhenError {
        WhenError {
            message: message.to_owned(),
            offset: self.offset,
        }
    }
}

#[cfg(feature = "serde")]
mod serde_impl {
    use serde::{Deserialize, Deserializer, Serializer};

    use super::When;

    impl serde::Serialize for When {
        fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
            serializer.serialize_str(self.source())
        }
    }

    impl<'de> Deserialize<'de> for When {
        fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
            let text = String::deserialize(deserializer)?;
            Self::parse(&text).map_err(serde::de::Error::custom)
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn context(keys: &[&str]) -> WhenContext {
        let mut context = WhenContext::new();
        for key in keys {
            context.insert(*key);
        }
        context
    }

    #[test]
    fn empty_is_always_true() {
        let when = When::parse("").expect("empty");
        assert!(when.is_always());
        assert!(when.evaluate(&WhenContext::new()));
    }

    #[test]
    fn keys_and_negation_follow_the_context() {
        let when = When::parse("editorFocus && !dialogOpen").expect("expression");
        assert!(when.evaluate(&context(&[EDITOR_FOCUS])));
        assert!(!when.evaluate(&context(&[EDITOR_FOCUS, DIALOG_OPEN])));
        assert!(!when.evaluate(&WhenContext::new()));
    }

    #[test]
    fn precedence_is_not_then_and_then_or() {
        let when = When::parse("!dialogOpen && editorFocus || hasSelection").expect("expression");
        assert!(when.evaluate(&context(&[EDITOR_FOCUS])));
        assert!(when.evaluate(&context(&[HAS_SELECTION])));
        assert!(!when.evaluate(&context(&[EDITOR_FOCUS, DIALOG_OPEN])));
        let grouped = When::parse("!(dialogOpen && editorFocus)").expect("grouped");
        assert!(grouped.evaluate(&context(&[EDITOR_FOCUS])));
    }

    #[test]
    fn errors_have_an_offset() {
        let error = When::parse("editorFocus &&").expect_err("missing operand");
        assert_eq!(error.offset(), 14);
        assert!(When::parse("(editorFocus").is_err());
        assert!(When::parse("editorFocus dialogOpen").is_err());
    }

    #[cfg(feature = "serde")]
    #[test]
    fn expressions_round_trip_through_json() {
        let when = When::parse("editorFocus && !dialogOpen").expect("expression");
        let json = serde_json::to_string(&when).expect("serialize");
        assert_eq!(json, "\"editorFocus && !dialogOpen\"");
        let back: When = serde_json::from_str(&json).expect("deserialize");
        assert_eq!(back, when);
    }
}