Public repository: timo / feel

Reader

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

feat(core): recognise multi-word FEEL names in the lexer (ADR-17)

public

feat(core): recognise multi-word FEEL names in the lexer (ADR-17)

Full FEEL names may contain spaces (`full name`, `string length`). A second
pass over the token stream joins them into a single `Name` token, so the
grammar is unchanged — the `Name` terminal just carries a space-normalised
payload now.

Two tiers, both sound without scope knowledge (FEEL has no juxtaposition, so
two adjacent `Name` tokens can only be one name):

- Tier 1: greedily merge a run of adjacent `Name` tokens; keywords are separate
  tokens and stop the run, so `x and y` stays boolean and stays back-compatible.
- Tier 2: a fixed, closed dictionary of keyword-containing builtin phrases
  (`date and time`) recognised only in call position (followed by `(`). This is
  the bounded "built-in exception" — it needs no name oracle because the set is
  finite and holds only builtin names, never user variables.

Builtin dispatch and value semantics for the new multi-word functions follow in
the next unit; keyword-phrase builtins are temporal and still dispatch to an
error-null for now (the name machinery is what lands here).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Changesetc1abc8bcec97de47e6707823e383fc52972ad59a
Author (claimed)Timo Stolz <timo.stolz@gmail.com>,
Parents9641f3585a8d
Children
Pushlog
by timo via ssh

modified crates/feel-core/src/builtins.rs +11 −2

@@ -23,8 +23,17 @@
2323
 use crate::regex_provider::{match_value, FeelRegex};
2424
 use crate::Value;
2525
 
26
-/// Dispatch a single-word built-in call. Arguments are already evaluated. The
27
-/// `regex` provider is consulted only by `matches`/`replace`/`split`.
26
+/// Built-in function names that contain a *keyword* word-part, which Tier-1
27
+/// whitespace joining in the lexer cannot form (a keyword is a separate token
28
+/// that stops the merge). The lexer recognises these against this fixed, closed
29
+/// dictionary and only in call position (DECISIONS.md ADR-17). They are all
30
+/// temporal, so they currently dispatch to an error-null (the `_` arm of
31
+/// [`call`]) — the *name* machinery is in place; the temporal value semantics
32
+/// land later. The phrases share no prefix.
33
+pub(crate) const KEYWORD_PHRASE_BUILTINS: &[&str] = &["date and time", "years and months duration"];
34
+
35
+/// Dispatch a single- or multi-word built-in call. Arguments are already
36
+/// evaluated. The `regex` provider is consulted only by `matches`/`replace`/`split`.
2837
 pub(crate) fn call(name: &str, args: Vec<Value>, regex: &dyn FeelRegex) -> Value {
2938
     // A type error in any (top-level) argument propagates as an error-null.
3039
     if args.iter().any(|a| matches!(a, Value::Error)) {

modified crates/feel-core/src/feel.lalrpop +16 −10

@@ -4,11 +4,14 @@
44
 // (`+ - * /`, `**`, unary `-`), comparison (`< <= > >= = !=`, `between`, `in`),
55
 // three-valued logic (`and`/`or`/`not`), control flow (`if/then/else`,
66
 // `for … return`, `some/every … satisfies`), variable references, and
7
-// single-word built-in function calls (`abs(-1)`, `count([1,2])`, …; see
8
-// DECISIONS.md ADR-15). Still a deliberate subset of full FEEL: no space-
9
-// containing function names (`string length`), no temporal types, no ranges as
10
-// first-class values (see ADR-7/ADR-8). It is left-recursive on purpose;
11
-// lalrpop (LR(1)) handles that natively, which is the reason we chose it.
7
+// built-in function calls (`abs(-1)`, `string length("x")`, …; see DECISIONS.md
8
+// ADR-15/ADR-17). Names may contain spaces (`full name`, `string length`): the
9
+// lexer joins multi-word names into one `Name` token (ADR-17), so the grammar is
10
+// unchanged — `Name` simply carries a space-normalised payload. Still a
11
+// deliberate subset of full FEEL: no special characters in names (`+ - * / . '`),
12
+// no temporal types, no ranges as first-class values (see ADR-7/ADR-8). It is
13
+// left-recursive on purpose; lalrpop (LR(1)) handles that natively, which is the
14
+// reason we chose it.
1215
 
1316
 use crate::ast::{ArithOp, CmpOp, Expr, Interval, IterSource, Quantifier};
1417
 use crate::lexer::{LexError, Tok};
@@ -140,9 +143,11 @@
140143
 // Postfix path access `a.b.c` binds tighter than unary minus, so `-a.b` is
141144
 // `-(a.b)`. `..` is its own (longer) token, so it never collides with `.`.
142145
 //
143
-// A single-word built-in call `name(args)` also lives here. After a `Name`, an
144
-// LR(1) lookahead of `(` shifts into the call; any other lookahead reduces to
145
-// `Primary → Name → Var`, so plain variable references are unaffected.
146
+// A built-in call `name(args)` also lives here. After a `Name`, an LR(1)
147
+// lookahead of `(` shifts into the call; any other lookahead reduces to
148
+// `Primary → Name → Var`, so plain variable references are unaffected. Multi-word
149
+// heads (`string length(…)`) are a single `Name` token by the time the parser
150
+// sees them (the lexer joined them), so this production needs no change.
146151
 // `not(...)` keeps its own Primary rule because `not` is a keyword token (not a
147152
 // `Name`), so it never reaches this production.
148153
 Postfix: Expr = {
@@ -218,5 +223,6 @@
218223
 
219224
 // `Num` (f64 literal), `Str` (double-quoted, no escapes) and `Name` (a Unicode
220225
 // identifier: XID-start then XID-continue, so `über`/`preis`/`naïve` parse, and
221
-// longest-match keeps `fortune` a name not the keyword `for`) are produced by the
222
-// external `logos` lexer — see `lexer.rs` and the `extern` block above.
226
+// longest-match keeps `fortune` a name not the keyword `for`; multi-word names
227
+// like `full name` arrive pre-joined) are produced by the external `logos` lexer
228
+// — see `lexer.rs` and the `extern` block above.

modified crates/feel-core/src/lexer.rs +130 −9

@@ -12,6 +12,14 @@
1212
 //! `unicode-ident`'s compact XID tables in [`lex_name`]. Keywords are not separate
1313
 //! `logos` tokens — that would break maximal munch (`fortune` must stay one name,
1414
 //! 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* built-in phrases (`date and time`) in call
22
+//! position. Spaces in names are normalised to a single space.
1523
 
1624
 use core::fmt;
1725
 
@@ -162,17 +170,130 @@
162170
     })
163171
 }
164172
 
173
+/// One `(start, token, end)` triple, or a lex error for an unrecognised char.
174
+type Spanned = Result<(usize, Tok, usize), LexError>;
175
+
165176
 /// Token stream for the lalrpop parser: `(start, token, end)` byte offsets, with
166
-/// lexed identifiers remapped to keyword tokens. A lex error becomes the `Err`
167
-/// arm, which lalrpop reports as a `ParseError::User`.
168
-pub(crate) fn lex(input: &str) -> impl Iterator<Item = Result<(usize, Tok, usize), LexError>> + '_ {
169
-    Tok::lexer(input).spanned().map(|(tok, span)| {
170
-        let tok = tok?;
171
-        let tok = match &tok {
172
-            Tok::Name(name) => keyword(name).unwrap_or(tok),
173
-            _ => tok,
177
+/// lexed identifiers remapped to keyword tokens and multi-word FEEL names joined.
178
+/// A lex error becomes the `Err` arm, which lalrpop reports as a `ParseError::User`.
179
+pub(crate) fn lex(input: &str) -> impl Iterator<Item = Spanned> {
180
+    // Pass 1: raw `logos` tokens, with identifiers remapped to keyword tokens.
181
+    let raw: Vec<Spanned> = Tok::lexer(input)
182
+        .spanned()
183
+        .map(|(tok, span)| {
184
+            let tok = tok?;
185
+            let tok = match &tok {
186
+                Tok::Name(name) => keyword(name).unwrap_or(tok),
187
+                _ => tok,
188
+            };
189
+            Ok((span.start, tok, span.end))
190
+        })
191
+        .collect();
192
+    // Pass 2: join multi-word names into single `Name` tokens (ADR-17).
193
+    join_names(raw).into_iter()
194
+}
195
+
196
+/// Collapse multi-word FEEL names into single `Name` tokens. Two tiers, both
197
+/// sound without scope knowledge because FEEL has no juxtaposition of two
198
+/// expressions:
199
+///
200
+/// - **Tier 1:** a run of adjacent `Name` tokens (keywords are separate tokens
201
+///   and stop the run) is one name — `string length`, `full name`. Payloads are
202
+///   joined with a single space.
203
+/// - **Tier 2:** a fixed dictionary of *keyword-containing* built-in phrases
204
+///   ([`crate::builtins::KEYWORD_PHRASE_BUILTINS`], e.g. `date and time`) is
205
+///   recognised only in **call position** (immediately followed by `(`). This is
206
+///   the bounded "built-in exception": the set is finite and holds only built-in
207
+///   names, never user variables, so no name oracle is needed.
208
+fn join_names(toks: Vec<Spanned>) -> Vec<Spanned> {
209
+    let mut out: Vec<Spanned> = Vec::with_capacity(toks.len());
210
+    let mut i = 0;
211
+    while i < toks.len() {
212
+        // Errors and non-name tokens that don't start a phrase pass straight through.
213
+        let Ok((start, tok, end)) = &toks[i] else {
214
+            out.push(toks[i].clone());
215
+            i += 1;
216
+            continue;
174217
         };
175
-        Ok((span.start, tok, span.end))
218
+        // Tier 2 first: a known keyword-phrase builtin would otherwise be split
219
+        // by Tier 1 at its keyword (`date` | `and` | `time`).
220
+        if let Some((payload, span_end, next)) = match_keyword_phrase(&toks, i) {
221
+            out.push(Ok((*start, Tok::Name(payload), span_end)));
222
+            i = next;
223
+            continue;
224
+        }
225
+        // Tier 1: greedily merge a run of adjacent `Name` tokens.
226
+        if let Tok::Name(first) = tok {
227
+            let run_start = *start;
228
+            let mut words = first.clone();
229
+            let mut run_end = *end;
230
+            let mut j = i + 1;
231
+            while let Some(Ok((_, Tok::Name(next), e))) = toks.get(j) {
232
+                words.push(' ');
233
+                words.push_str(next);
234
+                run_end = *e;
235
+                j += 1;
236
+            }
237
+            out.push(Ok((run_start, Tok::Name(words), run_end)));
238
+            i = j;
239
+            continue;
240
+        }
241
+        out.push(toks[i].clone());
242
+        i += 1;
243
+    }
244
+    out
245
+}
246
+
247
+/// If a fixed keyword-phrase builtin matches the tokens starting at `i` *and* is
248
+/// immediately followed by `(`, return its joined payload, the byte offset where
249
+/// the phrase ends, and the index of the following `(`. The phrases share no
250
+/// prefix, so iteration order is irrelevant.
251
+fn match_keyword_phrase(toks: &[Spanned], i: usize) -> Option<(String, usize, usize)> {
252
+    for phrase in crate::builtins::KEYWORD_PHRASE_BUILTINS {
253
+        let words: Vec<&str> = phrase.split(' ').collect();
254
+        let after = i + words.len();
255
+        // Need the phrase words plus a following `(` to even consider it.
256
+        if after >= toks.len() {
257
+            continue;
258
+        }
259
+        let mut end = 0;
260
+        let matched = words.iter().enumerate().all(|(k, word)| match &toks[i + k] {
261
+            Ok((_, tok, e)) if tok_word(tok) == Some(*word) => {
262
+                end = *e;
263
+                true
264
+            }
265
+            _ => false,
266
+        });
267
+        if matched && matches!(toks.get(after), Some(Ok((_, Tok::LParen, _)))) {
268
+            return Some(((*phrase).to_string(), end, after));
269
+        }
270
+    }
271
+    None
272
+}
273
+
274
+/// The "word" a token contributes to a multi-word name: an identifier's text, or
275
+/// a keyword's spelling (so phrase matching can see the `and` in `date and time`).
276
+/// Operators and punctuation are not words.
277
+fn tok_word(tok: &Tok) -> Option<&str> {
278
+    Some(match tok {
279
+        Tok::Name(s) => s.as_str(),
280
+        Tok::For => "for",
281
+        Tok::In => "in",
282
+        Tok::Return => "return",
283
+        Tok::If => "if",
284
+        Tok::Then => "then",
285
+        Tok::Else => "else",
286
+        Tok::Some => "some",
287
+        Tok::Every => "every",
288
+        Tok::Satisfies => "satisfies",
289
+        Tok::Or => "or",
290
+        Tok::And => "and",
291
+        Tok::Between => "between",
292
+        Tok::True => "true",
293
+        Tok::False => "false",
294
+        Tok::Null => "null",
295
+        Tok::Not => "not",
296
+        _ => return None,
176297
     })
177298
 }
178299
 

modified crates/feel-core/src/lib.rs +46 −0

@@ -464,6 +464,52 @@
464464
         assert_eq!(ev("{a: 1} = {a: 2}"), b(false));
465465
         assert_eq!(ev("{a: 1} = {a: 1, b: 2}"), b(false));
466466
         assert_eq!(ev("{a: 1} = 1"), Value::Null); // different types -> null
467
+    }
468
+
469
+    #[test]
470
+    fn multi_word_names_as_identifiers() {
471
+        // Full FEEL names may contain spaces (ADR-17). The lexer joins them.
472
+        let mut ctx = Context::empty();
473
+        ctx.insert("full name", Value::String("Ada".into()));
474
+        ctx.insert("year of birth", num(1815.0));
475
+        let ev = |src: &str| evaluate(src, &ctx).unwrap_or_else(|e| panic!("`{src}` failed: {e}"));
476
+
477
+        assert_eq!(ev("full name"), Value::String("Ada".into()));
478
+        assert_eq!(ev("year of birth + 1"), num(1816.0));
479
+        // Multi-word loop variable, referenced in the body.
480
+        assert_eq!(
481
+            ev("for my index in [1, 2] return my index + 1"),
482
+            list(vec![num(2.0), num(3.0)])
483
+        );
484
+        // Multi-word context-literal key, read back via a multi-word path segment.
485
+        assert_eq!(ev("{first name: 1}.first name"), num(1.0));
486
+        // An unbound multi-word name is a value-null, not a parse error.
487
+        assert_eq!(ev("unbound display name"), Value::Null);
488
+    }
489
+
490
+    #[test]
491
+    fn multi_word_join_is_backward_compatible() {
492
+        // Keywords still break a name run: `and` stays the boolean operator.
493
+        assert_eq!(ev("true and false"), b(false));
494
+        // Chained path access is unaffected.
495
+        assert_eq!(ev("{a: {b: 1}}.a.b"), num(1.0));
496
+        // A single-word builtin call is unaffected by the join machinery; the
497
+        // `(` lookahead keeps `string(1)` one word, not a merge with what follows.
498
+        assert_eq!(ev("string(1)"), Value::String("1".into()));
499
+        assert_eq!(ev("count([1, 2, 3])"), num(3.0));
500
+    }
501
+
502
+    #[test]
503
+    fn keyword_phrase_builtin_parses_in_call_position() {
504
+        // A keyword-containing builtin name (`date and time`) is recognised as one
505
+        // call head in call position — raw error-null until temporal types land,
506
+        // NOT `date and (time(...))` (ADR-17). Out of call position it stays the
507
+        // boolean `and` (back-compat), so `date`/`time` unbound -> a value-null.
508
+        let raw = |src: &str| {
509
+            evaluate(src, &Context::empty()).unwrap_or_else(|e| panic!("`{src}` failed: {e}"))
510
+        };
511
+        assert_eq!(raw(r#"date and time("2018-12-08")"#), Value::Error);
512
+        assert_eq!(ev("date and time"), Value::Null);
467513
     }
468514
 
469515
     #[test]