Public repository: timo / feel

Reader

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

feat(feel-core): backticks, resolution levels, adaptive compile, path members (ADR-48)

draft feat/name-resolution-v2

feat(feel-core): backticks, resolution levels, adaptive compile, path members (ADR-48)

- Backtick-quoted names (feel-scala syntax): a distinct token, never joined
  or fused, valid in every name slot and at every level.
- `NameResolution::{Quoted, Symbols}` via `ParseOptions`; `compile_with`,
  `evaluate_with`. `Quoted` skips fusion entirely (Camunda semantics).
- `CompiledExpr` is scope-adaptive: it keeps the pre-fusion tokens, records
  the fusion's probe answers per evaluation and caches one parse per answer
  trace (LRU, 8). `compile` and `evaluate` now agree; `compile_with_probe`
  pins a scope; `has_name_runs` is gone.
- `ScopeProbe::contains_member`: on a static path the navigated value is
  probed (`applicant.first-name`, lists: any element); member runs stop at
  `.` so plain paths are never probed.
- `FunctionRegistry::contains`; the env's registry joins the probe.
- Guard test: no built-in name contains a name symbol.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Changesetcfa46ffe229ed1ee02c82452b2147956eefafae8
Author (claimed)Timo Stolz <timo.stolz@gmail.com>,
Parents93b43c1c833b
Children
Pushlog
by timo via ssh

modified crates/feel-core/src/lexer.rs +239 −114

@@ -27,10 +27,17 @@
2727
 //! from arithmetic/paths at the token level. §10.3.1.6 resolves this against the
2828
 //! **scope**: left to right, longest in-scope match preferred, spaces not part of
2929
 //! 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.
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.
3441
 //!
3542
 //! Java-style comments (`// … \n` and `/* … */`) are skipped at the logos level
3643
 //! (pass 1). `logos` maximal munch makes `//` / `/*` win over the single `/`
@@ -179,6 +186,15 @@
179186
     // over XID-continue characters. Keywords are remapped out of this in `lex`.
180187
     #[regex(r"[A-Za-z_\u{80}-\u{10FFFF}]", lex_name)]
181188
     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),
182198
 }
183199
 
184200
 /// Validate the already-matched lead character as an identifier start and extend
@@ -305,43 +321,33 @@
305321
 }
306322
 
307323
 /// One `(start, token, end)` triple, or a lex error for an unrecognised char.
308
-type Spanned = Result<(usize, Tok, usize), LexError>;
324
+pub(crate) type Spanned = Result<(usize, Tok, usize), LexError>;
309325
 
310326
 /// Token stream for the lalrpop parser: `(start, token, end)` byte offsets, with
311
-/// lexed identifiers remapped to keyword tokens, multi-word FEEL names joined,
312
-/// and — only when a scope probe is supplied — special-character name runs fused
313
-/// (§10.3.1.6, ADR-47). A lex error becomes the `Err` arm, which lalrpop reports
314
-/// as a `ParseError::User`.
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`.
315330
 pub(crate) fn lex(input: &str) -> impl Iterator<Item = Spanned> {
316
-    lex_pipeline(input, None).0.into_iter()
317
-}
318
-
319
-/// The probe-aware pipeline: like [`lex`], but runs the §10.3.1.6 name-run
320
-/// fusion against `probe`. Returns the tokens plus whether any special-character
321
-/// run was seen (fused or not) — i.e. this parse consulted the scope (ADR-47).
322
-pub(crate) fn lex_with_probe(
323
-    input: &str,
324
-    probe: &dyn crate::ScopeProbe,
325
-) -> (impl Iterator<Item = Spanned>, bool) {
326
-    let (toks, name_runs) = lex_pipeline(input, Some(probe));
327
-    (toks.into_iter(), name_runs)
328
-}
329
-
330
-/// The full multi-pass pipeline, probe optional. Pass 1 lexes with `logos` and
331
-/// remaps keywords; 1.5 fuses the `instance of` operator; 2 joins multi-word
332
-/// names; 2.5 (only with a probe) fuses special-character name runs; 3 retags
333
-/// reverse-open interval openers.
334
-fn lex_pipeline(input: &str, probe: Option<&dyn crate::ScopeProbe>) -> (Vec<Spanned>, bool) {
335
-    // `lex_joined` runs passes 1 + 1.5 (keywords, `instance of`); pass 2 joins
336
-    // multi-word names on its output; the fusion pass 2.5 must see the joined
337
-    // word units (`total price-total`), and pass 3 must classify `]` against
338
-    // fused names (they complete a value).
339
-    let raw = join_names(lex_joined(input));
340
-    let (raw, name_runs) = match probe {
341
-        Some(probe) => fuse_special_names(raw, probe),
342
-        None => (raw, false),
343
-    };
344
-    (mark_reverse_open(raw), name_runs)
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)
345351
 }
346352
 
347353
 /// Passes 1 + 1.5: raw `logos` tokens with identifiers remapped to keyword
@@ -617,20 +623,19 @@
617623
 /// `word ((-|+|*|/|.) word)*`, where a later word is a joined `Name` payload or
618624
 /// a keyword's spelling (`tok_word` — keywords are legal name *parts*,
619625
 /// §10.3.1.4; `x-in`). The run must START at a `Name` ([`run_start_word`] — a
620
-/// name start is never a keyword) that is not a path member — a word
621
-/// directly after an unfused `.` resolves against the *structure* the path
622
-/// navigates, never against the outer scope, so a root key like `y-z` must not
623
-/// turn `x.y-z` into a member access (`x.(y-z)`); it stays `(x.y) - z`.
624
-/// Parens, commas, brackets, literals, adjacency (`a and b`) and any other
625
-/// token end the run. Returns the per-unit `(word, start, end)` and the
626
-/// separator chars. A lone word is not a run — `None`.
627
-fn scan_name_run(toks: &[Spanned], i: usize) -> Option<(Vec<RunUnit<'_>>, Vec<char>)> {
628
-    // Member position: the previous token is a `.` that no fusion consumed (a
629
-    // fused span always ends with a word, so an unfused dot at i-1 is exactly
630
-    // the member position; ADR-47).
631
-    if i > 0 && matches!(&toks[i - 1], Ok((_, Tok::Dot, _))) {
632
-        return None;
633
-    }
626
+/// name start is never a keyword). Whether position `i` is a root or a path
627
+/// member is the caller's business ([`plan`]); a **member** run (`member`)
628
+/// does not continue over `.` — there the dot is path navigation, so a plain
629
+/// path `a.b.c` forms no member run and is never probed (laziness, ADR-21); a
630
+/// member key containing a dot needs backticks (ADR-48). Parens, commas, brackets,
631
+/// literals, quoted names, adjacency (`a and b`) and any other token end the
632
+/// run. Returns the per-unit `(word, start, end)` and the separator chars. A
633
+/// lone word is not a run — `None`.
634
+fn scan_name_run(
635
+    toks: &[Spanned],
636
+    i: usize,
637
+    member: bool,
638
+) -> Option<(Vec<RunUnit<'_>>, Vec<char>)> {
634639
     let (word, start, end) = match &toks[i] {
635640
         Ok((s, tok, e)) => (run_start_word(tok)?, *s, *e),
636641
         Err(_) => return None,
@@ -643,7 +648,9 @@
643648
             .get(j)
644649
             .and_then(|t| t.as_ref().ok())
645650
             .and_then(|(_, t, _)| name_symbol(t));
646
-        let Some(sep) = sep else { break };
651
+        let Some(sep) = sep.filter(|&c| !(member && c == '.')) else {
652
+            break;
653
+        };
647654
         let next = toks
648655
             .get(j + 1)
649656
             .and_then(|t| t.as_ref().ok())
@@ -656,85 +663,202 @@
656663
     (units.len() > 1).then_some((units, seps))
657664
 }
658665
 
659
-/// The candidate name a run prefix stands for: the word units joined by their
660
-/// separators, verbatim. Spaces are not part of the token sequence (§10.3.1.6),
661
-/// so `a - b` and `a-b` produce the same candidate — the separator *characters*
662
-/// are part of the name, the whitespace around them is not.
663
-fn candidate_payload(units: &[RunUnit<'_>], seps: &[char]) -> String {
664
-    let mut payload = units[0].0.to_string();
666
+/// Write the candidate name a run prefix stands for into `buf`: the word units
667
+/// joined by their separators, verbatim. Spaces are not part of the token
668
+/// sequence (§10.3.1.6), so `a - b` and `a-b` produce the same candidate — the
669
+/// separator *characters* are part of the name, the whitespace around them is
670
+/// not. A reused buffer keeps the per-evaluation scope check allocation-free.
671
+fn candidate_into(buf: &mut String, units: &[RunUnit<'_>], seps: &[char]) {
672
+    buf.clear();
673
+    buf.push_str(units[0].0);
665674
     for ((word, _, _), sep) in units[1..].iter().zip(seps) {
666
-        payload.push(*sep);
667
-        payload.push_str(word);
668
-    }
669
-    payload
670
-}
671
-
672
-/// Fuse special-character name runs into single `Name` tokens, resolving the
673
-/// §10.3.1.6 ambiguity against `probe` (ADR-47). At each word-unit position the
674
-/// maximal run is scanned; its prefixes are tried **longest first** against the
675
-/// probe, and the first in-scope prefix is fused into one `Name` spanning it.
676
-/// Scanning then continues *after* the fused name, so `Date-Time - Date-Time2`
677
-/// fuses `Date-Time`, leaves the `-` an operator, and fuses `Date-Time2` — the
678
-/// subtraction the TCK expects, reproduced by longest-match-at-each-position.
679
-/// When no prefix is in scope the run is left alone (arithmetic stands) and the
680
-/// scan resumes at the next token, so `a-b-c` with only `b-c` bound parses as
681
-/// `a - b-c`. A keyword word-unit makes reserved-word parts reachable (`x-in`)
682
-/// but, without a symbol, adjacency never forms a run (`a and b` is untouched).
675
+        buf.push(*sep);
676
+        buf.push_str(word);
677
+    }
678
+}
679
+
680
+/// Whether token `i` directly follows a `.` — a path **member** position. A
681
+/// fused span always ends with a word, so a `.` at `i - 1` is never consumed by
682
+/// a fusion: it is in the plan exactly when this is true.
683
+fn after_dot(toks: &[Spanned], i: usize) -> bool {
684
+    i > 0 && matches!(&toks[i - 1], Ok((_, Tok::Dot, _)))
685
+}
686
+
687
+/// The answers a fusion got from its probe, in query order (ADR-48). The plan is
688
+/// a pure function of the base tokens and this trace, so it is the parse-cache
689
+/// key: two scopes with the same trace parse identically.
690
+pub(crate) type Trace = Vec<bool>;
691
+
692
+/// One element of a fusion plan: an input token kept as is, or a fused name
693
+/// spanning input tokens `first..=last`.
694
+enum Planned {
695
+    Tok(usize),
696
+    Fused { first: usize, last: usize, payload: String },
697
+}
698
+
699
+/// The input token a plan element keeps (`None` for a fused name).
700
+fn planned_tok<'a>(p: &Planned, toks: &'a [Spanned]) -> Option<&'a Tok> {
701
+    match p {
702
+        Planned::Tok(i) => toks[*i].as_ref().ok().map(|(_, t, _)| t),
703
+        Planned::Fused { .. } => None,
704
+    }
705
+}
706
+
707
+/// The name a plan element stands for — a plain, quoted or fused name.
708
+fn planned_name<'a>(p: &'a Planned, toks: &'a [Spanned]) -> Option<&'a str> {
709
+    match p {
710
+        Planned::Fused { payload, .. } => Some(payload),
711
+        Planned::Tok(_) => match planned_tok(p, toks)? {
712
+            Tok::Name(s) | Tok::QuotedName(s) => Some(s),
713
+            _ => None,
714
+        },
715
+    }
716
+}
717
+
718
+/// The **static** path in front of a member position (ADR-48): the plan ends in
719
+/// `name (. name)* .`, and the chain's root is a name that is not itself a path
720
+/// member. Returns the plan indices of the chain's names, root first — e.g.
721
+/// `[applicant]` for `applicant.first-name`, `[p, q]` for `p.q.r-s`. `None` for
722
+/// a dynamic base (`f(x).a-b`, `(e).a-b`, `xs[1].a-b`, `e...n.a-b`): its member
723
+/// names cannot be known at parse time (backticks cover them).
724
+fn static_path(out: &[Planned], toks: &[Spanned]) -> Option<Vec<usize>> {
725
+    let mut idxs = Vec::new();
726
+    // `out[j - 1]` is the `.` in front of the current segment.
727
+    let mut j = out.len();
728
+    loop {
729
+        let k = j.checked_sub(2)?;
730
+        planned_name(&out[k], toks)?;
731
+        idxs.push(k);
732
+        match k.checked_sub(1).map(|p| planned_tok(&out[p], toks)) {
733
+            Some(Some(Tok::Dot)) => j = k,
734
+            Some(Some(Tok::DotDotDot)) => return None,
735
+            _ => break,
736
+        }
737
+    }
738
+    idxs.reverse();
739
+    Some(idxs)
740
+}
741
+
742
+/// Try a run's prefixes longest first (§10.3.1.6), recording every answer in
743
+/// `trace`; the first in-scope prefix wins as `(units, name)`.
744
+fn longest_in_scope(
745
+    units: &[RunUnit<'_>],
746
+    seps: &[char],
747
+    buf: &mut String,
748
+    trace: &mut Trace,
749
+    mut in_scope: impl FnMut(&str) -> bool,
750
+) -> Option<(usize, String)> {
751
+    for k in (2..=units.len()).rev() {
752
+        candidate_into(buf, &units[..k], &seps[..k - 1]);
753
+        let hit = in_scope(buf);
754
+        trace.push(hit);
755
+        if hit {
756
+            return Some((k, buf.clone()));
757
+        }
758
+    }
759
+    None
760
+}
761
+
762
+/// Plan the §10.3.1.6 fusion of special-character name runs against `probe`
763
+/// (ADR-47/48). At each word position the maximal run is scanned and its
764
+/// prefixes are tried **longest first**; the first in-scope prefix is fused.
765
+/// Scanning continues *after* a fused name (`Date-Time - Date-Time2` fuses both
766
+/// and keeps the minus an operator — the TCK expectation) and *inside* the run
767
+/// after a miss (`a-b-c` with only `b-c` bound is `a - b-c`).
683768
 ///
684
-/// Returns the tokens plus `true` when any run was seen — the parse consulted
685
-/// the scope ([`crate::CompiledExpr::has_name_runs`]).
686
-fn fuse_special_names(toks: Vec<Spanned>, probe: &dyn crate::ScopeProbe) -> (Vec<Spanned>, bool) {
687
-    let mut out: Vec<Spanned> = Vec::with_capacity(toks.len());
688
-    let mut saw_run = false;
769
+/// A root position asks [`crate::ScopeProbe::contains`]. A **member** position
770
+/// (after an unfused `.`) never consults the root scope — a root key `y-z` must
771
+/// not turn `x.y-z` into `x.(y-z)` — but, on a *static* path ([`static_path`]),
772
+/// asks [`crate::ScopeProbe::contains_member`] whether the navigated value has
773
+/// that key: `applicant.first-name` fuses `first-name` when `applicant` has it.
774
+/// Every answer is appended to `trace`.
775
+fn plan(toks: &[Spanned], probe: &dyn crate::ScopeProbe, trace: &mut Trace) -> Vec<Planned> {
776
+    let mut out: Vec<Planned> = Vec::with_capacity(toks.len());
777
+    let mut buf = String::new();
689778
     let mut i = 0;
690779
     while i < toks.len() {
691
-        let Some((units, seps)) = scan_name_run(&toks, i) else {
692
-            out.push(toks[i].clone());
693
-            i += 1;
694
-            continue;
780
+        let member = after_dot(toks, i);
781
+        let fused = match scan_name_run(toks, i, member) {
782
+            None => None,
783
+            Some((units, seps)) if member => match static_path(&out, toks) {
784
+                Some(idxs) => {
785
+                    let path: Vec<&str> = idxs
786
+                        .iter()
787
+                        .map(|&k| planned_name(&out[k], toks).expect("static path element is a name"))
788
+                        .collect();
789
+                    longest_in_scope(&units, &seps, &mut buf, trace, |c| probe.contains_member(&path, c))
790
+                }
791
+                None => None,
792
+            },
793
+            Some((units, seps)) => {
794
+                longest_in_scope(&units, &seps, &mut buf, trace, |c| probe.contains(c))
795
+            }
695796
         };
696
-        saw_run = true;
697
-        // Candidate prefixes, longest first (§10.3.1.6): only prefixes with at
698
-        // least one separator are fusable — a lone word is already one token.
699
-        let mut fused = None;
700
-        for k in (2..=units.len()).rev() {
701
-            let payload = candidate_payload(&units[..k], &seps[..k - 1]);
702
-            if probe.contains(&payload) {
703
-                fused = Some((k, payload));
704
-                break;
705
-            }
706
-        }
707797
         match fused {
708798
             Some((k, payload)) => {
709
-                let (_, start, _) = units[0];
710
-                let (_, _, end) = units[k - 1];
711
-                out.push(Ok((start, Tok::Name(payload), end)));
712
-                // Skip the fused prefix: k units plus the k-1 separators.
713
-                i += 2 * k - 1;
799
+                // k units plus the k-1 separators between them.
800
+                let last = i + 2 * (k - 1);
801
+                out.push(Planned::Fused { first: i, last, payload });
802
+                i = last + 1;
714803
             }
715804
             None => {
716
-                out.push(toks[i].clone());
805
+                out.push(Planned::Tok(i));
717806
                 i += 1;
718807
             }
719808
         }
720809
     }
721
-    (out, saw_run)
722
-}
723
-
724
-/// Every special-character name candidate `expr` could fuse under *some* scope
725
-/// (ADR-47): all ≥2-unit prefixes of every run, from every unit position (so
726
-/// `a-b-c` yields `a-b-c`, `a-b` and `b-c`). Probe-free and AST-free — a host
727
-/// that caches a probe-free parse across contexts (feel-pg's `fn_extra` slot)
728
-/// checks these per context: none bound ⇒ the cached parse is already
729
-/// scope-correct; any bound ⇒ re-parse against that context (§10.3.1.6).
810
+    out
811
+}
812
+
813
+/// Whether the base tokens contain any special-character run at all — i.e.
814
+/// whether some scope could make [`plan`] fuse. `false` ⇒ the base parse is the
815
+/// only parse, for every scope (ADR-48's fast path).
816
+pub(crate) fn may_fuse(toks: &[Spanned]) -> bool {
817
+    (0..toks.len()).any(|i| scan_name_run(toks, i, after_dot(toks, i)).is_some())
818
+}
819
+
820
+/// Fuse special-character name runs against `probe` — the token stream for
821
+/// that scope (feed it to [`finish`]). See [`plan`].
822
+pub(crate) fn fuse(toks: &[Spanned], probe: &dyn crate::ScopeProbe) -> Vec<Spanned> {
823
+    let mut trace = Trace::new();
824
+    plan(toks, probe, &mut trace)
825
+        .into_iter()
826
+        .map(|p| match p {
827
+            Planned::Tok(i) => toks[i].clone(),
828
+            Planned::Fused { first, last, payload } => {
829
+                let start = toks[first].as_ref().map(|(s, _, _)| *s).unwrap_or(0);
830
+                let end = toks[last].as_ref().map(|(_, _, e)| *e).unwrap_or(start);
831
+                Ok((start, Tok::Name(payload), end))
832
+            }
833
+        })
834
+        .collect()
835
+}
836
+
837
+/// Run the fusion against `probe` only to record its probe answers (the
838
+/// parse-cache key; ADR-48) — nothing is materialised.
839
+pub(crate) fn fusion_trace(toks: &[Spanned], probe: &dyn crate::ScopeProbe, trace: &mut Trace) {
840
+    plan(toks, probe, trace);
841
+}
842
+
843
+/// Every **root-level** special-character name candidate `expr` could fuse
844
+/// under *some* scope (ADR-47): all ≥2-unit prefixes of every run that starts
845
+/// at a non-member position (so `a-b-c` yields `a-b-c`, `a-b` and `b-c`, and
846
+/// `x.y-z` yields `x.y-z` and `x.y`). Path-member candidates (ADR-48) depend on
847
+/// the navigated value and are not listed. A diagnostic: its length is the
848
+/// number of root-scope lookups an evaluation pays.
730849
 pub(crate) fn name_run_candidates(input: &str) -> Vec<String> {
731
-    let toks = join_names(lex_joined(input));
850
+    let toks = lex_base(input);
732851
     let mut out = Vec::new();
852
+    let mut buf = String::new();
733853
     for i in 0..toks.len() {
734
-        if let Some((units, seps)) = scan_name_run(&toks, i) {
854
+        if after_dot(&toks, i) {
855
+            continue;
856
+        }
857
+        if let Some((units, seps)) = scan_name_run(&toks, i, false) {
735858
             // Longest first, mirroring the probe's resolution order (§10.3.1.6).
736859
             for k in (2..=units.len()).rev() {
737
-                out.push(candidate_payload(&units[..k], &seps[..k - 1]));
860
+                candidate_into(&mut buf, &units[..k], &seps[..k - 1]);
861
+                out.push(buf.clone());
738862
             }
739863
         }
740864
     }
@@ -790,6 +914,7 @@
790914
             Tok::Str(s) => return write!(f, "{s:?}"),
791915
             Tok::TemporalLit(s) => return write!(f, "@{s:?}"),
792916
             Tok::Name(s) => return write!(f, "{s}"),
917
+            Tok::QuotedName(s) => return write!(f, "`{s}`"),
793918
             Tok::Comment => unreachable!("Comment is logos::skip — never emitted"),
794919
         };
795920
         f.write_str(s)

modified crates/feel-core/src/lib.rs +434 −109

@@ -81,20 +81,28 @@
8181
     }
8282
 }
8383
 
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.
84
+/// The parse-time "name oracle" for special-character names (§10.3.1.6,
85
+/// ADR-47/48): decides which candidate names are in scope, so the lexer can fuse
86
+/// FEEL's additional name symbols (`a-b`, `Date-Time`, `x.y`) into single names.
8787
 ///
8888
 /// std-only (ADR-1), like the other host seams. The canonical implementation is
8989
 /// [`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).
90
+/// [`contains`](ScopeProbe::contains) mirrors `Expr::Var` resolution exactly: a
91
+/// context binding or a built-in function name.
9492
 pub trait ScopeProbe {
9593
     /// Whether `name` resolves at evaluation time — i.e. `Expr::Var(name)` would
9694
     /// find a value (a context binding or a built-in function name).
9795
     fn contains(&self, name: &str) -> bool;
96
+
97
+    /// Whether the value reached by the **static** path `path` (root name first,
98
+    /// e.g. `["applicant"]` for `applicant.first-name`) has a member `name`
99
+    /// (ADR-48). A list on the way is mapped over, as the FEEL dot does; the
100
+    /// member counts if **any** element has it. The default — `false` — keeps
101
+    /// member positions arithmetic (`applicant.first - name`).
102
+    fn contains_member(&self, path: &[&str], name: &str) -> bool {
103
+        let _ = (path, name);
104
+        false
105
+    }
98106
 }
99107
 
100108
 impl ScopeProbe for Context {
@@ -104,13 +112,38 @@
104112
         // about the first two.
105113
         self.get(name).is_some() || crate::builtins::is_builtin(name)
106114
     }
115
+
116
+    fn contains_member(&self, path: &[&str], name: &str) -> bool {
117
+        let Some((root, rest)) = path.split_first() else {
118
+            return false;
119
+        };
120
+        self.get(root).is_some_and(|v| has_member(v, rest, name))
121
+    }
122
+}
123
+
124
+/// Navigate `rest` from `v` like the FEEL dot (a list maps over its elements)
125
+/// and report whether the end has a member `name` — for a list: any element.
126
+/// Navigation is by reference for owned values; a lazy [`Foreign`] node is asked
127
+/// via [`ForeignObject::get`] one segment at a time (feel-pg's jsonb, the
128
+/// wrappers' host objects), so only the probed path is touched.
129
+fn has_member(v: &Value, rest: &[&str], name: &str) -> bool {
130
+    match (v, rest.split_first()) {
131
+        (Value::List(items), _) => items.iter().any(|it| has_member(it, rest, name)),
132
+        (Value::Context(map), None) => map.contains_key(name),
133
+        (Value::Context(map), Some((seg, more))) => {
134
+            map.get(*seg).is_some_and(|next| has_member(next, more, name))
135
+        }
136
+        (Value::Foreign(f), None) => !matches!(f.0.get(name), Value::Null),
137
+        (Value::Foreign(f), Some((seg, more))) => has_member(&f.0.get(seg), more, name),
138
+        _ => false,
139
+    }
107140
 }
108141
 
109142
 /// A [`Context`] plus an ambient [`FunctionRegistry`] (ADR-23) as one parse-time
110143
 /// scope (ADR-47): a call head resolves against context, built-ins and — third —
111144
 /// the registry (`eval_call`), so a hyphen-named host function (`my-fn(1)`) must
112
-/// be in scope for the fusion too. The wrappers' one-shot `evaluate` parses
113
-/// against this when a `functions` registry is supplied.
145
+/// be in scope for the fusion too. [`CompiledExpr::evaluate_with_env`] probes
146
+/// this automatically with the env's registry.
114147
 ///
115148
 /// Slightly wider than `Expr::Var` (which never consults the registry): a bare,
116149
 /// uncalled `my-fn` fuses to a name that evaluates to null — the same null the
@@ -124,9 +157,59 @@
124157
 
125158
 impl ScopeProbe for ScopeWithFunctions<'_> {
126159
     fn contains(&self, name: &str) -> bool {
127
-        self.context.contains(name) || self.functions.get(name).is_some()
160
+        self.context.contains(name) || self.functions.contains(name)
161
+    }
162
+
163
+    fn contains_member(&self, path: &[&str], name: &str) -> bool {
164
+        self.context.contains_member(path, name)
128165
     }
129166
 }
167
+
168
+/// How far the parser goes in reading FEEL's ambiguous names (ADR-48) — a parse
169
+/// option ([`ParseOptions`]). Backtick-quoted names (`` `a-b` ``, the feel-scala
170
+/// extension) work at every level.
171
+#[non_exhaustive]
172
+#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Hash)]
173
+pub enum NameResolution {
174
+    /// Only backtick-quoted names are special; `a-b` is always subtraction —
175
+    /// Camunda/feel-scala semantics. No scope checks at all: the cheapest level.
176
+    Quoted,
177
+    /// Backticks plus §10.3.1.6 runs over `- + * / .`, resolved against the
178
+    /// scope (ADR-47) and, on static paths, against the navigated value (ADR-48).
179
+    #[default]
180
+    Symbols,
181
+}
182
+
183
+impl NameResolution {
184
+    /// Parse the textual level used by the wrappers and feel-pg
185
+    /// (`"quoted"` | `"symbols"`, case-insensitive).
186
+    pub fn from_name(s: &str) -> Option<Self> {
187
+        match s.to_ascii_lowercase().as_str() {
188
+            "quoted" => Some(Self::Quoted),
189
+            "symbols" => Some(Self::Symbols),
190
+            _ => None,
191
+        }
192
+    }
193
+}
194
+
195
+/// Options for [`compile_with`] / [`evaluate_with`] (ADR-48).
196
+#[non_exhaustive]
197
+#[derive(Debug, Default, Clone, PartialEq, Eq)]
198
+pub struct ParseOptions {
199
+    /// The name-resolution level (default [`NameResolution::Symbols`]).
200
+    pub names: NameResolution,
201
+}
202
+
203
+impl ParseOptions {
204
+    /// Options with the given name-resolution level.
205
+    pub fn names(names: NameResolution) -> Self {
206
+        Self { names }
207
+    }
208
+}
209
+
210
+/// How many scope-specific parses a [`CompiledExpr`] keeps (LRU). One per
211
+/// distinct probe-answer trace; real workloads see one or two.
212
+const SCOPED_PARSE_CACHE: usize = 8;
130213
 
131214
 /// A parsed FEEL expression, ready to be evaluated repeatedly.
132215
 ///
@@ -134,6 +217,12 @@
134217
 /// that evaluate the same expression against many contexts (e.g. one decision
135218
 /// over many rows) should [`compile`] once and reuse the result. The wrapped AST
136219
 /// is fully owning, so a `CompiledExpr` carries no borrow of the source string.
220
+///
221
+/// **Scope-adaptive** (ADR-48): when the text contains special-character runs
222
+/// (`a-b`, `x.y`), each evaluation checks them against the context — one lookup
223
+/// per candidate — and picks the parse for that scope. The parse is a pure
224
+/// function of the text and the probe's answers, so it is cached per answer set
225
+/// (bounded, LRU); a text without runs never checks anything.
137226
 ///
138227
 /// ```
139228
 /// use feel_core::{compile, Context, Value};
@@ -144,14 +233,23 @@
144233
 /// ```
145234
 #[derive(Debug, Clone)]
146235
 pub struct CompiledExpr {
147
-    /// The parsed program.
148
-    expr: ast::Expr,
149
-    /// Whether the parse consulted a scope probe on a special-character name
150
-    /// run (`a-b`, `Date-Time`, …) — i.e. is **scope-dependent**: another scope
151
-    /// could fuse the same text differently (ADR-47). Only a probe-aware parse
152
-    /// (`compile_with_probe`/`evaluate`) sets it; `compile` is probe-free and
153
-    /// reports `false`.
154
-    name_runs: bool,
236
+    /// The scope-free parse: no run fused. Correct for every scope that binds
237
+    /// none of the run candidates — the overwhelming case.
238
+    base: std::sync::Arc<ast::Expr>,
239
+    /// Present iff some scope could fuse a run (see [`Scoped`]); `None` for
240
+    /// run-free texts, [`NameResolution::Quoted`] and probe-pinned parses.
241
+    scoped: Option<std::sync::Arc<Scoped>>,
242
+    /// The level this was compiled at.
243
+    names: NameResolution,
244
+}
245
+
246
+/// The scope-dependent half of a [`CompiledExpr`]: the pre-fusion tokens to
247
+/// re-fuse against each evaluation's scope, and the parses already built, keyed
248
+/// by the fusion's probe-answer trace. Shared between clones.
249
+#[derive(Debug)]
250
+struct Scoped {
251
+    toks: Vec<lexer::Spanned>,
252
+    cache: std::sync::Mutex<Vec<(lexer::Trace, std::sync::Arc<ast::Expr>)>>,
155253
 }
156254
 
157255
 impl CompiledExpr {
@@ -176,15 +274,51 @@
176274
     /// `now()`/`today()` read (ADR-18). The wrappers inject their host's clock
177275
     /// here (e.g. feel-pg's transaction start), which also makes `now()`/`today()`
178276
     /// deterministic in tests.
277
+    ///
278
+    /// The scope for special-character names is `context` plus the env's
279
+    /// function registry ([`ScopeWithFunctions`]; ADR-48).
179280
     pub fn evaluate_with_env(&self, context: &Context, env: &EvalEnv) -> Result<Value, FeelError> {
180
-        eval::Evaluator::new(env).eval(&self.expr, context)
181
-    }
182
-
183
-    /// The parsed AST. `pub(crate)` so the `range(string)` built-in can inspect a
184
-    /// freshly-parsed range literal's *shape* (its endpoints must be literals, not
185
-    /// arbitrary expressions — DMN §10.3.4.6) before evaluating it.
281
+        let scope = ScopeWithFunctions {
282
+            context,
283
+            functions: env.functions,
284
+        };
285
+        let expr = self.resolve(&scope)?;
286
+        eval::Evaluator::new(env).eval(&expr, context)
287
+    }
288
+
289
+    /// The parse for `probe`'s scope: the base parse when no run fuses, else
290
+    /// the cached (or newly built) parse for this probe-answer trace.
291
+    fn resolve(&self, probe: &dyn ScopeProbe) -> Result<std::sync::Arc<ast::Expr>, FeelError> {
292
+        let Some(scoped) = &self.scoped else {
293
+            return Ok(self.base.clone());
294
+        };
295
+        let mut trace = lexer::Trace::new();
296
+        lexer::fusion_trace(&scoped.toks, probe, &mut trace);
297
+        if !trace.iter().any(|&hit| hit) {
298
+            return Ok(self.base.clone());
299
+        }
300
+        {
301
+            let mut cache = scoped.cache.lock().unwrap_or_else(|e| e.into_inner());
302
+            if let Some(pos) = cache.iter().position(|(t, _)| *t == trace) {
303
+                let hit = cache.remove(pos);
304
+                let expr = hit.1.clone();
305
+                cache.insert(0, hit);
306
+                return Ok(expr);
307
+            }
308
+        }
309
+        let expr = std::sync::Arc::new(parse_tokens(lexer::fuse(&scoped.toks, probe))?);
310
+        let mut cache = scoped.cache.lock().unwrap_or_else(|e| e.into_inner());
311
+        cache.insert(0, (trace, expr.clone()));
312
+        cache.truncate(SCOPED_PARSE_CACHE);
313
+        Ok(expr)
314
+    }
315
+
316
+    /// The parsed AST (the base parse). `pub(crate)` so the `range(string)`
317
+    /// built-in can inspect a freshly-parsed range literal's *shape* (its
318
+    /// endpoints must be literals, not arbitrary expressions — DMN §10.3.4.6)
319
+    /// before evaluating it.
186320
     pub(crate) fn ast(&self) -> &ast::Expr {
187
-        &self.expr
321
+        &self.base
188322
     }
189323
 
190324
     /// `true` if this expression never reads the wall clock — it calls neither
@@ -193,23 +327,28 @@
193327
     /// expression indexes; RD-10) gate on this: a non-clock-free expression cannot
194328
     /// be IMMUTABLE because `now()`/`today()` vary over time.
195329
     ///
330
+    /// Judged on the base parse, which is conservative: a scope can only fuse a
331
+    /// call head *into* a special name (`x-now()`), never create a `now()` call.
332
+    ///
196333
     /// This is the *static* half. The runtime half — forbidding *named* time zones,
197334
     /// whose offsets depend on the updatable IANA tzdb — is
198335
     /// [`EvalEnv::forbidding_named_zones`]. Host functions/objects are out of scope
199336
     /// here (the embedder's concern; feel-pg has no host-function seam).
200337
     pub fn is_clock_free(&self) -> bool {
201
-        self.expr.is_clock_free()
202
-    }
203
-
204
-    /// `true` if parsing consulted a scope probe on a special-character name run
205
-    /// (`a-b`, `Date-Time`, …; §10.3.1.6, ADR-47): this parse is
206
-    /// **scope-dependent** — the same text could parse differently under another
207
-    /// scope. Only a probe-aware parse sets it; [`compile`] is probe-free and
208
-    /// reports `false`. Hosts that cache parses across contexts can instead check
209
-    /// [`name_run_candidates`] against each context, which distinguishes "could
210
-    /// be ambiguous" from "this scope actually changes the parse".
211
-    pub fn has_name_runs(&self) -> bool {
212
-        self.name_runs
338
+        self.base.is_clock_free()
339
+    }
340
+
341
+    /// The name-resolution level this was compiled at (ADR-48).
342
+    pub fn name_resolution(&self) -> NameResolution {
343
+        self.names
344
+    }
345
+
346
+    /// How many scope-specific parses are cached right now (≤ 8; ADR-48) — a
347
+    /// diagnostic for tests and benchmarks.
348
+    pub fn scoped_parses(&self) -> usize {
349
+        self.scoped
350
+            .as_ref()
351
+            .map_or(0, |s| s.cache.lock().unwrap_or_else(|e| e.into_inner()).len())
213352
     }
214353
 }
215354
 
@@ -223,6 +362,14 @@
223362
     /// Resolve a host function by name. Absent -> `None` (the call is then a
224363
     /// built-in or, failing that, an error-null).
225364
     fn get(&self, name: &str) -> Option<std::sync::Arc<dyn ForeignFunction>>;
365
+
366
+    /// Whether a host function `name` exists — the scope check for
367
+    /// special-character call heads (ADR-48), run once per candidate per
368
+    /// evaluation. Override with an allocation-free lookup; the default builds
369
+    /// the callable via [`get`](FunctionRegistry::get).
370
+    fn contains(&self, name: &str) -> bool {
371
+        self.get(name).is_some()
372
+    }
226373
 }
227374
 
228375
 /// The empty registry: no ambient host functions. Used as the default in
@@ -309,69 +456,99 @@
309456
     jiff::Zoned::now()
310457
 }
311458
 
312
-/// Parse a FEEL expression into a reusable [`CompiledExpr`] without evaluating it.
459
+/// Run the lalrpop parser over a finished-or-not token stream.
460
+fn parse_tokens(toks: Vec<lexer::Spanned>) -> Result<ast::Expr, FeelError> {
461
+    feel::ExprParser::new()
462
+        .parse(lexer::finish(toks))
463
+        .map_err(|e| FeelError::Parse(e.to_string()))
464
+}
465
+
466
+/// Parse a FEEL expression into a reusable [`CompiledExpr`] without evaluating
467
+/// it, at the default [`NameResolution::Symbols`] level.
313468
 ///
314469
 /// Returns [`FeelError::Parse`] if the expression is syntactically invalid.
315470
 ///
316
-/// **Probe-free** (ADR-47): special-character name runs (`a-b`, `Date-Time`)
317
-/// parse as arithmetic here — a compiled program must not pin one scope. Use
318
-/// [`compile_with_probe`] when the scope is known at parse time, or the one-shot
319
-/// [`evaluate`], which uses the context as the probe (§10.3.1.6).
471
+/// **Scope-adaptive** (ADR-48): special-character names (`a-b`, `Date-Time`,
472
+/// `applicant.first-name`) resolve per evaluation against the context, exactly
473
+/// like the one-shot [`evaluate`] — see [`CompiledExpr`].
320474
 ///
321475
 /// `ExprParser::new()` is now cheap (the external `logos` lexer builds no runtime
322476
 /// matcher — see `lexer.rs`), so there is no parser to cache; the cost is the
323477
 /// per-call parse itself, which [`CompiledExpr`] lets callers pay once.
324478
 pub fn compile(expr: &str) -> Result<CompiledExpr, FeelError> {
325
-    feel::ExprParser::new()
326
-        .parse(lexer::lex(expr))
327
-        .map(|expr| CompiledExpr { expr, name_runs: false })
328
-        .map_err(|e| FeelError::Parse(e.to_string()))
479
+    compile_with(expr, &ParseOptions::default())
329480
 }
330481
 
331
-/// Parse a FEEL expression with scope-dependent name resolution (§10.3.1.6,
332
-/// ADR-47): special-character name runs (`a-b`, `Date-Time`, `x.y`) are fused
333
-/// into single names when — and only when — the joined candidate is in scope
334
-/// per `probe`, longest in-scope match preferred, left to right. Spaces are not
335
-/// part of the name (`a - b` is the same candidate as `a-b`); `(a)-(b)` forces
336
-/// the operator reading.
337
-///
338
-/// The result's [`CompiledExpr::has_name_runs`] tells whether the parse
339
-/// consulted the scope at all. For expressions with no name-run *pattern*
340
-/// (see [`name_run_candidates`]), this is byte-identical to [`compile`].
482
+/// [`compile`] with explicit [`ParseOptions`] (ADR-48).
483
+pub fn compile_with(expr: &str, options: &ParseOptions) -> Result<CompiledExpr, FeelError> {
484
+    let toks = lexer::lex_base(expr);
485
+    let scoped = (options.names == NameResolution::Symbols && lexer::may_fuse(&toks))
486
+        .then(|| Scoped {
487
+            toks: toks.clone(),
488
+            cache: std::sync::Mutex::new(Vec::new()),
489
+        })
490
+        .map(std::sync::Arc::new);
491
+    Ok(CompiledExpr {
492
+        base: std::sync::Arc::new(parse_tokens(toks)?),
493
+        scoped,
494
+        names: options.names,
495
+    })
496
+}
497
+
498
+/// Parse a FEEL expression **pinned** to one scope (§10.3.1.6, ADR-47/48):
499
+/// special-character runs (`a-b`, `Date-Time`, `x.y`, `applicant.first-name`)
500
+/// are fused into names exactly when `probe` has them in scope, longest match
501
+/// first, left to right; `(a)-(b)` forces the operator reading. The result does
502
+/// **not** adapt to later contexts — use it when the scope is known up front
503
+/// (a one-shot evaluation, a host with a fixed schema); otherwise prefer the
504
+/// adaptive [`compile`]. At [`NameResolution::Quoted`] the probe is ignored.
341505
 pub fn compile_with_probe(
342506
     expr: &str,
343507
     probe: &dyn ScopeProbe,
508
+    options: &ParseOptions,
344509
 ) -> Result<CompiledExpr, FeelError> {
345
-    let (toks, name_runs) = lexer::lex_with_probe(expr, probe);
346
-    feel::ExprParser::new()
347
-        .parse(toks)
348
-        .map(|expr| CompiledExpr { expr, name_runs })
349
-        .map_err(|e| FeelError::Parse(e.to_string()))
510
+    let toks = lexer::lex_base(expr);
511
+    let toks = match options.names {
512
+        NameResolution::Symbols => lexer::fuse(&toks, probe),
513
+        NameResolution::Quoted => toks,
514
+    };
515
+    Ok(CompiledExpr {
516
+        base: std::sync::Arc::new(parse_tokens(toks)?),
517
+        scoped: None,
518
+        names: options.names,
519
+    })
350520
 }
351521
 
352522
 /// Parse and evaluate a FEEL expression against a context.
353523
 ///
354
-/// Convenience for `compile_with_probe(expr, context)?.evaluate(context)`;
355
-/// prefer [`compile_with_probe`] when evaluating the same expression more than
356
-/// once against the same scope. The context **is** the scope for §10.3.1.6
357
-/// name resolution (ADR-47): a name like `a-b` resolves to the context binding
358
-/// when one exists, and to subtraction otherwise.
524
+/// One parse, pinned to `context` as the §10.3.1.6 scope (ADR-47): a name like
525
+/// `a-b` resolves to the context binding when one exists, and to subtraction
526
+/// otherwise. Prefer [`compile`] when evaluating the same expression more than
527
+/// once.
359528
 ///
360529
 /// ```
361530
 /// use feel_core::{evaluate, Context, Value};
362531
 /// assert_eq!(evaluate("1 + 1", &Context::empty()).unwrap(), Value::Number(2.0));
363532
 /// ```
364533
 pub fn evaluate(expr: &str, context: &Context) -> Result<Value, FeelError> {
365
-    compile_with_probe(expr, context)?.evaluate(context)
534
+    evaluate_with(expr, context, &ParseOptions::default())
366535
 }
367536
 
368
-/// Every special-character name candidate `expr` could fuse under *some* scope
369
-/// (§10.3.1.6, ADR-47) — e.g. `a-b-c` yields `a-b-c`, `a-b`, `b-c`. Probe-free
370
-/// and cheap; the use case is a host that caches a probe-free parse across
371
-/// contexts (feel-pg's `fn_extra` slot): if none of the candidates is bound in
372
-/// a given context, the cached parse is already scope-correct; if any is bound,
373
-/// re-parse that context with [`compile_with_probe`]. An empty result means the
374
-/// expression's parse is scope-independent for every possible context.
537
+/// [`evaluate`] with explicit [`ParseOptions`] (ADR-48).
538
+pub fn evaluate_with(
539
+    expr: &str,
540
+    context: &Context,
541
+    options: &ParseOptions,
542
+) -> Result<Value, FeelError> {
543
+    compile_with_probe(expr, context, options)?.evaluate(context)
544
+}
545
+
546
+/// Every **root-level** special-character name candidate `expr` could fuse
547
+/// under *some* scope (§10.3.1.6, ADR-47) — e.g. `a-b-c` yields `a-b-c`,
548
+/// `a-b`, `b-c`. A diagnostic: its length is the number of root-scope lookups
549
+/// one evaluation of the compiled expression pays (path-member candidates,
550
+/// ADR-48, come on top and are not listed). Empty ⇒ the parse is
551
+/// scope-independent at the root level.
375552
 pub fn name_run_candidates(expr: &str) -> Vec<String> {
376553
     lexer::name_run_candidates(expr)
377554
 }
@@ -550,33 +727,27 @@
550727
     }
551728
 
552729
     #[test]
553
-    fn compile_is_probe_free_and_reports_name_runs() {
554
-        // `compile` never fuses: `a-b` stays subtraction even when bound in the
555
-        // context it is later evaluated against (a compiled program pins no
556
-        // scope — the documented compile-once policy, ADR-47).
730
+    fn compile_is_scope_adaptive_and_pinned_parse_is_not() {
731
+        // ADR-48: `compile` follows each evaluation's scope, exactly like the
732
+        // one-shot `evaluate` — one compiled program, both readings.
557733
         let bound = ctx_of(&[("a-b", num(10.0))]);
558
-        assert_eq!(
559
-            compile("a-b").unwrap().evaluate(&bound).unwrap().into_lenient(),
560
-            Value::Null
561
-        );
562
-        assert_eq!(
563
-            compile_with_probe("a-b", &bound)
564
-                .unwrap()
565
-                .evaluate(&bound)
566
-                .unwrap()
567
-                .into_lenient(),
568
-            num(10.0)
569
-        );
570
-
571
-        // `has_name_runs`: set when a probe-aware parse SAW a run (fused or
572
-        // not) — the parse consulted the scope; false without a run pattern.
573
-        let empty = Context::empty();
574
-        assert!(compile_with_probe("a-b", &empty).unwrap().has_name_runs());
575
-        assert!(!compile_with_probe("a + 1", &empty).unwrap().has_name_runs()); // `1` is no word
576
-        assert!(!compile("a-b").unwrap().has_name_runs()); // probe-free parse never consults
577
-        // Adjacency never forms a run (`a and b`, `for x in y` are untouched).
578
-        assert!(!compile_with_probe("a and b", &empty).unwrap().has_name_runs());
579
-        assert!(!compile_with_probe("for x in y return x", &empty).unwrap().has_name_runs());
734
+        let parts = ctx_of(&[("a", num(7.0)), ("b", num(3.0))]);
735
+        let prog = compile("a-b").unwrap();
736
+        assert_eq!(prog.evaluate(&bound).unwrap().into_lenient(), num(10.0));
737
+        assert_eq!(prog.evaluate(&parts).unwrap().into_lenient(), num(4.0));
738
+        assert_eq!(prog.evaluate(&bound).unwrap().into_lenient(), num(10.0));
739
+        // One scoped parse cached (the `a-b` reading); the base serves `parts`.
740
+        assert_eq!(prog.scoped_parses(), 1);
741
+
742
+        // `compile_with_probe` PINS its probe's scope: no adaptation later.
743
+        let pinned = compile_with_probe("a-b", &bound, &ParseOptions::default()).unwrap();
744
+        assert_eq!(pinned.evaluate(&bound).unwrap().into_lenient(), num(10.0));
745
+        assert_eq!(pinned.evaluate(&parts).unwrap().into_lenient(), Value::Null);
746
+
747
+        // Run-free texts never build a scoped half.
748
+        let plain = compile("a + 1").unwrap();
749
+        assert_eq!(plain.evaluate(&parts).unwrap().into_lenient(), num(8.0));
750
+        assert_eq!(plain.scoped_parses(), 0);
580751
 
581752
         // `name_run_candidates`: every fusable candidate, from every unit
582753
         // position — the probe-free "could this parse be scope-dependent" set
@@ -662,16 +833,15 @@
662833
             ("r-s", num(1.0)),
663834
         ]);
664835
         assert_eq!(evaluate("p.q.r-s", &deep).unwrap().into_lenient(), num(-3.0));
665
-        // Pinned v1 gap (ADR-47 deviation "names in inner scopes"): only the root
666
-        // level is probed, so a nested hyphen KEY is not reachable as a member —
667
-        // `applicant.first-name` stays `applicant.first - name`.
836
+        // ADR-48 lifts the ADR-47 root-only gap: on a static path the navigated
837
+        // value is probed, so a nested hyphen KEY is reachable as a member.
668838
         let nested = ctx_of(&[(
669839
             "applicant",
670840
             ctx_value(&[("first-name", Value::String("Ada".into()))]),
671841
         )]);
672842
         assert_eq!(
673843
             evaluate("applicant.first-name", &nested).unwrap().into_lenient(),
674
-            Value::Null
844
+            Value::String("Ada".into())
675845
         );
676846
     }
677847
 
@@ -693,11 +863,6 @@
693863
                 .into_lenient(),
694864
             list(vec![num(-1.0), num(-2.0)])
695865
         );
696
-        assert!(
697
-            !compile_with_probe("for i in [1,2] return -i", &ctx)
698
-                .unwrap()
699
-                .has_name_runs()
700
-        );
701866
         // Value keywords do not start runs either: a bound `if-then` is not a
702867
         // name (it stays the — invalid — `if - then`), nor is `true-x`.
703868
         let if_then = ctx_of(&[("if-then", b(true))]);
@@ -706,6 +871,166 @@
706871
         // Keywords stay legal as NON-starting run words (`x-in`, `a-if`).
707872
         assert_eq!(eval_in("x-in", &[("x-in", num(4.0))]), num(4.0));
708873
         assert_eq!(eval_in("a-if", &[("a-if", num(5.0))]), num(5.0));
874
+    }
875
+
876
+    // ----------------------------------------------------------------------- //
877
+    // ADR-48: backtick-quoted names, resolution levels, adaptive compile cache,
878
+    // path-member probe
879
+    // ----------------------------------------------------------------------- //
880
+
881
+    fn s(v: &str) -> Value {
882
+        Value::String(v.into())
883
+    }
884
+
885
+    #[test]
886
+    fn backtick_names_work_in_every_name_slot() {
887
+        // Scope-independent: decided by the text, so it needs no binding to parse.
888
+        assert_eq!(eval_in("`a-b`", &[("a-b", num(5.0))]), num(5.0));
889
+        assert_eq!(eval_in("`Profit and loss`", &[("Profit and loss", num(9.0))]), num(9.0));
890
+        assert_eq!(eval_in("`what if?`", &[("what if?", b(true))]), b(true));
891
+        assert_eq!(eval_in("`if`", &[("if", num(1.0))]), num(1.0)); // a keyword, quoted
892
+        // Content is verbatim: no space normalisation inside backticks.
893
+        assert_eq!(eval_in("`a  b`", &[("a  b", num(2.0))]), num(2.0));
894
+        // Path member, context key + reference, loop variable, call head.
895
+        let app = &[("applicant", ctx_value(&[("first-name", s("Ada"))]))];
896
+        assert_eq!(eval_in("applicant.`first-name`", app), s("Ada"));
897
+        assert_eq!(eval_in("{`a-b`: 5, c: `a-b` + 1}.c", &[]), num(6.0));
898
+        assert_eq!(
899
+            eval_in("for `x-y` in [1, 2] return `x-y` * 2", &[]),
900
+            list(vec![num(2.0), num(4.0)])
901
+        );
902
+        assert_eq!(eval_in("{`my-fn`: function(x) x * 2, r: `my-fn`(3)}.r", &[]), num(6.0));
903
+        // A quoted path base feeds the member probe's static path.
904
+        let quoted_base = &[("the app", ctx_value(&[("net-income", num(3.0))]))];
905
+        assert_eq!(eval_in("`the app`.net-income", quoted_base), num(3.0));
906
+    }
907
+
908
+    #[test]
909
+    fn backtick_names_are_never_joined_or_fused() {
910
+        // Not fused: `` `a`-b `` is `a` minus `b`, even with `a-b` bound.
911
+        let ctx = &[("a", num(7.0)), ("b", num(3.0)), ("a-b", num(100.0))];
912
+        assert_eq!(eval_in("`a`-b", ctx), num(4.0));
913
+        // Not joined with an adjacent word: two names side by side is no FEEL.
914
+        assert!(evaluate("`a b` c", &Context::empty()).is_err());
915
+        // Unterminated or empty quotes are lex errors.
916
+        assert!(evaluate("`a-b", &Context::empty()).is_err());
917
+        assert!(evaluate("``", &Context::empty()).is_err());
918
+    }
919
+
920
+    #[test]
921
+    fn name_resolution_levels() {
922
+        let quoted = ParseOptions::names(NameResolution::Quoted);
923
+        let ctx = ctx_of(&[("a", num(7.0)), ("b", num(3.0)), ("a-b", num(100.0))]);
924
+        // Quoted: `a-b` is always subtraction (Camunda semantics) ...
925
+        assert_eq!(evaluate_with("a-b", &ctx, &quoted).unwrap(), num(4.0));
926
+        let prog = compile_with("a-b", &quoted).unwrap();
927
+        assert_eq!(prog.evaluate(&ctx).unwrap(), num(4.0));
928
+        assert_eq!(prog.scoped_parses(), 0);
929
+        assert_eq!(prog.name_resolution(), NameResolution::Quoted);
930
+        // ... backticks still work ...
931
+        assert_eq!(evaluate_with("`a-b`", &ctx, &quoted).unwrap(), num(100.0));
932
+        // ... and member runs are not probed either.
933
+        let app = ctx_of(&[("applicant", ctx_value(&[("first-name", s("Ada"))]))]);
934
+        assert_eq!(
935
+            evaluate_with("applicant.first-name", &app, &quoted).unwrap().into_lenient(),
936
+            Value::Null
937
+        );
938
+        // Symbols (the default) resolves against the scope.
939
+        assert_eq!(evaluate("a-b", &ctx).unwrap(), num(100.0));
940
+        assert_eq!(NameResolution::from_name("Quoted"), Some(NameResolution::Quoted));
941
+        assert_eq!(NameResolution::from_name("symbols"), Some(NameResolution::Symbols));
942
+        assert_eq!(NameResolution::from_name("full"), None);
943
+    }
944
+
945
+    #[test]
946
+    fn compiled_parse_cache_is_bounded_and_always_correct() {
947
+        // Four independent runs -> 16 binding combinations, more than the
948
+        // 8-entry cache holds: every evaluation must still be scope-correct.
949
+        let src = "a-b + c-d + e-f + g-h";
950
+        let prog = compile(src).unwrap();
951
+        for mask in 0..16u32 {
952
+            for _round in 0..2 {
953
+                let mut ctx = Context::empty();
954
+                for (bit, (l, r)) in [("a", "b"), ("c", "d"), ("e", "f"), ("g", "h")]
955
+                    .into_iter()
956
+                    .enumerate()
957
+                {
958
+                    ctx.insert(l, num(10.0));
959
+                    ctx.insert(r, num(1.0));
960
+                    if mask & (1 << bit) != 0 {
961
+                        ctx.insert(format!("{l}-{r}"), num(100.0));
962
+                    }
963
+                }
964
+                let expected = evaluate(src, &ctx).unwrap();
965
+                assert_eq!(prog.evaluate(&ctx).unwrap(), expected, "mask {mask}");
966
+            }
967
+        }
968
+        assert!(prog.scoped_parses() <= 8);
969
+    }
970
+
971
+    #[test]
972
+    fn path_members_resolve_against_the_navigated_value() {
973
+        let app = ctx_value(&[("net-income", num(100.0)), ("age", num(30.0))]);
974
+        let ctx = &[("applicant", app.clone()), ("total", num(150.0))];
975
+        assert_eq!(eval_in("applicant.net-income", ctx), num(100.0));
976
+        // A member run after an operator and as an operand.
977
+        assert_eq!(eval_in("total - applicant.net-income", ctx), num(50.0));
978
+        assert_eq!(eval_in("applicant.net-income / 4", ctx), num(25.0));
979
+        // Deeper static chains.
980
+        let deep = &[("p", ctx_value(&[("q", ctx_value(&[("r-s", num(7.0))]))]))];
981
+        assert_eq!(eval_in("p.q.r-s", deep), num(7.0));
982
+        // A member of a fused root name.
983
+        let dt = &[("Date-Time2", ctx_value(&[("time-zone", s("Z"))]))];
984
+        assert_eq!(eval_in("Date-Time2.time-zone", dt), s("Z"));
985
+        // A list step maps over the elements; ANY element having the key counts.
986
+        let orders = Value::List(vec![
987
+            ctx_value(&[("unit-price", num(2.0))]),
988
+            ctx_value(&[("unit-price", num(3.0))]),
989
+        ]);
990
+        assert_eq!(
991
+            eval_in("orders.unit-price", &[("orders", orders)]),
992
+            list(vec![num(2.0), num(3.0)])
993
+        );
994
+        // No such member -> the arithmetic reading stands.
995
+        let plain = &[("x", ctx_value(&[("y", num(10.0))])), ("z", num(3.0))];
996
+        assert_eq!(eval_in("x.y-z", plain), num(7.0));
997
+        // A dynamic base is never probed: `(applicant).net-income` stays
998
+        // `(applicant).net - income` (backticks cover it).
999
+        assert_eq!(eval_in("(applicant).net-income", ctx), Value::Null);
1000
+        assert_eq!(eval_in("(applicant).`net-income`", ctx), num(100.0));
1001
+        // The adaptive compile path probes members too.
1002
+        let prog = compile("applicant.net-income").unwrap();
1003
+        assert_eq!(prog.evaluate(&ctx_of(ctx)).unwrap().into_lenient(), num(100.0));
1004
+        let other = ctx_of(&[("applicant", ctx_value(&[("net", num(5.0))])), ("income", num(1.0))]);
1005
+        assert_eq!(prog.evaluate(&other).unwrap().into_lenient(), num(4.0));
1006
+    }
1007
+
1008
+    #[test]
1009
+    fn plain_paths_and_dotted_members_never_probe_members() {
1010
+        // At a member position `.` is navigation, not a name symbol: a plain
1011
+        // path forms no member run (laziness, ADR-21). A dotted member key
1012
+        // needs backticks.
1013
+        let ctx = &[("o", ctx_value(&[("a.b", num(1.0)), ("a", ctx_value(&[("b", num(2.0))]))]))];
1014
+        assert_eq!(eval_in("o.a.b", ctx), num(2.0));
1015
+        assert_eq!(eval_in("o.`a.b`", ctx), num(1.0));
1016
+    }
1017
+
1018
+    #[test]
1019
+    fn no_builtin_name_contains_a_name_symbol() {
1020
+        // Built-in names are in scope for the fusion probe. A built-in whose name
1021
+        // contained `- + * / .` would silently change how existing expressions
1022
+        // parse — and the values stored in feel-pg expression indexes (ADR-48).
1023
+        let src = include_str!("builtins.rs");
1024
+        let start = src.find("pub(crate) fn is_builtin").expect("is_builtin present");
1025
+        let body = &src[start..start + src[start..].find("\n}\n").expect("end of fn")];
1026
+        let names: Vec<&str> = body.split('"').skip(1).step_by(2).collect();
1027
+        assert!(names.len() > 50, "parsed the is_builtin name list ({})", names.len());
1028
+        for n in names {
1029
+            assert!(
1030
+                !n.contains(['-', '+', '*', '/', '.']),
1031
+                "built-in `{n}` contains a name symbol"
1032
+            );
1033
+        }
7091034
     }
7101035
 
7111036
     #[test]