Public repository: timo / feel

Reader

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

feat(feel-core): fuse special-character name runs via parse-time scope probe

draft feat/special-char-names

feat(feel-core): fuse special-character name runs via parse-time scope probe

FEEL grammar rules 25-30 let names contain the additional name symbols
- + * / . ; section 10.3.1.6 resolves the ambiguity against the scope
(longest in-scope match, left to right; spaces are not part of the name;
(a)-(b) is the escape hatch). Until now such names silently misparsed
(Date-Time2.hour as Date - (Time2.hour)).

- ScopeProbe trait (std-only, ADR-1): the parse-time name oracle; impl for
  Context mirrors Expr::Var resolution (context binding or built-in name).
- Lexer pass 2.5 (after join_names, before mark_reverse_open):
  fuse_special_names scans maximal word ((-|+|*|/|.) word)+ runs -
  words are joined Name payloads or keyword spellings (tok_word), so
  if-then-style reserved-word parts are reachable - tries candidate
  prefixes longest-first against the probe, and fuses the first hit.
  The scan resumes after a fused name (Date-Time - Date-Time2 keeps the
  minus an operator: the TCK 0007 expectation) and inside a run after a
  miss (a-b-c with only b-c bound parses as a - b-c). Adjacency never
  forms a run, so a and b / for x in y are untouched.
- compile_with_probe(expr, probe) + probe-aware one-shot evaluate
  (the context is the scope); compile() stays probe-free - a compiled
  program pins no scope - so existing parses are byte-identical.
- CompiledExpr::has_name_runs() reports whether the parse consulted the
  scope; name_run_candidates(expr) lists every fusable candidate
  probe-free, for hosts that cache parses across contexts (feel-pg).
- Declaration slots (for a-b in, params, context keys) are deferred:
  the in-grammar production is not LR(1)-conflict-free in call args
  (f(a-b: 1) vs f(a-b)); no TCK shape needs them (ADR-47).
Changeset1149ec6ba1b319dc9d1edb60ec1cca430df93072
Author (claimed)Timo Stolz <timo.stolz@gmail.com>,
Parentsa00c766d04db
Children
Pushlog
by timo via ssh

modified crates/feel-core/src/lexer.rs +190 −12

@@ -21,6 +21,16 @@
2121
 //! recognises *keyword-containing* reserved phrases (`date and time`, the two
2222
 //! durations) wherever they occur — they are atomic temporal type/constructor
2323
 //! 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.
2434
 //!
2535
 //! Java-style comments (`// … \n` and `/* … */`) are skipped at the logos level
2636
 //! (pass 1). `logos` maximal munch makes `//` / `/*` win over the single `/`
@@ -298,10 +308,46 @@
298308
 type Spanned = Result<(usize, Tok, usize), LexError>;
299309
 
300310
 /// Token stream for the lalrpop parser: `(start, token, end)` byte offsets, with
301
-/// lexed identifiers remapped to keyword tokens and multi-word FEEL names joined.
302
-/// A lex error becomes the `Err` arm, which lalrpop reports as a `ParseError::User`.
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`.
303315
 pub(crate) fn lex(input: &str) -> impl Iterator<Item = Spanned> {
304
-    // Pass 1: raw `logos` tokens, with identifiers remapped to keyword tokens.
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> {
305351
     let raw: Vec<Spanned> = Tok::lexer(input)
306352
         .spanned()
307353
         .map(|(tok, span)| {
@@ -313,15 +359,7 @@
313359
             Ok((span.start, tok, span.end))
314360
         })
315361
         .collect();
316
-    // Pass 1.5: fuse the `instance` `of` pair into a single operator token *before*
317
-    // name-joining, so the surrounding words don't merge across it and a lone `of`
318
-    // (`year of birth`, the `day of week` built-in) stays an ordinary name-word.
319
-    let raw = mark_instance_of(raw);
320
-    // Pass 2: join multi-word names into single `Name` tokens (ADR-17).
321
-    let raw = join_names(raw);
322
-    // Pass 3: retag a reverse-open interval opener `]a..b]` to `RBracketOpen` (runs
323
-    // last so it sees joined `Name` tokens when classifying value-completed position).
324
-    mark_reverse_open(raw).into_iter()
362
+    mark_instance_of(raw)
325363
 }
326364
 
327365
 /// Retag every `]` that *opens* a reverse-bracket interval (`]a..b]`, FEEL's
@@ -536,6 +574,146 @@
536574
         Tok::Function => "function",
537575
         _ => return None,
538576
     })
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
+/// Scan the maximal special-character name run starting at token `i`:
602
+/// `word ((-|+|*|/|.) word)*`, where a word is a joined `Name` payload or a
603
+/// keyword's spelling (`tok_word` — keywords are legal name parts, and this is
604
+/// what makes `if-then`-style names reachable; §10.3.1.6). Parens, commas,
605
+/// brackets, literals, adjacency (`a and b`) and any other token end the run.
606
+/// Returns the per-unit `(word, start, end)` and the separator chars.
607
+/// A lone word is not a run — `None`.
608
+fn scan_name_run<'a>(toks: &'a [Spanned], i: usize) -> Option<(Vec<RunUnit<'a>>, Vec<char>)> {
609
+    let (word, start, end) = match &toks[i] {
610
+        Ok((s, tok, e)) => (tok_word(tok)?, *s, *e),
611
+        Err(_) => return None,
612
+    };
613
+    let mut units = vec![(word, start, end)];
614
+    let mut seps = Vec::new();
615
+    let mut j = i + 1;
616
+    loop {
617
+        let sep = toks
618
+            .get(j)
619
+            .and_then(|t| t.as_ref().ok())
620
+            .and_then(|(_, t, _)| name_symbol(t));
621
+        let Some(sep) = sep else { break };
622
+        let next = toks
623
+            .get(j + 1)
624
+            .and_then(|t| t.as_ref().ok())
625
+            .and_then(|(s, t, e)| tok_word(t).map(|w| (w, *s, *e)));
626
+        let Some((w, s, e)) = next else { break };
627
+        seps.push(sep);
628
+        units.push((w, s, e));
629
+        j += 2;
630
+    }
631
+    (units.len() > 1).then_some((units, seps))
632
+}
633
+
634
+/// The candidate name a run prefix stands for: the word units joined by their
635
+/// separators, verbatim. Spaces are not part of the token sequence (§10.3.1.6),
636
+/// so `a - b` and `a-b` produce the same candidate — the separator *characters*
637
+/// are part of the name, the whitespace around them is not.
638
+fn candidate_payload(units: &[RunUnit<'_>], seps: &[char]) -> String {
639
+    let mut payload = units[0].0.to_string();
640
+    for ((word, _, _), sep) in units[1..].iter().zip(seps) {
641
+        payload.push(*sep);
642
+        payload.push_str(word);
643
+    }
644
+    payload
645
+}
646
+
647
+/// Fuse special-character name runs into single `Name` tokens, resolving the
648
+/// §10.3.1.6 ambiguity against `probe` (ADR-47). At each word-unit position the
649
+/// maximal run is scanned; its prefixes are tried **longest first** against the
650
+/// probe, and the first in-scope prefix is fused into one `Name` spanning it.
651
+/// Scanning then continues *after* the fused name, so `Date-Time - Date-Time2`
652
+/// fuses `Date-Time`, leaves the `-` an operator, and fuses `Date-Time2` — the
653
+/// subtraction the TCK expects, reproduced by longest-match-at-each-position.
654
+/// When no prefix is in scope the run is left alone (arithmetic stands) and the
655
+/// scan resumes at the next token, so `a-b-c` with only `b-c` bound parses as
656
+/// `a - b-c`. A keyword word-unit makes reserved-word parts reachable (`if-then`)
657
+/// but, without a symbol, adjacency never forms a run (`a and b` is untouched).
658
+///
659
+/// Returns the tokens plus `true` when any run was seen — the parse consulted
660
+/// the scope ([`crate::CompiledExpr::has_name_runs`]).
661
+fn fuse_special_names(toks: Vec<Spanned>, probe: &dyn crate::ScopeProbe) -> (Vec<Spanned>, bool) {
662
+    let mut out: Vec<Spanned> = Vec::with_capacity(toks.len());
663
+    let mut saw_run = false;
664
+    let mut i = 0;
665
+    while i < toks.len() {
666
+        let Some((units, seps)) = scan_name_run(&toks, i) else {
667
+            out.push(toks[i].clone());
668
+            i += 1;
669
+            continue;
670
+        };
671
+        saw_run = true;
672
+        // Candidate prefixes, longest first (§10.3.1.6): only prefixes with at
673
+        // least one separator are fusable — a lone word is already one token.
674
+        let mut fused = None;
675
+        for k in (2..=units.len()).rev() {
676
+            let payload = candidate_payload(&units[..k], &seps[..k - 1]);
677
+            if probe.contains(&payload) {
678
+                fused = Some((k, payload));
679
+                break;
680
+            }
681
+        }
682
+        match fused {
683
+            Some((k, payload)) => {
684
+                let (_, start, _) = units[0];
685
+                let (_, _, end) = units[k - 1];
686
+                out.push(Ok((start, Tok::Name(payload), end)));
687
+                // Skip the fused prefix: k units plus the k-1 separators.
688
+                i += 2 * k - 1;
689
+            }
690
+            None => {
691
+                out.push(toks[i].clone());
692
+                i += 1;
693
+            }
694
+        }
695
+    }
696
+    (out, saw_run)
697
+}
698
+
699
+/// Every special-character name candidate `expr` could fuse under *some* scope
700
+/// (ADR-47): all ≥2-unit prefixes of every run, from every unit position (so
701
+/// `a-b-c` yields `a-b-c`, `a-b` and `b-c`). Probe-free and AST-free — a host
702
+/// that caches a probe-free parse across contexts (feel-pg's `fn_extra` slot)
703
+/// checks these per context: none bound ⇒ the cached parse is already
704
+/// scope-correct; any bound ⇒ re-parse against that context (§10.3.1.6).
705
+pub(crate) fn name_run_candidates(input: &str) -> Vec<String> {
706
+    let toks = join_names(lex_joined(input));
707
+    let mut out = Vec::new();
708
+    for i in 0..toks.len() {
709
+        if let Some((units, seps)) = scan_name_run(&toks, i) {
710
+            // Longest first, mirroring the probe's resolution order (§10.3.1.6).
711
+            for k in (2..=units.len()).rev() {
712
+                out.push(candidate_payload(&units[..k], &seps[..k - 1]));
713
+            }
714
+        }
715
+    }
716
+    out
539717
 }
540718
 
541719
 impl fmt::Display for Tok {

modified crates/feel-core/src/lib.rs +271 −8

@@ -78,6 +78,31 @@
7878
         let mut child = self.clone();
7979
         child.insert(name, value);
8080
         child
81
+    }
82
+}
83
+
84
+/// The parse-time "name oracle" for special-character names (§10.3.1.6, ADR-47):
85
+/// decides which candidate names are in scope, so the lexer can fuse FEEL's
86
+/// additional name symbols (`a-b`, `Date-Time`, `x.y`) into single names.
87
+///
88
+/// std-only (ADR-1), like the other host seams. The canonical implementation is
89
+/// [`Context`] itself — parse and eval must agree on what "in scope" means, so
90
+/// the impl mirrors `Expr::Var` resolution exactly: a context binding or a
91
+/// built-in function name. A host that parses before its context exists can
92
+/// implement this against its own root-key view (e.g. a jsonb row's top-level
93
+/// keys — feel-pg just builds the `Context` first, which is already cheap).
94
+pub trait ScopeProbe {
95
+    /// Whether `name` resolves at evaluation time — i.e. `Expr::Var(name)` would
96
+    /// find a value (a context binding or a built-in function name).
97
+    fn contains(&self, name: &str) -> bool;
98
+}
99
+
100
+impl ScopeProbe for Context {
101
+    fn contains(&self, name: &str) -> bool {
102
+        // Mirrors `Expr::Var` (eval.rs): a context binding wins, then a built-in
103
+        // name (a first-class function value, ADR-36), then null — the probe asks
104
+        // about the first two.
105
+        self.get(name).is_some() || crate::builtins::is_builtin(name)
81106
     }
82107
 }
83108
 
@@ -96,7 +121,16 @@
96121
 /// assert_eq!(prog.evaluate(&ctx).unwrap(), Value::Number(2.0));
97122
 /// ```
98123
 #[derive(Debug, Clone)]
99
-pub struct CompiledExpr(ast::Expr);
124
+pub struct CompiledExpr {
125
+    /// The parsed program.
126
+    expr: ast::Expr,
127
+    /// Whether the parse consulted a scope probe on a special-character name
128
+    /// run (`a-b`, `Date-Time`, …) — i.e. is **scope-dependent**: another scope
129
+    /// could fuse the same text differently (ADR-47). Only a probe-aware parse
130
+    /// (`compile_with_probe`/`evaluate`) sets it; `compile` is probe-free and
131
+    /// reports `false`.
132
+    name_runs: bool,
133
+}
100134
 
101135
 impl CompiledExpr {
102136
     /// Evaluate this already-parsed expression against a context, using the
@@ -121,14 +155,14 @@
121155
     /// here (e.g. feel-pg's transaction start), which also makes `now()`/`today()`
122156
     /// deterministic in tests.
123157
     pub fn evaluate_with_env(&self, context: &Context, env: &EvalEnv) -> Result<Value, FeelError> {
124
-        eval::Evaluator::new(env).eval(&self.0, context)
158
+        eval::Evaluator::new(env).eval(&self.expr, context)
125159
     }
126160
 
127161
     /// The parsed AST. `pub(crate)` so the `range(string)` built-in can inspect a
128162
     /// freshly-parsed range literal's *shape* (its endpoints must be literals, not
129163
     /// arbitrary expressions — DMN §10.3.4.6) before evaluating it.
130164
     pub(crate) fn ast(&self) -> &ast::Expr {
131
-        &self.0
165
+        &self.expr
132166
     }
133167
 
134168
     /// `true` if this expression never reads the wall clock — it calls neither
@@ -142,7 +176,18 @@
142176
     /// [`EvalEnv::forbidding_named_zones`]. Host functions/objects are out of scope
143177
     /// here (the embedder's concern; feel-pg has no host-function seam).
144178
     pub fn is_clock_free(&self) -> bool {
145
-        self.0.is_clock_free()
179
+        self.expr.is_clock_free()
180
+    }
181
+
182
+    /// `true` if parsing consulted a scope probe on a special-character name run
183
+    /// (`a-b`, `Date-Time`, …; §10.3.1.6, ADR-47): this parse is
184
+    /// **scope-dependent** — the same text could parse differently under another
185
+    /// scope. Only a probe-aware parse sets it; [`compile`] is probe-free and
186
+    /// reports `false`. Hosts that cache parses across contexts can instead check
187
+    /// [`name_run_candidates`] against each context, which distinguishes "could
188
+    /// be ambiguous" from "this scope actually changes the parse".
189
+    pub fn has_name_runs(&self) -> bool {
190
+        self.name_runs
146191
     }
147192
 }
148193
 
@@ -246,27 +291,67 @@
246291
 ///
247292
 /// Returns [`FeelError::Parse`] if the expression is syntactically invalid.
248293
 ///
294
+/// **Probe-free** (ADR-47): special-character name runs (`a-b`, `Date-Time`)
295
+/// parse as arithmetic here — a compiled program must not pin one scope. Use
296
+/// [`compile_with_probe`] when the scope is known at parse time, or the one-shot
297
+/// [`evaluate`], which uses the context as the probe (§10.3.1.6).
298
+///
249299
 /// `ExprParser::new()` is now cheap (the external `logos` lexer builds no runtime
250300
 /// matcher — see `lexer.rs`), so there is no parser to cache; the cost is the
251301
 /// per-call parse itself, which [`CompiledExpr`] lets callers pay once.
252302
 pub fn compile(expr: &str) -> Result<CompiledExpr, FeelError> {
253303
     feel::ExprParser::new()
254304
         .parse(lexer::lex(expr))
255
-        .map(CompiledExpr)
305
+        .map(|expr| CompiledExpr { expr, name_runs: false })
256306
         .map_err(|e| FeelError::Parse(e.to_string()))
257307
 }
258308
 
309
+/// Parse a FEEL expression with scope-dependent name resolution (§10.3.1.6,
310
+/// ADR-47): special-character name runs (`a-b`, `Date-Time`, `x.y`) are fused
311
+/// into single names when — and only when — the joined candidate is in scope
312
+/// per `probe`, longest in-scope match preferred, left to right. Spaces are not
313
+/// part of the name (`a - b` is the same candidate as `a-b`); `(a)-(b)` forces
314
+/// the operator reading.
315
+///
316
+/// The result's [`CompiledExpr::has_name_runs`] tells whether the parse
317
+/// consulted the scope at all. For expressions with no name-run *pattern*
318
+/// (see [`name_run_candidates`]), this is byte-identical to [`compile`].
319
+pub fn compile_with_probe(
320
+    expr: &str,
321
+    probe: &dyn ScopeProbe,
322
+) -> Result<CompiledExpr, FeelError> {
323
+    let (toks, name_runs) = lexer::lex_with_probe(expr, probe);
324
+    feel::ExprParser::new()
325
+        .parse(toks)
326
+        .map(|expr| CompiledExpr { expr, name_runs })
327
+        .map_err(|e| FeelError::Parse(e.to_string()))
328
+}
329
+
259330
 /// Parse and evaluate a FEEL expression against a context.
260331
 ///
261
-/// Convenience for `compile(expr)?.evaluate(context)`; prefer [`compile`] when
262
-/// evaluating the same expression more than once.
332
+/// Convenience for `compile_with_probe(expr, context)?.evaluate(context)`;
333
+/// prefer [`compile_with_probe`] when evaluating the same expression more than
334
+/// once against the same scope. The context **is** the scope for §10.3.1.6
335
+/// name resolution (ADR-47): a name like `a-b` resolves to the context binding
336
+/// when one exists, and to subtraction otherwise.
263337
 ///
264338
 /// ```
265339
 /// use feel_core::{evaluate, Context, Value};
266340
 /// assert_eq!(evaluate("1 + 1", &Context::empty()).unwrap(), Value::Number(2.0));
267341
 /// ```
268342
 pub fn evaluate(expr: &str, context: &Context) -> Result<Value, FeelError> {
269
-    compile(expr)?.evaluate(context)
343
+    compile_with_probe(expr, context)?.evaluate(context)
344
+}
345
+
346
+/// Every special-character name candidate `expr` could fuse under *some* scope
347
+/// (§10.3.1.6, ADR-47) — e.g. `a-b-c` yields `a-b-c`, `a-b`, `b-c`. Probe-free
348
+/// and cheap; the use case is a host that caches a probe-free parse across
349
+/// contexts (feel-pg's `fn_extra` slot): if none of the candidates is bound in
350
+/// a given context, the cached parse is already scope-correct; if any is bound,
351
+/// re-parse that context with [`compile_with_probe`]. An empty result means the
352
+/// expression's parse is scope-independent for every possible context.
353
+pub fn name_run_candidates(expr: &str) -> Vec<String> {
354
+    lexer::name_run_candidates(expr)
270355
 }
271356
 
272357
 /// Parse a structural FEEL type expression (`number`, `list<string>`,
@@ -339,6 +424,184 @@
339424
     #[test]
340425
     fn compile_reports_parse_error() {
341426
         assert!(matches!(compile("1 +"), Err(FeelError::Parse(_))));
427
+    }
428
+
429
+    // ----------------------------------------------------------------------- //
430
+    // Special-character names (§10.3.1.6, ADR-47)
431
+    // ----------------------------------------------------------------------- //
432
+
433
+    fn ctx_of(pairs: &[(&str, Value)]) -> Context {
434
+        let mut c = Context::empty();
435
+        for (k, v) in pairs {
436
+            c.insert(*k, v.clone());
437
+        }
438
+        c
439
+    }
440
+
441
+    /// A FEEL context value from `(key, value)` pairs.
442
+    fn ctx_value(pairs: &[(&str, Value)]) -> Value {
443
+        Value::Context(pairs.iter().map(|(k, v)| (k.to_string(), v.clone())).collect())
444
+    }
445
+
446
+    /// One-shot evaluation against a scope built from `(name, value)` pairs —
447
+    /// the §10.3.1.6 stance: the context is the name oracle.
448
+    fn eval_in(src: &str, pairs: &[(&str, Value)]) -> Value {
449
+        evaluate(src, &ctx_of(pairs))
450
+            .unwrap_or_else(|e| panic!("`{src}` failed: {e}"))
451
+            .into_lenient()
452
+    }
453
+
454
+    #[test]
455
+    fn special_char_names_resolve_against_scope() {
456
+        // `a-b` is the in-scope NAME when bound, subtraction otherwise — and
457
+        // `a - b` is the same candidate: spaces are not part of the name.
458
+        assert_eq!(eval_in("a-b", &[("a-b", num(10.0))]), num(10.0));
459
+        assert_eq!(eval_in("a - b", &[("a-b", num(10.0))]), num(10.0));
460
+        assert_eq!(eval_in("a-b", &[]), Value::Null); // unbound: subtraction of two nulls
461
+        // All five additional name symbols (grammar rule 30).
462
+        assert_eq!(eval_in("a+b", &[("a+b", num(1.0))]), num(1.0));
463
+        assert_eq!(eval_in("a*b", &[("a*b", num(2.0))]), num(2.0));
464
+        assert_eq!(eval_in("a/b", &[("a/b", num(3.0))]), num(3.0));
465
+        assert_eq!(eval_in("a.b", &[("a.b", num(4.0))]), num(4.0));
466
+        // Keywords are legal name parts in symbol runs (`if-then`; unfused, the
467
+        // `if` keyword would make it a parse error).
468
+        assert_eq!(eval_in("if-then", &[("if-then", b(true))]), b(true));
469
+        // A multi-word name part joins before fusion (`total price-total`).
470
+        assert_eq!(
471
+            eval_in("total price-total", &[("total price-total", num(5.0))]),
472
+            num(5.0)
473
+        );
474
+        // Fusion reaches every reference slot — call arguments:
475
+        assert_eq!(eval_in("not(x-y)", &[("x-y", b(true))]), b(false));
476
+    }
477
+
478
+    #[test]
479
+    fn special_char_name_longest_match_left_to_right() {
480
+        // Longest in-scope prefix wins: with `a-b-c` also bound, the whole run
481
+        // is one name.
482
+        assert_eq!(
483
+            eval_in("a-b-c", &[("a-b", num(1.0)), ("a-b-c", num(2.0))]),
484
+            num(2.0)
485
+        );
486
+        // With only `a-b` bound, the run fuses `a-b` and subtracts the rest.
487
+        assert_eq!(
488
+            eval_in("a-b-c", &[("a-b", num(10.0)), ("c", num(4.0))]),
489
+            num(6.0)
490
+        );
491
+        // The scan resumes after a fused name: `Date-Time - Date-Time2` fuses
492
+        // BOTH names and keeps the minus an operator — the TCK 0007 expectation
493
+        // (subtraction), reproduced by longest-match at each position.
494
+        let dt = &[("Date-Time", num(100.0)), ("Date-Time2", num(58.0))];
495
+        assert_eq!(eval_in("Date-Time - Date-Time2", dt), num(42.0));
496
+        // ... and after a miss the scan continues INSIDE the run: `b-c` bound
497
+        // in `a-b-c` parses as `a - b-c`.
498
+        assert_eq!(
499
+            eval_in("a-b-c", &[("a", num(8.0)), ("b-c", num(3.0))]),
500
+            num(5.0)
501
+        );
502
+        // `(a)-(b)` is the escape hatch: subtraction even when `a-b` is the name.
503
+        let esc = &[("a", num(7.0)), ("b", num(3.0)), ("a-b", num(100.0))];
504
+        assert_eq!(eval_in("(a)-(b)", esc), num(4.0));
505
+    }
506
+
507
+    #[test]
508
+    fn special_char_name_vs_path_and_members() {
509
+        // `x.y` is ambiguous between one name and a path (§10.3.1.6): the
510
+        // in-scope name wins when bound; otherwise the path stands.
511
+        let nested = &[("x", ctx_value(&[("y", num(5.0))]))];
512
+        assert_eq!(eval_in("x.y", nested), num(5.0)); // path
513
+        assert_eq!(eval_in("x.y", &[("x.y", num(9.0))]), num(9.0)); // name
514
+        // A hyphen name as a PATH BASE: the whole-run candidate `Date-Time2.hour`
515
+        // is not in scope, so `Date-Time2` fuses and `.hour` stays a member.
516
+        let dt2 = &[("Date-Time2", ctx_value(&[("hour", num(3.0))]))];
517
+        assert_eq!(eval_in("Date-Time2.hour", dt2), num(3.0));
518
+        // A multi-word member stays a member: `Date-Time2.time offset`.
519
+        let off = &[("Date-Time2", ctx_value(&[("time offset", num(2.0))]))];
520
+        assert_eq!(eval_in("Date-Time2.time offset", off), num(2.0));
521
+        // But a bound name of the WHOLE dotted run wins over the path (longest
522
+        // match at the run start).
523
+        let whole = &[
524
+            ("Date-Time2", ctx_value(&[("hour", num(3.0))])),
525
+            ("Date-Time2.hour", num(7.0)),
526
+        ];
527
+        assert_eq!(eval_in("Date-Time2.hour", whole), num(7.0));
528
+    }
529
+
530
+    #[test]
531
+    fn compile_is_probe_free_and_reports_name_runs() {
532
+        // `compile` never fuses: `a-b` stays subtraction even when bound in the
533
+        // context it is later evaluated against (a compiled program pins no
534
+        // scope — the documented compile-once policy, ADR-47).
535
+        let bound = ctx_of(&[("a-b", num(10.0))]);
536
+        assert_eq!(
537
+            compile("a-b").unwrap().evaluate(&bound).unwrap().into_lenient(),
538
+            Value::Null
539
+        );
540
+        assert_eq!(
541
+            compile_with_probe("a-b", &bound)
542
+                .unwrap()
543
+                .evaluate(&bound)
544
+                .unwrap()
545
+                .into_lenient(),
546
+            num(10.0)
547
+        );
548
+
549
+        // `has_name_runs`: set when a probe-aware parse SAW a run (fused or
550
+        // not) — the parse consulted the scope; false without a run pattern.
551
+        let empty = Context::empty();
552
+        assert!(compile_with_probe("a-b", &empty).unwrap().has_name_runs());
553
+        assert!(!compile_with_probe("a + 1", &empty).unwrap().has_name_runs()); // `1` is no word
554
+        assert!(!compile("a-b").unwrap().has_name_runs()); // probe-free parse never consults
555
+        // Adjacency never forms a run (`a and b`, `for x in y` are untouched).
556
+        assert!(!compile_with_probe("a and b", &empty).unwrap().has_name_runs());
557
+        assert!(!compile_with_probe("for x in y return x", &empty).unwrap().has_name_runs());
558
+
559
+        // `name_run_candidates`: every fusable candidate, from every unit
560
+        // position — the probe-free "could this parse be scope-dependent" set
561
+        // (feel-pg's cache check). Empty for run-free texts.
562
+        assert_eq!(name_run_candidates("a-b-c"), vec!["a-b-c", "a-b", "b-c"]);
563
+        assert!(name_run_candidates("1 + 1").is_empty());
564
+        assert!(name_run_candidates("a and b").is_empty());
565
+        assert_eq!(name_run_candidates("x.y"), vec!["x.y"]);
566
+        assert_eq!(name_run_candidates("if-then"), vec!["if-then"]);
567
+        assert_eq!(
568
+            name_run_candidates("Date-Time - Date-Time2"),
569
+            vec![
570
+                "Date-Time-Date-Time2",
571
+                "Date-Time-Date",
572
+                "Date-Time",
573
+                "Time-Date-Time2",
574
+                "Time-Date",
575
+                "Date-Time2"
576
+            ]
577
+        );
578
+    }
579
+
580
+    #[test]
581
+    fn special_char_name_run_free_shapes_stay_untouched() {
582
+        // No candidate in scope: every one of these keeps its operator reading.
583
+        let empty = Context::empty();
584
+        let ev0 = |src: &str| {
585
+            evaluate(src, &empty)
586
+                .unwrap_or_else(|e| panic!("`{src}` failed: {e}"))
587
+                .into_lenient()
588
+        };
589
+        // Numeric operands never form runs (a name part cannot start with a digit).
590
+        assert_eq!(ev0("1 + 1"), num(2.0));
591
+        assert_eq!(ev0("3 - 1"), num(2.0));
592
+        assert_eq!(ev0("a - 1"), Value::Null); // unbound `a`, minus 1
593
+        assert_eq!(ev0("x and y"), Value::Null); // adjacency: boolean and of nulls
594
+        // Range/descendant/exponent separators are not name symbols.
595
+        assert_eq!(ev0("5 in [1..10]"), b(true));
596
+        assert_eq!(ev0("2 ** 3"), num(8.0));
597
+        assert_eq!(ev0("for i in [1,2] return i"), list(vec![num(1.0), num(2.0)]));
598
+        assert_eq!(
599
+            ev0("for i in [2, 3] return i - 1"),
600
+            list(vec![num(1.0), num(2.0)])
601
+        );
602
+        // Declaration slots are deferred (ADR-47): `for a-b in …` declares no
603
+        // hyphen loop variable — it stays a parse error.
604
+        assert!(compile("for a-b in [1] return a-b").is_err());
342605
     }
343606
 
344607
     #[test]