# Research: names with `-` and other special characters (scope-dependent parsing)

> **Outcome:** shipped as **ADR-47** (branch `feat/special-char-names`) —
> Design A, v1 = reference slots. This document is the research record; where
> it and ADR-47 differ, ADR-47 is authoritative (the fusion pass runs *after*
> `join_names`; `Profit and loss`-style space-joined reserved-word names are a
> documented deferral, not v1).

Question: how much effort to support FEEL names containing `-` (and other
"additional name symbols") that can only be parsed with context — and can the
ADR-21 lazy-traversal architecture carry it? Status: **research only, nothing
decided or built.** Companion to the ADR-17 deviation note (DECISIONS.md:430)
and the ROADMAP deferral entry.

## 1. What the spec requires

- **Grammar rules 25–30** (`specs/FEEL/feel.md:497-507`): a name is a name start
  plus name parts, and the *additional name symbols* (rule 30) are
  `"." | "/" | "-" | "+" | "*"`. Rule 28 also allows `?` and a wide set of
  non-XID Unicode as name-start chars. So `a-b`, `Date-Time`, `a.b` (one name
  with a dot!) are all legal FEEL names.
- **§10.3.1.6 "Ambiguity"** (`specs/FEEL/feel.md:668-679`): because names are
  *token sequences* and some of those tokens are operators/keywords, ambiguity
  is resolved **using the scope**: "Name tokens are matched from left to right
  against the names in-scope, and the longest match is preferred." Spaces are
  *not* part of the token sequence — `a - b` and `a-b` are the same candidate
  name; to force subtraction when `a-b` is in scope one must write `(a)-(b)`.
  The spec's own examples: `a-b`, `what if?`, `Profit and loss` (a keyword
  inside a name).
- **§10.3.1.5** (`specs/FEEL/feel.md:651`): qualified names `N1.N2.…` are
  dot-chains, and `.` is *both* the path separator and a name symbol — so even
  `Date-Time2.hour` is ambiguous between one name and name+path.

This is exactly the "name oracle" ADR-17 predicted would be needed
(`DECISIONS.md:430-432`): parse must consult the set of in-scope names.

## 2. Where the engine stands today

- Names are whitespace-joined words only (ADR-17, `lexer.rs:442-479`
  `join_names`, Tier 1 adjacent `Name` runs; Tier 2 fixed keyword phrases).
  Special-char names are a documented deviation (`README.md:69-72`,
  `DECISIONS.md:1671`).
- Hyphen names do not *fail* to parse — they **silently mis-parse** into
  subtraction: `Date-Time2.hour` parses as `Date - (Time2.hour)`. The ingester's
  free-name scan (`tools/ingest_tck.py`, `fits_slice_grammar`) therefore rejects
  them at ingestion time.
- Name resolution at eval is already scope-based and cheap:
  `Expr::Var` → `ctx.get(name)` → builtins → null (`eval.rs:106-114`). The
  parser itself is strictly context-free: `compile(expr)` (`lib.rs:252`),
  LR(1) with a build.rs no-conflict gate, and the lexer already owns the
  "lexer resolves what the grammar cannot" pattern (`mark_instance_of`,
  `mark_reverse_open`, `join_names`; `lexer.rs:303-325`).

## 3. What it unlocks in the DMN-TCK (measured, not guessed)

Re-running `tools/ingest_tck.py` over the relevant suites produced a **coverage
correction** to the naive expectation:

- **The TCK has no hyphen-named `inputData` anywhere** (verified over all
  suites' `<inputData name=…>`). In `0007-date-time` — the suite with the
  hyphen expressions — `Date-Time` and `Date-Time2` are *decisions*, and every
  hyphen expression (`Date-Time - Date-Time2`, `Date-Time2.hour`,
  `time(Date-Time2)`, `date(Date-Time)`,
  `years and months duration(Date-Time2,Date-Time)`) references *decision
  results*, not inputs. Today only **4 of 28** decisions are ingested; the
  other ~15 skip because the ingester's slice binds only `<inputNode>` values
  (BKMs are inlined) — a **DRG boundary**, hit before name charset matters.
  Name support alone therefore unlocks **zero** auto-ingested cases.
- The real unlock needs a second, small ingester capability: **decision-result
  binding** — bind the testCase's `<resultNode>` values (the TCK records
  `Date-Time`, `Date-Time2`, … per case) into the case context, the same
  expected-as-input stance the boxed-context suites take. With it, the ~9–11
  hyphen cases of `0007` become self-contained *and* exercise the hardest
  forms: subtraction of two hyphen names — the TCK expects *subtraction*,
  which left-to-right longest-match reproduces; a hyphen name as a **path
  base** (today's mis-parse `Date - (Time2.hour)`); hyphen call arguments.
- Until that lands, the names increment proves TCK-shaped coverage the way
  `0092-feel-lambda` did: a **hand-written fixture** with the 0007 expressions
  and result-derived context values, plus unit tests.
- **`0004-lending`**: hyphenated decision/parameter names
  (`Pre-bureauRiskCategory: Pre-bureauRiskCategory`, …) — decision tables plus
  DRG on top; not unlocked by names.
- **`0083-feel-unicode`** (2 emoji-key skips, `NON_XID_NAME_SKIPS` in
  `tools/ingest_tck.py:810`): a *different* feature — name-start chars beyond
  XID (rule 28). A small lexer widening; not the oracle problem.

## 4. The ADR-21 connection (the user's premise, verified)

The traversal architecture is the enabler, but in a specific place: since ADR-21
(and RD-11 for pg), **every wrapper materializes exactly the root level** of the
context and traverses everything below lazily:

- feel-pg: `context_from_jsonb` iterates the top-level keys, nested containers
  become `JsonbForeign` (`crates/feel-pg/src/jsonb.rs:302-343`).
- feel-py: `context_to_ctx` one-level-forces the root into `Context`; nested
  objects stay lazy `Foreign`s (`crates/feel-py/src/lib.rs:185-258`). Same
  shape in feel-wasm/feel-lua.

The scope a name oracle needs is **only the root key set** (+ builtin names) —
which every wrapper already holds at `evaluate()` entry. No eager deep
conversion, no new `ForeignObject` method, no change to laziness or cycle
safety. So the answer to "kann man daran anknüpfen?" is **yes — at the
root-materialization seam, not inside the evaluator.**

## 5. Design space

### Design A — parse-time scope probe (spec-faithful; recommended)

`compile(expr)` stays context-free. Add a second, scope-aware parse entry
point: `compile_with_probe(expr, &ScopeProbe)` where `ScopeProbe` is a
std-only `contains(&self, name) -> bool` (ADR-1-safe; a `Context::contains`
mirroring eval's Var order — context binding, then builtins — is trivial).
Then:

- **Lexer**: one new pass *after* `join_names` (implemented order: a multi-word
  part like `total price` must already be one word unit, or `total price-total`
  would be unreachable — see ADR-47): scan maximal runs
  `word (op word)*` with op ∈ {`-`, `+`, `*`, `/`} (and `.` for dot-names),
  where a word is a `Name` or a keyword's spelling (`tok_word` already exists,
  `lexer.rs` — keywords are legal name parts, which is what makes `if-then`
  reachable). *[Superseded: §10.3.1.4 forbids a keyword as name start —
  shipped runs start only at a `Name`; `x-in` is reachable, `if-then` is not.]* At each run start, try candidates **longest-first** against the
  probe; fuse the longest hit into one `Name` token (space-normalised payload,
  as today) and continue after it. This is mechanically precedented:
  `match_keyword_phrase` / `mark_instance_of` fuse tokens the same way. Est.
  ~100–200 lines + tests.
- **Grammar, AST, evaluator: unchanged.** The LR(1) parser never sees an
  ambiguity — the same trick as the `instance of` fusion and the
  `RBracketOpen` retag. Every `Name` slot (call heads, named-arg names, loop
  bindings, context keys, path members) gets the feature for free.
- Spec semantics fall out exactly: `a - b` (spaces) also resolves to the name;
  `(a)-(b)` forces subtraction (parens break the run); `Date-Time2.hour`
  resolves as name+path because the whole-run candidate is not in scope;
  `Date-Time - Date-Time2` resolves to subtraction by left-to-right
  longest-match, matching the TCK expectation.

**The architecture cost — the only real one:** parsing gains an optional
context dependence. Three invariants are affected, each with a cheap, statically
detectable guard (the lexer pass can set `CompiledExpr::has_name_runs`):

1. **compile-once/eval-many** (`compile()` classes in py/wasm/lua): a compiled
   prog would be pinned to one scope. Policy: `compile()` stays probe-free
   (today's behavior); the one-shot `evaluate(expr, context)` paths become
   probe-aware (they already hold the root key set). Optionally a
   `compile(expr, scope=…)` later.
2. **feel-pg `fn_extra` parse cache** keyed on expression text
   (`crates/feel-pg/src/lib.rs:110-126`): a row-dependent parse must not be
   cached across rows → skip the cache for `has_name_runs` expressions; they
   parse per row against that row's keys (logos parse is ~µs; only ambiguous
   expressions pay it).
3. **`feel_eval_immutable`** (RD-10): an index must never embed a row-shaped
   parse → IMMUTABLE statically rejects `has_name_runs` expressions, the same
   loud-and-documented style as the named-zone ban.

**Declaration slots** (`for Date-Time in …`, formal params, context keys):
these *declare* names, so no oracle knows them — but the slots are
syntactically unambiguous (after `for` only a name can come), so a greedy run
bounded by `in`/`,`/`:`/`(` is context-free-correct. **Deferred from v1:** an
in-grammar `DeclName: Name (Minus|Plus|Star|Slash Name)*` production is *not*
conflict-free in call-args — `f(a-b: 1)` (named) vs `f(a-b)` (expression)
forces a shift/reduce decision on `-` after the first `Name` that LR(1) cannot
make — so declaration slots need either a slot-aware lexer pass (the
`mark_reverse_open` forward-scan style, bounded by `in`/`:`/`,`/`) or a
grammar fork with its own conflict analysis. No TCK shape needs them, so v1
ships reference slots only and ADRs the deferral.

### Design B — eval-time resolution (examined, rejected)

Keep parse scope-free, record the ambiguity in the AST, and at eval probe
`ctx.get("a-b")` longest-first before evaluating the primary parse. Tempting
because it uses `Context::get` directly (the ADR-21 seam) with zero API change
— but it fails on inspection:

1. The primary parse **mis-shapes the tree** (`Date-Time2.hour` →
   `Date - (Time2.hour)`), so the eval-time reinterpretation must re-chunk the
   token run per candidate — i.e. carry raw source runs in the AST and run a
   mini re-parse at eval. Threading spans/candidates through the grammar is
   invasive and touches the LR(1) gate; `Expr`'s `Clone/PartialEq` carries the
   baggage.
2. **Syntactic name slots cannot be deferred**: named-arg names
   (`Pre-bureauRiskCategory: …`), loop bindings, context keys are parse-time
   bindings; every consumer (`bind_params`, FnCall dispatch, `Entry`, …) would
   need its own eval-time re-resolution — 6–8 resolution sites vs. one lexer
   pass.
3. Chunking edge cases become per-context behavior that is harder to specify,
   test, and ADR than A's "the parse is resolved against one scope".

More code, less coverage, worse testability. B's *intuition* (the scope lives
at eval time) is right, but A cashes it at the right place: the root key set
that the wrappers materialize anyway.

## 6. Effort estimate

| Piece | Est. |
|---|---|
| Core: lexer run-scan pass + `ScopeProbe` + `compile_with_probe` + `has_name_runs` flag (declaration slots deferred — none of the TCK shapes need them) | ~1–2 d |
| Wrappers: probe plumbing (py `in`/`hasattr`, wasm `Reflect.has`, lua table probe, pg top-level keys) + `compile()` policy | ~0.5–1 d |
| feel-pg: cache skip + IMMUTABLE guard for `has_name_runs` | incl. above |
| Ingester: free-name-scan alignment (hyphen-joined bound names) + hand-written 0007-shaped fixture | ~0.5 d |
| ADR (ADR-17 successor) + unit tests (longest-match, `(a)-(b)`, spaces-irrelevance, `Profit and loss`, path-base names, cache/IMMUTABLE guards) | ~0.5–1 d |
| **Total (names increment)** | **~3–4 days** |
| *Follow-up, separate increment:* decision-result binding in the ingester (`<resultNode>` values as case context) — auto-ingests the 0007 hyphen cases (+~9–11) and any other DRG-chained suite | *~1–2 d* |

## 7. Architecture impact (the actual question)

**Contained.** No change to the evaluator, AST shape, `Value`, builtins, the
`ForeignObject` seam, or the LR(1) grammar body. What changes:

- one new std-only seam (`ScopeProbe`) + one optional scope-aware parse mode,
  both no-ops without a probe (behavior byte-identical to today);
- ADR-17's tier model gains a "Tier 0" (oracle-joined special-char names);
- two existing invariants (pg parse cache, IMMUTABLE subset) gain a static,
  loud exclusion for ambiguous expressions — the same style as the existing
  clock/named-zone guards;
- the ingestion loop gains the probe input it already almost has (the fixture
  `context`), unlocking `0007-date-time` as the acceptance suite.

Recommendation, if picked up: Design A, recorded as an ADR-17 successor; v1 =
reference slots, proven by a hand-written 0007-shaped fixture plus unit tests
(the `0092-feel-lambda` pattern). The auto-ingest of `0007-date-time` lands
with the separate decision-result-binding ingester increment. Leave 0083
(non-XID name chars) as the separate small lexer widening it is.
