Public repository: timo / feel

Reader

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

feel / crates / feel-core / src / lexer.rs · 32.4 KB · at 93b43c1c833b · raw

Outline: 33 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
//! Beyond spaces, grammar rules 25–30 let a name contain the *additional name
26
//! symbols* `- + * / .` — `a-b`, `Date-Time`, `x.y` — which are indistinguishable
27
//! from arithmetic/paths at the token level. §10.3.1.6 resolves this against the
28
//! **scope**: left to right, longest in-scope match preferred, spaces not part of
29
//! the name (`a - b` is the same candidate as `a-b`), and `(a)-(b)` the escape
30
//! hatch. A probe-gated pass ([`fuse_special_names`], ADR-47) runs *after*
31
//! `join_names` (so a multi-word part like `total price` is already one word
32
//! unit) and consults the [`crate::ScopeProbe`] oracle before fusing a run;
33
//! without a probe the pass is a no-op, so `compile` stays byte-identical.
34
//!
35
//! Java-style comments (`// … \n` and `/* … */`) are skipped at the logos level
36
//! (pass 1). `logos` maximal munch makes `//` / `/*` win over the single `/`
37
//! (`Slash`), so a bare `/` used as division or in `->` is unaffected.
38
39
use core::fmt;
40
41
use logos::Logos;
42
43
/// A lexer error. The grammar maps this to a `ParseError::User`, which surfaces
44
/// as a [`crate::FeelError::Parse`] — the same outcome the old regex lexer gave
45
/// for an unrecognised character.
46
#[derive(Default, Debug, Clone, PartialEq, Eq)]
47
pub struct LexError;
48
49
impl fmt::Display for LexError {
50
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
51
        f.write_str("invalid token")
52
    }
53
}
54
55
/// The FEEL token set. Keywords/operators/punctuation are unit variants; the
56
/// three value-carrying terminals (`Num`/`Str`/`Name`) carry their parsed payload.
57
///
58
/// Word keywords are produced via [`lex`]'s [`keyword`] remap of a lexed `Name`,
59
/// not by `logos`, so identifier maximal-munch is preserved.
60
#[derive(Logos, Clone, Debug, PartialEq)]
61
#[logos(skip r"[ \t\r\n]+", error = LexError)]
62
pub enum Tok {
63
    // FEEL Java-style comments — skipped at the logos level (never emitted).
64
    // Maximal munch: `//`/`/*` beat the 1-char `/` Slash, so bare `/` is unaffected.
65
    #[regex(r"//[^\n]*", logos::skip, priority = 5, allow_greedy = true)]
66
    #[regex(r"/\*([^*]|\*[^/])*\*/", logos::skip, priority = 5)]
67
    Comment,
68
69
    // --- word keywords (never emitted by logos directly; see `keyword`) ---
70
    For,
71
    In,
72
    Return,
73
    If,
74
    Then,
75
    Else,
76
    Some,
77
    Every,
78
    Satisfies,
79
    Or,
80
    And,
81
    Between,
82
    True,
83
    False,
84
    Null,
85
    Not,
86
    Function,
87
    // The two-word `instance of` operator. `instance` and `of` are NOT reserved
88
    // words (FEEL names may contain them — `year of birth`, the `day of week`
89
    // built-in), so this is emitted only for the adjacent `instance` `of` pair by a
90
    // dedicated lexer pass ([`mark_instance_of`]), never by `keyword`.
91
    InstanceOf,
92
93
    // --- operators (longer forms listed first so the intent is obvious; logos
94
    //     does maximal munch regardless, so `<=` beats `<`, `**` beats `*`) ---
95
    #[token("<=")]
96
    Le,
97
    #[token("<")]
98
    Lt,
99
    #[token(">=")]
100
    Ge,
101
    #[token(">")]
102
    Gt,
103
    #[token("=")]
104
    Eq,
105
    #[token("!=")]
106
    Ne,
107
    #[token("+")]
108
    Plus,
109
    // `->` (function-type arrow) before `-`: only appears literally in a
110
    // `function<…> -> T` type, and logos maximal-munch picks it over `-` `>`.
111
    #[token("->")]
112
    Arrow,
113
    #[token("-")]
114
    Minus,
115
    #[token("**")]
116
    StarStar,
117
    #[token("*")]
118
    Star,
119
    #[token("/")]
120
    Slash,
121
    #[token("...")]
122
    DotDotDot,
123
    #[token("..")]
124
    DotDot,
125
    #[token(".")]
126
    Dot,
127
128
    // --- punctuation ---
129
    #[token("(")]
130
    LParen,
131
    #[token(")")]
132
    RParen,
133
    #[token("[")]
134
    LBracket,
135
    #[token("]")]
136
    RBracket,
137
    // A `]` that *opens* a reverse-bracket interval `]a..b]` (the exclusive-lower
138
    // notation for `(a..b]`). Never emitted by logos — `]` always lexes as
139
    // `RBracket`; a post-pass ([`mark_reverse_open`]) retags the opening role to this
140
    // distinct token. Without the split, `]` would be both a closer and a primary
141
    // opener, which is not LR(1)-resolvable (the empty list `[]` collides with `[`
142
    // then a reverse-open `]`; see ROADMAP).
143
    RBracketOpen,
144
    #[token("{")]
145
    LBrace,
146
    #[token("}")]
147
    RBrace,
148
    #[token(",")]
149
    Comma,
150
    #[token(":")]
151
    Colon,
152
153
    // --- value-carrying terminals ---
154
    // FEEL grammar rule 35 / §10.3.2.3.1: a numeric literal is an optional
155
    // leading-dot mantissa OR a digit-led mantissa, with an optional exponent.
156
    // The leading-dot branch (`\.[0-9]+`) requires at least one digit after the
157
    // dot, so it never overlaps with `..` (DotDot, two chars) or a lone `.`
158
    // (Dot, one char); logos's maximal-munch resolves any tie. Negatives are
159
    // produced by unary minus over the literal — there is no signed-literal token.
160
    #[regex(r"([0-9]+(\.[0-9]+)?|\.[0-9]+)([eE][+-]?[0-9]+)?", |lex| lex.slice().parse::<f64>().ok())]
161
    Num(f64),
162
163
    // A double-quoted string. The body is any run of non-quote/non-backslash
164
    // characters and backslash-escapes (`\\.`), so an escaped quote `\"` does not
165
    // end the literal. `decode_string_escapes` then resolves the FEEL escapes
166
    // (`\n \r \t \" \' \\`, `\uXXXX` incl. surrogate pairs, `\UXXXXXX`); an
167
    // unrecognised escape (e.g. a regex `\d`) is left verbatim (DMN §10.3.1.2).
168
    #[regex(r#""([^"\\]|\\.)*""#, |lex| { let s = lex.slice(); decode_string_escapes(&s[1..s.len() - 1]) })]
169
    Str(String),
170
171
    // A temporal literal `@"…"` (ADR-18). Carries the inner text; the type is
172
    // resolved by the evaluator from its lexical form. A value token like `Str`,
173
    // so `join_names` leaves it alone.
174
    #[regex(r#"@"[^"]*""#, |lex| { let s = lex.slice(); s[2..s.len() - 1].to_string() })]
175
    TemporalLit(String),
176
177
    // Lead char: ASCII letter / underscore / any non-ASCII scalar (a cheap range,
178
    // no Unicode tables). `lex_name` then validates it as an XID start and extends
179
    // over XID-continue characters. Keywords are remapped out of this in `lex`.
180
    #[regex(r"[A-Za-z_\u{80}-\u{10FFFF}]", lex_name)]
181
    Name(String),
182
}
183
184
/// Validate the already-matched lead character as an identifier start and extend
185
/// the token over the following XID-continue characters. Returns `None` (a lex
186
/// error) when the lead is a non-ASCII, non-identifier scalar (e.g. `€`, `±`).
187
fn lex_name(lex: &mut logos::Lexer<'_, Tok>) -> Option<String> {
188
    let first = lex.slice().chars().next()?;
189
    if first != '_' && !unicode_ident::is_xid_start(first) {
190
        return None;
191
    }
192
    let mut extra = 0;
193
    for c in lex.remainder().chars() {
194
        if c == '_' || unicode_ident::is_xid_continue(c) {
195
            extra += c.len_utf8();
196
        } else {
197
            break;
198
        }
199
    }
200
    lex.bump(extra);
201
    Some(lex.slice().to_string())
202
}
203
204
/// Resolve the FEEL string escapes in a string literal's body (the text between
205
/// the quotes), per DMN §10.3.1.2: `\n \r \t \" \' \\`, a `\uXXXX` 4-hex code unit
206
/// (consecutive high+low surrogates combine into one code point), and a `\UXXXXXX`
207
/// 6-hex code point. An unrecognised escape (e.g. a regex metacharacter like `\d`,
208
/// `\s`, `\3`) is preserved verbatim — feel-core does not own the regex dialect
209
/// (ADR-16), so such backslashes must reach the provider untouched. A malformed
210
/// `\u`/`\U` or a lone surrogate likewise falls back to copying the backslash.
211
fn decode_string_escapes(body: &str) -> String {
212
    // Fast path: nothing to decode.
213
    if !body.contains('\\') {
214
        return body.to_string();
215
    }
216
    let b = body.as_bytes();
217
    let mut out = String::with_capacity(body.len());
218
    let mut i = 0;
219
    while i < b.len() {
220
        if b[i] != b'\\' {
221
            // Copy one whole UTF-8 scalar (the byte at `i` starts a char).
222
            let ch = body[i..].chars().next().expect("char boundary");
223
            out.push(ch);
224
            i += ch.len_utf8();
225
            continue;
226
        }
227
        match b.get(i + 1) {
228
            Some(b'n') => { out.push('\n'); i += 2; }
229
            Some(b'r') => { out.push('\r'); i += 2; }
230
            Some(b't') => { out.push('\t'); i += 2; }
231
            Some(b'"') => { out.push('"'); i += 2; }
232
            Some(b'\'') => { out.push('\''); i += 2; }
233
            Some(b'\\') => { out.push('\\'); i += 2; }
234
            Some(b'u') => match hex_escape(&b[i..], 4) {
235
                Some(cp) if (0xD800..=0xDBFF).contains(&cp) => {
236
                    // High surrogate: pair it with a following low surrogate.
237
                    match hex_escape(&b[i + 6..], 4) {
238
                        Some(lo) if (0xDC00..=0xDFFF).contains(&lo) => {
239
                            let c = 0x1_0000 + ((cp - 0xD800) << 10) + (lo - 0xDC00);
240
                            out.push(char::from_u32(c).unwrap_or('\u{FFFD}'));
241
                            i += 12;
242
                        }
243
                        // Lone high surrogate: keep the backslash verbatim.
244
                        _ => { out.push('\\'); i += 1; }
245
                    }
246
                }
247
                // Lone low surrogate or unmappable: keep the backslash verbatim.
248
                Some(cp) => match char::from_u32(cp) {
249
                    Some(ch) => { out.push(ch); i += 6; }
250
                    None => { out.push('\\'); i += 1; }
251
                },
252
                None => { out.push('\\'); i += 1; }
253
            },
254
            Some(b'U') => match hex_escape(&b[i..], 6) {
255
                Some(cp) => match char::from_u32(cp) {
256
                    Some(ch) => { out.push(ch); i += 8; }
257
                    None => { out.push('\\'); i += 1; }
258
                },
259
                None => { out.push('\\'); i += 1; }
260
            },
261
            // Unknown escape or trailing backslash: keep the backslash verbatim and
262
            // reprocess the next byte normally (so `\d` stays `\d`).
263
            _ => { out.push('\\'); i += 1; }
264
        }
265
    }
266
    out
267
}
268
269
/// Parse a `\u`/`\U` escape at the start of `b` with `n` hex digits (4 or 6),
270
/// returning the code point. `b` must begin with `\` then the `u`/`U` marker.
271
/// `None` if there are not `n` hex digits.
272
fn hex_escape(b: &[u8], n: usize) -> Option<u32> {
273
    let digits = b.get(2..2 + n)?;
274
    let mut v = 0u32;
275
    for &c in digits {
276
        v = v * 16 + (c as char).to_digit(16)?;
277
    }
278
    Some(v)
279
}
280
281
/// Map a lexed identifier to its keyword token, if it is one. FEEL keywords are
282
/// reserved words, so a name equal to a keyword is the keyword (longest-match
283
/// already kept `fortune` a name, since this only runs on a complete identifier).
284
fn keyword(name: &str) -> Option<Tok> {
285
    Some(match name {
286
        "for" => Tok::For,
287
        "in" => Tok::In,
288
        "return" => Tok::Return,
289
        "if" => Tok::If,
290
        "then" => Tok::Then,
291
        "else" => Tok::Else,
292
        "some" => Tok::Some,
293
        "every" => Tok::Every,
294
        "satisfies" => Tok::Satisfies,
295
        "or" => Tok::Or,
296
        "and" => Tok::And,
297
        "between" => Tok::Between,
298
        "true" => Tok::True,
299
        "false" => Tok::False,
300
        "null" => Tok::Null,
301
        "not" => Tok::Not,
302
        "function" => Tok::Function,
303
        _ => return None,
304
    })
305
}
306
307
/// One `(start, token, end)` triple, or a lex error for an unrecognised char.
308
type Spanned = Result<(usize, Tok, usize), LexError>;
309
310
/// Token stream for the lalrpop parser: `(start, token, end)` byte offsets, with
311
/// lexed identifiers remapped to keyword tokens, multi-word FEEL names joined,
312
/// and — only when a scope probe is supplied — special-character name runs fused
313
/// (§10.3.1.6, ADR-47). A lex error becomes the `Err` arm, which lalrpop reports
314
/// as a `ParseError::User`.
315
pub(crate) fn lex(input: &str) -> impl Iterator<Item = Spanned> {
316
    lex_pipeline(input, None).0.into_iter()
317
}
318
319
/// The probe-aware pipeline: like [`lex`], but runs the §10.3.1.6 name-run
320
/// fusion against `probe`. Returns the tokens plus whether any special-character
321
/// run was seen (fused or not) — i.e. this parse consulted the scope (ADR-47).
322
pub(crate) fn lex_with_probe(
323
    input: &str,
324
    probe: &dyn crate::ScopeProbe,
325
) -> (impl Iterator<Item = Spanned>, bool) {
326
    let (toks, name_runs) = lex_pipeline(input, Some(probe));
327
    (toks.into_iter(), name_runs)
328
}
329
330
/// The full multi-pass pipeline, probe optional. Pass 1 lexes with `logos` and
331
/// remaps keywords; 1.5 fuses the `instance of` operator; 2 joins multi-word
332
/// names; 2.5 (only with a probe) fuses special-character name runs; 3 retags
333
/// reverse-open interval openers.
334
fn lex_pipeline(input: &str, probe: Option<&dyn crate::ScopeProbe>) -> (Vec<Spanned>, bool) {
335
    // `lex_joined` runs passes 1 + 1.5 (keywords, `instance of`); pass 2 joins
336
    // multi-word names on its output; the fusion pass 2.5 must see the joined
337
    // word units (`total price-total`), and pass 3 must classify `]` against
338
    // fused names (they complete a value).
339
    let raw = join_names(lex_joined(input));
340
    let (raw, name_runs) = match probe {
341
        Some(probe) => fuse_special_names(raw, probe),
342
        None => (raw, false),
343
    };
344
    (mark_reverse_open(raw), name_runs)
345
}
346
347
/// Passes 1 + 1.5: raw `logos` tokens with identifiers remapped to keyword
348
/// tokens, then the `instance of` operator fused. Shared by the token pipeline
349
/// and the probe-free candidate scan ([`name_run_candidates`]).
350
fn lex_joined(input: &str) -> Vec<Spanned> {
351
    let raw: Vec<Spanned> = Tok::lexer(input)
352
        .spanned()
353
        .map(|(tok, span)| {
354
            let tok = tok?;
355
            let tok = match &tok {
356
                Tok::Name(name) => keyword(name).unwrap_or(tok),
357
                _ => tok,
358
            };
359
            Ok((span.start, tok, span.end))
360
        })
361
        .collect();
362
    mark_instance_of(raw)
363
}
364
365
/// Retag every `]` that *opens* a reverse-bracket interval (`]a..b]`, FEEL's
366
/// exclusive-lower-bound spelling of `(a..b]`) as a distinct [`Tok::RBracketOpen`],
367
/// so the grammar can admit it as a range-literal opener. `]` otherwise plays only
368
/// the closer role; letting one terminal be both closer and primary opener is not
369
/// LR(1)-resolvable (the empty list `[]` collides with `[` then a reverse-open `]`).
370
///
371
/// A `]` opens iff it is in **value-expected** position — the previous token does not
372
/// complete a value (start of input, or after an operator / `(` / `[` / `,` / `..` /
373
/// keyword) — **and** a `..` follows at the same bracket depth before the group
374
/// closes (the shape of a reverse-open interval; see [`reverse_open_ahead`]). Every
375
/// other `]` — a list/filter/interval close, and the empty list `[]` (no `..` ahead)
376
/// — stays an ordinary `RBracket`. Lex errors reset the position to value-expected.
377
fn mark_reverse_open(toks: Vec<Spanned>) -> Vec<Spanned> {
378
    let mut out = toks;
379
    let mut prev_ends_value = false;
380
    for i in 0..out.len() {
381
        let Ok((start, tok, end)) = &out[i] else {
382
            prev_ends_value = false;
383
            continue;
384
        };
385
        if matches!(tok, Tok::RBracket) && !prev_ends_value && reverse_open_ahead(&out, i + 1) {
386
            let (start, end) = (*start, *end);
387
            out[i] = Ok((start, Tok::RBracketOpen, end));
388
            // An opener does not complete a value: the start endpoint follows.
389
            prev_ends_value = false;
390
        } else {
391
            prev_ends_value = ends_value(tok);
392
        }
393
    }
394
    out
395
}
396
397
/// Whether a token in this position completes a value, so a following `]` is a
398
/// *closer* (not a reverse-open opener). True for the value-producing terminals and
399
/// the three closing brackets; false for operators, openers, separators and keywords.
400
fn ends_value(tok: &Tok) -> bool {
401
    matches!(
402
        tok,
403
        Tok::Num(_)
404
            | Tok::Str(_)
405
            | Tok::TemporalLit(_)
406
            | Tok::Name(_)
407
            | Tok::True
408
            | Tok::False
409
            | Tok::Null
410
            | Tok::RParen
411
            | Tok::RBracket
412
            | Tok::RBrace
413
    )
414
}
415
416
/// Scan forward from `from` (just past a candidate opener `]`) for the `..` that
417
/// makes it a reverse-open interval. Returns true on a `..` at bracket depth 0; false
418
/// on a depth-0 `,` (a list separator), a closer that pops above the start depth, a
419
/// lex error, or end of input — none of which fit `] endpoint .. endpoint close`.
420
fn reverse_open_ahead(toks: &[Spanned], from: usize) -> bool {
421
    let mut depth: i32 = 0;
422
    for t in &toks[from..] {
423
        let Ok((_, tok, _)) = t else {
424
            return false;
425
        };
426
        match tok {
427
            Tok::LParen | Tok::LBracket | Tok::LBrace | Tok::RBracketOpen => depth += 1,
428
            Tok::DotDot if depth == 0 => return true,
429
            Tok::Comma if depth == 0 => return false,
430
            Tok::RParen | Tok::RBracket | Tok::RBrace => {
431
                if depth == 0 {
432
                    return false;
433
                }
434
                depth -= 1;
435
            }
436
            _ => {}
437
        }
438
    }
439
    false
440
}
441
442
/// Replace every adjacent `Name("instance")` `Name("of")` pair with a single
443
/// [`Tok::InstanceOf`] operator token (ADR-26). `instance of` is a reserved operator
444
/// sequence in FEEL, so this is unambiguous; a lone `instance` or `of` is left as a
445
/// `Name` word and joins into its neighbours normally. The fused token spans from the
446
/// start of `instance` to the end of `of`.
447
fn mark_instance_of(toks: Vec<Spanned>) -> Vec<Spanned> {
448
    let mut out: Vec<Spanned> = Vec::with_capacity(toks.len());
449
    let mut i = 0;
450
    while i < toks.len() {
451
        if let (Ok((start, Tok::Name(a), _)), Some(Ok((_, Tok::Name(b), end)))) =
452
            (&toks[i], toks.get(i + 1))
453
        {
454
            if a == "instance" && b == "of" {
455
                out.push(Ok((*start, Tok::InstanceOf, *end)));
456
                i += 2;
457
                continue;
458
            }
459
        }
460
        out.push(toks[i].clone());
461
        i += 1;
462
    }
463
    out
464
}
465
466
/// Collapse multi-word FEEL names into single `Name` tokens. Two tiers, both
467
/// sound without scope knowledge because FEEL has no juxtaposition of two
468
/// expressions:
469
///
470
/// - **Tier 1:** a run of adjacent `Name` tokens (keywords are separate tokens
471
///   and stop the run) is one name — `string length`, `full name`. Payloads are
472
///   joined with a single space.
473
/// - **Tier 2:** a fixed dictionary of *keyword-containing* reserved phrases
474
///   ([`crate::builtins::KEYWORD_PHRASE_BUILTINS`], e.g. `date and time`) is
475
///   recognised **wherever it occurs** (ADR-26). This is the bounded "reserved-name
476
///   exception": the set is finite and holds only FEEL temporal type/constructor
477
///   names, never user variables, so no name oracle is needed — and it lets these
478
///   names appear as `instance of` types (`… instance of date and time`), not just
479
///   call heads.
480
fn join_names(toks: Vec<Spanned>) -> Vec<Spanned> {
481
    let mut out: Vec<Spanned> = Vec::with_capacity(toks.len());
482
    let mut i = 0;
483
    while i < toks.len() {
484
        // Errors and non-name tokens that don't start a phrase pass straight through.
485
        let Ok((start, tok, end)) = &toks[i] else {
486
            out.push(toks[i].clone());
487
            i += 1;
488
            continue;
489
        };
490
        // Tier 2 first: a known keyword-phrase builtin would otherwise be split
491
        // by Tier 1 at its keyword (`date` | `and` | `time`).
492
        if let Some((payload, span_end, next)) = match_keyword_phrase(&toks, i) {
493
            out.push(Ok((*start, Tok::Name(payload), span_end)));
494
            i = next;
495
            continue;
496
        }
497
        // Tier 1: greedily merge a run of adjacent `Name` tokens.
498
        if let Tok::Name(first) = tok {
499
            let run_start = *start;
500
            let mut words = first.clone();
501
            let mut run_end = *end;
502
            let mut j = i + 1;
503
            while let Some(Ok((_, Tok::Name(next), e))) = toks.get(j) {
504
                words.push(' ');
505
                words.push_str(next);
506
                run_end = *e;
507
                j += 1;
508
            }
509
            out.push(Ok((run_start, Tok::Name(words), run_end)));
510
            i = j;
511
            continue;
512
        }
513
        out.push(toks[i].clone());
514
        i += 1;
515
    }
516
    out
517
}
518
519
/// If a fixed keyword-phrase name matches the tokens starting at `i`, return its
520
/// joined payload, the byte offset where the phrase ends, and the index of the
521
/// first token after it. The match is **unconditional** (not gated on a following
522
/// `(`): these phrases are FEEL's reserved temporal type/constructor names, atomic
523
/// wherever they occur (ADR-26), so joining them here lets them serve both as a
524
/// call head (`date and time(…)`) and as an `instance of` type (`… instance of date
525
/// and time`). The phrases share no prefix, so iteration order is irrelevant.
526
fn match_keyword_phrase(toks: &[Spanned], i: usize) -> Option<(String, usize, usize)> {
527
    for phrase in crate::builtins::KEYWORD_PHRASE_BUILTINS {
528
        let words: Vec<&str> = phrase.split(' ').collect();
529
        let after = i + words.len();
530
        // Need the whole phrase to fit in the remaining tokens.
531
        if after > toks.len() {
532
            continue;
533
        }
534
        let mut end = 0;
535
        let matched = words
536
            .iter()
537
            .enumerate()
538
            .all(|(k, word)| match &toks[i + k] {
539
                Ok((_, tok, e)) if tok_word(tok) == Some(*word) => {
540
                    end = *e;
541
                    true
542
                }
543
                _ => false,
544
            });
545
        if matched {
546
            return Some(((*phrase).to_string(), end, after));
547
        }
548
    }
549
    None
550
}
551
552
/// The "word" a token contributes to a multi-word name: an identifier's text, or
553
/// a keyword's spelling (so phrase matching can see the `and` in `date and time`).
554
/// Operators and punctuation are not words.
555
fn tok_word(tok: &Tok) -> Option<&str> {
556
    Some(match tok {
557
        Tok::Name(s) => s.as_str(),
558
        Tok::For => "for",
559
        Tok::In => "in",
560
        Tok::Return => "return",
561
        Tok::If => "if",
562
        Tok::Then => "then",
563
        Tok::Else => "else",
564
        Tok::Some => "some",
565
        Tok::Every => "every",
566
        Tok::Satisfies => "satisfies",
567
        Tok::Or => "or",
568
        Tok::And => "and",
569
        Tok::Between => "between",
570
        Tok::True => "true",
571
        Tok::False => "false",
572
        Tok::Null => "null",
573
        Tok::Not => "not",
574
        Tok::Function => "function",
575
        _ => return None,
576
    })
577
}
578
579
// --------------------------------------------------------------------------- //
580
// Special-character name runs (grammar rules 25–30, §10.3.1.6; ADR-47)
581
// --------------------------------------------------------------------------- //
582
583
/// The additional name symbols (grammar rule 30) a name may contain, as token →
584
/// symbol char. Deliberately excludes the multi-char operators (`..` `...` `**`,
585
/// `->`): only the single-character forms are name symbols, so a range separator
586
/// `x..y`, a descendant `x...y` and an exponent never form a run.
587
fn name_symbol(tok: &Tok) -> Option<char> {
588
    match tok {
589
        Tok::Minus => Some('-'),
590
        Tok::Plus => Some('+'),
591
        Tok::Star => Some('*'),
592
        Tok::Slash => Some('/'),
593
        Tok::Dot => Some('.'),
594
        _ => None,
595
    }
596
}
597
598
/// One word unit of a name run: its spelling and `(byte start, byte end)` span.
599
type RunUnit<'a> = (&'a str, usize, usize);
600
601
/// The word a token contributes to a name run **when the run starts at it**:
602
/// only a `Name`. §10.3.1.4 is explicit — "A name start (grammar rule 26) SHALL
603
/// NOT be a literal terminal symbol" — so no keyword (`if`, `true`, `return`,
604
/// `in`, …) can begin a name, while "a name part MAY be a literal terminal
605
/// symbol": keywords stay legal as *later* run words (`x-in`, `a-if`). Besides
606
/// conformance this keeps spurious candidates out (`return -i` yields no
607
/// `return-i`, which if bound would corrupt the loop parse and, in feel-pg, force
608
/// a per-row re-parse or an IMMUTABLE error; ADR-47).
609
fn run_start_word(tok: &Tok) -> Option<&str> {
610
    match tok {
611
        Tok::Name(s) => Some(s.as_str()),
612
        _ => None,
613
    }
614
}
615
616
/// Scan the maximal special-character name run starting at token `i`:
617
/// `word ((-|+|*|/|.) word)*`, where a later word is a joined `Name` payload or
618
/// a keyword's spelling (`tok_word` — keywords are legal name *parts*,
619
/// §10.3.1.4; `x-in`). The run must START at a `Name` ([`run_start_word`] — a
620
/// name start is never a keyword) that is not a path member — a word
621
/// directly after an unfused `.` resolves against the *structure* the path
622
/// navigates, never against the outer scope, so a root key like `y-z` must not
623
/// turn `x.y-z` into a member access (`x.(y-z)`); it stays `(x.y) - z`.
624
/// Parens, commas, brackets, literals, adjacency (`a and b`) and any other
625
/// token end the run. Returns the per-unit `(word, start, end)` and the
626
/// separator chars. A lone word is not a run — `None`.
627
fn scan_name_run(toks: &[Spanned], i: usize) -> Option<(Vec<RunUnit<'_>>, Vec<char>)> {
628
    // Member position: the previous token is a `.` that no fusion consumed (a
629
    // fused span always ends with a word, so an unfused dot at i-1 is exactly
630
    // the member position; ADR-47).
631
    if i > 0 && matches!(&toks[i - 1], Ok((_, Tok::Dot, _))) {
632
        return None;
633
    }
634
    let (word, start, end) = match &toks[i] {
635
        Ok((s, tok, e)) => (run_start_word(tok)?, *s, *e),
636
        Err(_) => return None,
637
    };
638
    let mut units = vec![(word, start, end)];
639
    let mut seps = Vec::new();
640
    let mut j = i + 1;
641
    loop {
642
        let sep = toks
643
            .get(j)
644
            .and_then(|t| t.as_ref().ok())
645
            .and_then(|(_, t, _)| name_symbol(t));
646
        let Some(sep) = sep else { break };
647
        let next = toks
648
            .get(j + 1)
649
            .and_then(|t| t.as_ref().ok())
650
            .and_then(|(s, t, e)| tok_word(t).map(|w| (w, *s, *e)));
651
        let Some((w, s, e)) = next else { break };
652
        seps.push(sep);
653
        units.push((w, s, e));
654
        j += 2;
655
    }
656
    (units.len() > 1).then_some((units, seps))
657
}
658
659
/// The candidate name a run prefix stands for: the word units joined by their
660
/// separators, verbatim. Spaces are not part of the token sequence (§10.3.1.6),
661
/// so `a - b` and `a-b` produce the same candidate — the separator *characters*
662
/// are part of the name, the whitespace around them is not.
663
fn candidate_payload(units: &[RunUnit<'_>], seps: &[char]) -> String {
664
    let mut payload = units[0].0.to_string();
665
    for ((word, _, _), sep) in units[1..].iter().zip(seps) {
666
        payload.push(*sep);
667
        payload.push_str(word);
668
    }
669
    payload
670
}
671
672
/// Fuse special-character name runs into single `Name` tokens, resolving the
673
/// §10.3.1.6 ambiguity against `probe` (ADR-47). At each word-unit position the
674
/// maximal run is scanned; its prefixes are tried **longest first** against the
675
/// probe, and the first in-scope prefix is fused into one `Name` spanning it.
676
/// Scanning then continues *after* the fused name, so `Date-Time - Date-Time2`
677
/// fuses `Date-Time`, leaves the `-` an operator, and fuses `Date-Time2` — the
678
/// subtraction the TCK expects, reproduced by longest-match-at-each-position.
679
/// When no prefix is in scope the run is left alone (arithmetic stands) and the
680
/// scan resumes at the next token, so `a-b-c` with only `b-c` bound parses as
681
/// `a - b-c`. A keyword word-unit makes reserved-word parts reachable (`x-in`)
682
/// but, without a symbol, adjacency never forms a run (`a and b` is untouched).
683
///
684
/// Returns the tokens plus `true` when any run was seen — the parse consulted
685
/// the scope ([`crate::CompiledExpr::has_name_runs`]).
686
fn fuse_special_names(toks: Vec<Spanned>, probe: &dyn crate::ScopeProbe) -> (Vec<Spanned>, bool) {
687
    let mut out: Vec<Spanned> = Vec::with_capacity(toks.len());
688
    let mut saw_run = false;
689
    let mut i = 0;
690
    while i < toks.len() {
691
        let Some((units, seps)) = scan_name_run(&toks, i) else {
692
            out.push(toks[i].clone());
693
            i += 1;
694
            continue;
695
        };
696
        saw_run = true;
697
        // Candidate prefixes, longest first (§10.3.1.6): only prefixes with at
698
        // least one separator are fusable — a lone word is already one token.
699
        let mut fused = None;
700
        for k in (2..=units.len()).rev() {
701
            let payload = candidate_payload(&units[..k], &seps[..k - 1]);
702
            if probe.contains(&payload) {
703
                fused = Some((k, payload));
704
                break;
705
            }
706
        }
707
        match fused {
708
            Some((k, payload)) => {
709
                let (_, start, _) = units[0];
710
                let (_, _, end) = units[k - 1];
711
                out.push(Ok((start, Tok::Name(payload), end)));
712
                // Skip the fused prefix: k units plus the k-1 separators.
713
                i += 2 * k - 1;
714
            }
715
            None => {
716
                out.push(toks[i].clone());
717
                i += 1;
718
            }
719
        }
720
    }
721
    (out, saw_run)
722
}
723
724
/// Every special-character name candidate `expr` could fuse under *some* scope
725
/// (ADR-47): all ≥2-unit prefixes of every run, from every unit position (so
726
/// `a-b-c` yields `a-b-c`, `a-b` and `b-c`). Probe-free and AST-free — a host
727
/// that caches a probe-free parse across contexts (feel-pg's `fn_extra` slot)
728
/// checks these per context: none bound ⇒ the cached parse is already
729
/// scope-correct; any bound ⇒ re-parse against that context (§10.3.1.6).
730
pub(crate) fn name_run_candidates(input: &str) -> Vec<String> {
731
    let toks = join_names(lex_joined(input));
732
    let mut out = Vec::new();
733
    for i in 0..toks.len() {
734
        if let Some((units, seps)) = scan_name_run(&toks, i) {
735
            // Longest first, mirroring the probe's resolution order (§10.3.1.6).
736
            for k in (2..=units.len()).rev() {
737
                out.push(candidate_payload(&units[..k], &seps[..k - 1]));
738
            }
739
        }
740
    }
741
    out
742
}
743
744
impl fmt::Display for Tok {
745
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
746
        let s = match self {
747
            Tok::For => "for",
748
            Tok::In => "in",
749
            Tok::Return => "return",
750
            Tok::If => "if",
751
            Tok::Then => "then",
752
            Tok::Else => "else",
753
            Tok::Some => "some",
754
            Tok::Every => "every",
755
            Tok::Satisfies => "satisfies",
756
            Tok::Or => "or",
757
            Tok::And => "and",
758
            Tok::Between => "between",
759
            Tok::True => "true",
760
            Tok::False => "false",
761
            Tok::Null => "null",
762
            Tok::Not => "not",
763
            Tok::Function => "function",
764
            Tok::InstanceOf => "instance of",
765
            Tok::Le => "<=",
766
            Tok::Lt => "<",
767
            Tok::Ge => ">=",
768
            Tok::Gt => ">",
769
            Tok::Eq => "=",
770
            Tok::Ne => "!=",
771
            Tok::Plus => "+",
772
            Tok::Arrow => "->",
773
            Tok::Minus => "-",
774
            Tok::StarStar => "**",
775
            Tok::Star => "*",
776
            Tok::Slash => "/",
777
            Tok::DotDotDot => "...",
778
            Tok::DotDot => "..",
779
            Tok::Dot => ".",
780
            Tok::LParen => "(",
781
            Tok::RParen => ")",
782
            Tok::LBracket => "[",
783
            Tok::RBracket => "]",
784
            Tok::RBracketOpen => "]",
785
            Tok::LBrace => "{",
786
            Tok::RBrace => "}",
787
            Tok::Comma => ",",
788
            Tok::Colon => ":",
789
            Tok::Num(n) => return write!(f, "{n}"),
790
            Tok::Str(s) => return write!(f, "{s:?}"),
791
            Tok::TemporalLit(s) => return write!(f, "@{s:?}"),
792
            Tok::Name(s) => return write!(f, "{s}"),
793
            Tok::Comment => unreachable!("Comment is logos::skip — never emitted"),
794
        };
795
        f.write_str(s)
796
    }
797
}