Public repository: timo / feel

Reader

An interpreter of FEEL, written in Rust, with integrations for PostgreSQL, WASM, Lua, and Python.

Outline: 22 definitions
1
//! Hand-tuned token stream for the lalrpop parser, built on `logos`.
2
//!
3
//! Why this exists: lalrpop's built-in lexer is regex-driven — it pulls the
4
//! whole `regex-automata` stack into the binary *and* rebuilds a matcher DFA on
5
//! every `ExprParser::new()` (the ~680µs we used to cache around). `logos`
6
//! generates a compile-time DFA with no runtime regex dependency, so the parser
7
//! constructs instantly and the regex crate is no longer needed just to tokenize.
8
//!
9
//! Identifiers are deliberately **not** matched with a `\p{L}`-style regex (which
10
//! would bake large Unicode tables into the build). Instead the lead character is
11
//! caught by a cheap range and the token is validated/extended with
12
//! `unicode-ident`'s compact XID tables in [`lex_name`]. Keywords are not separate
13
//! `logos` tokens — that would break maximal munch (`fortune` must stay one name,
14
//! not `for` + `tune`); they are recognised from the lexed name in [`keyword`].
15
//!
16
//! Full FEEL names may contain spaces (`full name`, `string length`). A second
17
//! pass over the token stream ([`join_names`]) joins them without any
18
//! scope knowledge, exploiting that FEEL has no juxtaposition — two adjacent
19
//! `Name` tokens can only be one name (DECISIONS.md ADR-17). A small fixed
20
//! dictionary ([`crate::builtins::KEYWORD_PHRASE_BUILTINS`]) additionally
21
//! recognises *keyword-containing* reserved phrases (`date and time`, the two
22
//! durations) wherever they occur — they are atomic temporal type/constructor
23
//! names (ADR-26). Spaces in names are normalised to a single space.
24
//!
25
//! Java-style comments (`// … \n` and `/* … */`) are skipped at the logos level
26
//! (pass 1). `logos` maximal munch makes `//` / `/*` win over the single `/`
27
//! (`Slash`), so a bare `/` used as division or in `->` is unaffected.
28
29
use core::fmt;
30
31
use logos::Logos;
32
33
/// A lexer error. The grammar maps this to a `ParseError::User`, which surfaces
34
/// as a [`crate::FeelError::Parse`] — the same outcome the old regex lexer gave
35
/// for an unrecognised character.
36
#[derive(Default, Debug, Clone, PartialEq, Eq)]
37
pub struct LexError;
38
39
impl fmt::Display for LexError {
40
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
41
        f.write_str("invalid token")
42
    }
43
}
44
45
/// The FEEL token set. Keywords/operators/punctuation are unit variants; the
46
/// three value-carrying terminals (`Num`/`Str`/`Name`) carry their parsed payload.
47
///
48
/// Word keywords are produced via [`lex`]'s [`keyword`] remap of a lexed `Name`,
49
/// not by `logos`, so identifier maximal-munch is preserved.
50
#[derive(Logos, Clone, Debug, PartialEq)]
51
#[logos(skip r"[ \t\r\n]+", error = LexError)]
52
pub enum Tok {
53
    // FEEL Java-style comments — skipped at the logos level (never emitted).
54
    // Maximal munch: `//`/`/*` beat the 1-char `/` Slash, so bare `/` is unaffected.
55
    #[regex(r"//[^\n]*", logos::skip, priority = 5, allow_greedy = true)]
56
    #[regex(r"/\*([^*]|\*[^/])*\*/", logos::skip, priority = 5)]
57
    Comment,
58
59
    // --- word keywords (never emitted by logos directly; see `keyword`) ---
60
    For,
61
    In,
62
    Return,
63
    If,
64
    Then,
65
    Else,
66
    Some,
67
    Every,
68
    Satisfies,
69
    Or,
70
    And,
71
    Between,
72
    True,
73
    False,
74
    Null,
75
    Not,
76
    Function,
77
    // The two-word `instance of` operator. `instance` and `of` are NOT reserved
78
    // words (FEEL names may contain them — `year of birth`, the `day of week`
79
    // built-in), so this is emitted only for the adjacent `instance` `of` pair by a
80
    // dedicated lexer pass ([`mark_instance_of`]), never by `keyword`.
81
    InstanceOf,
82
83
    // --- operators (longer forms listed first so the intent is obvious; logos
84
    //     does maximal munch regardless, so `<=` beats `<`, `**` beats `*`) ---
85
    #[token("<=")]
86
    Le,
87
    #[token("<")]
88
    Lt,
89
    #[token(">=")]
90
    Ge,
91
    #[token(">")]
92
    Gt,
93
    #[token("=")]
94
    Eq,
95
    #[token("!=")]
96
    Ne,
97
    #[token("+")]
98
    Plus,
99
    // `->` (function-type arrow) before `-`: only appears literally in a
100
    // `function<…> -> T` type, and logos maximal-munch picks it over `-` `>`.
101
    #[token("->")]
102
    Arrow,
103
    #[token("-")]
104
    Minus,
105
    #[token("**")]
106
    StarStar,
107
    #[token("*")]
108
    Star,
109
    #[token("/")]
110
    Slash,
111
    #[token("...")]
112
    DotDotDot,
113
    #[token("..")]
114
    DotDot,
115
    #[token(".")]
116
    Dot,
117
118
    // --- punctuation ---
119
    #[token("(")]
120
    LParen,
121
    #[token(")")]
122
    RParen,
123
    #[token("[")]
124
    LBracket,
125
    #[token("]")]
126
    RBracket,
127
    // A `]` that *opens* a reverse-bracket interval `]a..b]` (the exclusive-lower
128
    // notation for `(a..b]`). Never emitted by logos — `]` always lexes as
129
    // `RBracket`; a post-pass ([`mark_reverse_open`]) retags the opening role to this
130
    // distinct token. Without the split, `]` would be both a closer and a primary
131
    // opener, which is not LR(1)-resolvable (the empty list `[]` collides with `[`
132
    // then a reverse-open `]`; see ROADMAP).
133
    RBracketOpen,
134
    #[token("{")]
135
    LBrace,
136
    #[token("}")]
137
    RBrace,
138
    #[token(",")]
139
    Comma,
140
    #[token(":")]
141
    Colon,
142
143
    // --- value-carrying terminals ---
144
    // FEEL grammar rule 35 / §10.3.2.3.1: a numeric literal is an optional
145
    // leading-dot mantissa OR a digit-led mantissa, with an optional exponent.
146
    // The leading-dot branch (`\.[0-9]+`) requires at least one digit after the
147
    // dot, so it never overlaps with `..` (DotDot, two chars) or a lone `.`
148
    // (Dot, one char); logos's maximal-munch resolves any tie. Negatives are
149
    // produced by unary minus over the literal — there is no signed-literal token.
150
    #[regex(r"([0-9]+(\.[0-9]+)?|\.[0-9]+)([eE][+-]?[0-9]+)?", |lex| lex.slice().parse::<f64>().ok())]
151
    Num(f64),
152
153
    // A double-quoted string. The body is any run of non-quote/non-backslash
154
    // characters and backslash-escapes (`\\.`), so an escaped quote `\"` does not
155
    // end the literal. `decode_string_escapes` then resolves the FEEL escapes
156
    // (`\n \r \t \" \' \\`, `\uXXXX` incl. surrogate pairs, `\UXXXXXX`); an
157
    // unrecognised escape (e.g. a regex `\d`) is left verbatim (DMN §10.3.1.2).
158
    #[regex(r#""([^"\\]|\\.)*""#, |lex| { let s = lex.slice(); decode_string_escapes(&s[1..s.len() - 1]) })]
159
    Str(String),
160
161
    // A temporal literal `@"…"` (ADR-18). Carries the inner text; the type is
162
    // resolved by the evaluator from its lexical form. A value token like `Str`,
163
    // so `join_names` leaves it alone.
164
    #[regex(r#"@"[^"]*""#, |lex| { let s = lex.slice(); s[2..s.len() - 1].to_string() })]
165
    TemporalLit(String),
166
167
    // Lead char: ASCII letter / underscore / any non-ASCII scalar (a cheap range,
168
    // no Unicode tables). `lex_name` then validates it as an XID start and extends
169
    // over XID-continue characters. Keywords are remapped out of this in `lex`.
170
    #[regex(r"[A-Za-z_\u{80}-\u{10FFFF}]", lex_name)]
171
    Name(String),
172
}
173
174
/// Validate the already-matched lead character as an identifier start and extend
175
/// the token over the following XID-continue characters. Returns `None` (a lex
176
/// error) when the lead is a non-ASCII, non-identifier scalar (e.g. `€`, `±`).
177
fn lex_name(lex: &mut logos::Lexer<'_, Tok>) -> Option<String> {
178
    let first = lex.slice().chars().next()?;
179
    if first != '_' && !unicode_ident::is_xid_start(first) {
180
        return None;
181
    }
182
    let mut extra = 0;
183
    for c in lex.remainder().chars() {
184
        if c == '_' || unicode_ident::is_xid_continue(c) {
185
            extra += c.len_utf8();
186
        } else {
187
            break;
188
        }
189
    }
190
    lex.bump(extra);
191
    Some(lex.slice().to_string())
192
}
193
194
/// Resolve the FEEL string escapes in a string literal's body (the text between
195
/// the quotes), per DMN §10.3.1.2: `\n \r \t \" \' \\`, a `\uXXXX` 4-hex code unit
196
/// (consecutive high+low surrogates combine into one code point), and a `\UXXXXXX`
197
/// 6-hex code point. An unrecognised escape (e.g. a regex metacharacter like `\d`,
198
/// `\s`, `\3`) is preserved verbatim — feel-core does not own the regex dialect
199
/// (ADR-16), so such backslashes must reach the provider untouched. A malformed
200
/// `\u`/`\U` or a lone surrogate likewise falls back to copying the backslash.
201
fn decode_string_escapes(body: &str) -> String {
202
    // Fast path: nothing to decode.
203
    if !body.contains('\\') {
204
        return body.to_string();
205
    }
206
    let b = body.as_bytes();
207
    let mut out = String::with_capacity(body.len());
208
    let mut i = 0;
209
    while i < b.len() {
210
        if b[i] != b'\\' {
211
            // Copy one whole UTF-8 scalar (the byte at `i` starts a char).
212
            let ch = body[i..].chars().next().expect("char boundary");
213
            out.push(ch);
214
            i += ch.len_utf8();
215
            continue;
216
        }
217
        match b.get(i + 1) {
218
            Some(b'n') => { out.push('\n'); i += 2; }
219
            Some(b'r') => { out.push('\r'); i += 2; }
220
            Some(b't') => { out.push('\t'); i += 2; }
221
            Some(b'"') => { out.push('"'); i += 2; }
222
            Some(b'\'') => { out.push('\''); i += 2; }
223
            Some(b'\\') => { out.push('\\'); i += 2; }
224
            Some(b'u') => match hex_escape(&b[i..], 4) {
225
                Some(cp) if (0xD800..=0xDBFF).contains(&cp) => {
226
                    // High surrogate: pair it with a following low surrogate.
227
                    match hex_escape(&b[i + 6..], 4) {
228
                        Some(lo) if (0xDC00..=0xDFFF).contains(&lo) => {
229
                            let c = 0x1_0000 + ((cp - 0xD800) << 10) + (lo - 0xDC00);
230
                            out.push(char::from_u32(c).unwrap_or('\u{FFFD}'));
231
                            i += 12;
232
                        }
233
                        // Lone high surrogate: keep the backslash verbatim.
234
                        _ => { out.push('\\'); i += 1; }
235
                    }
236
                }
237
                // Lone low surrogate or unmappable: keep the backslash verbatim.
238
                Some(cp) => match char::from_u32(cp) {
239
                    Some(ch) => { out.push(ch); i += 6; }
240
                    None => { out.push('\\'); i += 1; }
241
                },
242
                None => { out.push('\\'); i += 1; }
243
            },
244
            Some(b'U') => match hex_escape(&b[i..], 6) {
245
                Some(cp) => match char::from_u32(cp) {
246
                    Some(ch) => { out.push(ch); i += 8; }
247
                    None => { out.push('\\'); i += 1; }
248
                },
249
                None => { out.push('\\'); i += 1; }
250
            },
251
            // Unknown escape or trailing backslash: keep the backslash verbatim and
252
            // reprocess the next byte normally (so `\d` stays `\d`).
253
            _ => { out.push('\\'); i += 1; }
254
        }
255
    }
256
    out
257
}
258
259
/// Parse a `\u`/`\U` escape at the start of `b` with `n` hex digits (4 or 6),
260
/// returning the code point. `b` must begin with `\` then the `u`/`U` marker.
261
/// `None` if there are not `n` hex digits.
262
fn hex_escape(b: &[u8], n: usize) -> Option<u32> {
263
    let digits = b.get(2..2 + n)?;
264
    let mut v = 0u32;
265
    for &c in digits {
266
        v = v * 16 + (c as char).to_digit(16)?;
267
    }
268
    Some(v)
269
}
270
271
/// Map a lexed identifier to its keyword token, if it is one. FEEL keywords are
272
/// reserved words, so a name equal to a keyword is the keyword (longest-match
273
/// already kept `fortune` a name, since this only runs on a complete identifier).
274
fn keyword(name: &str) -> Option<Tok> {
275
    Some(match name {
276
        "for" => Tok::For,
277
        "in" => Tok::In,
278
        "return" => Tok::Return,
279
        "if" => Tok::If,
280
        "then" => Tok::Then,
281
        "else" => Tok::Else,
282
        "some" => Tok::Some,
283
        "every" => Tok::Every,
284
        "satisfies" => Tok::Satisfies,
285
        "or" => Tok::Or,
286
        "and" => Tok::And,
287
        "between" => Tok::Between,
288
        "true" => Tok::True,
289
        "false" => Tok::False,
290
        "null" => Tok::Null,
291
        "not" => Tok::Not,
292
        "function" => Tok::Function,
293
        _ => return None,
294
    })
295
}
296
297
/// One `(start, token, end)` triple, or a lex error for an unrecognised char.
298
type Spanned = Result<(usize, Tok, usize), LexError>;
299
300
/// Token stream for the lalrpop parser: `(start, token, end)` byte offsets, with
301
/// lexed identifiers remapped to keyword tokens and multi-word FEEL names joined.
302
/// A lex error becomes the `Err` arm, which lalrpop reports as a `ParseError::User`.
303
pub(crate) fn lex(input: &str) -> impl Iterator<Item = Spanned> {
304
    // Pass 1: raw `logos` tokens, with identifiers remapped to keyword tokens.
305
    let raw: Vec<Spanned> = Tok::lexer(input)
306
        .spanned()
307
        .map(|(tok, span)| {
308
            let tok = tok?;
309
            let tok = match &tok {
310
                Tok::Name(name) => keyword(name).unwrap_or(tok),
311
                _ => tok,
312
            };
313
            Ok((span.start, tok, span.end))
314
        })
315
        .collect();
316
    // Pass 1.5: fuse the `instance` `of` pair into a single operator token *before*
317
    // name-joining, so the surrounding words don't merge across it and a lone `of`
318
    // (`year of birth`, the `day of week` built-in) stays an ordinary name-word.
319
    let raw = mark_instance_of(raw);
320
    // Pass 2: join multi-word names into single `Name` tokens (ADR-17).
321
    let raw = join_names(raw);
322
    // Pass 3: retag a reverse-open interval opener `]a..b]` to `RBracketOpen` (runs
323
    // last so it sees joined `Name` tokens when classifying value-completed position).
324
    mark_reverse_open(raw).into_iter()
325
}
326
327
/// Retag every `]` that *opens* a reverse-bracket interval (`]a..b]`, FEEL's
328
/// exclusive-lower-bound spelling of `(a..b]`) as a distinct [`Tok::RBracketOpen`],
329
/// so the grammar can admit it as a range-literal opener. `]` otherwise plays only
330
/// the closer role; letting one terminal be both closer and primary opener is not
331
/// LR(1)-resolvable (the empty list `[]` collides with `[` then a reverse-open `]`).
332
///
333
/// A `]` opens iff it is in **value-expected** position — the previous token does not
334
/// complete a value (start of input, or after an operator / `(` / `[` / `,` / `..` /
335
/// keyword) — **and** a `..` follows at the same bracket depth before the group
336
/// closes (the shape of a reverse-open interval; see [`reverse_open_ahead`]). Every
337
/// other `]` — a list/filter/interval close, and the empty list `[]` (no `..` ahead)
338
/// — stays an ordinary `RBracket`. Lex errors reset the position to value-expected.
339
fn mark_reverse_open(toks: Vec<Spanned>) -> Vec<Spanned> {
340
    let mut out = toks;
341
    let mut prev_ends_value = false;
342
    for i in 0..out.len() {
343
        let Ok((start, tok, end)) = &out[i] else {
344
            prev_ends_value = false;
345
            continue;
346
        };
347
        if matches!(tok, Tok::RBracket) && !prev_ends_value && reverse_open_ahead(&out, i + 1) {
348
            let (start, end) = (*start, *end);
349
            out[i] = Ok((start, Tok::RBracketOpen, end));
350
            // An opener does not complete a value: the start endpoint follows.
351
            prev_ends_value = false;
352
        } else {
353
            prev_ends_value = ends_value(tok);
354
        }
355
    }
356
    out
357
}
358
359
/// Whether a token in this position completes a value, so a following `]` is a
360
/// *closer* (not a reverse-open opener). True for the value-producing terminals and
361
/// the three closing brackets; false for operators, openers, separators and keywords.
362
fn ends_value(tok: &Tok) -> bool {
363
    matches!(
364
        tok,
365
        Tok::Num(_)
366
            | Tok::Str(_)
367
            | Tok::TemporalLit(_)
368
            | Tok::Name(_)
369
            | Tok::True
370
            | Tok::False
371
            | Tok::Null
372
            | Tok::RParen
373
            | Tok::RBracket
374
            | Tok::RBrace
375
    )
376
}
377
378
/// Scan forward from `from` (just past a candidate opener `]`) for the `..` that
379
/// makes it a reverse-open interval. Returns true on a `..` at bracket depth 0; false
380
/// on a depth-0 `,` (a list separator), a closer that pops above the start depth, a
381
/// lex error, or end of input — none of which fit `] endpoint .. endpoint close`.
382
fn reverse_open_ahead(toks: &[Spanned], from: usize) -> bool {
383
    let mut depth: i32 = 0;
384
    for t in &toks[from..] {
385
        let Ok((_, tok, _)) = t else {
386
            return false;
387
        };
388
        match tok {
389
            Tok::LParen | Tok::LBracket | Tok::LBrace | Tok::RBracketOpen => depth += 1,
390
            Tok::DotDot if depth == 0 => return true,
391
            Tok::Comma if depth == 0 => return false,
392
            Tok::RParen | Tok::RBracket | Tok::RBrace => {
393
                if depth == 0 {
394
                    return false;
395
                }
396
                depth -= 1;
397
            }
398
            _ => {}
399
        }
400
    }
401
    false
402
}
403
404
/// Replace every adjacent `Name("instance")` `Name("of")` pair with a single
405
/// [`Tok::InstanceOf`] operator token (ADR-26). `instance of` is a reserved operator
406
/// sequence in FEEL, so this is unambiguous; a lone `instance` or `of` is left as a
407
/// `Name` word and joins into its neighbours normally. The fused token spans from the
408
/// start of `instance` to the end of `of`.
409
fn mark_instance_of(toks: Vec<Spanned>) -> Vec<Spanned> {
410
    let mut out: Vec<Spanned> = Vec::with_capacity(toks.len());
411
    let mut i = 0;
412
    while i < toks.len() {
413
        if let (Ok((start, Tok::Name(a), _)), Some(Ok((_, Tok::Name(b), end)))) =
414
            (&toks[i], toks.get(i + 1))
415
        {
416
            if a == "instance" && b == "of" {
417
                out.push(Ok((*start, Tok::InstanceOf, *end)));
418
                i += 2;
419
                continue;
420
            }
421
        }
422
        out.push(toks[i].clone());
423
        i += 1;
424
    }
425
    out
426
}
427
428
/// Collapse multi-word FEEL names into single `Name` tokens. Two tiers, both
429
/// sound without scope knowledge because FEEL has no juxtaposition of two
430
/// expressions:
431
///
432
/// - **Tier 1:** a run of adjacent `Name` tokens (keywords are separate tokens
433
///   and stop the run) is one name — `string length`, `full name`. Payloads are
434
///   joined with a single space.
435
/// - **Tier 2:** a fixed dictionary of *keyword-containing* reserved phrases
436
///   ([`crate::builtins::KEYWORD_PHRASE_BUILTINS`], e.g. `date and time`) is
437
///   recognised **wherever it occurs** (ADR-26). This is the bounded "reserved-name
438
///   exception": the set is finite and holds only FEEL temporal type/constructor
439
///   names, never user variables, so no name oracle is needed — and it lets these
440
///   names appear as `instance of` types (`… instance of date and time`), not just
441
///   call heads.
442
fn join_names(toks: Vec<Spanned>) -> Vec<Spanned> {
443
    let mut out: Vec<Spanned> = Vec::with_capacity(toks.len());
444
    let mut i = 0;
445
    while i < toks.len() {
446
        // Errors and non-name tokens that don't start a phrase pass straight through.
447
        let Ok((start, tok, end)) = &toks[i] else {
448
            out.push(toks[i].clone());
449
            i += 1;
450
            continue;
451
        };
452
        // Tier 2 first: a known keyword-phrase builtin would otherwise be split
453
        // by Tier 1 at its keyword (`date` | `and` | `time`).
454
        if let Some((payload, span_end, next)) = match_keyword_phrase(&toks, i) {
455
            out.push(Ok((*start, Tok::Name(payload), span_end)));
456
            i = next;
457
            continue;
458
        }
459
        // Tier 1: greedily merge a run of adjacent `Name` tokens.
460
        if let Tok::Name(first) = tok {
461
            let run_start = *start;
462
            let mut words = first.clone();
463
            let mut run_end = *end;
464
            let mut j = i + 1;
465
            while let Some(Ok((_, Tok::Name(next), e))) = toks.get(j) {
466
                words.push(' ');
467
                words.push_str(next);
468
                run_end = *e;
469
                j += 1;
470
            }
471
            out.push(Ok((run_start, Tok::Name(words), run_end)));
472
            i = j;
473
            continue;
474
        }
475
        out.push(toks[i].clone());
476
        i += 1;
477
    }
478
    out
479
}
480
481
/// If a fixed keyword-phrase name matches the tokens starting at `i`, return its
482
/// joined payload, the byte offset where the phrase ends, and the index of the
483
/// first token after it. The match is **unconditional** (not gated on a following
484
/// `(`): these phrases are FEEL's reserved temporal type/constructor names, atomic
485
/// wherever they occur (ADR-26), so joining them here lets them serve both as a
486
/// call head (`date and time(…)`) and as an `instance of` type (`… instance of date
487
/// and time`). The phrases share no prefix, so iteration order is irrelevant.
488
fn match_keyword_phrase(toks: &[Spanned], i: usize) -> Option<(String, usize, usize)> {
489
    for phrase in crate::builtins::KEYWORD_PHRASE_BUILTINS {
490
        let words: Vec<&str> = phrase.split(' ').collect();
491
        let after = i + words.len();
492
        // Need the whole phrase to fit in the remaining tokens.
493
        if after > toks.len() {
494
            continue;
495
        }
496
        let mut end = 0;
497
        let matched = words
498
            .iter()
499
            .enumerate()
500
            .all(|(k, word)| match &toks[i + k] {
501
                Ok((_, tok, e)) if tok_word(tok) == Some(*word) => {
502
                    end = *e;
503
                    true
504
                }
505
                _ => false,
506
            });
507
        if matched {
508
            return Some(((*phrase).to_string(), end, after));
509
        }
510
    }
511
    None
512
}
513
514
/// The "word" a token contributes to a multi-word name: an identifier's text, or
515
/// a keyword's spelling (so phrase matching can see the `and` in `date and time`).
516
/// Operators and punctuation are not words.
517
fn tok_word(tok: &Tok) -> Option<&str> {
518
    Some(match tok {
519
        Tok::Name(s) => s.as_str(),
520
        Tok::For => "for",
521
        Tok::In => "in",
522
        Tok::Return => "return",
523
        Tok::If => "if",
524
        Tok::Then => "then",
525
        Tok::Else => "else",
526
        Tok::Some => "some",
527
        Tok::Every => "every",
528
        Tok::Satisfies => "satisfies",
529
        Tok::Or => "or",
530
        Tok::And => "and",
531
        Tok::Between => "between",
532
        Tok::True => "true",
533
        Tok::False => "false",
534
        Tok::Null => "null",
535
        Tok::Not => "not",
536
        Tok::Function => "function",
537
        _ => return None,
538
    })
539
}
540
541
impl fmt::Display for Tok {
542
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
543
        let s = match self {
544
            Tok::For => "for",
545
            Tok::In => "in",
546
            Tok::Return => "return",
547
            Tok::If => "if",
548
            Tok::Then => "then",
549
            Tok::Else => "else",
550
            Tok::Some => "some",
551
            Tok::Every => "every",
552
            Tok::Satisfies => "satisfies",
553
            Tok::Or => "or",
554
            Tok::And => "and",
555
            Tok::Between => "between",
556
            Tok::True => "true",
557
            Tok::False => "false",
558
            Tok::Null => "null",
559
            Tok::Not => "not",
560
            Tok::Function => "function",
561
            Tok::InstanceOf => "instance of",
562
            Tok::Le => "<=",
563
            Tok::Lt => "<",
564
            Tok::Ge => ">=",
565
            Tok::Gt => ">",
566
            Tok::Eq => "=",
567
            Tok::Ne => "!=",
568
            Tok::Plus => "+",
569
            Tok::Arrow => "->",
570
            Tok::Minus => "-",
571
            Tok::StarStar => "**",
572
            Tok::Star => "*",
573
            Tok::Slash => "/",
574
            Tok::DotDotDot => "...",
575
            Tok::DotDot => "..",
576
            Tok::Dot => ".",
577
            Tok::LParen => "(",
578
            Tok::RParen => ")",
579
            Tok::LBracket => "[",
580
            Tok::RBracket => "]",
581
            Tok::RBracketOpen => "]",
582
            Tok::LBrace => "{",
583
            Tok::RBrace => "}",
584
            Tok::Comma => ",",
585
            Tok::Colon => ":",
586
            Tok::Num(n) => return write!(f, "{n}"),
587
            Tok::Str(s) => return write!(f, "{s:?}"),
588
            Tok::TemporalLit(s) => return write!(f, "@{s:?}"),
589
            Tok::Name(s) => return write!(f, "{s}"),
590
            Tok::Comment => unreachable!("Comment is logos::skip — never emitted"),
591
        };
592
        f.write_str(s)
593
    }
594
}