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 · 42.0 KB · at da382279c66c · raw

Outline: 50 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`], ADR-47) runs *after* `join_names` (so a
31
//! multi-word part like `total price` is already one word unit) and consults
32
//! the [`crate::ScopeProbe`] oracle before fusing a run — at a root position the
33
//! root scope, at a member position on a static path the navigated value
34
//! (ADR-48). The plan is a pure function of the base tokens and the probe's
35
//! answers ([`Trace`]), which is what lets a compiled expression cache one
36
//! parse per distinct answer set instead of re-parsing per scope.
37
//!
38
//! Backtick-quoted names (`` `a-b` ``, `` `Profit and loss` `` — the feel-scala
39
//! extension, ADR-48) are a distinct token through all of this: never joined,
40
//! never fused, scope-independent; [`finish`] makes them plain names.
41
//!
42
//! Java-style comments (`// … \n` and `/* … */`) are skipped at the logos level
43
//! (pass 1). `logos` maximal munch makes `//` / `/*` win over the single `/`
44
//! (`Slash`), so a bare `/` used as division or in `->` is unaffected.
45
46
use core::fmt;
47
48
use logos::Logos;
49
50
/// A lexer error. The grammar maps this to a `ParseError::User`, which surfaces
51
/// as a [`crate::FeelError::Parse`] — the same outcome the old regex lexer gave
52
/// for an unrecognised character.
53
#[derive(Default, Debug, Clone, PartialEq, Eq)]
54
pub struct LexError;
55
56
impl fmt::Display for LexError {
57
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
58
        f.write_str("invalid token")
59
    }
60
}
61
62
/// The FEEL token set. Keywords/operators/punctuation are unit variants; the
63
/// three value-carrying terminals (`Num`/`Str`/`Name`) carry their parsed payload.
64
///
65
/// Word keywords are produced via [`lex`]'s [`keyword`] remap of a lexed `Name`,
66
/// not by `logos`, so identifier maximal-munch is preserved.
67
#[derive(Logos, Clone, Debug, PartialEq)]
68
#[logos(skip r"[ \t\r\n]+", error = LexError)]
69
pub enum Tok {
70
    // FEEL Java-style comments — skipped at the logos level (never emitted).
71
    // Maximal munch: `//`/`/*` beat the 1-char `/` Slash, so bare `/` is unaffected.
72
    #[regex(r"//[^\n]*", logos::skip, priority = 5, allow_greedy = true)]
73
    #[regex(r"/\*([^*]|\*[^/])*\*/", logos::skip, priority = 5)]
74
    Comment,
75
76
    // --- word keywords (never emitted by logos directly; see `keyword`) ---
77
    For,
78
    In,
79
    Return,
80
    If,
81
    Then,
82
    Else,
83
    Some,
84
    Every,
85
    Satisfies,
86
    Or,
87
    And,
88
    Between,
89
    True,
90
    False,
91
    Null,
92
    Not,
93
    Function,
94
    // The two-word `instance of` operator. `instance` and `of` are NOT reserved
95
    // words (FEEL names may contain them — `year of birth`, the `day of week`
96
    // built-in), so this is emitted only for the adjacent `instance` `of` pair by a
97
    // dedicated lexer pass ([`mark_instance_of`]), never by `keyword`.
98
    InstanceOf,
99
100
    // --- operators (longer forms listed first so the intent is obvious; logos
101
    //     does maximal munch regardless, so `<=` beats `<`, `**` beats `*`) ---
102
    #[token("<=")]
103
    Le,
104
    #[token("<")]
105
    Lt,
106
    #[token(">=")]
107
    Ge,
108
    #[token(">")]
109
    Gt,
110
    #[token("=")]
111
    Eq,
112
    #[token("!=")]
113
    Ne,
114
    #[token("+")]
115
    Plus,
116
    // `->` (function-type arrow) before `-`: only appears literally in a
117
    // `function<…> -> T` type, and logos maximal-munch picks it over `-` `>`.
118
    #[token("->")]
119
    Arrow,
120
    #[token("-")]
121
    Minus,
122
    #[token("**")]
123
    StarStar,
124
    #[token("*")]
125
    Star,
126
    #[token("/")]
127
    Slash,
128
    #[token("...")]
129
    DotDotDot,
130
    #[token("..")]
131
    DotDot,
132
    #[token(".")]
133
    Dot,
134
135
    // --- punctuation ---
136
    #[token("(")]
137
    LParen,
138
    #[token(")")]
139
    RParen,
140
    #[token("[")]
141
    LBracket,
142
    #[token("]")]
143
    RBracket,
144
    // A `]` that *opens* a reverse-bracket interval `]a..b]` (the exclusive-lower
145
    // notation for `(a..b]`). Never emitted by logos — `]` always lexes as
146
    // `RBracket`; a post-pass ([`mark_reverse_open`]) retags the opening role to this
147
    // distinct token. Without the split, `]` would be both a closer and a primary
148
    // opener, which is not LR(1)-resolvable (the empty list `[]` collides with `[`
149
    // then a reverse-open `]`; see ROADMAP).
150
    RBracketOpen,
151
    #[token("{")]
152
    LBrace,
153
    #[token("}")]
154
    RBrace,
155
    #[token(",")]
156
    Comma,
157
    #[token(":")]
158
    Colon,
159
160
    // --- value-carrying terminals ---
161
    // FEEL grammar rule 35 / §10.3.2.3.1: a numeric literal is an optional
162
    // leading-dot mantissa OR a digit-led mantissa, with an optional exponent.
163
    // The leading-dot branch (`\.[0-9]+`) requires at least one digit after the
164
    // dot, so it never overlaps with `..` (DotDot, two chars) or a lone `.`
165
    // (Dot, one char); logos's maximal-munch resolves any tie. Negatives are
166
    // produced by unary minus over the literal — there is no signed-literal token.
167
    #[regex(r"([0-9]+(\.[0-9]+)?|\.[0-9]+)([eE][+-]?[0-9]+)?", |lex| lex.slice().parse::<f64>().ok())]
168
    Num(f64),
169
170
    // A double-quoted string. The body is any run of non-quote/non-backslash
171
    // characters and backslash-escapes (`\\.`), so an escaped quote `\"` does not
172
    // end the literal. `decode_string_escapes` then resolves the FEEL escapes
173
    // (`\n \r \t \" \' \\`, `\uXXXX` incl. surrogate pairs, `\UXXXXXX`); an
174
    // unrecognised escape (e.g. a regex `\d`) is left verbatim (DMN §10.3.1.2).
175
    #[regex(r#""([^"\\]|\\.)*""#, |lex| { let s = lex.slice(); decode_string_escapes(&s[1..s.len() - 1]) })]
176
    Str(String),
177
178
    // A temporal literal `@"…"` (ADR-18). Carries the inner text; the type is
179
    // resolved by the evaluator from its lexical form. A value token like `Str`,
180
    // so `join_names` leaves it alone.
181
    #[regex(r#"@"[^"]*""#, |lex| { let s = lex.slice(); s[2..s.len() - 1].to_string() })]
182
    TemporalLit(String),
183
184
    // Lead char: ASCII letter / underscore / any non-ASCII scalar (a cheap range,
185
    // no Unicode tables). `lex_name` then validates it as an XID start and extends
186
    // over XID-continue characters. Keywords are remapped out of this in `lex`.
187
    #[regex(r"[A-Za-z_\u{80}-\u{10FFFF}]", lex_name)]
188
    Name(String),
189
190
    // A backtick-quoted name `` `a-b` ``, `` `Profit and loss` `` — the feel-scala
191
    // (Camunda) extension, ADR-48: one or more characters except a backtick, no
192
    // escape, content verbatim (no space normalisation). Kept a *distinct* token
193
    // through the name passes so it is never joined (`` `a b` c `` is not `a b c`)
194
    // nor fused (`` `a`-b `` is not `a-b`); [`finish`] turns it into a plain
195
    // `Name` just before the parser sees it, so the grammar is unchanged.
196
    #[regex(r"`[^`]+`", |lex| { let s = lex.slice(); s[1..s.len() - 1].to_string() })]
197
    QuotedName(String),
198
}
199
200
/// Validate the already-matched lead character as an identifier start and extend
201
/// the token over the following XID-continue characters. Returns `None` (a lex
202
/// error) when the lead is a non-ASCII, non-identifier scalar (e.g. `€`, `±`).
203
fn lex_name(lex: &mut logos::Lexer<'_, Tok>) -> Option<String> {
204
    let first = lex.slice().chars().next()?;
205
    if first != '_' && !unicode_ident::is_xid_start(first) {
206
        return None;
207
    }
208
    let mut extra = 0;
209
    for c in lex.remainder().chars() {
210
        if c == '_' || unicode_ident::is_xid_continue(c) {
211
            extra += c.len_utf8();
212
        } else {
213
            break;
214
        }
215
    }
216
    lex.bump(extra);
217
    Some(lex.slice().to_string())
218
}
219
220
/// Resolve the FEEL string escapes in a string literal's body (the text between
221
/// the quotes), per DMN §10.3.1.2: `\n \r \t \" \' \\`, a `\uXXXX` 4-hex code unit
222
/// (consecutive high+low surrogates combine into one code point), and a `\UXXXXXX`
223
/// 6-hex code point. An unrecognised escape (e.g. a regex metacharacter like `\d`,
224
/// `\s`, `\3`) is preserved verbatim — feel-core does not own the regex dialect
225
/// (ADR-16), so such backslashes must reach the provider untouched. A malformed
226
/// `\u`/`\U` or a lone surrogate likewise falls back to copying the backslash.
227
fn decode_string_escapes(body: &str) -> String {
228
    // Fast path: nothing to decode.
229
    if !body.contains('\\') {
230
        return body.to_string();
231
    }
232
    let b = body.as_bytes();
233
    let mut out = String::with_capacity(body.len());
234
    let mut i = 0;
235
    while i < b.len() {
236
        if b[i] != b'\\' {
237
            // Copy one whole UTF-8 scalar (the byte at `i` starts a char).
238
            let ch = body[i..].chars().next().expect("char boundary");
239
            out.push(ch);
240
            i += ch.len_utf8();
241
            continue;
242
        }
243
        match b.get(i + 1) {
244
            Some(b'n') => { out.push('\n'); i += 2; }
245
            Some(b'r') => { out.push('\r'); i += 2; }
246
            Some(b't') => { out.push('\t'); i += 2; }
247
            Some(b'"') => { out.push('"'); i += 2; }
248
            Some(b'\'') => { out.push('\''); i += 2; }
249
            Some(b'\\') => { out.push('\\'); i += 2; }
250
            Some(b'u') => match hex_escape(&b[i..], 4) {
251
                Some(cp) if (0xD800..=0xDBFF).contains(&cp) => {
252
                    // High surrogate: pair it with a following low surrogate.
253
                    match hex_escape(&b[i + 6..], 4) {
254
                        Some(lo) if (0xDC00..=0xDFFF).contains(&lo) => {
255
                            let c = 0x1_0000 + ((cp - 0xD800) << 10) + (lo - 0xDC00);
256
                            out.push(char::from_u32(c).unwrap_or('\u{FFFD}'));
257
                            i += 12;
258
                        }
259
                        // Lone high surrogate: keep the backslash verbatim.
260
                        _ => { out.push('\\'); i += 1; }
261
                    }
262
                }
263
                // Lone low surrogate or unmappable: keep the backslash verbatim.
264
                Some(cp) => match char::from_u32(cp) {
265
                    Some(ch) => { out.push(ch); i += 6; }
266
                    None => { out.push('\\'); i += 1; }
267
                },
268
                None => { out.push('\\'); i += 1; }
269
            },
270
            Some(b'U') => match hex_escape(&b[i..], 6) {
271
                Some(cp) => match char::from_u32(cp) {
272
                    Some(ch) => { out.push(ch); i += 8; }
273
                    None => { out.push('\\'); i += 1; }
274
                },
275
                None => { out.push('\\'); i += 1; }
276
            },
277
            // Unknown escape or trailing backslash: keep the backslash verbatim and
278
            // reprocess the next byte normally (so `\d` stays `\d`).
279
            _ => { out.push('\\'); i += 1; }
280
        }
281
    }
282
    out
283
}
284
285
/// Parse a `\u`/`\U` escape at the start of `b` with `n` hex digits (4 or 6),
286
/// returning the code point. `b` must begin with `\` then the `u`/`U` marker.
287
/// `None` if there are not `n` hex digits.
288
fn hex_escape(b: &[u8], n: usize) -> Option<u32> {
289
    let digits = b.get(2..2 + n)?;
290
    let mut v = 0u32;
291
    for &c in digits {
292
        v = v * 16 + (c as char).to_digit(16)?;
293
    }
294
    Some(v)
295
}
296
297
/// Map a lexed identifier to its keyword token, if it is one. FEEL keywords are
298
/// reserved words, so a name equal to a keyword is the keyword (longest-match
299
/// already kept `fortune` a name, since this only runs on a complete identifier).
300
fn keyword(name: &str) -> Option<Tok> {
301
    Some(match name {
302
        "for" => Tok::For,
303
        "in" => Tok::In,
304
        "return" => Tok::Return,
305
        "if" => Tok::If,
306
        "then" => Tok::Then,
307
        "else" => Tok::Else,
308
        "some" => Tok::Some,
309
        "every" => Tok::Every,
310
        "satisfies" => Tok::Satisfies,
311
        "or" => Tok::Or,
312
        "and" => Tok::And,
313
        "between" => Tok::Between,
314
        "true" => Tok::True,
315
        "false" => Tok::False,
316
        "null" => Tok::Null,
317
        "not" => Tok::Not,
318
        "function" => Tok::Function,
319
        _ => return None,
320
    })
321
}
322
323
/// One `(start, token, end)` triple, or a lex error for an unrecognised char.
324
pub(crate) type Spanned = Result<(usize, Tok, usize), LexError>;
325
326
/// Token stream for the lalrpop parser: `(start, token, end)` byte offsets, with
327
/// lexed identifiers remapped to keyword tokens and multi-word FEEL names joined —
328
/// **no** special-character fusion (the scope-free base parse; ADR-47/48). A lex
329
/// error becomes the `Err` arm, which lalrpop reports as a `ParseError::User`.
330
pub(crate) fn lex(input: &str) -> impl Iterator<Item = Spanned> {
331
    finish(lex_base(input)).into_iter()
332
}
333
334
/// Passes 1–2: logos tokens with keywords remapped, `instance of` fused, and
335
/// multi-word names joined. The input of the §10.3.1.6 fusion ([`fuse`]) and of
336
/// [`finish`]; a [`crate::CompiledExpr`] keeps it to re-fuse per scope (ADR-48).
337
pub(crate) fn lex_base(input: &str) -> Vec<Spanned> {
338
    join_names(lex_joined(input))
339
}
340
341
/// The last pass before the parser: quoted names become plain `Name`s (the
342
/// grammar knows only `Name`), then reverse-open interval openers are retagged
343
/// (pass 3 — it must see fused and quoted names as value-completing).
344
pub(crate) fn finish(mut toks: Vec<Spanned>) -> Vec<Spanned> {
345
    for t in toks.iter_mut() {
346
        if let Ok((s, Tok::QuotedName(name), e)) = t {
347
            *t = Ok((*s, Tok::Name(std::mem::take(name)), *e));
348
        }
349
    }
350
    mark_reverse_open(toks)
351
}
352
353
/// Passes 1 + 1.5: raw `logos` tokens with identifiers remapped to keyword
354
/// tokens, then the `instance of` operator fused. Shared by the token pipeline
355
/// and the probe-free candidate scan ([`name_run_candidates`]).
356
fn lex_joined(input: &str) -> Vec<Spanned> {
357
    let raw: Vec<Spanned> = Tok::lexer(input)
358
        .spanned()
359
        .map(|(tok, span)| {
360
            let tok = tok?;
361
            let tok = match &tok {
362
                Tok::Name(name) => keyword(name).unwrap_or(tok),
363
                _ => tok,
364
            };
365
            Ok((span.start, tok, span.end))
366
        })
367
        .collect();
368
    mark_instance_of(raw)
369
}
370
371
/// Retag every `]` that *opens* a reverse-bracket interval (`]a..b]`, FEEL's
372
/// exclusive-lower-bound spelling of `(a..b]`) as a distinct [`Tok::RBracketOpen`],
373
/// so the grammar can admit it as a range-literal opener. `]` otherwise plays only
374
/// the closer role; letting one terminal be both closer and primary opener is not
375
/// LR(1)-resolvable (the empty list `[]` collides with `[` then a reverse-open `]`).
376
///
377
/// A `]` opens iff it is in **value-expected** position — the previous token does not
378
/// complete a value (start of input, or after an operator / `(` / `[` / `,` / `..` /
379
/// keyword) — **and** a `..` follows at the same bracket depth before the group
380
/// closes (the shape of a reverse-open interval; see [`reverse_open_ahead`]). Every
381
/// other `]` — a list/filter/interval close, and the empty list `[]` (no `..` ahead)
382
/// — stays an ordinary `RBracket`. Lex errors reset the position to value-expected.
383
fn mark_reverse_open(toks: Vec<Spanned>) -> Vec<Spanned> {
384
    let mut out = toks;
385
    let mut prev_ends_value = false;
386
    for i in 0..out.len() {
387
        let Ok((start, tok, end)) = &out[i] else {
388
            prev_ends_value = false;
389
            continue;
390
        };
391
        if matches!(tok, Tok::RBracket) && !prev_ends_value && reverse_open_ahead(&out, i + 1) {
392
            let (start, end) = (*start, *end);
393
            out[i] = Ok((start, Tok::RBracketOpen, end));
394
            // An opener does not complete a value: the start endpoint follows.
395
            prev_ends_value = false;
396
        } else {
397
            prev_ends_value = ends_value(tok);
398
        }
399
    }
400
    out
401
}
402
403
/// Whether a token in this position completes a value, so a following `]` is a
404
/// *closer* (not a reverse-open opener). True for the value-producing terminals and
405
/// the three closing brackets; false for operators, openers, separators and keywords.
406
fn ends_value(tok: &Tok) -> bool {
407
    matches!(
408
        tok,
409
        Tok::Num(_)
410
            | Tok::Str(_)
411
            | Tok::TemporalLit(_)
412
            | Tok::Name(_)
413
            | Tok::QuotedName(_)
414
            | Tok::True
415
            | Tok::False
416
            | Tok::Null
417
            | Tok::RParen
418
            | Tok::RBracket
419
            | Tok::RBrace
420
    )
421
}
422
423
/// Scan forward from `from` (just past a candidate opener `]`) for the `..` that
424
/// makes it a reverse-open interval. Returns true on a `..` at bracket depth 0; false
425
/// on a depth-0 `,` (a list separator), a closer that pops above the start depth, a
426
/// lex error, or end of input — none of which fit `] endpoint .. endpoint close`.
427
fn reverse_open_ahead(toks: &[Spanned], from: usize) -> bool {
428
    let mut depth: i32 = 0;
429
    for t in &toks[from..] {
430
        let Ok((_, tok, _)) = t else {
431
            return false;
432
        };
433
        match tok {
434
            Tok::LParen | Tok::LBracket | Tok::LBrace | Tok::RBracketOpen => depth += 1,
435
            Tok::DotDot if depth == 0 => return true,
436
            Tok::Comma if depth == 0 => return false,
437
            Tok::RParen | Tok::RBracket | Tok::RBrace => {
438
                if depth == 0 {
439
                    return false;
440
                }
441
                depth -= 1;
442
            }
443
            _ => {}
444
        }
445
    }
446
    false
447
}
448
449
/// Replace every adjacent `Name("instance")` `Name("of")` pair with a single
450
/// [`Tok::InstanceOf`] operator token (ADR-26). `instance of` is a reserved operator
451
/// sequence in FEEL, so this is unambiguous; a lone `instance` or `of` is left as a
452
/// `Name` word and joins into its neighbours normally. The fused token spans from the
453
/// start of `instance` to the end of `of`.
454
fn mark_instance_of(toks: Vec<Spanned>) -> Vec<Spanned> {
455
    let mut out: Vec<Spanned> = Vec::with_capacity(toks.len());
456
    let mut i = 0;
457
    while i < toks.len() {
458
        if let (Ok((start, Tok::Name(a), _)), Some(Ok((_, Tok::Name(b), end)))) =
459
            (&toks[i], toks.get(i + 1))
460
        {
461
            if a == "instance" && b == "of" {
462
                out.push(Ok((*start, Tok::InstanceOf, *end)));
463
                i += 2;
464
                continue;
465
            }
466
        }
467
        out.push(toks[i].clone());
468
        i += 1;
469
    }
470
    out
471
}
472
473
/// Collapse multi-word FEEL names into single `Name` tokens. Two tiers, both
474
/// sound without scope knowledge because FEEL has no juxtaposition of two
475
/// expressions:
476
///
477
/// - **Tier 1:** a run of adjacent `Name` tokens (keywords are separate tokens
478
///   and stop the run) is one name — `string length`, `full name`. Payloads are
479
///   joined with a single space.
480
/// - **Tier 2:** a fixed dictionary of *keyword-containing* reserved phrases
481
///   ([`crate::builtins::KEYWORD_PHRASE_BUILTINS`], e.g. `date and time`) is
482
///   recognised **wherever it occurs** (ADR-26). This is the bounded "reserved-name
483
///   exception": the set is finite and holds only FEEL temporal type/constructor
484
///   names, never user variables, so no name oracle is needed — and it lets these
485
///   names appear as `instance of` types (`… instance of date and time`), not just
486
///   call heads.
487
fn join_names(toks: Vec<Spanned>) -> Vec<Spanned> {
488
    let mut out: Vec<Spanned> = Vec::with_capacity(toks.len());
489
    let mut i = 0;
490
    while i < toks.len() {
491
        // Errors and non-name tokens that don't start a phrase pass straight through.
492
        let Ok((start, tok, end)) = &toks[i] else {
493
            out.push(toks[i].clone());
494
            i += 1;
495
            continue;
496
        };
497
        // Tier 2 first: a known keyword-phrase builtin would otherwise be split
498
        // by Tier 1 at its keyword (`date` | `and` | `time`).
499
        if let Some((payload, span_end, next)) = match_keyword_phrase(&toks, i) {
500
            out.push(Ok((*start, Tok::Name(payload), span_end)));
501
            i = next;
502
            continue;
503
        }
504
        // Tier 1: greedily merge a run of adjacent `Name` tokens.
505
        if let Tok::Name(first) = tok {
506
            let run_start = *start;
507
            let mut words = first.clone();
508
            let mut run_end = *end;
509
            let mut j = i + 1;
510
            while let Some(Ok((_, Tok::Name(next), e))) = toks.get(j) {
511
                words.push(' ');
512
                words.push_str(next);
513
                run_end = *e;
514
                j += 1;
515
            }
516
            out.push(Ok((run_start, Tok::Name(words), run_end)));
517
            i = j;
518
            continue;
519
        }
520
        out.push(toks[i].clone());
521
        i += 1;
522
    }
523
    out
524
}
525
526
/// If a fixed keyword-phrase name matches the tokens starting at `i`, return its
527
/// joined payload, the byte offset where the phrase ends, and the index of the
528
/// first token after it. The match is **unconditional** (not gated on a following
529
/// `(`): these phrases are FEEL's reserved temporal type/constructor names, atomic
530
/// wherever they occur (ADR-26), so joining them here lets them serve both as a
531
/// call head (`date and time(…)`) and as an `instance of` type (`… instance of date
532
/// and time`). The phrases share no prefix, so iteration order is irrelevant.
533
fn match_keyword_phrase(toks: &[Spanned], i: usize) -> Option<(String, usize, usize)> {
534
    for phrase in crate::builtins::KEYWORD_PHRASE_BUILTINS {
535
        let words: Vec<&str> = phrase.split(' ').collect();
536
        let after = i + words.len();
537
        // Need the whole phrase to fit in the remaining tokens.
538
        if after > toks.len() {
539
            continue;
540
        }
541
        let mut end = 0;
542
        let matched = words
543
            .iter()
544
            .enumerate()
545
            .all(|(k, word)| match &toks[i + k] {
546
                Ok((_, tok, e)) if tok_word(tok) == Some(*word) => {
547
                    end = *e;
548
                    true
549
                }
550
                _ => false,
551
            });
552
        if matched {
553
            return Some(((*phrase).to_string(), end, after));
554
        }
555
    }
556
    None
557
}
558
559
/// The "word" a token contributes to a multi-word name: an identifier's text, or
560
/// a keyword's spelling (so phrase matching can see the `and` in `date and time`).
561
/// Operators and punctuation are not words.
562
fn tok_word(tok: &Tok) -> Option<&str> {
563
    Some(match tok {
564
        Tok::Name(s) => s.as_str(),
565
        Tok::For => "for",
566
        Tok::In => "in",
567
        Tok::Return => "return",
568
        Tok::If => "if",
569
        Tok::Then => "then",
570
        Tok::Else => "else",
571
        Tok::Some => "some",
572
        Tok::Every => "every",
573
        Tok::Satisfies => "satisfies",
574
        Tok::Or => "or",
575
        Tok::And => "and",
576
        Tok::Between => "between",
577
        Tok::True => "true",
578
        Tok::False => "false",
579
        Tok::Null => "null",
580
        Tok::Not => "not",
581
        Tok::Function => "function",
582
        _ => return None,
583
    })
584
}
585
586
// --------------------------------------------------------------------------- //
587
// Special-character name runs (grammar rules 25–30, §10.3.1.6; ADR-47)
588
// --------------------------------------------------------------------------- //
589
590
/// The additional name symbols (grammar rule 30) a name may contain, as token →
591
/// symbol char. Deliberately excludes the multi-char operators (`..` `...` `**`,
592
/// `->`): only the single-character forms are name symbols, so a range separator
593
/// `x..y`, a descendant `x...y` and an exponent never form a run.
594
fn name_symbol(tok: &Tok) -> Option<char> {
595
    match tok {
596
        Tok::Minus => Some('-'),
597
        Tok::Plus => Some('+'),
598
        Tok::Star => Some('*'),
599
        Tok::Slash => Some('/'),
600
        Tok::Dot => Some('.'),
601
        _ => None,
602
    }
603
}
604
605
/// One word unit of a name run: its spelling and `(byte start, byte end)` span.
606
type RunUnit<'a> = (&'a str, usize, usize);
607
608
/// The word a token contributes to a name run **when the run starts at it**:
609
/// only a `Name`. §10.3.1.4 is explicit — "A name start (grammar rule 26) SHALL
610
/// NOT be a literal terminal symbol" — so no keyword (`if`, `true`, `return`,
611
/// `in`, …) can begin a name, while "a name part MAY be a literal terminal
612
/// symbol": keywords stay legal as *later* run words (`x-in`, `a-if`). Besides
613
/// conformance this keeps spurious candidates out (`return -i` yields no
614
/// `return-i`, which if bound would corrupt the loop parse and, in feel-pg, force
615
/// a per-row re-parse or an IMMUTABLE error; ADR-47).
616
fn run_start_word(tok: &Tok) -> Option<&str> {
617
    match tok {
618
        Tok::Name(s) => Some(s.as_str()),
619
        _ => None,
620
    }
621
}
622
623
/// Scan the maximal special-character name run starting at token `i`:
624
/// `word ((-|+|*|/|.) word)*`, where a later word is a joined `Name` payload or
625
/// a keyword's spelling (`tok_word` — keywords are legal name *parts*,
626
/// §10.3.1.4; `x-in`). The run must START at a `Name` ([`run_start_word`] — a
627
/// name start is never a keyword). Whether position `i` is a root or a path
628
/// member is the caller's business ([`plan`]); a **member** run (`member`)
629
/// does not continue over `.` — there the dot is path navigation, so a plain
630
/// path `a.b.c` forms no member run and is never probed (laziness, ADR-21); a
631
/// member key containing a dot needs backticks (ADR-48). Parens, commas, brackets,
632
/// literals, quoted names, adjacency (`a and b`) and any other token end the
633
/// run. Returns the per-unit `(word, start, end)` and the separator chars. A
634
/// lone word is not a run — `None`.
635
fn scan_name_run(
636
    toks: &[Spanned],
637
    i: usize,
638
    member: bool,
639
) -> Option<(Vec<RunUnit<'_>>, Vec<char>)> {
640
    let (word, start, end) = match &toks[i] {
641
        Ok((s, tok, e)) => (run_start_word(tok)?, *s, *e),
642
        Err(_) => return None,
643
    };
644
    let mut units = vec![(word, start, end)];
645
    let mut seps = Vec::new();
646
    let mut j = i + 1;
647
    loop {
648
        let sep = toks
649
            .get(j)
650
            .and_then(|t| t.as_ref().ok())
651
            .and_then(|(_, t, _)| name_symbol(t));
652
        let Some(sep) = sep.filter(|&c| !(member && c == '.')) else {
653
            break;
654
        };
655
        let next = toks
656
            .get(j + 1)
657
            .and_then(|t| t.as_ref().ok())
658
            .and_then(|(s, t, e)| tok_word(t).map(|w| (w, *s, *e)));
659
        let Some((w, s, e)) = next else { break };
660
        seps.push(sep);
661
        units.push((w, s, e));
662
        j += 2;
663
    }
664
    (units.len() > 1).then_some((units, seps))
665
}
666
667
/// Write the candidate name a run prefix stands for into `buf`: the word units
668
/// joined by their separators, verbatim. Spaces are not part of the token
669
/// sequence (§10.3.1.6), so `a - b` and `a-b` produce the same candidate — the
670
/// separator *characters* are part of the name, the whitespace around them is
671
/// not. A reused buffer keeps the per-evaluation scope check allocation-free.
672
fn candidate_into(buf: &mut String, units: &[RunUnit<'_>], seps: &[char]) {
673
    buf.clear();
674
    buf.push_str(units[0].0);
675
    for ((word, _, _), sep) in units[1..].iter().zip(seps) {
676
        buf.push(*sep);
677
        buf.push_str(word);
678
    }
679
}
680
681
/// Whether token `i` directly follows a `.` — a path **member** position. A
682
/// fused span always ends with a word, so a `.` at `i - 1` is never consumed by
683
/// a fusion: it is in the plan exactly when this is true.
684
fn after_dot(toks: &[Spanned], i: usize) -> bool {
685
    i > 0 && matches!(&toks[i - 1], Ok((_, Tok::Dot, _)))
686
}
687
688
/// The answers a fusion got from its probe, in query order (ADR-48). The plan is
689
/// a pure function of the base tokens and this trace, so it is the parse-cache
690
/// key: two scopes with the same trace parse identically.
691
pub(crate) type Trace = Vec<bool>;
692
693
/// One element of a fusion plan: an input token kept as is, or a fused name
694
/// spanning input tokens `first..=last`.
695
enum Planned {
696
    Tok(usize),
697
    Fused { first: usize, last: usize, payload: String },
698
}
699
700
/// The input token a plan element keeps (`None` for a fused name).
701
fn planned_tok<'a>(p: &Planned, toks: &'a [Spanned]) -> Option<&'a Tok> {
702
    match p {
703
        Planned::Tok(i) => toks[*i].as_ref().ok().map(|(_, t, _)| t),
704
        Planned::Fused { .. } => None,
705
    }
706
}
707
708
/// The name a plan element stands for — a plain, quoted or fused name.
709
fn planned_name<'a>(p: &'a Planned, toks: &'a [Spanned]) -> Option<&'a str> {
710
    match p {
711
        Planned::Fused { payload, .. } => Some(payload),
712
        Planned::Tok(_) => match planned_tok(p, toks)? {
713
            Tok::Name(s) | Tok::QuotedName(s) => Some(s),
714
            _ => None,
715
        },
716
    }
717
}
718
719
/// The **static** path in front of a member position (ADR-48): the plan ends in
720
/// `name (. name)* .`, and the chain's root is a name that is not itself a path
721
/// member. Returns the plan indices of the chain's names, root first — e.g.
722
/// `[applicant]` for `applicant.first-name`, `[p, q]` for `p.q.r-s`. `None` for
723
/// a dynamic base (`f(x).a-b`, `(e).a-b`, `xs[1].a-b`, `e...n.a-b`): its member
724
/// names cannot be known at parse time (backticks cover them).
725
fn static_path(out: &[Planned], toks: &[Spanned]) -> Option<Vec<usize>> {
726
    let mut idxs = Vec::new();
727
    // `out[j - 1]` is the `.` in front of the current segment.
728
    let mut j = out.len();
729
    loop {
730
        let k = j.checked_sub(2)?;
731
        planned_name(&out[k], toks)?;
732
        idxs.push(k);
733
        match k.checked_sub(1).map(|p| planned_tok(&out[p], toks)) {
734
            Some(Some(Tok::Dot)) => j = k,
735
            Some(Some(Tok::DotDotDot)) => return None,
736
            _ => break,
737
        }
738
    }
739
    idxs.reverse();
740
    Some(idxs)
741
}
742
743
/// A plain or backtick-quoted name token's text.
744
fn name_text(t: &Spanned) -> Option<&str> {
745
    match t {
746
        Ok((_, Tok::Name(s) | Tok::QuotedName(s), _)) => Some(s),
747
        _ => None,
748
    }
749
}
750
751
/// Whether input token `i` is exactly `tok` (a unit variant).
752
fn tok_is(toks: &[Spanned], i: usize, tok: &Tok) -> bool {
753
    matches!(toks.get(i), Some(Ok((_, t, _))) if t == tok)
754
}
755
756
/// Names the expression binds **itself** (ADR-48 safety rule): `for`/`some`/
757
/// `every` variables (`for x in`, `, y in`), function parameters
758
/// (`function(a, b: number)`) and context-literal keys (`{k: …, j: …}`). A static
759
/// path rooted at one of them may mean the local binding — a loop element, an
760
/// argument, a sibling entry — whose value the parser cannot know, so it is
761
/// never member-probed (the root-scope value of the same name would be the
762
/// wrong answer). Scope-insensitive on purpose: the over-approximation only
763
/// ever falls back to the arithmetic reading, which backticks override.
764
fn locally_bound(toks: &[Spanned]) -> Vec<&str> {
765
    let mut out = Vec::new();
766
    let mut i = 0;
767
    while i < toks.len() {
768
        if let Some(name) = name_text(&toks[i]) {
769
            let prev_is = |t: &Tok| i > 0 && tok_is(toks, i - 1, t);
770
            // `for x in` / `some x in` / `every x in` / `…, y in`.
771
            let iter_var = tok_is(toks, i + 1, &Tok::In)
772
                && (prev_is(&Tok::For) || prev_is(&Tok::Some) || prev_is(&Tok::Every) || prev_is(&Tok::Comma));
773
            // `{k: …}` / `…, k: …` — context keys (and, harmlessly, named args).
774
            let key = tok_is(toks, i + 1, &Tok::Colon) && (prev_is(&Tok::LBrace) || prev_is(&Tok::Comma));
775
            if iter_var || key {
776
                out.push(name);
777
            }
778
        }
779
        // `function(` params `)`: names right after `(` or a depth-0 `,`.
780
        if tok_is(toks, i, &Tok::Function) && tok_is(toks, i + 1, &Tok::LParen) {
781
            let mut depth = 0usize;
782
            let mut j = i + 2;
783
            let mut expect_name = true;
784
            while j < toks.len() {
785
                match &toks[j] {
786
                    Ok((_, Tok::LParen | Tok::LBracket | Tok::LBrace, _)) => depth += 1,
787
                    Ok((_, Tok::RParen, _)) if depth == 0 => break,
788
                    Ok((_, Tok::RParen | Tok::RBracket | Tok::RBrace, _)) => depth = depth.saturating_sub(1),
789
                    Ok((_, Tok::Comma, _)) if depth == 0 => {
790
                        expect_name = true;
791
                        j += 1;
792
                        continue;
793
                    }
794
                    t => {
795
                        if expect_name {
796
                            if let Some(n) = name_text(t) {
797
                                out.push(n);
798
                            }
799
                        }
800
                    }
801
                }
802
                expect_name = false;
803
                j += 1;
804
            }
805
            i = j;
806
            continue;
807
        }
808
        i += 1;
809
    }
810
    out
811
}
812
813
/// Try a run's prefixes longest first (§10.3.1.6), recording every answer in
814
/// `trace`; the first in-scope prefix wins as `(units, name)`.
815
fn longest_in_scope(
816
    units: &[RunUnit<'_>],
817
    seps: &[char],
818
    buf: &mut String,
819
    trace: &mut Trace,
820
    mut in_scope: impl FnMut(&str) -> bool,
821
) -> Option<(usize, String)> {
822
    for k in (2..=units.len()).rev() {
823
        candidate_into(buf, &units[..k], &seps[..k - 1]);
824
        let hit = in_scope(buf);
825
        trace.push(hit);
826
        if hit {
827
            return Some((k, buf.clone()));
828
        }
829
    }
830
    None
831
}
832
833
/// Plan the §10.3.1.6 fusion of special-character name runs against `probe`
834
/// (ADR-47/48). At each word position the maximal run is scanned and its
835
/// prefixes are tried **longest first**; the first in-scope prefix is fused.
836
/// Scanning continues *after* a fused name (`Date-Time - Date-Time2` fuses both
837
/// and keeps the minus an operator — the TCK expectation) and *inside* the run
838
/// after a miss (`a-b-c` with only `b-c` bound is `a - b-c`).
839
///
840
/// A root position asks [`crate::ScopeProbe::contains`]. A **member** position
841
/// (after an unfused `.`) never consults the root scope — a root key `y-z` must
842
/// not turn `x.y-z` into `x.(y-z)` — but, on a *static* path ([`static_path`]),
843
/// asks [`crate::ScopeProbe::contains_member`] whether the navigated value has
844
/// that key: `applicant.first-name` fuses `first-name` when `applicant` has it.
845
/// Never, though, inside a **filter** bracket (`items[detail.a-b > 1]` — names
846
/// there may be element keys) or when the path's root is **bound by the
847
/// expression itself** ([`locally_bound`] — `for item in … return item.a-b`):
848
/// the root-scope value would be the wrong one, so the arithmetic reading
849
/// stands (backticks override). Every answer is appended to `trace`.
850
fn plan(toks: &[Spanned], probe: &dyn crate::ScopeProbe, trace: &mut Trace) -> Vec<Planned> {
851
    let mut out: Vec<Planned> = Vec::with_capacity(toks.len());
852
    let mut buf = String::new();
853
    let may_root = probe.may_bind_special();
854
    // Open brackets, `true` for a filter (`[` right after a value).
855
    let mut brackets: Vec<bool> = Vec::new();
856
    let mut locals: Option<Vec<&str>> = None;
857
    let mut i = 0;
858
    while i < toks.len() {
859
        match &toks[i] {
860
            Ok((_, Tok::LBracket, _)) => brackets.push(
861
                i > 0 && toks[i - 1].as_ref().is_ok_and(|(_, t, _)| ends_value(t)),
862
            ),
863
            Ok((_, Tok::RBracket, _)) => {
864
                brackets.pop();
865
            }
866
            _ => {}
867
        }
868
        let member = after_dot(toks, i);
869
        let fused = match scan_name_run(toks, i, member) {
870
            None => None,
871
            Some((units, seps)) if member => match static_path(&out, toks) {
872
                Some(_) if brackets.iter().any(|&filter| filter) => None,
873
                Some(idxs) => {
874
                    let path: Vec<&str> = idxs
875
                        .iter()
876
                        .map(|&k| planned_name(&out[k], toks).expect("static path element is a name"))
877
                        .collect();
878
                    let local = locals
879
                        .get_or_insert_with(|| locally_bound(toks))
880
                        .contains(&path[0]);
881
                    if local {
882
                        None
883
                    } else {
884
                        longest_in_scope(&units, &seps, &mut buf, trace, |c| {
885
                            probe.contains_member(&path, c)
886
                        })
887
                    }
888
                }
889
                None => None,
890
            },
891
            Some((units, seps)) if may_root => {
892
                longest_in_scope(&units, &seps, &mut buf, trace, |c| probe.contains(c))
893
            }
894
            // No special name can be in scope: every root answer is `false`.
895
            Some((units, _)) => {
896
                trace.extend(std::iter::repeat_n(false, units.len() - 1));
897
                None
898
            }
899
        };
900
        match fused {
901
            Some((k, payload)) => {
902
                // k units plus the k-1 separators between them.
903
                let last = i + 2 * (k - 1);
904
                out.push(Planned::Fused { first: i, last, payload });
905
                i = last + 1;
906
            }
907
            None => {
908
                out.push(Planned::Tok(i));
909
                i += 1;
910
            }
911
        }
912
    }
913
    out
914
}
915
916
/// Whether the base tokens contain any special-character run at all — i.e.
917
/// whether some scope could make [`plan`] fuse. `false` ⇒ the base parse is the
918
/// only parse, for every scope (ADR-48's fast path).
919
pub(crate) fn may_fuse(toks: &[Spanned]) -> bool {
920
    (0..toks.len()).any(|i| scan_name_run(toks, i, after_dot(toks, i)).is_some())
921
}
922
923
/// Whether any **member** position starts a run (`applicant.net-income`) — the
924
/// sites whose probe answers depend on nested values rather than root keys.
925
pub(crate) fn has_member_sites(toks: &[Spanned]) -> bool {
926
    (0..toks.len()).any(|i| after_dot(toks, i) && scan_name_run(toks, i, true).is_some())
927
}
928
929
/// Fuse special-character name runs against `probe` — the token stream for
930
/// that scope (feed it to [`finish`]). See [`plan`].
931
pub(crate) fn fuse(toks: &[Spanned], probe: &dyn crate::ScopeProbe) -> Vec<Spanned> {
932
    let mut trace = Trace::new();
933
    plan(toks, probe, &mut trace)
934
        .into_iter()
935
        .map(|p| match p {
936
            Planned::Tok(i) => toks[i].clone(),
937
            Planned::Fused { first, last, payload } => {
938
                let start = toks[first].as_ref().map(|(s, _, _)| *s).unwrap_or(0);
939
                let end = toks[last].as_ref().map(|(_, _, e)| *e).unwrap_or(start);
940
                Ok((start, Tok::Name(payload), end))
941
            }
942
        })
943
        .collect()
944
}
945
946
/// Run the fusion against `probe` only to record its probe answers (the
947
/// parse-cache key; ADR-48) — nothing is materialised.
948
pub(crate) fn fusion_trace(toks: &[Spanned], probe: &dyn crate::ScopeProbe, trace: &mut Trace) {
949
    plan(toks, probe, trace);
950
}
951
952
/// Every **root-level** special-character name candidate `expr` could fuse
953
/// under *some* scope (ADR-47): all ≥2-unit prefixes of every run that starts
954
/// at a non-member position (so `a-b-c` yields `a-b-c`, `a-b` and `b-c`, and
955
/// `x.y-z` yields `x.y-z` and `x.y`). Path-member candidates (ADR-48) depend on
956
/// the navigated value and are not listed. A diagnostic: its length is the
957
/// number of root-scope lookups an evaluation pays.
958
pub(crate) fn name_run_candidates(input: &str) -> Vec<String> {
959
    let toks = lex_base(input);
960
    let mut out = Vec::new();
961
    let mut buf = String::new();
962
    for i in 0..toks.len() {
963
        if after_dot(&toks, i) {
964
            continue;
965
        }
966
        if let Some((units, seps)) = scan_name_run(&toks, i, false) {
967
            // Longest first, mirroring the probe's resolution order (§10.3.1.6).
968
            for k in (2..=units.len()).rev() {
969
                candidate_into(&mut buf, &units[..k], &seps[..k - 1]);
970
                out.push(buf.clone());
971
            }
972
        }
973
    }
974
    out
975
}
976
977
impl fmt::Display for Tok {
978
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
979
        let s = match self {
980
            Tok::For => "for",
981
            Tok::In => "in",
982
            Tok::Return => "return",
983
            Tok::If => "if",
984
            Tok::Then => "then",
985
            Tok::Else => "else",
986
            Tok::Some => "some",
987
            Tok::Every => "every",
988
            Tok::Satisfies => "satisfies",
989
            Tok::Or => "or",
990
            Tok::And => "and",
991
            Tok::Between => "between",
992
            Tok::True => "true",
993
            Tok::False => "false",
994
            Tok::Null => "null",
995
            Tok::Not => "not",
996
            Tok::Function => "function",
997
            Tok::InstanceOf => "instance of",
998
            Tok::Le => "<=",
999
            Tok::Lt => "<",
1000
            Tok::Ge => ">=",
1001
            Tok::Gt => ">",
1002
            Tok::Eq => "=",
1003
            Tok::Ne => "!=",
1004
            Tok::Plus => "+",
1005
            Tok::Arrow => "->",
1006
            Tok::Minus => "-",
1007
            Tok::StarStar => "**",
1008
            Tok::Star => "*",
1009
            Tok::Slash => "/",
1010
            Tok::DotDotDot => "...",
1011
            Tok::DotDot => "..",
1012
            Tok::Dot => ".",
1013
            Tok::LParen => "(",
1014
            Tok::RParen => ")",
1015
            Tok::LBracket => "[",
1016
            Tok::RBracket => "]",
1017
            Tok::RBracketOpen => "]",
1018
            Tok::LBrace => "{",
1019
            Tok::RBrace => "}",
1020
            Tok::Comma => ",",
1021
            Tok::Colon => ":",
1022
            Tok::Num(n) => return write!(f, "{n}"),
1023
            Tok::Str(s) => return write!(f, "{s:?}"),
1024
            Tok::TemporalLit(s) => return write!(f, "@{s:?}"),
1025
            Tok::Name(s) => return write!(f, "{s}"),
1026
            Tok::QuotedName(s) => return write!(f, "`{s}`"),
1027
            Tok::Comment => unreachable!("Comment is logos::skip — never emitted"),
1028
        };
1029
        f.write_str(s)
1030
    }
1031
}