# DS grammar

The grammar of DS source files: lexical
structure (tokens, whitespace, comments, indentation handling),
syntactic structure (productions), and operator precedence.

This document is authoritative for DS syntax. If it
disagrees with any other language doc on a syntactic point,
this doc wins.

Paired with [LLEX], which describes how source
bytes become the terminal stream the productions consume. This
doc carries both the BNF productions and the prose rationale /
disambiguation notes — when normative grammar and prose
disagree, the productions in this doc win.

These productions are the specification, and a parser conforms
to them. When a parser and this document disagree, the parser
is wrong — including the reference one. A change to the
language is made here first, and the parser follows.

This doc does not specify semantics — those live in the
per-topic language specs (FACT_MODEL, EXPRESSIONS, etc.).
This doc specifies what a DS file *looks like* and how a
parser recognises its structure.

## What this is not

- Not a semantic specification. Behaviour of constructs
  (what `emit` does, what `logical` maintenance means, how
  `cooldown` enforces rate limits) lives in topical spec
  docs.
- Not an implementation guide. The reference compiler
  implements this grammar; compiler-internal choices
  (tokeniser structure, parser technique) are runtime
  concerns.
- Not exhaustive of every error condition. Individual
  constructs have their own compile-time diagnostics
  specified in their respective spec docs.

---

(LGRA-1)=
## Notation [LGRA.1]

(LGRA-1-1)=
[LGRA.1.1] The grammar uses an EBNF-style notation:

(LGRA-1-2)=
- [LGRA.1.2] `::=` defines a production.

(LGRA-1-3)=
- [LGRA.1.3] `|` separates alternatives.

(LGRA-1-4)=
- [LGRA.1.4] `*` means zero or more.

(LGRA-1-5)=
- [LGRA.1.5] `+` means one or more.

(LGRA-1-6)=
- [LGRA.1.6] `?` means optional (zero or one).

(LGRA-1-7)=
- [LGRA.1.7] `( ... )` groups for precedence.

(LGRA-1-8)=
- [LGRA.1.8] **Terminal keywords** are written in bold lowercase:
  **rule**, **schema**, **where**.

(LGRA-1-9)=
- [LGRA.1.9] Terminal punctuation is written in single quotes: `':'`,
  `'->'`, `'.'`.

(LGRA-1-10)=
- [LGRA.1.10] Terminal character classes are written in uppercase:
  `DIGIT`, `LETTER`.

(LGRA-1-11)=
- [LGRA.1.11] Non-terminals are lowercase identifiers in plain text:
  `rule_decl`, `expression`, `pattern`.

---

(LGRA-2)=
## Lexical structure [LGRA.2]

(LGRA-2-1)=
### Source encoding [LGRA.2.1]

(LGRA-2-1-1)=
[LGRA.2.1.1] DS source files are UTF-8, and identifiers are Unicode:
the legal character set is `XID_Start`/`XID_Continue` narrowed by
`Identifier_Status=Allowed`, per [LNAM.2.2.1]. Every ASCII
identifier of the form `[A-Za-z_][A-Za-z0-9_]*` is legal
([LNAM.2.2.2]), and so is a great deal more.

*see also:* [LNAM.2.2.1](#LNAM-2-2-1), [LNAM.2.2.2](#LNAM-2-2-2)

(LGRA-2-2)=
### Whitespace [LGRA.2.2]

(LGRA-2-2-1)=
[LGRA.2.2.1] Spaces (ASCII 0x20) are the only horizontal whitespace;
tabs are rejected by the lexer. See [LLEX.3].

*see also:* [LLEX.3](#LLEX-3)

(LGRA-2-2-2)=
[LGRA.2.2.2] Newlines are LF (`\n`) or CRLF (`\r\n`). CR-only is not
accepted.

(LGRA-2-2-3)=
[LGRA.2.2.3] Blank lines (only spaces or only a comment) are ignored
for block structure.

(LGRA-2-3)=
### Indentation [LGRA.2.3]

(LGRA-2-3-1)=
[LGRA.2.3.1] Indentation is exactly 4 spaces per level. The lexer
emits `INDENT`, `DEDENT`, and `NEWLINE` synthetic tokens
that the productions below consume. Full rules at [LLEX.6].
Inside parentheses `(` / `)`, square brackets `[ ]`, or
curly braces `{ }`, indentation tracking is suspended and any
leading-space count is legal (LLEX.7.5.5). This is the
standard mechanism for multi-line expressions.

*see also:* [LLEX.6](#LLEX-6), [LLEX.7.5.5](#LLEX-7-5-5)

(LGRA-2-4)=
### Comments [LGRA.2.4]

(LGRA-2-4-1)=
[LGRA.2.4.1] Grammar production:

```
comment ::= '#' <any-char-except-newline>*
```

(LGRA-2-4-2)=
[LGRA.2.4.2] A line comment begins with one or more `#` characters
and runs to end-of-line. Stripped by the lexer. No block
comments.

*ratified*

(LGRA-2-4-3)=
[LGRA.2.4.3] Comments are non-semantic: the parser produces the
same AST whether comments are present or absent. They are
**preserved as compiler trivia** — carried verbatim in the
DSC's `DsSource` source atom per
[RLOW.7.8](#RLOW-7-8).

*see also:* [RLOW.7.8](#RLOW-7-8)

(LGRA-2-5)=
### Identifiers [LGRA.2.5]

(LGRA-2-5-1)=
[LGRA.2.5.1] Identifier and type-symbol terminals:

```
NAME     ::= <one identifier terminal over the XID class,
             NFC-normalized; legality per [LNAM.2.2], lexer
             realization per [LLEX]>
TYPE_SYM ::= <the type-symbol terminal: the NAME class plus the non-XID unit
             glyphs (`°` `′` `″`, …); valid only in type positions
             ([LGRA.22]); lexer realization per [LLEX]>
NULLABLE ::= '?'                                # the nullable-type marker ([LNUL])
```

*see also:* [LGRA.22](#LGRA-22), [LNAM.2.2](#LNAM-2-2)

(LGRA-2-5-2)=
[LGRA.2.5.2] `NAME` is the **single** identifier terminal — bindings, slot
names, constants, and schema / type references all lex as `NAME`. An
identifier's role (type reference versus binding) is fixed by grammatical
**position**, not by case ([LGRA.22]). A `NAME` never carries a unit glyph; a
type spelled with a non-XID glyph (`slot: °C`, `x::°C`) lexes `TYPE_SYM`.

*ratified*  —  *checks:* `alloy`  —  *see also:* [LGRA.22](#LGRA-22)

(LGRA-2-5-3)=
[LGRA.2.5.3] `TYPE_SYM` is the terminal at every **type position** — a `slot:
T` annotation, a `let x: T` annotation, a `::T` cast target ([LCST.4.1]), and a
unit literal. It resolves in the **type namespace** ([LGRA.22]): the scalar
builtins (`String` / `Int` / `Float` / `Bool` / `Bytes`), `Json`,
unit symbols, and schemas ([LGRA.22.7]).

*see also:* [LCST.4.1](#LCST-4-1), [LGRA.22](#LGRA-22), [LGRA.22.7](#LGRA-22-7)

(LGRA-2-5-4)=
[LGRA.2.5.4] Hyphens are not permitted in identifiers (they are not `XID`).

(LGRA-2-6)=
### Reserved words [LGRA.2.6]

Which words are reserved, and against what, is [LLEX.9.5]; the list is
[LLEX.9.6]. How each is recognised — a distinct terminal, or a `NAME`
promoted by position — is the business of the production that matches it,
stated there and not restated here.

*see also:* [LLEX.9.5](#LLEX-9-5), [LLEX.9.6](#LLEX-9-6)

(LGRA-2-6-19)=
[LGRA.2.6.19] Adapter-registered type names (`Hass`, `Mqtt`,
`Weather`, …) are not keywords — adapter registration and grammatical
**position** ([LGRA.22]) determine which `NAME` tokens resolve as type
references. (Case does not classify: an adapter type need not be CamelCase.)

*see also:* [LGRA.22](#LGRA-22)

(LGRA-2-7)=
### Numeric literals [LGRA.2.7]

(LGRA-2-7-1)=
[LGRA.2.7.1] The numeric literal tokens are the lexer's: [LLEX.11.1] states
`INT_LIT`'s productions and [LLEX.11.2] `FLOAT_LIT`'s.

*see also:* [LLEX.11.1](#LLEX-11-1), [LLEX.11.2](#LLEX-11-2)

(LGRA-2-7-3)=
[LGRA.2.7.3] A literal exceeding the `Int` range at parse time is a
compile error. Numeric widths and arithmetic semantics at
[LDET.6.2] / [LDET.6.3].

*ratified*  —  *see also:* [LDET.6.2](#LDET-6-2), [LDET.6.3](#LDET-6-3)

(LGRA-2-7-5)=
[LGRA.2.7.5] No leading-dot, trailing-dot, hex floats, or typed
suffixes.

(LGRA-2-7-6)=
[LGRA.2.7.6] Negative numbers are unary minus applied to a
non-negative literal.

(LGRA-2-8)=
### Unit literals and time expressions [LGRA.2.8]

(LGRA-2-8-1)=
[LGRA.2.8.1] A duration is written as a `time_expr`: a `UNIT_LIT` whose
`UNIT_SUFFIX` resolves to the `time` dimension, or a `NAME` that names a
constant whose value is a `Duration` ([LGRA.2.8.11]). The `UNIT_LIT`
production is defined **authoritatively** in [LLEX.12] and is not restated
here:

```
time_expr   ::= UNIT_LIT    ;; UNIT_LIT (LLEX.12), unit resolves to `time`
             |  NAME         ;; a constant whose value is a `Duration` (LGRA.2.8.11)
```

*ratified*  —  *see also:* [LGRA.2.8.11](#LGRA-2-8-11), [LLEX.12](#LLEX-12)

(LGRA-2-8-2)=
[LGRA.2.8.2] Every construct that takes a duration accepts `time_expr`, except
an `after` clause, which takes a `UNIT_LIT` only ([LGRA.6.1]).
Examples: `30_s`, `5_min`, `2_h`, `24_h`, `7_d`, `100_ms`.

*ratified*  —  *see also:* [LGRA.6.1](#LGRA-6-1)

(LGRA-2-8-11)=
[LGRA.2.8.11] **A `NAME` in a `time_expr`** names a constant ([LGRA.4.1])
whose value is a `Duration`. The compiler must read the constant's folded
value at that position as it reads a `UNIT_LIT` of the same duration, so a
rule the position sets on its duration ([LTIM.2.7.1], [LGRA.13.5],
[LGRA.5.2]) holds of the value. The compiler must refuse any other `NAME` in
a `time_expr`: one that names a constant whose value is a quantity of
another dimension with `DS_VALIDATE_BAD_UNIT_DIMENSION`, as it refuses a
`UNIT_LIT` of another dimension ([LLEX.12.8]); one that names a constant of
any other type with `DS_VALIDATE_TYPE_MISMATCH`; and one that names no
constant, a binding included, with `DS_VALIDATE_UNKNOWN_CONST`.

*ratified*  —  *see also:* [LGRA.13.5](#LGRA-13-5), [LGRA.4.1](#LGRA-4-1), [LGRA.5.2](#LGRA-5-2), [LLEX.12.8](#LLEX-12-8), [LTIM.2.7.1](#LTIM-2-7-1)

(LGRA-2-8-9)=
[LGRA.2.8.9] `m` means meters; minutes are spelled `min`. `ms` means
milliseconds.

(LGRA-2-8-10)=
[LGRA.2.8.10] A `time_expr` position ([LGRA.2.8.1]) takes a bare `UNIT_LIT` or
a `NAME` and admits no sign, so the compiler must refuse `within -5_s` and
`scope ttl -5_s` at parse. A rate modifier's sign has its own code instead
([LGRA.6.6.7]). In an expression position `-5_s` parses, as unary minus through the
`unary` production of [LGRA.9.5.1], and the compiler refuses it: a `Duration`
is never negative ([LUNI.3.3]). A "no value" opt-out uses a dedicated flag
(`nocooldown`), not a duration.

*ratified*  —  *see also:* [LGRA.2.8.1](#LGRA-2-8-1), [LGRA.6.6.7](#LGRA-6-6-7), [LGRA.9.5.1](#LGRA-9-5-1), [LUNI.3.3](#LUNI-3-3)

(LGRA-2-9)=
### String literals [LGRA.2.9]

(LGRA-2-9-1)=
[LGRA.2.9.1] String literal productions:

```
STRING_LIT  ::= SINGLE_STR | TRIPLE_STR
SINGLE_STR  ::= '"' SINGLE_CHAR* '"'
SINGLE_CHAR ::= <any character except '"', NEWLINE, or '\'>
             |  '\\' ESCAPE_SEQ
TRIPLE_STR  ::= '"""' TRIPLE_CHAR* '"""'
TRIPLE_CHAR ::= <any character except '"""' or '\'>
             |  '\\' ESCAPE_SEQ

ESCAPE_SEQ  ::= '"'  | '\'' | '\\' | 'n' | 't' | 'r'
             |  'x' HEX_DIGIT HEX_DIGIT
             |  'u' HEX_DIGIT HEX_DIGIT HEX_DIGIT HEX_DIGIT
             |  'U' HEX_DIGIT HEX_DIGIT HEX_DIGIT HEX_DIGIT
                    HEX_DIGIT HEX_DIGIT HEX_DIGIT HEX_DIGIT
```

*ratified*

(LGRA-2-9-2)=
[LGRA.2.9.2] Single-line literals (`"..."`) may not contain physical
newlines.

*ratified*

(LGRA-2-9-3)=
[LGRA.2.9.3] Triple-quoted literals (`"""..."""`) may span multiple
lines; indentation trimmed per inspect.cleandoc rules.

(LGRA-2-9-4)=
[LGRA.2.9.4] Unknown escape sequences are compile errors. So is a `\x`, `\u`
or `\U` escape that names a codepoint no `String` can hold ([LSTR.1.1]):
U+0000, a surrogate, or a value above U+10FFFF. The compiler must refuse each
as it refuses an unknown escape, and must not emit a string that omits or
substitutes the character.

*ratified*  —  *see also:* [LSTR.1.1](#LSTR-1-1)

(LGRA-2-9-5)=
[LGRA.2.9.5] `"` is the only string delimiter: the lexer must refuse a `'`
that opens a token, with `DS_LEX_GENERIC`. One `STRING_LIT` is one string, and
an interpolation ([LGRA.2.9.6]) is how an author builds one from parts.

*ratified*  —  *see also:* [LGRA.2.9.6](#LGRA-2-9-6)

(LGRA-2-9-7)=
[LGRA.2.9.7] The lexer must accept `\'` as a valid `ESCAPE_SEQ` alternative
in a double-quoted string, though an apostrophe never needs escaping
there. An author coming from a language with
single-quote-delimited strings types `\'` out of habit; rejecting it forces
a needless correction for content that is not ambiguous in DS's grammar.

*ratified*  —  *see also:* [LGRA.2.9.4](#LGRA-2-9-4), [LGRA.2.9.5](#LGRA-2-9-5)

(LGRA-2-9-6)=
#### String interpolation [LGRA.2.9.6]

(LGRA-2-9-6-1)=
[LGRA.2.9.6.1] Inside a single-line double-quoted string or a triple-quoted
string that appears in action-argument position, the
following interpolation grammar applies:

```
interp_site   ::= '{' interp_body (':' interp_format)? '}'
interp_body   ::= NAME ( '.' NAME | '[' INT_LIT ']' )*
interp_format ::= TIME_SPEC | NUM_SPEC

TIME_SPEC     ::= TIME_DIR TIME_ITEM*
TIME_ITEM     ::= TIME_DIR | TIME_CHAR
TIME_DIR      ::= '%' ( 'Y' | 'm' | 'd' | 'H' | 'M' | 'S' | 'f' | 'z' | '%' )
TIME_CHAR     ::= <any character except '%', '{' and '}'>

NUM_SPEC      ::= ALIGN? SIGN? ZERO? WIDTH? PRECISION? TYPE?
ALIGN         ::= '<' | '>'
SIGN          ::= '+'
ZERO          ::= '0'
WIDTH         ::= DIGIT+
PRECISION     ::= '.' DIGIT+
TYPE          ::= 'd' | 'f' | 's' | 'x' | 'X' | 'b' | 'u'
```

*ratified*

(LGRA-2-9-6-2)=
[LGRA.2.9.6.2] `interp_body`'s leading `NAME` resolves to any
**in-scope value-binding** — an LHS pattern binding, a `const`, a
series companion, or a `let` (pure **or sync-impure**, e.g. a `let`
bound to `now()` or `cached("k")`) — and interpolation formats that
**bound value**; the `('.'NAME | '['INT_LIT']')*` tail applies to the
value. A dotted body resolves as a dotted name in expression position does
([LGRA.22.9]), so `{lib.CONST}` formats the constant `CONST` of an imported
library `lib`, a `const` like the file's own. A `let`'s RHS purity is irrelevant to interpolability: a
sync-impure `let` is bound once per activation ([LGRA.9.8.4]), so its
captured value formats deterministically. The body is a **name/path,
not an inline expression** — an inline call or operator (`{now()}`,
`{cached("k")}`, `{c.a + c.b}`) is a compile error ([LGRA.2.9.6.9]). An
unknown binding is a compile error; a null / absent bound value (e.g. a
`cached` miss) renders as the **empty string**.

*ratified*  —  *see also:* [LGRA.2.9.6.9](#LGRA-2-9-6-9), [LGRA.22.9](#LGRA-22-9), [LGRA.9.8.4](#LGRA-9-8-4)

(LGRA-2-9-6-3)=
[LGRA.2.9.6.3] Format specifiers split by the first character after `:`:

(LGRA-2-9-6-4)=
- [LGRA.2.9.6.4] **Timestamp** (`:%…`) — a pattern of directives and literal
  text, applied to a `Time`. The directives are Python's, and DS admits only
  these:

  | Directive | Renders |
  |---|---|
  | `%Y` | the year, four digits |
  | `%m` | the month, `01`–`12` |
  | `%d` | the day of the month, `01`–`31` |
  | `%H` | the hour, `00`–`23` |
  | `%M` | the minute, `00`–`59` |
  | `%S` | the second, `00`–`59` |
  | `%f` | the microsecond, six digits; the nanoseconds below it are truncated, never rounded |
  | `%z` | the UTC offset as `+HHMM` or `-HHMM`, then `SS` when the offset has seconds, then `.ffffff` when it has a fraction of a second |
  | `%%` | a literal `%` |

  Every field renders in the value's own UTC offset. Every other character is
  written as it is. The compiler must refuse any other `%` sequence, and a
  timestamp spec on a value that is not a `Time`, with
  `DS_VALIDATE_INTERP_BAD_FORMAT`. The compiler resolves the pattern into
  literal text and fields, and no pattern reaches the runtime.

*ratified*

(LGRA-2-9-6-5)=
- [LGRA.2.9.6.5] **Numeric / string specs** — `[align][sign][0][width][.precision][type]`
  ([LGRA.2.9.6.1]): Python's order, with Python's meaning for every part DS
  admits. DS admits less than Python — no fill character, no centre or `=`
  alignment, no space sign, no alternate form, no grouping. Types: `d`, `f`, `s`,
  `x`, `X`, `b`, and the unit type `u` ([LUNI.11.2]).

  The compiler must refuse, with `DS_VALIDATE_INTERP_BAD_FORMAT`, what the
  grammar cannot express ([STYL.2.15.4]):

  - an alignment with no width;
  - zero padding together with left alignment;
  - a sign or zero padding on a `String` or a `Bool`;
  - a precision on an integer type (`d`, `x`, `X`, `b`);
  - a precision above `20` on `f`. A value that needs more places is written
    with no type, in its canonical form ([LDET.3.2.7]);
  - a precision with no type on a value of any kind but `String`: an `Int`, a
    `Float`, a `Bool`, a `Time`, a `Duration` alike. Decimal places are `f`'s;
    with no type, only a `String` takes a precision;
  - a type the value's kind does not take: `d`, `x`, `X` and `b` take `Int`;
    `f` and `u` take `Float` and `Int`; `s` takes `String`. A `Bool` takes no
    type.

  A `u` on a number that carries no unit is refused with
  `DS_VALIDATE_INTERP_UNIT_NON_UNIT` instead, and `i` or `j` as a type, which
  belong to the deferred complex type, with `DS_VALIDATE_COMPLEX_NOT_IN_V1`
  ([LUNI.14.9]).

  **This is DS's own format language.** Its grammar follows Python's; its
  rendering is DS's, stated in [LGRA.2.9.6.10], because determinism cannot be
  delegated to another language's runtime. The compiler must not lower a spec
  into any other formatting language: the artefact carries the spec's parts,
  and the runtime renders them itself.

*ratified*  —  *see also:* [LDET.3.2.7](#LDET-3-2-7), [LGRA.2.9.6.1](#LGRA-2-9-6-1), [LGRA.2.9.6.10](#LGRA-2-9-6-10), [LUNI.11.2](#LUNI-11-2), [LUNI.14.9](#LUNI-14-9)

(LGRA-2-9-6-10)=
- [LGRA.2.9.6.10] **How a numeric or string spec renders.** The runtime must
  render an interpolated value under a spec of [LGRA.2.9.6.5] as follows. Width
  and precision count Unicode code points.

  - **The digits or text.**
    - No type: the value's canonical text — an `Int` in decimal, a `Float` in
      [LDET.3.2.7]'s form, a `String` as itself, a `Bool` as `true` or `false`,
      a `Time` as [LTIM.8.2.1]'s `iso8601` in UTC, a
      `Date` as `iso8601`, and a `Duration` as [LTIM.8.4]'s compact form.
      A precision keeps at most that many code points of a `String`, as for
      `s`.
    - `d`: an `Int` in decimal.
    - `x`, `X`: an `Int` in hexadecimal, with lowercase or uppercase digits.
      `b`: an `Int` in binary. A negative value renders as `-` followed by the
      digits of its magnitude. No base prefix is written.
    - `f`: fixed-point, never with an exponent: the value correctly rounded to
      as many fractional digits as the precision, or six when none is given,
      ties to even ([LDET.3.2.8]). A precision of `0` writes no decimal point. An `Int` renders as the `Float` of the same value. `±Inf`
      renders `inf` or `-inf`. A negative value keeps its sign even when every
      digit written is zero, so `-0.0` and `-0.001` at precision 2 both
      render `-0.00`.
    - `s`: the `String`. A precision keeps at most that many code points.
    - `u`: the label of the value's unit ([LUNI.11.4]), rendered as a
      `String` is: it aligns left by default, a precision keeps at most that
      many code points, and `+` and `0` have no effect.
  - **The sign.** With `+`, a number that is not negative is written with a
    leading `+`. Without it, only a negative number carries a sign.
  - **The width.** Text shorter than the width is padded with spaces: before it
    for right alignment, after it for left alignment. With no alignment given,
    a number aligns right, and a `String` or a `Bool` aligns left. With `0`,
    the padding is zeros, placed between the sign and the digits. Text as long
    as the width or longer is written whole, never truncated.
  - **Null.** A null value renders as the empty string, with no padding
    ([LGRA.2.9.6.2]).

*ratified*  —  *see also:* [LDET.3.2.7](#LDET-3-2-7), [LDET.3.2.8](#LDET-3-2-8), [LGRA.2.9.6.2](#LGRA-2-9-6-2), [LGRA.2.9.6.5](#LGRA-2-9-6-5), [LTIM.8.2.1](#LTIM-8-2-1), [LTIM.8.4](#LTIM-8-4), [LUNI.11.4](#LUNI-11-4)

(LGRA-2-9-6-11)=
- [LGRA.2.9.6.11] **A spec on a `Json` leaf is checked when the leaf is read.**
  The compiler cannot know a `Json` leaf's kind, so [LGRA.2.9.6.5]'s refusals
  bind only a value whose kind is known statically, and the compiler must
  accept a spec on a leaf. At run time, a spec part that the leaf's kind does
  not take under [LGRA.2.9.6.5]'s rules is a **TypeError**, as any operation
  on a wrong-typed leaf is ([LEXP.7.12.1]): the activation is abandoned and
  the fault reaches the fault surfaces ([LERR.9.1]). The runtime must not render the
  value with the spec part dropped. A leaf whose kind takes the spec renders
  as [LGRA.2.9.6.10] states.

  Only a leaf renders. A path that reaches an object or an array is not a
  leaf, and interpolating it is a TypeError, with or without a spec, with the
  same disposition as above.

  A whole `Json` value ([LEXP.7.19]) is not a leaf, whatever it holds. The
  compiler must refuse interpolating one, or a `let` bound to one
  ([LGRA.2.9.6.2]), with `DS_VALIDATE_INTERP_UNSUPPORTED` ([LGRA.2.9.6.9]), with
  or without a spec.

*ratified*  —  *see also:* [LERR.9.1](#LERR-9-1), [LEXP.7.12.1](#LEXP-7-12-1), [LEXP.7.19](#LEXP-7-19), [LGRA.2.9.6.10](#LGRA-2-9-6-10), [LGRA.2.9.6.2](#LGRA-2-9-6-2), [LGRA.2.9.6.5](#LGRA-2-9-6-5), [LGRA.2.9.6.9](#LGRA-2-9-6-9)

(LGRA-2-9-6-6)=
[LGRA.2.9.6.6] No whitespace inside braces.

(LGRA-2-9-6-7)=
[LGRA.2.9.6.7] `{{` / `}}` escape literal braces. In every string position, the
compiler must refuse any other unescaped `{` or `}` that forms no valid site
([LGRA.2.9.6.1]) with `DS_VALIDATE_INTERP_BAD_PATH`, and must not keep it as
literal text. A valid site in a string where interpolation is not eligible is
[LGRA.2.9.6.8]'s. A `json()` argument is outside this clause: its braces are
literal text ([LTSL.4.1]).

*ratified*  —  *see also:* [LGRA.2.9.6.1](#LGRA-2-9-6-1), [LGRA.2.9.6.8](#LGRA-2-9-6-8), [LTSL.4.1](#LTSL-4-1)

(LGRA-2-9-6-8)=
[LGRA.2.9.6.8] Interpolation is eligible in action arguments — `log`
strings, `call` kwarg values, `emit` and `publish` slot
values, and the `call … as` correlation string — and in the
key argument of `cached(…)`, wherever that call is admitted
([LSTO.4.3.1a] allows it in a `where`). Any other
position is a compile error: a valid `{path}` span ([LGRA.2.9.6.1])
in an ineligible string — an expression context such as a `let`
RHS, a `where` predicate, or any operand — is
`DS_VALIDATE_INTERP_INERT_POSITION`, never silent literal text (the
span would otherwise ship inert, e.g. an identical correlation for
every fact). `{{`/`}}` escaping ([LGRA.2.9.6.7]) applies in every
string position, so a literal brace stays expressible everywhere.
In the `as` position interpolation is *one* String-valued `<expr>`
form ([LRST.1.4]); `as` stays a general `<expr>`, so bare bindings
and non-String key types remain valid, and an interpolated
correlation's bindings are subject to [LRST.1.5] (non-nullable,
non-absent).

**A `cached(…)` key is a key, and carries the same non-null
rule.** Every segment of an interpolated key must be non-nullable and
non-absent; a segment reading a nullable slot or a `Json` sub-path is
`DS_VALIDATE_INTERP_NULLABLE_KEY`. The general interpolation rule —
a null renders as the empty string ([LGRA.2.9.6.2]) — would silently
collapse the keys of two entities into one cache entry, which is the
same reason [LRST.1.5.1] refuses it in a correlation.

*ratified*  —  *see also:* [LGRA.2.9.6.1](#LGRA-2-9-6-1), [LGRA.2.9.6.2](#LGRA-2-9-6-2), [LGRA.2.9.6.7](#LGRA-2-9-6-7), [LRST.1.4](#LRST-1-4), [LRST.1.5](#LRST-1-5), [LRST.1.5.1](#LRST-1-5-1), [LSTO.4.3.1a](#LSTO-4-3-1a)

(LGRA-2-9-6-9)=
[LGRA.2.9.6.9] An unescaped `{` in an interpolation-eligible string
([LGRA.2.9.6.8]) whose brace span has a body that is not a valid
`interp_body` ([LGRA.2.9.6.1]) — a body containing an operator or any
token outside the `NAME ( '.' NAME | '[' INT_LIT ']' )*` path
grammar, e.g. `{c.a + c.b}` — is a compile error
(`DS_VALIDATE_INTERP_BAD_PATH`). The compiler must not emit such a span
as literal text. A computed value in an interpolation is expressed by
binding it with a `let` and interpolating the bound name.

A **valid** `interp_body` is refused with `DS_VALIDATE_INTERP_UNSUPPORTED`, and
likewise never emitted as literal text, in two cases. In the first, its value
kind is one a compiler cannot render: the code is distinct from
`DS_VALIDATE_INTERP_BAD_PATH` for the reason [LCST.4.5.3] gives for its cast pair,
that the program is well-formed and the compiler is incomplete. In the second, it
is a whole `Json` value, which is not a leaf ([LGRA.2.9.6.11]): the program
breaks a rule, and the compiler must refuse it however complete it is.

*ratified*  —  *see also:* [LCST.4.5.3](#LCST-4-5-3), [LGRA.2.9.6.1](#LGRA-2-9-6-1), [LGRA.2.9.6.11](#LGRA-2-9-6-11), [LGRA.2.9.6.8](#LGRA-2-9-6-8)

(LGRA-2-10)=
### Operators and punctuation [LGRA.2.10]

(LGRA-2-10-1)=
[LGRA.2.10.1] Single-character tokens:
```
'+' '-' '*' '/' '%' '&' '|' '^' '~'
'<' '>' '='
'(' ')' '[' ']' '{' '}'
',' '.' ':' '@' '?'
```

(LGRA-2-10-2)=
[LGRA.2.10.2] Multi-character tokens:
```
'->' '**' '//' '<<' '>>' '::' '??' '..'
'==' '!=' '!~' '<=' '>='
'"""'
```

(LGRA-2-10-3)=
[LGRA.2.10.3] `@` is lexed but has no v1 production: it is reserved, so a
stray use is a clean parse error ([LLEX.8.2.1]). A lone `=` is accepted only by
the productions that name it, and is a parse error anywhere else
([LLEX.8.2.2]).

*ratified*  —  *see also:* [LLEX.8.2.1](#LLEX-8-2-1), [LLEX.8.2.2](#LLEX-8-2-2)

(LGRA-2-10-4)=
[LGRA.2.10.4] `::` (COLONCOLON) is the postfix conversion cast ([LGRA.9.6],
[LCST.4.1]); `?` (NULLABLE) marks a nullable type in a type position
([LGRA.2.5.3], [LNUL]); `.` (DOT) is both slot access and the separator between
a library path and a member it exports (`units.si.meter`, `lib.CONST`). Which it is
in a given name is decided by scope ([LGRA.22.9]), never by the grammar. `;` is not
a DS token ([LLEX.16.5]).

*ratified*  —  *see also:* [LCST.4.1](#LCST-4-1), [LGRA.2.5.3](#LGRA-2-5-3), [LGRA.22.9](#LGRA-22-9), [LGRA.9.6](#LGRA-9-6), [LLEX.16.5](#LLEX-16-5)

(LGRA-2-11)=
### Keyword-form operators [LGRA.2.11]

(LGRA-2-11-1)=
[LGRA.2.11.1] Expression keyword operators: `and`, `or`, `not`.

*ratified*

(LGRA-2-11-5)=
[LGRA.2.11.5] `not` (expression) is distinct from `no` (pattern
absence).

---

(LGRA-3)=
## File structure [LGRA.3]

(LGRA-3-1)=
[LGRA.3.1] File-level productions:

```
file ::= use_decl? (import_decl | top_level_decl)*

use_decl ::= 'use' NAME NEWLINE
          |  'use' NAME ':' NEWLINE INDENT setting_line+ DEDENT

setting_line ::= NAME ':' BOOL_LIT NEWLINE

top_level_decl ::= const_decl        # [LGRA.4]
                |  schema_decl       # [LGRA.5]
                |  rule_decl         # [LGRA.6]
                |  series_decl       # [LGRA.7]
                |  service_decl      # [LGRA.23]
                |  unit_decl         # [LUNI.4]
                |  opaque_decl       # [LOPQ.2.1]
                |  test_decl         # [LGRA.21.1]
                |  initial_block     # [LGRA.24.1]
```

`import_decl` is [LIMP.2.1.1]'s two import forms. Each `top_level_decl`
alternative is defined at the clause beside it.

**Residue the grammar does not carry ([STYL.2.15.4]):** every `import_decl`
precedes every `top_level_decl` — an import after one is a compile error, not a
parse error ([LIMP.2.3.2]); whether a file may or must have a `use_decl`
([LDIA.2.10.1]); that each `setting_line` names a registered capability
([LDIA.3.3.2]) at most once ([LDIA.3.3.6]); and how the block resolves
against the named dialect ([LDIA.3.3.1]).

(Comments and blank lines are stripped at the lexer level
per LGRA.2.4 / LGRA.2.2.3 and never reach the parser.)

*ratified*  —  *see also:* [LDIA.2.10.1](#LDIA-2-10-1), [LDIA.3.3.1](#LDIA-3-3-1), [LDIA.3.3.2](#LDIA-3-3-2), [LDIA.3.3.6](#LDIA-3-3-6), [LGRA.2.2.3](#LGRA-2-2-3), [LGRA.2.4](#LGRA-2-4), [LGRA.21.1](#LGRA-21-1), [LGRA.23](#LGRA-23), [LGRA.24.1](#LGRA-24-1), [LGRA.4](#LGRA-4), [LGRA.5](#LGRA-5), [LGRA.6](#LGRA-6), [LGRA.7](#LGRA-7), [LIMP.2.1.1](#LIMP-2-1-1), [LIMP.2.3.2](#LIMP-2-3-2), [LOPQ.2.1](#LOPQ-2-1), [LUNI.4](#LUNI-4)

(LGRA-3-2)=
[LGRA.3.2] If present, `use` must be the first non-comment,
non-blank statement. A `use` preceded by any other statement is a
compile error. Where an `import` precedes the `use`, [LIMP.2.3.3]
is the more specific rule and the compiler must raise its error
rather than this clause's. Whether a file has a `use` is what makes it a
program or a library ([LDIA.2.10.1]).

*ratified*  —  *see also:* [LDIA.2.10.1](#LDIA-2-10-1), [LIMP.2.3.3](#LIMP-2-3-3)

(LGRA-3-3)=
[LGRA.3.3] Top-level declarations appear in any order.

---

(LGRA-4)=
## Constant declarations [LGRA.4]

(LGRA-4-1)=
[LGRA.4.1] Constant productions:

```
const_decl ::= 'const' NAME (':' TYPE_SYM NULLABLE?)? '=' expression NEWLINE

literal ::= INT_LIT
         |  FLOAT_LIT
         |  STRING_LIT
         |  UNIT_LIT
         |  BOOL_LIT
BOOL_LIT ::= 'true' | 'false'
```

`=` introduces the RHS expression; the optional `:` is a **type annotation**
— the DS declaration convention (`=` where expressions are allowed, `:` for
types, as in `let`). `type` is a scalar builtin `String` / `Int` / `Float` /
`Bool` / `Json` or a **canonical unit symbol** ([LUNI.8.6]; alias / bare-dimension name rejected). A `const` annotation is
**checked against the folded value** — a mismatch is a compile error
(`const N: Int = "x"`) — and answers no refusal of a value ([LUNI.8.4]). An `Int` value under `: Float`
is no mismatch ([LEXP.8.8.1]). When omitted, the type is
inferred from the folded value. The grammar accepts the full `expression`; that the
expression must **fold to a compile-time constant** is a *validate* rule
([LGRA.13.3]; [LEXP.8.8]), not a grammar
restriction — the grammar-permissive / validate-strict split that `where` and
`let` also follow, which gives better diagnostics. A `const` reads only the
constants declared above it; a read of one declared there or later is
`DS_VALIDATE_UNKNOWN_CONST`.

**A colon does not introduce a value.** `const NAME: <literal>` is a compile
error (`DS_VALIDATE_CONST_COLON_LITERAL_RETIRED`), and the diagnostic names the
fix: `const NAME = <literal>`, or `const NAME: <type> = <literal>` to annotate
as well.

*ratified*  —  *see also:* [LEXP.8.8](#LEXP-8-8), [LEXP.8.8.1](#LEXP-8-8-1), [LGRA.13.3](#LGRA-13-3), [LUNI.8.4](#LUNI-8-4), [LUNI.8.6](#LUNI-8-6)

(LGRA-4-2)=
[LGRA.4.2] The RHS is a compile-time-constant expression
(`=`-introduced; [LGRA.13.3], [LEXP.8.8]) —
literals, earlier consts, imported consts, and the foldable operators over
them. No runtime construct, and no interpolation.

*see also:* [LEXP.8.8](#LEXP-8-8), [LGRA.13.3](#LGRA-13-3)

(LGRA-4-3)=
[LGRA.4.3] Redefinition in the same file is a compile error.

*ratified*

(LGRA-4-6)=
[LGRA.4.6] **A constant's bare name is bound once.** The compiler must reject,
with `DS_VALIDATE_IMPORT_NAME_COLLISION`, a program that brings two distinct
constants into bare scope under one NFC name:

- a local `const` whose name a selective import ([LIMP.4.2.4]) binds to a
  library's constant;
- two selective imports that bind one name to constants of different
  libraries.

One constant reached by two import paths is one constant, and no collision. A
qualified import binds no bare name ([LGRA.22.9]), so `ha.LIMIT` beside a local
`LIMIT` is none either. The author renames the local declaration, or renames
the import with `as` ([LIMP.2.1.7]).

Two other cases have their own homes: two local declarations of one name are
[LGRA.4.3]'s, and a local constant named for a member of a library that
carries builtins ([LIMP.3.3.4]), imported bare, is [LGRA.22.9]'s, refused with
`DS_VALIDATE_BINDING_SHADOWS_LIBRARY`.

*ratified*  —  *see also:* [LGRA.22.9](#LGRA-22-9), [LGRA.4.3](#LGRA-4-3), [LIMP.2.1.7](#LIMP-2-1-7), [LIMP.3.3.4](#LIMP-3-3-4), [LIMP.4.2.4](#LIMP-4-2-4)

(LGRA-4-4)=
[LGRA.4.4] A constant name is a `NAME` of any case; it lives in the **value
namespace** ([LGRA.22.7]) and does not collide with a type reference of the same
NFC name — the two are position-selected. A constant must not take a reserved
word ([LLEX.9.5]), which includes every builtin function name.

*ratified*  —  *see also:* [LGRA.22.7](#LGRA-22-7), [LLEX.9.5](#LLEX-9-5)

(LGRA-4-5)=
[LGRA.4.5] The optional `NULLABLE` on a `const` annotation (`const N: T?`) is
**accepted and inert**: the parser must accept the `?` marker and skip it, and
the annotation is checked as the bare `T` ([LGRA.4.1]).
*(Parallels the `let` annotation, [LGRA.6.7.3].)*

---

*ratified*  —  *see also:* [LGRA.4.1](#LGRA-4-1), [LGRA.6.7.3](#LGRA-6-7-3)

(LGRA-5)=
## Schema declarations [LGRA.5]

(LGRA-5-1)=
[LGRA.5.1] Schema productions:

```
schema_decl ::= 'schema' NAME schema_lifecycle? ':' NEWLINE
                INDENT
                    docstring?
                    field_decl+
                DEDENT

schema_lifecycle ::= 'scope' scope_value
scope_value      ::= 'explicit'
                  |  'activation'
                  |  'logical' 'ambient'?
                  |  'ttl' time_expr 'ambient'?

field_decl ::= NAME ':' field_type NULLABLE? field_capacity? slot_marker* field_tolerance? STRING_LIT? NEWLINE

field_capacity ::= 'capacity' INT_LIT                          # String slots only; see [LSTR.11]

field_type ::= TYPE_SYM
            # TYPE_SYM resolves in the type namespace (LGRA.22): a scalar builtin
            # (String/Int/Float/Bool/Bytes), Json, a unit symbol, a
            # dimension or scalar-group name (LUNI.7.1), or a schema reference. Nullable slot: field_type NULLABLE? (`state: String?`).

slot_marker ::= 'retained' | 'key' | 'mutable'     # retained per SCOPE / FORM_CATALOG; key/mutable per LFAC.1.7

field_tolerance ::= 'tolerance' (INT_LIT | FLOAT_LIT)          # unsigned, no unit; see [LGRA.5.9]

docstring ::= STRING_LIT NEWLINE
```

*ratified*  —  *see also:* [LFAC.1.7](#LFAC-1-7), [LGRA.22](#LGRA-22), [LGRA.5.9](#LGRA-5-9), [LSTR.11](#LSTR-11), [LUNI.7.1](#LUNI-7-1)

(LGRA-5-2)=
[LGRA.5.2] The grammar admits an optional `schema_lifecycle`
clause (`scope <value>`) **after** the type name. The four
scope values (`explicit`, `logical`, `ttl <time_expr>`,
`activation`), the `ambient` modifier `logical` and `ttl` admit, and their
semantics live at [LSCP.1.5] and [LSCP.1.7]. When the clause is
omitted, the schema defaults to `scope explicit` per
[LSCP.1.4]. The `ttl` form takes a mandatory duration, a
`time_expr` ([LGRA.2.8.2]), whose value becomes the schema's default
per-fact TTL per [LFAC.1.3.3] / [RDSC.5.3.3]. The compiler must refuse
a `ttl` whose duration is zero, written as `0_s` or as a constant whose
value is zero ([LGRA.2.8.11]), with `DS_VALIDATE_TTL_ZERO`: a fact
whose TTL is zero would be retracted before any rule could observe it.

*ratified*  —  *see also:* [LFAC.1.3.3](#LFAC-1-3-3), [LGRA.2.8.11](#LGRA-2-8-11), [LGRA.2.8.2](#LGRA-2-8-2), [LSCP.1.4](#LSCP-1-4), [LSCP.1.5](#LSCP-1-5), [LSCP.1.7](#LSCP-1-7), [RDSC.5.3.3](#RDSC-5-3-3)

(LGRA-5-6)=
[LGRA.5.6] A bare string literal as the first statement of a schema
body is the schema docstring.

*ratified*

(LGRA-5-7)=
[LGRA.5.7] Field declarations use `name: type` with optional slot
markers and an optional trailing per-field docstring.

*ratified*

(LGRA-5-7-1)=
[LGRA.5.7.1] **A field type must resolve.** The type in a
`name: type` field declaration must resolve in the type namespace
([LGRA.22.7]): a builtin type, a declared unit symbol, dimension or
scalar-group name ([LUNI.7.1]), or a declared schema. The compiler must
refuse one that resolves to none of these, naming the slot and the
unresolved type (`DS_VALIDATE_UNKNOWN_TYPE`). A service kwarg's type
resolves the same way ([LGRA.23.2]).

*see also:* [LGRA.22.7](#LGRA-22-7), [LGRA.23.2](#LGRA-23-2), [LUNI.7.1](#LUNI-7-1)

(LGRA-5-10)=
[LGRA.5.10] **Identity markers key on the base lifecycle; the
`ambient` modifier is transparent.** Every slot of a `logical`-based
schema — `scope logical` or `scope logical ambient` — must carry
exactly one of the `key` / `mutable` slot markers (require-all); the
compiler rejects a `logical`-based schema with an unmarked slot. `key`
/ `mutable` are barred on an `explicit` / `ttl` / `activation` base
(including `scope ttl <dur> ambient`); the compiler rejects either
marker there. The identity-key model these markers declare is
[LFAC.1.7]. A `ts` slot carries neither marker on any base: it is the
engine's ([LFAC.9.1]), and the compiler rejects a marker on it.

*ratified*  —  *see also:* [LFAC.1.7](#LFAC-1-7), [LFAC.9.1](#LFAC-9-1)

(LGRA-5-11)=
[LGRA.5.11] **A schema has at most 255 slots.** The
compiler **must** refuse a program in which any schema has more, with
`DS_VALIDATE_SCHEMA_TOO_MANY_SLOTS`. The limit counts every slot the schema
holds, and binds every schema the program declares or the compiler declares for
it, such as a capture fact's ([LTAC.3.5], [LCCO.5.2]). A slot's index in the
artefact is a byte, and 255 is reserved ([RDSC.4a.9.1]).

*ratified*  —  *see also:* [LCCO.5.2](#LCCO-5-2), [LTAC.3.5](#LTAC-3-5), [RDSC.4a.9.1](#RDSC-4a-9-1)

(LGRA-5-7a)=
### Schema-typed fields [LGRA.5.7a]

(LGRA-5-7a-1)=
[LGRA.5.7a.1] A field whose `TYPE_SYM` resolves to a schema (an existing schema
name rather than a builtin, `Json`, or a unit) declares a fact-reference slot.
The slot stores a pointer to a fact of the named schema.

(LGRA-5-7a-2)=
[LGRA.5.7a.2] A schema-typed slot is written once, by the kwarg of the `emit`
that asserts its fact or of the `publish` that sends it. Reading the
nested fact's slots via chained dotted access (`b.pan.capacity_l`) is
not supported in v1 — the slot value is a fact pointer, not an inlined
struct. Denormalize: copy needed slots onto the parent schema directly.

(LGRA-5-7a-3)=
[LGRA.5.7a.3] Chained dotted access on schema-typed slots produces
`DS_VALIDATE_BAD_PATH` with a denormalize hint.

(LGRA-5-8)=
### The `Json` field type [LGRA.5.8]

(LGRA-5-8-1)=
[LGRA.5.8.1] `Json` is the fallback `field_type` for opaque adapter
payloads. Accessed via standard dot/bracket operators;
leaves are runtime-typed. Adapter usage policy at
[LADP.5.5]; rule-side access and type-mismatch semantics at
[LEXP.7.12].

*ratified*  —  *checks:* `idris×2`  —  *see also:* [LADP.5.5](#LADP-5-5), [LEXP.7.12](#LEXP-7-12)

(LGRA-5-8-10)=
[LGRA.5.8.10] **A `Json` float is finite.** A `Json` value holds no `±Inf` and
no NaN. Wherever a `Json` value comes into being, at each place
[LGRA.5.8.6] lists and in a host call that builds one, a runtime **must** refuse
a non-finite float, and **must not** hold one:

- **JSON text.** A number literal written with a fraction or an exponent reads
  as the `Float` nearest its value, ties to even ([LDET.3.2.8]). Text holding
  such a literal whose value lies past the largest finite `Float`, so that it
  would round to an infinity, is malformed. A runtime **must** refuse such text
  wherever it parses JSON text, whoever supplies it, as it refuses any other
  malformed text: a host call that parses it returns `DS_ERR_PARSE` ([NERR.5])
  and changes nothing. A runtime **must not** read the literal as an infinity,
  and **must not** saturate it to the largest finite `Float`. A recording read
  on replay whose `Json` text holds such a literal is a malformed atom body, and
  the runtime refuses the stream.
- **A host call that builds a value.** A host call that would put a non-finite
  `Float` into a `Json` value returns `DS_ERR_JSON_NONFINITE` ([NERR.6]) and
  changes nothing. The status is the whole refusal: the runtime records no
  event for it, since the call that refuses may hold no engine.
- **A rule.** A `Json` value a rule builds refuses a non-finite `Float` already
  ([LCST.4.5.2], [LDET.3.2.7]).

A literal whose value rounds to zero is a zero, which a `Json` value holds as
`+0.0` ([LGRA.5.8.8]). So `1.7976931348623157e308` is a float a `Json` value
holds, `1e-400` is `+0.0`, and `1.8e308` and `-1e400` are malformed text.

Every `Json` value therefore has the text [LGRA.5.8.7a] gives it, so a value a
runtime holds can always be recorded, published to another tier and compared
by its text.

*ratified*  —  *checks:* `alloy`  —  *see also:* [LCST.4.5.2](#LCST-4-5-2), [LDET.3.2.7](#LDET-3-2-7), [LDET.3.2.8](#LDET-3-2-8), [LGRA.5.8.6](#LGRA-5-8-6), [LGRA.5.8.7a](#LGRA-5-8-7a), [LGRA.5.8.8](#LGRA-5-8-8), [NERR.5](#NERR-5), [NERR.6](#NERR-6)

(LGRA-5-8-9)=
[LGRA.5.8.9] **A `Json` integer is a 64-bit signed integer.** JSON text holding
an integer literal, one written with no fraction and no exponent, whose value
lies outside the range of a 64-bit signed integer is malformed. A runtime **must** refuse such text wherever it parses JSON
text, whoever supplies it, as it refuses any other malformed text: a host call
that parses it returns `DS_ERR_PARSE` ([NERR.5]) and changes nothing. A runtime
**must not** saturate the literal to the nearest representable integer, and
**must not** read it as a float.

So `9223372036854775807` and `-9223372036854775808` are integers a `Json` value
holds, and `9223372036854775808` and `-9223372036854775809` are malformed text.

*ratified*  —  *see also:* [NERR.5](#NERR-5)

(LGRA-5-8-7a)=
[LGRA.5.8.7a] **A runtime writes a `Json` value as one text.** Wherever a runtime
writes a `Json` value as JSON text, it **must** write exactly this text:

- no whitespace between tokens;
- an object's members in ascending order of their keys, compared as UTF-8 bytes;
- in a string or a key: `"` and `\` as `\"` and `\\`; U+0008, U+000C, U+000A,
  U+000D and U+0009 as `\b`, `\f`, `\n`, `\r` and `\t`; any other character
  below U+0020 as `\u00` followed by two lowercase hexadecimal digits; and every
  other character as its own UTF-8 bytes;
- an integer in decimal, with a `-` for a negative one;
- a `Float` in the canonical form of [LDET.3.2.7];
- `true`, `false` and `null` as themselves.

So no string byte is written as more than six bytes, and no number as more than
24.

*ratified*  —  *see also:* [LDET.3.2.7](#LDET-3-2-7)

(LGRA-5-8-3)=
[LGRA.5.8.3] Values of type `Json` enter from adapters. A rule
cannot write one as a literal: `json()` is not admitted ([LGRA.9.8.3]). A
fact does not convert to one ([LCST.4.5.2]).

*see also:* [LCST.4.5.2](#LCST-4-5-2), [LGRA.9.8.3](#LGRA-9-8-3)

(LGRA-5-8-6)=
[LGRA.5.8.6] **A `Json` value is bounded.** Every `Json` value a runtime holds
is within four limits, and every conforming runtime **must** enforce the same
ones:

| Limit | Maximum | Counted as |
|---|---|---|
| depth | 16 | a scalar, or an empty array or object, is one level; each enclosing array or object adds one |
| nodes | 256 | every scalar, array and object in the value, the root included |
| string bytes | 16,384 | the UTF-8 bytes of every string and every object key in the value, summed |
| text | 24,576 | the bytes of JSON text handed to a parse |

A realtime contract may lower any of the four for its tier, and may not raise
one ([RTCT.6.10]).

Depth, nodes and string bytes hold wherever a `Json` value comes into being: a
fact asserted with a `Json` slot, JSON text parsed, a value built in a rule, a
call response, the cache, and a recording read on replay. The text limit holds
for JSON text a runtime is handed to parse: by the host, as a call response, or
as a `String` a rule parses. It is checked before any of the text is read, so
text over it is refused unread. A runtime's own serialization of a value it
holds is not handed text, and the text limit does not apply to it.

The `Json` field of a `FactExternal` a runtime receives ([RFCS.23.2]) has a text
limit of its own: 106,496 bytes, the most [LGRA.5.8.7a] writes for a value within
the other three limits (six bytes for each string byte, and 32 for each node).
A value one runtime holds can therefore always reach another. The text is still
checked before any of it is read, and depth, nodes and string bytes hold for it
as for any other.

A value that would exceed a limit is refused, never truncated. A host call that
would admit such a value **must** return `DS_ERR_JSON_LIMIT` and change
nothing. The status is the whole refusal: the runtime records no event for it,
since the call that refuses may hold no engine. Inside a rule, the engine raises
a `ComputationError` of kind `NOT_REPRESENTABLE` ([LERR.1.4]) and abandons the
activation.

*ratified*  —  *see also:* [LERR.1.4](#LERR-1-4), [LGRA.5.8.7a](#LGRA-5-8-7a), [RFCS.23.2](#RFCS-23-2), [RTCT.6.10](#RTCT-6-10)

(LGRA-5-8-7)=
[LGRA.5.8.7] **A `Json` object names each key once.** JSON text in which one
object has two members with the same key is malformed. A runtime **must**
refuse such text wherever it parses JSON text, whoever supplies it, as it
refuses any other malformed text: a host call that parses it returns
`DS_ERR_PARSE` ([NERR.5]) and changes nothing. A runtime **must not** keep one
of the two members and drop the other.

Two keys are the same key when their strings are equal once escapes are
resolved, compared as UTF-8 bytes: `"a"` and `"\u0061"` are one key.

A recording read on replay whose `Json` value has an object with a repeated key
is a malformed atom body, and the runtime refuses the stream.

*ratified*  —  *checks:* `idris×5`  —  *see also:* [NERR.5](#NERR-5)

(LGRA-5-8-8)=
[LGRA.5.8.8] **A float zero in a `Json` value has no sign.** Every float zero a
`Json` value holds is `+0.0`. Wherever a `Json` value comes into being, at each
place [LGRA.5.8.6] lists, a runtime **must** make every float `-0.0` inside it
`+0.0`.

The zero stays a float: an integer `0` and a float `0.0` are still different
kinds ([LFAC.2.5.1]). Outside a `Json` value nothing changes: a `Float` slot
keeps `-0.0`, and so do its text forms ([LDET.3.2.7]).

So a leaf read of a JSON `-0.0` is `+0.0`, a `Json` value's canonical text
carries no `-0.0`, and a recording read on replay holds the value the live
run held.

*ratified*  —  *checks:* `idris×5`  —  *see also:* [LDET.3.2.7](#LDET-3-2-7), [LFAC.2.5.1](#LFAC-2-5-1), [LGRA.5.8.6](#LGRA-5-8-6)

(LGRA-5-8-4)=
[LGRA.5.8.4] No composite field types (`List`, `Map`, tuples).

(LGRA-5-8-5)=
[LGRA.5.8.5] **Only a `Json` slot chains.** Access that continues past a slot —
a bracket index or a further dotted segment — addresses a part of the slot's
value only where that slot is `Json`. Past a slot of any other builtin type the
compiler must refuse a bracket index, with `DS_VALIDATE_BAD_PATH`: the slot's
value has no parts to address. A dotted segment past such a slot is a member
read, which [LGRA.9.6.2] resolves and refuses. A schema-typed slot is
[LGRA.5.7a.3]'s case.

*ratified*  —  *checks:* `idris×2`  —  *see also:* [LGRA.5.7a.3](#LGRA-5-7a-3), [LGRA.9.6.2](#LGRA-9-6-2)

(LGRA-5-9)=
### Slot tolerance [LGRA.5.9]

(LGRA-5-9-3)=
[LGRA.5.9.3] Compile-time rules:

(LGRA-5-9-4)=
- [LGRA.5.9.4] Legal only on a `Float` slot, an `Int` slot, and a slot typed
  by a base or tier-1 unit symbol ([LUNI.4.3], [LUNI.7.3]). The compiler
  **must** refuse a `tolerance` on any other slot with
  `DS_VALIDATE_TOLERANCE_BAD_TYPE`: a tier-2 unit has no scale to convert a
  difference by ([LUNI.7.4]), and a slot typed by a dimension or scalar-group
  name names no unit to read the literal in ([LUNI.7.1]).

*ratified*  —  *see also:* [LUNI.4.3](#LUNI-4-3), [LUNI.7.1](#LUNI-7-1), [LUNI.7.3](#LUNI-7-3), [LUNI.7.4](#LUNI-7-4)

(LGRA-5-9-5)=
- [LGRA.5.9.5] Legal on `logical` schemas only. `tolerance` on a
  `ttl`-scoped schema is a **compile error** (`DS_VALIDATE_TOLERANCE_TTL_SCHEMA`):
  `ttl` / event facts carry no identity and do not dedup ([LFAC.1.7.6]), so
  there is no within-tolerance reassertion to suppress. On a schema of any other
  non-`logical` lifecycle it is `DS_VALIDATE_TOLERANCE_NON_LOGICAL`. See [LFAC.2.5.1]
  and [LFAC.2.6.4].

*ratified*  —  *see also:* [LFAC.1.7.6](#LFAC-1-7-6), [LFAC.2.5.1](#LFAC-2-5-1), [LFAC.2.6.4](#LFAC-2-6-4)

(LGRA-5-9-6)=
- [LGRA.5.9.6] Literal type must match the slot type.

*ratified*

(LGRA-5-9-7)=
- [LGRA.5.9.7] The literal is non-negative and finite. `INT_LIT` and
  `FLOAT_LIT` carry no sign ([LLEX.11.1], [LLEX.11.2]), [LGRA.5.1]'s
  `field_tolerance` admits no unary minus and no `inf`, and the lexer refuses a
  float literal past the largest finite `Float` ([LLEX.11.2.4]).

*ratified*  —  *see also:* [LGRA.5.1](#LGRA-5-1), [LLEX.11.1](#LLEX-11-1), [LLEX.11.2](#LLEX-11-2), [LLEX.11.2.4](#LLEX-11-2-4)

(LGRA-5-9-8)=
- [LGRA.5.9.8] `tolerance 0` is legal (explicit exact-equality).

(LGRA-5-9-9)=
[LGRA.5.9.9] Without `tolerance`, numeric slots use exact-equality.

*ratified*

(LGRA-5-9-10)=
[LGRA.5.9.10] **`tolerance` is admissible only on a `mutable` slot.**
`tolerance` on a `key` slot ([LGRA.5.10], [LFAC.1.7]) is a **compile error**: a
`logical` fact's identity is exact, and a tolerance on an identity slot would
make identity fuzzy and non-transitive (`1.00 ≈ 1.05 ≈ 1.10` yet
`1.00 ≉ 1.10`). `tolerance` is a meaningful-change threshold for *payload*
([LFAC.2.5.1]); identity is exact. (This key-slot rule does not arise on a
`ttl` schema — `tolerance` is rejected there outright per [LGRA.5.9.5].)

---

*ratified*  —  *see also:* [LFAC.1.7](#LFAC-1-7), [LFAC.2.5.1](#LFAC-2-5-1), [LGRA.5.10](#LGRA-5-10), [LGRA.5.9.5](#LGRA-5-9-5)

(LGRA-6)=
## Rule declarations [LGRA.6]

(LGRA-6-1)=
[LGRA.6.1] Rule productions:

```
rule_decl ::= 'rule' NAME rule_modifier* ':' NEWLINE
              INDENT
                  docstring?
                  pattern+
              DEDENT
              '->' NEWLINE
              INDENT
                  let_decl*
                  action_body
              DEDENT

action_body   ::= action+ after_clause*
               |  after_clause+

after_clause  ::= 'after' UNIT_LIT ('as' expression)? ':' NEWLINE
                  INDENT
                      action_body
                  DEDENT

rule_modifier ::= rate_mod
               |  rate_key


rate_mod      ::= 'cooldown' time_expr

rate_key      ::= 'by' ':' ( key_path (',' key_path)* | 'none' )

key_path      ::= NAME '.' NAME

let_decl      ::= 'let' let_binding
                  (INDENT let_binding+ DEDENT)?

let_binding   ::= NAME (':' TYPE_SYM NULLABLE?)? '=' expression NEWLINE
               |  '(' NAME (',' NAME)* ')' '=' expression NEWLINE
```

The optional indented block is a **hanging indent**: `let` is written once and
the rest of the group hangs under it. The per-line form is the same production
with the block absent, so the two coexist and a rule body may use either or both
([LGRA.6.7.4]).

`let_binding`'s second alternative is **kept parseable, not legal.** [LREG.4.1]
requires a capture-bearing match to bind in `where`, never in `let` — a
`let`-position capture is a compile refusal pointing the author at the `where`
form, rather than a generic parse error. The alternatives are
distinguished by their first token — `NAME` against `(` — so the choice needs
no lookahead.

`after_clause` is a timed action ([LTAC.2]). Its duration is a bare
`UNIT_LIT`, not a `time_expr` ([LGRA.2.8.1]): it takes no `NAME` and no sign, so
a named, computed or negative duration does not parse ([LTAC.2.2]). Its body is
an `action_body`, so it nests ([LTAC.6.2.2]) and takes no `let_decl`. The `as`
expression is the clause's correlation key ([LRST.1.1]).

*ratified*  —  *checks:* `idris×4`  —  *see also:* [LGRA.2.8.1](#LGRA-2-8-1), [LGRA.6.7.4](#LGRA-6-7-4), [LREG.4.1](#LREG-4-1), [LRST.1.1](#LRST-1-1), [LTAC.2](#LTAC-2), [LTAC.2.2](#LTAC-2-2), [LTAC.6.2.2](#LTAC-6-2-2)

(LGRA-6-2)=
[LGRA.6.2] `->` appears at column 0 as the LHS/RHS separator. The
LHS block (column 4) DEDENTs to column 0, then `->`
NEWLINE, then INDENT for the RHS block.

(LGRA-6-5)=
[LGRA.6.5] A bare string literal as the first line of the rule body, after
the rule header and its modifiers and before the first pattern, is the rule
docstring. Either string form carries it: a one-line string or a triple-quoted
one.

*ratified*

(LGRA-6-6)=
### Rule-header rate modifiers [LGRA.6.6]

(LGRA-6-6-1)=
[LGRA.6.6.1] Zero or more `rate_mod`s appear between the rule name
and the `:`, per [LGRA.6.1]'s `rule_modifier*` list.

*ratified*  —  *see also:* [LGRA.6.1](#LGRA-6-1)

(LGRA-6-6-2)=
[LGRA.6.6.2] The one legal `rate_mod` is `cooldown`; its semantics are at
[LCDB.3.2] and its keying at [LCDB.3.3].

*ratified*  —  *see also:* [LCDB.3.2](#LCDB-3-2), [LCDB.3.3](#LCDB-3-3)

(LGRA-6-6-7)=
[LGRA.6.6.7] The compiler must reject a duplicate `cooldown` on the same
rule with `DS_PARSE_DUP_RATE_MOD` ([LCDB.7.8]), and a negative duration with
`DS_VALIDATE_RATE_NEGATIVE_DURATION`. `0_s` is legal
but degenerate (no-op at runtime — the rate-allow gate
emits but always permits the fire).

*ratified*  —  *see also:* [LCDB.7.8](#LCDB-7-8)

(LGRA-6-7)=
### Let bindings [LGRA.6.7]

(LGRA-6-7-1)=
[LGRA.6.7.1] `let` declarations appear after `->`, before actions.

*ratified*

(LGRA-6-7-2)=
[LGRA.6.7.2] Grammatical form: `let NAME (':' TYPE_SYM NULLABLE?)? '=' expression`. The
optional `:` annotation is a unit / `Float` / `Int` **assertion** per
[LUNI.8.6] — metadata, not verified against the
RHS (unlike a `const`'s *checked* annotation, [LGRA.4.1]). Scope,
ordering, visibility, and constraints at [LLET].

*ratified*  —  *see also:* [LGRA.4.1](#LGRA-4-1), [LUNI.8.6](#LUNI-8-6)

(LGRA-6-7-3)=
[LGRA.6.7.3] The optional `NULLABLE` on a `let` annotation (`let x: T?`) is
**accepted and inert**: the parser must accept the `?` marker and skip it. The
unit / `Float` / `Int` assertion is metadata-only ([LUNI.8.6]).
*(Parallels the `const` annotation, [LGRA.4.5].)*

---

*see also:* [LGRA.4.5](#LGRA-4-5), [LUNI.8.6](#LUNI-8-6)

(LGRA-6-7-4)=
[LGRA.6.7.4] **The hanging-indent form.** `let` may be written once with its
remaining bindings indented under it, one per line ([LGRA.6.1]).

**It is layout and nothing else.** The bindings of a group are the same ordered
sequence the per-line form produces — same order, same scope, same visibility,
same prohibition on forward references ([LLET.10.1], [LLET.10.6]). A group and
the equivalent per-line run **must** compile to the same artefact.

**Groups and single `let` lines may be interleaved freely** in one rule body, in
any order. A grammar restriction there would buy a reader nothing and cost a
rule nobody can remember; which form to use is style.

**`let_binding`'s tuple-form alternative is kept parseable but is not legal in
any position, hanging or per-line** ([LGRA.6.1]). A capture-bearing match binds
in `where`, never in `let` ([LREG.4.1]); a hanging group containing one is the
same compile refusal a per-line one is, not a layout question.

```{admonition} There is no ambiguity to resolve, and no new layout machinery
:class: note
**A DS expression does not span lines.** Every binding terminates in `NEWLINE`
and the grammar has no continuation or line-joining mechanism, so an indented
line after `let foo = expr` can only be another binding — there is no wrapped
expression for it to be confused with and no lookahead needed to tell them
apart.

This is a hanging indent, **not** an align-to-the-column-of-the-first-token
rule. The existing INDENT / DEDENT layout emits on any deeper indentation, which
is all this needs.

**The shape is already in the grammar.** An `emit`, `publish` or `call`
action ([LGRA.10.1]) is a statement whose first content sits on its head line,
followed by an optional indented block of more of the same ([LGRA.10.8]). This
applies that shape to `let` rather than inventing one.
```

*see also:* [LGRA.10.1](#LGRA-10-1), [LGRA.10.8](#LGRA-10-8), [LGRA.6.1](#LGRA-6-1), [LLET.10.1](#LLET-10-1), [LLET.10.6](#LLET-10-6), [LREG.4.1](#LREG-4-1)

(LGRA-6-8)=
[LGRA.6.8] **A rule name is unique in its compilation unit.** The compilation
unit is the file being compiled and every library in its import DAG
([LIMP.6.1]). Two rules in one compilation unit must not share a name, compared
as identifiers are compared ([LNAM.2.1.1]), whether both are in one file, one is
in the file and one in a library, or they are in two libraries. The compiler must
refuse such a program with `DS_VALIDATE_DUPLICATE_RULE`, naming both
declarations.

Every library rule compiles into the importer's artefact whatever the import
took ([LIMP.7.5]), and the artefact attaches a rule's metadata to its terminal
by name ([RDSC.8.3]), so each name must pick out exactly one rule.

*ratified*  —  *see also:* [LIMP.6.1](#LIMP-6-1), [LIMP.7.5](#LIMP-7-5), [LNAM.2.1.1](#LNAM-2-1-1), [RDSC.8.3](#RDSC-8-3)

(LGRA-7)=
## Series declarations [LGRA.7]

(LGRA-7-1)=
[LGRA.7.1] Series productions:

```
series_decl       ::= 'series' slot_ref block_opts? ':' NEWLINE
                      INDENT docstring? series_line+ DEDENT

slot_ref          ::= (NAME '.')? NAME

block_opts        ::= '(' block_kwarg (',' block_kwarg)* ')'
block_kwarg       ::= 'by' ':' (NAME | 'none')
                    | 'capacity' ':' INT_LIT               ;; LSER.13.14
                    | 'nulls' ':' ('skip' | 'hold' | 'zero') ;; LNUL.8.6

series_line       ::= agg_list time_model accuracy? gap_policy? ('as' NAME)? NEWLINE
agg_list          ::= agg_name (',' agg_name)*
agg_name          ::= NAME                           ;; per LSER.16
gap_policy        ::= 'gap' ('hold' | 'zero' | 'skip') ;; integral only — LSER.13.5.1
time_model        ::= 'all_time'
                    | 'sliding'  duration
                    | 'tumbling' duration
                    | 'sample'   INT_LIT
accuracy          ::= 'exact'                    ;; all five parse and are
                    | 'tolerance'  FLOAT_LIT     ;; then REJECTED — see below
                    | 'confidence' FLOAT_LIT
                    | 'delta'      FLOAT_LIT
                    | 'bound' 'deterministic'
```

The `accuracy` alternatives **parse**, and every one of them is then rejected
by the validator ([LSER.15.1]). They are in the grammar so
the diagnostic can name the phrase the author wrote.

*ratified*  —  *see also:* [LNUL.8.6](#LNUL-8-6), [LSER.13.14](#LSER-13-14), [LSER.13.5.1](#LSER-13-5-1), [LSER.15.1](#LSER-15-1), [LSER.16](#LSER-16)

(LGRA-7-2)=
[LGRA.7.2] One scaffolding keyword (`series`) introduces every
declaration. The body is one or more **observation lines**;
each line names what to compute (aggregations) and over what
window (time model). Every v1 aggregation is exact ([LSER.15.1]). Storage backings are
not author-visible — the compiler picks them per
[LSER.13.3] from the catalogue at
[LSER.18.1].

*see also:* [LSER.13.3](#LSER-13-3), [LSER.15.1](#LSER-15-1), [LSER.18.1](#LSER-18-1)

(LGRA-7-3)=
[LGRA.7.3] `slot_ref` accepts the qualified form
`<NAME>.<NAME>` and the unqualified form `<NAME>`.
Schema-scoping resolution at [LSER.7.7].

*ratified*  —  *see also:* [LSER.7.7](#LSER-7-7)

(LGRA-7-6)=
[LGRA.7.6] The grammar accepts any aggregation `NAME` in
`agg_name` position; per-type and per-time-model
applicability is a compile-time check per
[LSER.16] and [LSER.17].

*see also:* [LSER.16](#LSER-16), [LSER.17](#LSER-17)

(LGRA-7-6a)=
[LGRA.7.6a] The optional `gap_policy` phrase (`gap hold|zero|skip`)
follows `time_model`. Its words `gap`, `hold`, `zero` and `skip` are
reserved ([LLEX.9.5]). The grammar accepts the phrase on any series
line, but it is valid only on a time-integrating aggregation (`integral`)
and defaults to `gap hold` when omitted; applicability and default are a
compile-time contract per [LSER.13.5.1].

*see also:* [LLEX.9.5](#LLEX-9-5), [LSER.13.5.1](#LSER-13-5-1)

(LGRA-7-9)=
[LGRA.7.9] The block production requires `series_line+`; a body
with only a docstring is a compile error.

(LGRA-7-10)=
### What's grammar vs what's contract [LGRA.7.10]

(LGRA-7-10-1)=
[LGRA.7.10.1] The grammar accepts any aggregation × time-model
pair that parses; per-cell satisfiability is a
compile-time check per [LSER.13.3], [LSER.15.2] and
[LSER.17]. Empty cells (e.g. `mean` on a `String` slot,
`p95 all_time`) are rejected with closest-form hints.

*see also:* [LSER.13.3](#LSER-13-3), [LSER.15.2](#LSER-15-2), [LSER.17](#LSER-17)

(LGRA-7-11)=
### Companion-slot desugaring [LGRA.7.11]

(LGRA-7-11-1)=
[LGRA.7.11.1] At the parser level, `t.mean`, `t.recent.mean`,
`t.duration_s.recent.p95` and similar are parsed uniformly
as chains of postfix dotted accesses
(`NAME ('.' NAME)*`). The grammar does not distinguish
companion-slot access from ordinary slot reads at parse time.

(LGRA-7-11-2)=
[LGRA.7.11.2] At compile time the compiler identifies the
trailing component as an aggregation name (from the known
vocabulary per [LSER.16]) and treats
the preceding chain as a series cursor per
[LSER.6]. The cursor is resolved to a
(slot, observation, backing) triple; the aggregation is
applied to the resolved backing.

*see also:* [LSER.16](#LSER-16), [LSER.6](#LSER-6)

(LGRA-7-11-3)=
[LGRA.7.11.3] If the trailing component is not an aggregation
name, the chain is resolved as an ordinary slot read or
`Json`-path traversal; no cursor resolution is attempted.
The two interpretations do not overlap — aggregation names
are reserved and cannot be schema slot names on series-
carrying bindings per [LSER.6.12.1].

---

*see also:* [LSER.6.12.1](#LSER-6-12-1)

(LGRA-8)=
## Patterns [LGRA.8]

(LGRA-8-1)=
[LGRA.8.1] Pattern productions:

```
pattern ::= 'no' negated_pattern NEWLINE
         |  pattern_body NEWLINE
         |  sequence_pattern NEWLINE
         |  then_step+ NEWLINE                              # line-leading `then`

negated_pattern ::= pattern_body
                 |  '(' pattern_body ')'

pattern_body ::= type_ref binding? within_clause? where_clause?

sequence_pattern ::= 'latest'? pattern_body then_step+

then_step ::= 'then' 'latest'? type_ref binding? 'within' time_expr where_clause?

type_ref ::= NAME ('.' NAME)*                                # a schema, bare or library-qualified ([LGRA.22.4])

binding ::= NAME

within_clause ::= 'within' time_expr

where_clause ::= 'where' expression
              |  'where' capture_binding ('and' expression)?

capture_binding ::= '(' NAME (',' NAME)* ')' '=' expression
```

**`capture_binding` is deliberately permissive about its right-hand side**
([LGRA.10.3.2]'s phase split). The production accepts any `expression`; the
contract restricts it to a capture-bearing `~` and refuses everything else with
a diagnostic ([LREG.4.6]). A grammar that closed the surface here would fail
earlier and differently, and would have no code to raise.

**One token of lookahead separates it from a parenthesised expression.** After
`'(' NAME ')'` the parser must choose between reducing to `primary`
([LGRA.9.7.1]) and reducing to `capture_binding`; `=` selects the second and
anything else the first, and `=` and `==` are distinct tokens ([LLEX.9]). The
multi-name form is not ambiguous at all: `(a, b)` is not an expression.


*ratified*  —  *checks:* `idris×2`  —  *see also:* [LGRA.10.3.2](#LGRA-10-3-2), [LGRA.22.4](#LGRA-22-4), [LGRA.9.7.1](#LGRA-9-7-1), [LLEX.9](#LLEX-9), [LREG.4.6](#LREG-4-6)

(LGRA-8-2)=
[LGRA.8.2] `type_ref` and `binding` are both `NAME`, separated by grammatical
**position** ([LGRA.22]): `type_ref` heads the pattern body and resolves as a
schema reference — a bare local/imported `NAME`, or a library-qualified
`lib.Schema` ([LGRA.22.4]); `binding` is the optional trailing `NAME` ([LGRA.8.6]).
`within_clause` / `where_clause` are optional. An adapter entity is matched by
constraining its identity slot in the `where` clause (`where entity_id ~ /…/`),
not by a dotted entity-suffix ([LADP.2]).

*see also:* [LADP.2](#LADP-2), [LGRA.22](#LGRA-22), [LGRA.22.4](#LGRA-22-4), [LGRA.8.6](#LGRA-8-6)

(LGRA-8-6)=
[LGRA.8.6] **A pattern binding, if written, must be referenced — and the
binding is optional.** A reference in the pattern's own `where` clause, in a
later pattern's `where` clause, in a `let` right-hand side, or in an action
counts. A binding that is never referenced is a **compile error**.

**A negated pattern's binding is in scope in its own `where` alone.** It names
a fact whose absence the pattern tests, so no other part of the rule has a fact
to read through it. The compiler must refuse a reference to it in a later
pattern's `where`, in a `let` right-hand side or in an action with
`DS_VALIDATE_NEGATED_BINDING_OUT_OF_SCOPE`. The name is bound, so this is not
[LGRA.13.8]'s unknown binding; it is a bound name read where it has no fact.

An author who does not need the name omits it ([LGRA.8.1]): `Graph` and `no
Graph` are well-formed patterns, and say what the existence-trigger idiom means.

**A reference in the pattern's own `where` counts, and that is load-bearing.**
`Graph r where r.status == "ok"` cannot drop `r` — the filter is unexpressible
without the name. A rule that did not count same-pattern references would demand
the impossible.

⚠ **The inverse is NOT true: a `where` does not require a binding.** A
`where` is pattern-attached for Rete early-pruning but may legitimately
reference only constants or an **earlier** pattern's binding, and the pattern
it is attached to then needs no binding of its own. The rule is about an
unreferenced *binding*, never about an unaccompanied `where`.

**No ambiguity arises from making the binding optional.** `where`, `no` and
`within` are reserved words ([LLEX.9.5]), so `Graph where …` and
`TempReading within 30_s` cannot be read as a binding named `where` or `within`.

```{admonition} What this does and does not affect
:class: note
**`then` sequences.** Each member may omit its binding independently; the `ts`
ordering `then` enforces is structural, and the trailing `where` follows the
rule above.

**`latest`.** No interaction: it pins **the first pattern** to its most recent
match ([LTHE.2.5.3], [LTHE.2.5.4]), positionally rather than by name.

**Negation.** A negated pattern's binding is referenced when its own `where`
reads it, which is the one place it is in scope (above).
```

*ratified*  —  *see also:* [LGRA.13.8](#LGRA-13-8), [LGRA.8.1](#LGRA-8-1), [LLEX.9.5](#LLEX-9-5), [LTHE.2.5.3](#LTHE-2-5-3), [LTHE.2.5.4](#LTHE-2-5-4)

(LGRA-8-7)=
[LGRA.8.7] **A rule has at most 255 patterns**,
negated patterns included. The compiler **must** refuse a program in which any
rule has more, with `DS_VALIDATE_RULE_TOO_MANY_PATTERNS`. The limit binds every
rule the compiler builds as well, such as an `after` body's follow-up rule
([LTAC.3.5]). A pattern's index in the artefact is a byte, and 255 is reserved
([RDSC.4a.9.1]).

*ratified*  —  *see also:* [LTAC.3.5](#LTAC-3-5), [RDSC.4a.9.1](#RDSC-4a-9-1)

(LGRA-8-3)=
### Disambiguation [LGRA.8.3]

(LGRA-8-3-1)=
- [LGRA.8.3.1] Disambiguation is **positional** — by grammatical position, not
  case ([LGRA.22]). In `type_ref binding`, the head — a bare `NAME` or a
  `lib.Schema` qualified reference — reduces to `type_ref`, and a
  trailing `NAME` reduces to `binding`. A pattern head is a type position, so
  every `.` in it separates a library path from the schema ([LGRA.22.4]).

  **A lone `NAME` clause is a pattern with no binding** ([LGRA.8.6]). The head
  stays separable on one token of lookahead: after the `NAME` that reduces to
  `type_ref`, a following `NAME` is the binding, a `.` continues the head, and
  `NEWLINE` / `within` / `where` ends the clause unbound. [LGRA.22.3]'s gate,
  table regeneration with zero conflicts, is what establishes it.

*see also:* [LGRA.22](#LGRA-22), [LGRA.22.3](#LGRA-22-3), [LGRA.22.4](#LGRA-22-4), [LGRA.8.6](#LGRA-8-6)

(LGRA-8-3-2)=
- [LGRA.8.3.2] `no` as pattern prefix is distinct from `not` (the
  expression operator). `no` appears only at pattern
  position; `not` appears only in expression position.

*ratified*

(LGRA-8-3-3)=
- [LGRA.8.3.3] `within` appears only at pattern level, after the
  binding. It never appears inside a `where` clause.

(LGRA-8-3-4)=
- [LGRA.8.3.4] A pattern's `where` clause is a full expression, so
  nested parens, arithmetic, function calls, and all
  operators are valid there. Temporal predicates inside
  `where` express via slot access (`m.dwell < 5_min`), not
  via `within`.

(LGRA-8-3-5)=
- [LGRA.8.3.5] **Multi-line `where` predicates** use parentheses as the
  continuation mechanism ([LLEX.7.5.5]); inside the brackets any
  indentation is legal. Single-line `where expr` and inline `where (expr)`,
  with `(` and the expression on one line, are valid. The author should
  write the block form when the predicate would exceed 80 characters on one
  line: `where (` ends the pattern's line, the predicate's terms follow on
  lines of their own, and `)` stands alone on the last line.

*see also:* [LLEX.7.5.5](#LLEX-7-5-5)

(LGRA-8-4)=
### Negation with compound patterns [LGRA.8.4]

(LGRA-8-4-1)=
[LGRA.8.4.1] `no pattern_body` negates the existence of a fact matching
`pattern_body`. The parenthesised form groups the whole body under the
negation ([LGRA.8.1]'s `negated_pattern`).

*ratified*  —  *see also:* [LGRA.8.1](#LGRA-8-1)

(LGRA-8-4-2)=
[LGRA.8.4.2] Parens are optional around simple pattern bodies; required
when the negation ambiguity demands it.

*ratified*

(LGRA-8-5)=
### Pattern sequencing — `then ... within` [LGRA.8.5]

(LGRA-8-5-1)=
[LGRA.8.5.1] A `sequence_pattern` matches facts in temporal order.

(LGRA-8-5-2)=
[LGRA.8.5.2] Grammar shape: [LGRA.8.1]'s `sequence_pattern`. A `where_clause`
belongs to its step ([LGRA.8.5.10]). Semantics at [LTHE].

*ratified*  —  *see also:* [LGRA.8.1](#LGRA-8-1), [LGRA.8.5.10](#LGRA-8-5-10)

(LGRA-8-5-7)=
[LGRA.8.5.7] `within T` is mandatory on every `then`; see [LTHE.5.3].

*ratified*  —  *see also:* [LTHE.5.3](#LTHE-5-3)

(LGRA-8-5-8)=
[LGRA.8.5.8] Chains left-to-right; each `within` scopes the immediately
preceding `then`.

(LGRA-8-5-10)=
[LGRA.8.5.10] A `where_clause` after a step's `within` belongs to that step,
in the one-line layout and the line-leading one alike, and sees every binding
before it as well as the step's own. A sequence has no sequence-wide `where`:
on a one-line sequence, a trailing `where` is the last step's. Nothing is lost,
because the last step's `where` already sees every binding of the sequence.

*ratified*

(LGRA-8-5-14)=
[LGRA.8.5.14] Optional `latest` prefix pins the first pattern to its
most-recent match.

(LGRA-8-5-16)=
[LGRA.8.5.16] `latest` modifies only the first pattern; see [LTHE.5.4].

---

*see also:* [LTHE.5.4](#LTHE-5-4)

(LGRA-9)=
## Expressions [LGRA.9]

(LGRA-9-1)=
[LGRA.9.1] The expression grammar is used in `where` clauses, action
argument values, interpolation, and const literals (the
last restricted to literal-only).

(LGRA-9-2)=
### Operator precedence [LGRA.9.2]

(LGRA-9-2-1)=
[LGRA.9.2.1] From lowest to highest (below binds looser):

```
 1. or
 2. and
 3. not                                             (unary prefix)
 4. == != < <= > >=                                 (chainable, [LGRA.9.3.2])
    is, is not                                      (does not chain, [LGRA.9.3.1])
 5. ??                                              (left-assoc)
 6. ~ !~                                            (at most one; a regex literal on the right)
 7. in contains overlaps                            (at most one)
 8. ..                                              (at most one)
 9. |                                               (bitwise or)
10. ^                                               (bitwise xor)
11. &                                               (bitwise and)
12. << >>                                           (bitwise shift)
13. + -                                             (binary; left-assoc)
14. * / // %                                        (left-assoc)
15. ** (right-assoc)
16. - + ~                                           (unary prefix)
17. . [ ] ( ) ::                                    (member access, index, call, conversion cast)
18. <primary>                                       (literals, identifiers, parens)
```

The productions ([LGRA.9.3.1], [LGRA.9.4.1], [LGRA.9.5.1], [LGRA.9.6.1],
[LGRA.9.7.1]) are the notation; this table orders their levels in one place,
and where the two disagree the productions win ([STYL.2.15.5]).

*ratified*  —  *see also:* [LGRA.9.3.1](#LGRA-9-3-1), [LGRA.9.3.2](#LGRA-9-3-2), [LGRA.9.4.1](#LGRA-9-4-1), [LGRA.9.5.1](#LGRA-9-5-1), [LGRA.9.6.1](#LGRA-9-6-1), [LGRA.9.7.1](#LGRA-9-7-1)

(LGRA-9-2-2)=
[LGRA.9.2.2] The logical, comparison, bitwise and arithmetic levels are
Python 3's, in Python 3's order, with `//` among the multiplicative operators.
The rest are DS's own: `??`, `~` / `!~` and `..` have no Python counterpart,
and `in` binds tighter than the comparison operators, at level 7 of
[LGRA.9.2.1], where Python puts it among them. So `a in b == c` is
`(a in b) == c`.

*see also:* [LGRA.9.2.1](#LGRA-9-2-1)

(LGRA-9-3)=
### Comparison chains [LGRA.9.3]

(LGRA-9-3-1)=
[LGRA.9.3.1] Expression / comparison productions:

```
expression ::= or_expr

or_expr  ::= and_expr ('or' and_expr)*
and_expr ::= not_expr ('and' not_expr)*
not_expr ::= 'not' not_expr
          |  comparison

comparison    ::= coalesce_expr (comparison_op coalesce_expr)*
               |  coalesce_expr 'is' 'not'? is_subject          # LNUL.4.9
comparison_op ::= '==' | '!=' | '<' | '<=' | '>' | '>='

coalesce_expr ::= match_expr ('??' match_expr)*                 # LNUL.5.3
match_expr    ::= interval_rel (('~' | '!~') REGEX_LIT)?        # LREG.2.1
interval_rel  ::= interval (('in' | 'contains' | 'overlaps') interval)?
                                                                # LINT.4.1
interval      ::= bitwise_or ('..' bitwise_or)?                 # LINT.2.1
```

**Each level below `comparison` realises an operator specified elsewhere**, and
this production fixes only their precedence and associativity: `??` is
[LNUL.5.3], `~` / `!~` are [LREG.2.1], `in` / `contains` / `overlaps` are
[LINT.4.1], `..` is [LINT.2.1], and the `is` alternative is [LNUL.4.9].

**Residue the grammar cannot carry ([STYL.2.15.4]):**

- **`is not` is one operator**, not `not` applied to `is` ([LNUL.4.9]). The
  production spells it `'is' 'not'?` for that reason: the `not` here is part
  of the operator and is not the `not_expr` operator one level up.
- **The `is` subject is a closed vocabulary, not an expression position**
  ([LGRA.9.3.3]). This is the only operator in the chain whose right operand
  is not a nonterminal of the expression grammar, and it is why `is` is an
  alternative of `comparison` rather than a `comparison_op`.
- **`??` chains; the three below it do not.** `coalesce_expr` repeats, so
  `a ?? b ?? c` is legal and left-associative. `match_expr`, `interval_rel`
  and `interval` each admit **at most one** operator, so `a ~ /x/ ~ /y/`,
  `a in b in c` and `a .. b .. c` are parse errors rather than nested
  applications.
- **`is` does not chain either**, and for a different reason: its right
  operand is a subject rather than an expression, so there is nothing for a
  second `is` to apply to. [LGRA.9.3.2]'s pairwise-expansion rule governs
  `comparison_op` only and does not reach the `is` alternative.
- **A regex operand must be a literal** ([LREG.5.5]) — the production admits
  only `REGEX_LIT` on the right of `~` / `!~`, never an expression, so there
  is no interpolated or computed pattern to reject at a later phase.

*ratified*  —  *see also:* [LGRA.9.3.2](#LGRA-9-3-2), [LGRA.9.3.3](#LGRA-9-3-3), [LINT.2.1](#LINT-2-1), [LINT.4.1](#LINT-4-1), [LNUL.4.9](#LNUL-4-9), [LNUL.5.3](#LNUL-5-3), [LREG.2.1](#LREG-2-1), [LREG.5.5](#LREG-5-5)

(LGRA-9-3-2)=
[LGRA.9.3.2] Comparisons chain: `a < b < c` is `(a < b) and (b < c)`.
Any number of terms allowed. All comparison operators may
be mixed in one chain.

*ratified*

(LGRA-9-3-3)=
[LGRA.9.3.3] The `is` subject vocabulary:

```
is_subject ::= 'null'
            |  'true' | 'false'
            |  'inf'  | '-inf' | 'NaN'
            |  'Int'  | 'Float' | 'Bool' | 'String' | 'Bytes' | 'Json'
```

**Twelve subjects, and the set is closed** ([LNUL.4.9]): six distinguished
constants and six tag names. `[LNUL.4.9]` governs what each answers — a
constant tests tag **and** value, a tag name tests the tag alone — and is the
normative home of the semantics; this production is the surface. `x is Blah`
is a parse error rather than a later rejection, so an artefact can carry
exactly these twelve and no illegal thirteenth.

**Residue the grammar cannot carry ([STYL.2.15.4]):**

- **This vocabulary reserves nothing.** A subject is recognised **only** in
  subject position, so none of these spellings becomes unavailable to an
  author elsewhere by virtue of appearing here: a cast still reads `::Int`,
  and a bare `inf` is still the float constant. Whether any of these
  spellings is refused as an author-declared name is [LLEX.9.5]'s question
  and is answered by [LLEX.9.6], not by this production.
- **The tag names are not the type namespace**, though they are spelled like
  it. A schema name is not a subject: a schema has no representation of its
  own, so it is neither spellable here nor answerable ([LNUL.4.9]).
- **`-inf` is one subject, not `-` applied to `inf`.** It is admitted in
  subject position only, where no unary-arithmetic level ([LGRA.9.5.1]) is
  reachable, and there is nothing for a sign to attach to.
- **`NaN` is spelled as the initialism** and is the only subject that is.
  [LGRA.22.7] detects author-name collisions with case removed, so `nan` is
  not available to fill the apparent gap.
- **Extension is an amendment to [LNUL.4.9] first.** A subject added here
  with no stated answer parses and means nothing, which is worse than not
  parsing.

*checks:* `idris`  —  *see also:* [LGRA.22.7](#LGRA-22-7), [LGRA.9.5.1](#LGRA-9-5-1), [LLEX.9.5](#LLEX-9-5), [LLEX.9.6](#LLEX-9-6), [LNUL.4.9](#LNUL-4-9)

(LGRA-9-4)=
### Bitwise [LGRA.9.4]

(LGRA-9-4-1)=
[LGRA.9.4.1] Bitwise productions:

```
bitwise_or  ::= bitwise_xor ('|' bitwise_xor)*
bitwise_xor ::= bitwise_and ('^' bitwise_and)*
bitwise_and ::= bitwise_shift ('&' bitwise_shift)*
bitwise_shift ::= additive (('<<' | '>>') additive)*
```

*ratified*

(LGRA-9-5)=
### Arithmetic [LGRA.9.5]

(LGRA-9-5-1)=
[LGRA.9.5.1] Arithmetic productions:

```
additive       ::= multiplicative (('+' | '-') multiplicative)*
multiplicative ::= exponent (('*' | '/' | '//' | '%') exponent)*
exponent       ::= unary ('**' exponent)?                      # right-assoc (right-recursive)
unary          ::= ('-' | '+' | '~') unary
                |  postfix
```

`not` is the logical operator at the `not_expr` level (LGRA.9.3.1),
not the unary-arithmetic level. The `not_expr` production captures
that precedence position; `unary` here covers the arithmetic
unaries only.

*ratified*  —  *see also:* [LGRA.9.3.1](#LGRA-9-3-1)

(LGRA-9-6)=
### Postfix operations [LGRA.9.6]

(LGRA-9-6-1)=
[LGRA.9.6.1] Postfix productions:

```
postfix ::= primary postfix_op*
postfix_op ::= '.' NAME                                        # slot access, Json key, or member (LGRA.9.6.2)
            |  '[' expression ']'                              # index
            |  '(' argument_list? ')'                          # call: a built-in function, or a member's arguments
            |  '::' TYPE_SYM NULLABLE?                         # conversion cast (LCST.4)
argument_list ::= expression (',' expression)*
```

*ratified*  —  *see also:* [LCST.4](#LCST-4)

(LGRA-9-6-2)=
[LGRA.9.6.2] **Members.** A `.NAME` whose receiver is a value of a builtin
type other than `Json` names a **member** of that type, and the compiler must
resolve it by the receiver's static type, whether the receiver is a slot read
or a computed value. The members each type has are listed where the type is
specified: `Int` in [LEXP.3.7.1], and `String`, `Time`, `Date` and `Duration`
in [LTIM.3], [LTIM.4.3.1], [LTIM.6.1], [LTIM.7.1] and [LTIM.8.1]. `Float` and
`Bool` have no members, and neither does `Bytes` ([LSTR.4.6]).

- A member that takes no arguments is written without an argument list, as a
  slot is read.
- A member that takes arguments is followed by its argument list.

The compiler must refuse, with `DS_VALIDATE_UNKNOWN_MEMBER`, a `.NAME` that
names no member of its receiver's type, a zero-argument member written with an
argument list, and a member that takes arguments written without one. It must
refuse an argument of a type the member does not take with
`DS_VALIDATE_BAD_OPERAND_TYPE`.

Three receivers are not member receivers. On a fact binding `.NAME` reads a
slot, on a series binding it may read a companion aggregation ([LSER.10.6]),
and on a `Json` value it reads a key ([LGRA.5.8.1]). A `Json` value therefore has
no members, and a `Json` leaf is cast to its scalar type ([LCST.4]) before a
member is read from it.

*ratified*  —  *see also:* [LCST.4](#LCST-4), [LEXP.3.7.1](#LEXP-3-7-1), [LGRA.5.8.1](#LGRA-5-8-1), [LSER.10.6](#LSER-10-6), [LSTR.4.6](#LSTR-4-6), [LTIM.3](#LTIM-3), [LTIM.4.3.1](#LTIM-4-3-1), [LTIM.6.1](#LTIM-6-1), [LTIM.7.1](#LTIM-7-1), [LTIM.8.1](#LTIM-8-1)

(LGRA-9-6-3)=
[LGRA.9.6.3] **Spellings the compiler refuses in favour of a member, a
cast or an operator.** The compiler must refuse each spelling below with
`DS_VALIDATE_RETIRED_BUILTIN_SPELLING`, naming the spelling that replaces it,
rather than with an unknown-function or unknown-member error.

| Refused | Written as |
|---|---|
| `bit_count(x)` | `x.bit_count` ([LEXP.3.7.1]) |
| `bit_length(x)` | `x.bit_length` ([LEXP.3.7.1]) |
| `utc(t)` | `t.utc` ([LTIM.3.1.1]) |
| `local(t, tz)` | `t.local(tz)` ([LTIM.3.2.1]) |
| `math.floor(t, d)`, in either form of its import ([LIMP.3.3.4]), with a `Time` or `Date` first argument | `t.floor(d)` ([LTIM.7.1]) |
| `add_months(t, n)`, `add_years(t, n)` | `t.add_months(n)`, `t.add_years(n)` ([LTIM.4.3.1]) |
| `t.to_string()`, `d.to_string()` without a format | `t::String`, `d::String` ([LCST.4.5.9]) |
| `dur.to_string()` | `dur::String` ([LCST.4.5.9]) |
| `is_null(x)` | `x is null` ([LNUL.4.9]) |

*ratified*  —  *see also:* [LCST.4.5.9](#LCST-4-5-9), [LEXP.3.7.1](#LEXP-3-7-1), [LIMP.3.3.4](#LIMP-3-3-4), [LNUL.4.9](#LNUL-4-9), [LTIM.3.1.1](#LTIM-3-1-1), [LTIM.3.2.1](#LTIM-3-2-1), [LTIM.4.3.1](#LTIM-4-3-1), [LTIM.7.1](#LTIM-7-1)

(LGRA-9-7)=
### Primary [LGRA.9.7]

(LGRA-9-7-1)=
[LGRA.9.7.1] Primary productions:

```
primary ::= literal
         |  NAME                                               # binding / constant / type reference — classified by position (LGRA.22)
         |  '(' expression ')'

literal ::= INT_LIT
         |  FLOAT_LIT
         |  STRING_LIT
         |  UNIT_LIT
         |  BOOL_LIT
```

Function calls are not a primary alternative — they're a postfix
form, `primary postfix_op*` where `postfix_op` includes
`'(' argument_list? ')'` per [LGRA.9.6]. So `len(x)` parses as
the `NAME` `len` followed by a `(...)` postfix. The type-headed
coercion call forms (`Json(x)` / `Float(x)` / `Int(x)`) are
**removed** — a conversion is written with the `::` cast
(`x::Json`) — per [LGRA.9.7.3] and [LCST.4.6].

*see also:* [LCST.4.6](#LCST-4-6), [LGRA.22](#LGRA-22), [LGRA.9.6](#LGRA-9-6), [LGRA.9.7.3](#LGRA-9-7-3)

(LGRA-9-7-2)=
[LGRA.9.7.2] A `NAME` function call resolves to the built-in
library at [LEXP] (the distance and
vector-similarity functions at [LEXP.5]) or to a `unit formula`'s function
([LGRA.9.8.11]).

*see also:* [LEXP.5](#LEXP-5), [LGRA.9.8.11](#LGRA-9-8-11)

(LGRA-9-7-3)=
[LGRA.9.7.3] The type-headed coercion call forms `Json(x)` / `Float(x)` /
`Int(x)` / `<unit>(x)` are **removed**: a conversion is written with the `::`
cast ([LGRA.9.6], [LCST.4.6.1]). The compiler must reject the removed call
forms; for one language-version it emits a guided rewrite error naming the `::`
form. Ordinary `NAME(...)` calls (`len`, `has`, distance builtins) are
unaffected. `json("<lit>")` is not a coercion and is refused on its own terms
([LGRA.9.8.3]).

*see also:* [LCST.4.6.1](#LCST-4-6-1), [LGRA.9.6](#LGRA-9-6), [LGRA.9.8.3](#LGRA-9-8-3)

(LGRA-9-8)=
### Built-in functions [LGRA.9.8]

(LGRA-9-8-1)=
[LGRA.9.8.1] **Json introspection.** `len(<Json>) → Int` and
`has(<Json path>) → Bool` are the Json-introspection
built-ins. Details at [LEXP.6].

*see also:* [LEXP.6](#LEXP-6)

(LGRA-9-8-3)=
[LGRA.9.8.3] **`json()` is admitted in this edition as a test value only.**
The production `json("<str_lit>")` stays in the grammar. In a test block,
`json()` over one string literal is a test value ([LTSL.4.1]). Everywhere
else the compiler **must** refuse every `json()` call with
`DS_VALIDATE_JSON_LITERAL_REFUSED`: a rule's artefact has no form in which to
carry a `Json` literal, so no `json()` value could reach a `Json` slot or
argument.

The rules for its argument ([LEXP.6.4]) are deferred with it:
`DS_VALIDATE_JSON_NOT_LITERAL` and `DS_VALIDATE_JSON_PARSE_ERROR` stay
allocated and are not raised in this edition. In a rule the call is refused
first; in a test, [LTSL.4.1] states what the argument must be.

*ratified*  —  *see also:* [LEXP.6.4](#LEXP-6-4), [LTSL.4.1](#LTSL-4-1)

(LGRA-9-8-2)=
[LGRA.9.8.2] **The read function** — `cached(key)` reads
external state. It is an expression, not an action; it may
appear **only** as the entire RHS of a `let` binding.
Anywhere else (an action kwarg, an interpolation segment,
embedded inside another expression) is a compile error.

One exception, and only one: **`cached()` may also appear
inside a `where` clause**, because the cache is read-only
while patterns are being evaluated, so the value is stable
for the duration of an activation ([LSTO.4.3.1a]).

**`cached(key)` is the only read function.** A call naming
any other function is refused by [LGRA.9.8.11]'s closed
built-in set.

*ratified*  —  *see also:* [LGRA.9.8.11](#LGRA-9-8-11), [LSTO.4.3.1a](#LSTO-4-3-1a)

(LGRA-9-8-10)=
[LGRA.9.8.10] **Clock functions.** `now() → Time` returns the wall-clock
instant ([LTIM.2.1.1]) and `monotonic_ns() → Duration` the monotonic clock's
reading ([LTIM.2.2.1]). Unlike the read functions ([LGRA.9.8.2]), each may
appear in any expression position — a `where` clause, an action argument,
anywhere in a `let` RHS — except an interpolation body, which takes a path and
not a call ([LGRA.2.9.6.9]). In a `where` clause either makes the condition
time-dependent ([LTIM.2.4.1]). A `let` whose entire RHS is a clock read binds
the value once per activation; multiple references to the let name reuse that
single value rather than re-reading the clock. (See the let purity tiers
below.)

**That reuse is an optimisation, not a second semantics.**
[LTIM.2.1.3] already fixes one clock value for the whole
activation — activations are atomic with respect to the
clock — so two separate `let`s each binding `now()` take
the **same** value, and re-reading would be permitted to
change nothing. This clause says when the engine *may*
skip the read; [LTIM.2.1.3] says what the read must
return.

*see also:* [LGRA.2.9.6.9](#LGRA-2-9-6-9), [LGRA.9.8.2](#LGRA-9-8-2), [LTIM.2.1.1](#LTIM-2-1-1), [LTIM.2.1.3](#LTIM-2-1-3), [LTIM.2.2.1](#LTIM-2-2-1), [LTIM.2.4.1](#LTIM-2-4-1)

(LGRA-9-8-11)=
[LGRA.9.8.11] **The built-in set is closed** ([LCYC.1.2]): every
callable name in an expression is a built-in of this section. The compiler must reject a call to any other
name with `DS_VALIDATE_UNKNOWN_FUNCTION`, naming the admitted set.

A series aggregation read in call form ([LSER.16.1]) is a built-in for this
purpose. An aggregation the bound series does not declare is [LSER.6.9.4]'s
refusal, and a name that is no aggregation is refused here.

The two functions of a `unit formula` ([LUNI.4.5]) are callable too, in a file
that declares the formula or imports it ([LIMP.7.7]), outside a formula's body. The compiler **must**
resolve such a call to the formula, check its argument against the function's
parameter unit as any unit-typed operand is checked, and evaluate it as the
function's expression at the call site. A formula is declared only as a
conversion between two units, and its body is one expression over its one
parameter ([LUNI.4.5]).

Every call in a formula's body is to a built-in. The compiler **must** reject a
call there to a formula's function, the formula's own included, with
`DS_VALIDATE_UNKNOWN_FUNCTION`, at the formula's declaration, whether or not
anything calls the formula.

*ratified*  —  *see also:* [LCYC.1.2](#LCYC-1-2), [LIMP.7.7](#LIMP-7-7), [LSER.16.1](#LSER-16-1), [LSER.6.9.4](#LSER-6-9-4), [LUNI.4.5](#LUNI-4-5)

(LGRA-9-8-4)=
[LGRA.9.8.4] **Let purity tiers.** Every expression that may appear
in a `let` RHS belongs to one of two tiers
distinguishing its evaluation cost / observability:

- **Pure** — slot access, arithmetic, comparison,
  logical operators, Json introspection (`len`, `has`).
  Inlined at every reference site at compile time;
  no runtime artefact corresponds to the `let`.
- **Sync-impure** — `now()`, `monotonic_ns()` and
  `cached(key)`. Bound once per rule activation at the
  start of the RHS so subsequent references see the same
  value; cheap to evaluate (no I/O), but the bind-once
  semantics are author-visible.

The tier of a let's expression determines the lowering
strategy. Pure expressions inline; sync-impure expressions
are bound once at RHS entry and referenced at use sites.

A construct in the action block
that decides whether the rule fires, and how often, belongs
on the left-hand side where the pattern and its `no` twin
are written openly.

(LGRA-10)=
## Actions [LGRA.10]

(LGRA-10-1)=
[LGRA.10.1] Action productions:

```
action ::= call_action
        |  action_head action_arg* NEWLINE action_block?    # the block: [LGRA.10.8]

call_action ::= 'call' service_ref action_arg* call_as? NEWLINE action_block?
call_as     ::= 'as' expression                    # the correlation ([LRST.1.1]); not an action_arg

action_head ::= 'log' log_level STRING_LIT
             |  'emit' type_ref                   # Name or lib.Name, as a pattern's ([LGRA.8.1])
             |  'publish' type_ref
             |  'cache'
             |  'cache_delete'
             |  'withdraw' NAME                    # NAME is a positively-bound LHS variable, not a schema name

log_level      ::= 'debug' | 'info' | 'warning' | 'error' | 'critical'   # case-insensitive

service_ref    ::= service_name                                 # one global service namespace ([LGRA.10.1.6])
service_name   ::= NAME ('.' NAME)*                             # the service's own name (light.turn_on, hydrate_facts)
```

**Residue the grammar does not carry ([STYL.2.15.4]):** `as` is a reserved
word ([LLEX.9.5]), so `call_as` is never read as a flag, and an argument after
it is a parse error ([LCRS.6.2.3]). A `call` carries at most one `as`, on its
head line or in its block ([LGRA.10.8]).

*ratified*  —  *checks:* `idris×2`  —  *see also:* [LCRS.6.2.3](#LCRS-6-2-3), [LGRA.10.1.6](#LGRA-10-1-6), [LGRA.10.8](#LGRA-10-8), [LGRA.8.1](#LGRA-8-1), [LLEX.9.5](#LLEX-9-5), [LRST.1.1](#LRST-1-1)

(LGRA-10-1-1)=
[LGRA.10.1.1] **`log_level` is matched case-insensitively** —
`log info "x"`, `log INFO "x"`, and `log Info "x"` are all
valid and equivalent. The compiler normalises the value to
upper-case in the lowered `log` action. Unknown
names produce a compile error. The five levels mirror Python's
`logging` module.

*ratified*

(LGRA-10-1-3)=
[LGRA.10.1.3] **Nothing in a rule's RHS refers to a binding after it is
withdrawn.** A rule's actions run in source order, and `withdraw b` removes the
fact bound to `b` when it runs ([LSCO.4.5.9]). No action after it in the same
RHS may refer to `b`: not by reading a slot of `b`, anywhere in the action or in
a body nested in it, and not by withdrawing `b` again. The compiler **must**
refuse such a reference with `DS_VALIDATE_WITHDRAWN_BINDING_USED`, at the
action that contains it, naming the binding and the `withdraw` before it. A body
nested in a later action — a call continuation, an `after` body — counts,
although it runs later: the values it reads are captured from the fact when the
action containing it runs ([LCCO.5.2]), and that is after the `withdraw`. An
action before the `withdraw` may refer to `b` freely. A `logical` emit after the
`withdraw` in the same RHS is refused whether or not it refers to `b`
([LLOG.11.9]).

The same rule holds inside a nested body that itself withdraws `b`
([LGRA.10.1.4]): nothing after that `withdraw` in the body may refer to `b`. An
action of the outer RHS after the one containing that body may still refer to
`b`, because the body runs later.

*ratified*  —  *see also:* [LCCO.5.2](#LCCO-5-2), [LGRA.10.1.4](#LGRA-10-1-4), [LLOG.11.9](#LLOG-11-9), [LSCO.4.5.9](#LSCO-4-5-9)

(LGRA-10-1-4)=
[LGRA.10.1.4] **A `withdraw` in a nested body removes the fact the outer rule
matched, and only that fact.** `withdraw b` may stand in a body nested in an
action: a call continuation, an error or timeout body, or an `after` body.
It runs when that body runs, and it removes the fact the outer rule had bound
to `b` when it fired. If that fact is no longer in working memory when the
body runs — withdrawn, expired, or replaced by a meaningful change, which
makes the replacement a different fact ([LFAC.2.5.3]) — the action does
nothing. The engine **must not** withdraw a fact that has taken the matched
fact's place under the same identity key: the rule never saw it.

The removal is the author's own withdrawal, recorded as such ([RFCS.7a.2]).
Its sequencing within the body is [LGRA.10.1.3]'s.

*ratified*  —  *see also:* [LFAC.2.5.3](#LFAC-2-5-3), [LGRA.10.1.3](#LGRA-10-1-3), [RFCS.7a.2](#RFCS-7a-2)

(LGRA-10-1-5)=
[LGRA.10.1.5] **`record_event` is not an action.** The word is reserved
([LLEX.9.6]), and the compiler must reject an action line that begins with it
(`DS_VALIDATE_RECORD_EVENT_RETIRED`). The message names no replacement.

*ratified*  —  *see also:* [LLEX.9.6](#LLEX-9-6)

(LGRA-10-1-6)=
[LGRA.10.1.6] **Services live in one global namespace, and a service reference is
bare.** A `service_ref` names a service by its own name, and the compiler must
resolve it against every service declared in the compilation's import closure,
whatever form imported the declaring library. The name alone identifies a service
([LCRS.14.9]), so no library qualifier is needed to reach one, and none is
admitted.

A `call` position is not resolved by scope ([LGRA.22.9]). A dotted path whose first
segment happens to name an imported library is a service name like any other, and
it resolves only if a service of that exact name is declared.

*ratified*  —  *see also:* [LCRS.14.9](#LCRS-14-9), [LGRA.22.9](#LGRA-22-9)

(LGRA-10-2)=
[LGRA.10.2] One logical line per action (one terminating NEWLINE).
Line continuation available via parenthesised expressions
on a `name: value` RHS.

(LGRA-10-3)=
### Action arguments [LGRA.10.3]

(LGRA-10-3-1)=
[LGRA.10.3.1] Action-argument productions:

```
action_arg ::= kwarg | flag

kwarg ::= NAME ':' value
flag  ::= NAME

value ::= expression
```

Literals (INT_LIT, FLOAT_LIT, STRING_LIT, UNIT_LIT, BOOL_LIT) and
`NAME` are subsumed by `expression` — `literal` is a primary,
`NAME` is a primary alternative.

(LGRA-10-3-4)=
[LGRA.10.3.4] **The action-argument inventory is closed.** Each action verb
accepts exactly the language-defined kwargs and flags below, plus — where the
verb has one — the kwargs of its user-declared namespace. Any other kwarg name
is a compile error `DS_VALIDATE_BAD_KWARG`; any other flag name is
`DS_VALIDATE_BAD_FLAG`. [LGRA.10.3.3] is the *action's contract* that
[LGRA.10.3.2] delegates validity to, and is its single normative home.

The two kwarg namespaces cannot collide: [LLEX.9.5] reserves `retain`,
`cooldown`, `nocooldown` and `as` against use as an author binding target, so a
language-defined modifier is never also a slot or service kwarg.

`as` is **not** an action argument — it is a trailing clause of `call_action`
([LGRA.10.1]) rather than an `action_arg`, and appears above only where a row
would otherwise read as excluding it.

A verb whose user-declared namespace is `—` takes a **fixed** argument list, and
that is exactly the case in which nothing else in the corpus narrows the
grammar: [LGRA.10.1] admits `action_arg*` after every head, so for those verbs
this clause is the only thing that closes the set.

*ratified*  —  *see also:* [LGRA.10.1](#LGRA-10-1), [LGRA.10.3.2](#LGRA-10-3-2), [LGRA.10.3.3](#LGRA-10-3-3), [LLEX.9.5](#LLEX-9-5)

(LGRA-10-3-2)=
[LGRA.10.3.2] The grammar accepts any `kwarg | flag` sequence after the
action head; per-action validity is enforced at compile
time by the action's contract, which is [LGRA.10.3.3].

The split is one of **phase**, not of expressive power. A grammar applied
before name resolution must accept any `kwarg | flag` sequence, because "a
kwarg name must be a slot of the schema this action names" depends on which
schema that name resolves to, and at that point it has not. Once the name is
resolved the dependency is gone: the admissible set is fixed, and
[LGRA.10.3.3] closes the surface as a grammar over it. [LGRA.10.3.3] is where
every verb's contract lives.

So the contract is not a retreat from a grammar to a prose list. It is a
grammar, applied at the phase where its schema-dependent nonterminal has a
value: an ordinary attribute grammar, not a context-sensitive one.

*ratified*  —  *see also:* [LGRA.10.3.3](#LGRA-10-3-3)

(LGRA-10-3-3)=
[LGRA.10.3.3]

| Verb           | Head                        | Language-defined kwargs                                                        | Flags                             | User-declared kwarg namespace          |
|----------------|-----------------------------|--------------------------------------------------------------------------------|-----------------------------------|----------------------------------------|
| `log`          | `log_level STRING_LIT`      | —                                                                              | —                                 | —                                      |
| `emit`         | schema `NAME`               | `retain:` — ttl-lifecycle schema, `dynamic_ttl` ([LDTL.4.1])                   | `logical`                         | the named schema's slots               |
| `publish`      | schema `NAME`               | — (`retain:` refused, [LTIE.4.9])                                              | — (`logical` refused, [LTIE.4.9]) | the named schema's slots               |
| `call`         | `service_ref`               | `cooldown:`; `retain:` on hydration endpoints only ([LCRS.6.3.3])              | `nocooldown`                      | the resolved service's declared kwargs |
| `cache`        | —                           | `key:` **(required, literal, [LGRA.10.3.7])**, `value:` **(required)**, `ttl:` | —                                 | —                                      |
| `cache_delete` | —                           | `key:` **(required, literal, [LGRA.10.3.7])**                                  | —                                 | —                                      |
| `withdraw`     | positively-bound LHS `NAME` | —                                                                              | —                                 | —                                      |

*ratified*  —  *see also:* [LCRS.6.3.3](#LCRS-6-3-3), [LDTL.4.1](#LDTL-4-1), [LGRA.10.3.7](#LGRA-10-3-7), [LTIE.4.9](#LTIE-4-9)

(LGRA-10-3-5)=
[LGRA.10.3.5] **A kwarg is named at most once per action.** An action that
names the same kwarg twice, whether language-defined or from its user-declared
namespace ([LGRA.10.3.4]), is a compile error `DS_VALIDATE_DUPLICATE_KWARG`. The
compiler sorts kwargs by name, so a duplicate would leave the artefact
depending on the order the author wrote them in.

*ratified*  —  *see also:* [LGRA.10.3.4](#LGRA-10-3-4)

(LGRA-10-3-6)=
[LGRA.10.3.6] **A verb's required kwarg is written.** The compiler must refuse
an action that leaves out a kwarg [LGRA.10.3.3] marks **(required)** for its
verb, `cache` without `key:` or `value:` and `cache_delete` without `key:`, with
`DS_VALIDATE_MISSING_KWARG`, at the action. A `call`'s required kwargs are its
service's declaration, and [LADP.8.5.1] refuses a missing one with the same
code.

*ratified*  —  *see also:* [LADP.8.5.1](#LADP-8-5-1), [LGRA.10.3.3](#LGRA-10-3-3)

(LGRA-10-3-7)=
[LGRA.10.3.7] **A cache key is a literal.** The `key:` of a `cache` or a
`cache_delete` must be a `STRING_LIT` with no interpolation site
([LGRA.2.9.6]), and the compiler must refuse any other value with
`DS_VALIDATE_DYNAMIC_IDENT_KWARG`, at the action, naming the kwarg and the
verb. A key read back by `cached("<key>")` is written the same way
([LSTO.4.3.1]). `value:` and `ttl:` keep [LGRA.10.6]'s freedom.

*ratified*  —  *see also:* [LGRA.10.6](#LGRA-10-6), [LGRA.2.9.6](#LGRA-2-9-6), [LSTO.4.3.1](#LSTO-4-3-1)

(LGRA-10-5)=
### Special action forms [LGRA.10.5]

(LGRA-10-5-1)=
- [LGRA.10.5.1] `call` carries mandatory rate-expectation
  kwargs. See [LCRS.8.1] for the normative rule and its
  rationale. (Reads — `cached(key)` — are **not** actions; they're expressions callable from
  a `let` RHS and a `where` per [LGRA.9.8].)

*see also:* [LCRS.8.1](#LCRS-8-1), [LGRA.9.8](#LGRA-9-8)

(LGRA-11)=
## Interpolation grammar (inside string literals) [LGRA.11]

(LGRA-11-1)=
[LGRA.11.1] Already specified in Lexical structure [LGRA.2.9].
Summary for reference:

*see also:* [LGRA.2.9](#LGRA-2-9)

(LGRA-11-2)=
- [LGRA.11.2] `{binding.slot}` substitutes the slot value

(LGRA-11-3)=
- [LGRA.11.3] `{binding.slot:spec}` substitutes with format spec, [LGRA.2.9.6.1]'s
  `interp_format`

*see also:* [LGRA.2.9.6.1](#LGRA-2-9-6-1)

(LGRA-11-4)=
- [LGRA.11.4] `{binding.path[0].deeper}` substitutes via path access

(LGRA-11-5)=
- [LGRA.11.5] `{{` is a literal `{`, `}}` is a literal `}`

(LGRA-11-6)=
- [LGRA.11.6] Eligible positions are [LGRA.2.9.6.8]'s; no whitespace inside braces

*see also:* [LGRA.2.9.6.8](#LGRA-2-9-6-8)

(LGRA-11-7)=
- [LGRA.11.7] Malformed interpolation sites and malformed format specs
  are compile errors

---

(LGRA-12)=
## Disambiguation rules [LGRA.12]

(LGRA-12-1)=
[LGRA.12.1] Summary of context-sensitive disambiguations:

(LGRA-12-2)=
### A `NAME` in a type position [LGRA.12.2]

(LGRA-12-2-1)=
[LGRA.12.2.1] A `NAME` that heads a pattern body, or a `TYPE_SYM` in a type
annotation or `::T` cast target, resolves as a **type reference** (adapter type
or schema) in the type namespace ([LGRA.22], [LGRA.2.5.3]). Case is irrelevant.

*see also:* [LGRA.2.5.3](#LGRA-2-5-3), [LGRA.22](#LGRA-22)

(LGRA-12-3)=
### A `NAME` in a binding or expression position [LGRA.12.3]

(LGRA-12-3-1)=
[LGRA.12.3.1] In pattern-body position (after the type reference): the binding.
In expression position: a value-namespace reference resolved in the order
binding → constant → builtin function ([LGRA.22.7]); a `NAME` followed by `(` is
a builtin function call; an unresolved `NAME` is a compile error. A pattern head
that is not a type reference must be the `no` negation keyword, else a compile
error ("pattern must begin with a schema name or `no`"); an action head must be
an action keyword (`call`, `emit`, …), else a compile error.

*see also:* [LGRA.22.7](#LGRA-22-7)

(LGRA-12-4)=
### Dotted identifier [LGRA.12.4]

(LGRA-12-4-1)=
[LGRA.12.4.1] **What a `.` separates depends on where it stands.** In
expression position it is a slot-access / `Json`-path chain (`p.entity_id`,
`response.forecast[0].max`) or a library member (`math.pi`), resolved by scope
([LGRA.22.9]). Inside a library path (`import units.si`) or a service's own name
(the `light.turn_on` in `call light.turn_on`) it is an internal segment separator.
In a pattern head it separates a library path from a schema ([LGRA.22.4]).

*see also:* [LGRA.22.4](#LGRA-22-4), [LGRA.22.9](#LGRA-22-9)

(LGRA-12-5)=
### Within-line `->` [LGRA.12.5]

(LGRA-12-5-1)=
[LGRA.12.5.1] Inside a rule, at column 0: structural separator between
LHS and RHS.
Elsewhere: compile error.

(LGRA-12-6)=
### Integer vs duration [LGRA.12.6]

(LGRA-12-6-1)=
[LGRA.12.6.1] `30` alone: integer literal.
`30_s` and `30s`: the same duration literal — the
underscore separator is optional ([LUNI.3.1.1]).
`30 s` (whitespace): integer `30` followed by identifier
`s` — typically a compile error in context. Whitespace is
the one thing that breaks the literal; the separator's
presence does not.

*see also:* [LUNI.3.1.1](#LUNI-3-1-1)

(LGRA-12-8)=
### First-line bare string [LGRA.12.8]

(LGRA-12-8-1)=
[LGRA.12.8.1] Inside a rule or schema body, if the first statement is a
bare string literal (single or triple-quoted), it's the
docstring. Subsequent strings are not treated as
docstrings; they're part of the rule body (which for
rules means they'd need to be part of a larger
expression / action — a bare string alone in the middle
of a rule body is a compile error).

---

*ratified*

(LGRA-13)=
## Compile-time validation (beyond grammar) [LGRA.13]

(LGRA-13-1)=
[LGRA.13.1] The grammar accepts structurally-valid source; the
compiler additionally validates:

(LGRA-13-2)=
- [LGRA.13.2] Use declaration: the dialect name is registered; the
  extensions are allowed by that dialect

(LGRA-13-3)=
- [LGRA.13.3] Const declaration: the RHS must **fold to a compile-time
  constant** (the runtime-free foldable subset,
  [LEXP.8.8]); an optional `: type` annotation
  (a scalar builtin type, or a canonical unit) is **checked against
  the folded value** — a mismatch is a compile error; it may reference
  **earlier and imported consts only**; **no runtime construct** (`now()` /
  `cached()`, series aggregations, bindings, runtime-`Json` leaf
  reads, regex — a compile error naming the construct); **no forward or cyclic
  reference**

*ratified*  —  *see also:* [LEXP.8.8](#LEXP-8-8)

(LGRA-13-4)=
- [LGRA.13.4] Schema declaration: type names are unique; field names
  are unique within a schema; slot markers are valid

*ratified*

(LGRA-13-5)=
- [LGRA.13.5] Series declaration: every observation line names a
  satisfiable (aggregation, time-model) pair per
  [LSER.13.3], [LSER.15.2] and [LSER.17];
  durations and sample counts are positive, and one that is not is
  `DS_VALIDATE_SERIES_NONPOSITIVE_WINDOW`; the `by:` block
  kwarg names a slot of the bound schema or the literal `none`,
  and is required wherever the schema declares no identity to
  follow ([LSER.7.6.1]);
  duplicate `(label, aggregation)` pairs are rejected per
  [LSER.6.8.6]

*ratified*  —  *see also:* [LSER.13.3](#LSER-13-3), [LSER.15.2](#LSER-15-2), [LSER.17](#LSER-17), [LSER.6.8.6](#LSER-6-8-6), [LSER.7.6.1](#LSER-7-6-1)

(LGRA-13-6)=
- [LGRA.13.6] Rule declaration: bindings are unique within the rule;
  docstring is well-formed

*ratified*

(LGRA-13-7)=
- [LGRA.13.7] Patterns: type_ref resolves to a registered schema or
  adapter type (bare, or a library-qualified `lib.Schema`); `within`
  duration is non-negative

*ratified*

(LGRA-13-8)=
- [LGRA.13.8] Expressions: binding references are in scope
  (`DS_VALIDATE_UNKNOWN_BINDING`); slot accesses reference declared slots
  (`DS_VALIDATE_UNKNOWN_SLOT`); operator types match per the type rules
  (`DS_VALIDATE_TYPE_MISMATCH`)

*ratified*

(LGRA-13-9)=
- [LGRA.13.9] Actions: action head is a valid keyword; required
  kwargs are present; flag combinations are valid;
  cooldown requirement is satisfied for `call`

*ratified*

(LGRA-13-11)=
- [LGRA.13.11] `emit` / `publish`: every non-nullable slot of the schema is
  given a value, except `ts`, which takes the instant of assertion
  ([LFAC.1.3.4]); the compiler must reject an action that omits one
  (`DS_VALIDATE_MISSING_SLOT`), naming the slot. A nullable slot the action
  omits takes `null` ([LNUL.11.1]).

*ratified*  —  *see also:* [LFAC.1.3.4](#LFAC-1-3-4), [LNUL.11.1](#LNUL-11-1)

(LGRA-13-10)=
[LGRA.13.10] These are compile errors, not grammar errors. The grammar
is for shape; the compiler enforces semantic validity.

---

(LGRA-15)=
## Grammar commitments [LGRA.15]

(LGRA-15-1)=
- [LGRA.15.1] **Lexical structure committed**: UTF-8, 4-space indent
  only, tabs rejected, LF or CRLF line endings, INDENT /
  DEDENT / NEWLINE synthetic tokens.

*ratified*

(LGRA-15-2)=
- [LGRA.15.2] **Identifiers** are the single `NAME` terminal over
  Unicode (`XID`, NFC); classification as a type reference or a binding is by
  grammatical **position**, not case ([LGRA.22], [LNAM.2.1]). Case is author
  convention only. No `NAME` is reserved for the engine: its own names are
  synthetic, spelt with a `$` no `NAME` can contain ([LLEX.10.6.1]).

*ratified*  —  *see also:* [LGRA.22](#LGRA-22), [LLEX.10.6.1](#LLEX-10-6-1), [LNAM.2.1](#LNAM-2-1)

(LGRA-15-3)=
- [LGRA.15.3] **Keywords** are enumerated explicitly ([LGRA.2.6]).

*ratified*  —  *see also:* [LGRA.2.6](#LGRA-2-6)

(LGRA-15-4)=
- [LGRA.15.4] **Numeric literals** in decimal, hex (`0x`), binary
  (`0b`), octal (`0o`) with underscore separators.

*ratified*

(LGRA-15-5)=
- [LGRA.15.5] **Float literals** require digits on both sides of `.`;
  scientific notation allowed.

*ratified*

(LGRA-15-6)=
- [LGRA.15.6] **Rational literals.** `INT_LIT / INT_LIT` (two integer
  literals) is a `Rational`, reduced at parse time, in every context
  ([LUNI.2.2]); the `/` **operator** on any non-literal operand is `Float`
  ([LEXP.7.4]).

*see also:* [LEXP.7.4](#LEXP-7-4), [LUNI.2.2](#LUNI-2-2)

(LGRA-15-7)=
- [LGRA.15.7] **Duration values** are `time`-dimensioned unit literals
  (`30_s`, `5_min`, `100_ms`) — the `UNIT_LIT` form
  ([LGRA.2.8], [LLEX.12]). `m` is metres (use
  `min` for minutes). No sign ([LUNI.3.3]); no fractional.

*ratified*  —  *see also:* [LGRA.2.8](#LGRA-2-8), [LLEX.12](#LLEX-12), [LUNI.3.3](#LUNI-3-3)

(LGRA-15-8)=
- [LGRA.15.8] **String literals** double-quoted single-line or
  triple-quoted multi-line. Standard escapes. Unknown
  escape is a compile error. No single-quoted, no raw
  strings.

*ratified*

(LGRA-15-9)=
- [LGRA.15.9] **Comments** `#` to end-of-line; any count of leading
  `#` characters is valid (author style).

*ratified*

(LGRA-15-10)=
- [LGRA.15.10] **File structure** optional `use`, then imports, then
  constants, schemas, rules, series, services, units, opaque types and tests
  in any order ([LGRA.3.1]).

*ratified*  —  *see also:* [LGRA.3.1](#LGRA-3-1)

(LGRA-15-11)=
- [LGRA.15.11] **Schemas** with optional lifecycle clause
  (`scope <value>`) **after** the type name, builtin
  types (`String`, `Int`, `Float`, `Bool`, `Json`) ([LGRA.22.8]),
  optional docstring, fields with optional slot markers.
  No `Any`; no composite types (`List`, `Map`). `Json`
  is the fallback for slots whose shape can't be
  statically committed to. Five scope values per
  [LSCP]: `explicit` (default),
  `logical`, `ttl <time_expr>`, `activation`, `ambient`. Bare
  `schema Foo:` is shorthand for `scope explicit`.

*see also:* [LGRA.22.8](#LGRA-22-8)

(LGRA-15-12)=
- [LGRA.15.12] **Series** observation-shaped declarations per
  [LSER.13], with the body listing
  one or more aggregation × time-model × accuracy lines.
  Optional block-option in parentheses (`by:`).

*see also:* [LSER.13](#LSER-13)

(LGRA-15-13)=
- [LGRA.15.13] **Rules** with optional `rule_modifier*` list (`cooldown <DUR>`;
  no modifier orders firing, which is the terminal ordinal — source
  order — per [LDET.5.4])
  **after** the rule name, optional docstring, LHS
  patterns, `->` at column 0, RHS actions. Modifiers are
  tail-form — `rule X cooldown 5_min:`, never
  `rule cooldown 5_min X:` — the same "no extra words before the
  identifier" discipline as schemas ([LGRA.5]).

*ratified*  —  *see also:* [LDET.5.4](#LDET-5-4), [LGRA.5](#LGRA-5)

(LGRA-15-14)=
- [LGRA.15.14] **Patterns** `TypeName [binding] [within dur] [where expr]`
  ([LGRA.8.1]); a written binding must be referenced ([LGRA.8.6]). An adapter entity is matched by constraining its identity
  slot in the `where` clause, not by a dotted suffix ([LGRA.8.2]).

*ratified*  —  *see also:* [LGRA.8.1](#LGRA-8-1), [LGRA.8.2](#LGRA-8-2), [LGRA.8.6](#LGRA-8-6)

(LGRA-15-15)=
- [LGRA.15.15] **Expressions** The precedence of [LGRA.9.2.1], which is
  Python 3's for the logical, comparison, bitwise and arithmetic levels
  ([LGRA.9.2.2]), with `//` floor division, `**` right-assoc
  exponentiation, bitwise, comparison chains.

*see also:* [LGRA.9.2.1](#LGRA-9-2-1), [LGRA.9.2.2](#LGRA-9-2-2)

(LGRA-15-16)=
- [LGRA.15.16] **Actions** head + sequence of kwargs (`name: value`)
  and flags (bare identifiers). `call` with mandatory
  cooldown or `nocooldown`. The read expression `cached(key)`
  is callable only from a `let` RHS, per the let
  purity-tier rules in [LGRA.9.8].

*ratified*  —  *see also:* [LGRA.9.8](#LGRA-9-8)

(LGRA-15-18)=
- [LGRA.15.18] **Disambiguation rules** made explicit for context-
  sensitive constructs (positional type-vs-binding
  classification [LGRA.22]; a dotted name's resolution by scope
  [LGRA.22.9]).

*ratified*  —  *see also:* [LGRA.22](#LGRA-22), [LGRA.22.9](#LGRA-22-9)

(LGRA-16)=
## Grammar commitments [LGRA.16]

(LGRA-16-5)=
5. [LGRA.16.5] **Per-schema TTL value.**
   A `ttl` schema's `schema_lifecycle` ([LGRA.5.1]) is
   `scope ttl` and a `time_expr`, written after the schema
   NAME per [LGRA.5.2]. The duration is mandatory at the source
   level: a `ttl` schema whose source omits it does not
   parse, and no integrator config supplies a default.
   A per-emit override is available via
   `emit X retain: <DUR>` per [LDTL.4.1].

*see also:* [LGRA.5.1](#LGRA-5-1), [LGRA.5.2](#LGRA-5-2), [LDTL.4.1](#LDTL-4-1)

(LGRA-16-6)=
6. [LGRA.16.6] **`log` arity.**
   - **`log` takes a level.** [LGRA.10.1] reads
     `'log' log_level STRING_LIT` with `log_level` ∈
     `{debug, info, warning, error, critical}` (case-insensitive,
     mirroring Python's `logging`). The compiler normalises
     to UPPER-case in the lowered action and synthesises the
     category from the rule name (per [RLOW.7.7]).
   - The runtime log-level enum mirrors the same five names.

*see also:* [LGRA.10](#LGRA-10), [LGRA.10.1](#LGRA-10-1), [RLOW.7.7](#RLOW-7-7)

(LGRA-21)=
## Test declarations [LGRA.21]

(LGRA-21-1)=
[LGRA.21.1] **Production.** A `test` is a top-level declaration ([LGRA.3.1]); its
surface semantics are specified in [LTSL],
and it compiles to the `Test*` / `Oracle*` test atoms ([RDSC.7.1]).

```
test_decl        ::= 'test' STRING_LIT ':' INDENT test_section+ DEDENT
test_section     ::= test_inputs | test_initial | test_responses | test_produces | test_until
test_until       ::= 'until' time_coord NEWLINE
test_inputs      ::= 'inputs' ':' INDENT test_at_block+ DEDENT
test_at_block    ::= 'at' time_coord ':' INDENT test_fact+ DEDENT
time_coord       ::= UNIT_LIT | postfix   ;; UNIT_LIT = relative offset; postfix = absolute, a calendar.time call (LTSL.3.2)
test_fact        ::= type_ref action_arg* NEWLINE
test_initial     ::= 'initial' ':' INDENT test_initial_item+ DEDENT
test_initial_item ::= test_fact | test_cache_seed | test_cache_block
test_cache_seed  ::= 'cache' STRING_LIT ':' expression NEWLINE
test_cache_block ::= 'cache' ':' INDENT test_cache_entry+ DEDENT
test_cache_entry ::= STRING_LIT ':' expression NEWLINE
test_responses   ::= 'responses' ':' INDENT response_stub+ DEDENT
response_stub    ::= 'for' 'call' service_ref kwarg* ('as' STRING_LIT)? ('after' UNIT_LIT)? ':' INDENT response_body+ DEDENT
response_body    ::= reply_fact | no_response_line
reply_fact       ::= type_ref action_arg* NEWLINE
no_response_line ::= 'no' 'response' NEWLINE
test_produces    ::= 'produces' ':' INDENT test_assertion+ DEDENT
test_assertion   ::= 'never'? test_head NEWLINE
test_head        ::= 'activated' NAME
                   | 'emitted' type_ref test_match
                   | 'published' type_ref test_match
                   | 'retracted' type_ref action_arg*
                   | 'called' service_ref ('as' STRING_LIT)?
                   | 'cached' STRING_LIT (':' expression)?
                   | 'cache_deleted' STRING_LIT
                   | 'logged' log_level STRING_LIT?
                   | 'wm' test_wm
test_match       ::= where_binding | kwarg*   ;; one or the other, never both (LTSL.8.4)
where_binding    ::= NAME where_clause   ;; <binding> where <pred> (LTSL.8.4)
test_wm          ::= 'has' type_ref kwarg* | 'count' type_ref '==' INT_LIT | 'empty'
```

`type_ref` is a rule pattern's schema reference, `Name` or `lib.Name`
([LGRA.8.1]): a test names a schema as a rule does ([LTSL.4.4]).

*ratified*  —  *see also:* [LGRA.3.1](#LGRA-3-1), [LGRA.8.1](#LGRA-8-1), [LTSL.3.2](#LTSL-3-2), [LTSL.4.4](#LTSL-4-4), [LTSL.8.4](#LTSL-8-4), [RDSC.7.1](#RDSC-7-1)

(LGRA-21-2)=
[LGRA.21.2] **`test` is a reserved word** ([LLEX.9.5]), promoted to keyword
meaning at the start of a top-level declaration — the same position-promotion
`series` takes. Recognition is positional; reservation is not. An author must
not name a binding, slot, `const`, schema or rule `test`, and the compiler must
refuse one that is.

The heads inside a test body — `inputs`, `responses`, `produces`, `until`, `at`,
`for`, `response`, `activated`, `emitted`, `published`, `retracted`, `recorded`,
`called`, `cached`, `cache_deleted`, `logged`, `wm`, `has`, `count`, `empty` —
are promoted only in their body positions and reserved everywhere, as is
`never`, the oracle-polarity prefix on `test_assertion`. `no`, in `no response`,
is the same reserved word the rule surface uses.

*see also:* [LLEX.9.5](#LLEX-9-5)

(LGRA-21-3)=
[LGRA.21.3] **Construction and matching reuse the DS surface.** A constructed fact
(`test_fact`, `reply_fact`) reuses the emit-style `action_arg` colon-kwargs
([LGRA.10]); a matched head reuses subset kwargs or — on `emitted`, in
their place — the rule `where_clause` predicate ([LTSL.4.2], [LTSL.8.4]). No second fact syntax
is introduced. The eleven `test_head` alternatives map one-to-one to the surface
assertion heads and their `Oracle*` atoms ([LTSL.8.2]).

*see also:* [LGRA.10](#LGRA-10), [LTSL.4.2](#LTSL-4-2), [LTSL.8.2](#LTSL-8-2), [LTSL.8.4](#LTSL-8-4)

(LGRA-21-4)=
[LGRA.21.4] **Grammar scope.** The production above is the **full** `.dstest` surface — every
sub-production (`initial:` facts + cache seed, absolute coordinates, the
`emitted … where` predicate, `for call` argument match + `after
<dur>`, the `cached "k": v` value, and the `wm has <Schema> …` slot match) is
in the grammar, carried by the `Test*` / `Oracle*` atom fields ([RDSC.7.1]). `LTSL`
remains their normative home.

---

*see also:* [RDSC.7.1](#RDSC-7-1)

(LGRA-22)=
## Positional type classification [LGRA.22]

An identifier's role — type reference or binding — is fixed by grammatical
**position**, and case plays no part ([LGRA.2.5], [LNAM.2.1]). This section
is the normative home for that model; [LCST] and
[LEXP] reference it for how a `NAME` resolves in a cast target
and in expression position.

*see also:* [LGRA.2.5](#LGRA-2-5), [LNAM.2.1](#LNAM-2-1)

(LGRA-22-1)=
[LGRA.22.1] **One identifier terminal.** The lexer must emit a single terminal
`NAME` for every identifier ([LNAM.2.1]); the identifier's role is fixed by its
grammatical position ([LGRA.2.5]).

*see also:* [LGRA.2.5](#LGRA-2-5), [LNAM.2.1](#LNAM-2-1)

(LGRA-22-2)=
[LGRA.22.2] **Classification is by production, not by token.** The grammar must
assign the type-versus-binding role by which nonterminal reduces a `NAME`:

```
type_ref: NAME          // a NAME reduced in a type-reference slot → schema / type
binding:  NAME          // a NAME reduced in a binding slot        → binding
```

In a pattern, the schema is the `NAME` that heads the pattern body (after any
`no` / `latest` / `then` keyword) and reduces to `type_ref`; the binding is the
trailing `NAME` and reduces to `binding` ([LGRA.8]). In expression position, a
`NAME` reduces to a single `BindingRef` node whose meaning the compiler resolves
by name lookup ([LGRA.22.7]); the compiler must not depend on the token class to
make that resolution.

*ratified*  —  *see also:* [LGRA.22.7](#LGRA-22-7), [LGRA.8](#LGRA-8)

(LGRA-22-3)=
[LGRA.22.3] **The grammar with the single `NAME` terminal is unambiguous.**
Every input has at most one parse. A `NAME` reachable under two productions at
one state is permitted only where the productions build the same AST node
(expression atoms, call heads) or where a following token of a distinct class
separates them.

**This is a property of the language, not of a parsing technique.** An
implementation may recognise the language with any parser that accepts exactly
this grammar: conformance turns on what it accepts, not on how. A zero-conflict
LR table built from a fixed BNF desugaring of these productions is evidence of
the property, sufficient and not necessary.

(LGRA-22-4)=
[LGRA.22.4] **Schema references.** At every schema-reference site — a pattern
head, `latest`, `emit`, `publish` — a schema is named by one of two
forms:

- a **bare `NAME`** resolving to a schema in local scope: declared in the
  compilation unit, or imported by `from lib import Schema`; or
- a **library-qualified reference** `p.NAME` (`plant.sensors.Reading`), where `p`
  is the path of a library the file imports, or an `as` alias of one
  ([LIMP.2.1.7]), naming a schema that library exports.

These positions are type positions, so no binding can stand there: every `.` in a
schema reference separates the library path from the schema. A schema from a
library is referenced only when that library is imported ([LIMP.1]); a schema
declared in the compilation unit needs no import. With no entity-suffix in pattern
position ([LADP.2]), the pattern head is LALR(1)-clean ([LGRA.22.3]).

*ratified*  —  *see also:* [LADP.2](#LADP-2), [LGRA.22.3](#LGRA-22-3), [LIMP.1](#LIMP-1), [LIMP.2.1.7](#LIMP-2-1-7)

(LGRA-22-4-1)=
[LGRA.22.4.1] **An unknown schema is refused.** The compiler must refuse, with
`DS_VALIDATE_UNKNOWN_SCHEMA`, a schema-reference site ([LGRA.22.4]) — a pattern
head, a `latest`, an `emit` or a `publish` — whose bare `NAME` is no schema in
local scope, or whose library-qualified reference names a schema the imported
library does not export ([LIMP.4.3.2]).

*ratified*  —  *see also:* [LGRA.22.4](#LGRA-22-4), [LIMP.4.3.2](#LIMP-4-3-2)

(LGRA-22-5)=
[LGRA.22.5] **Import aliasing.** `import` must support an `as` alias so that two
schemas of the same NFC name from different libraries can both be brought into
bare local scope: `from b import Sensor as BSensor`. The compiler must reject a
program that brings two distinct schemas into scope under the same NFC name
without an alias, with `DS_VALIDATE_IMPORT_NAME_COLLISION`. The library-qualified form `lib.Schema` ([LGRA.22.4]) already
distinguishes the two by their library; aliasing is for **bare** local use.

*ratified*  —  *see also:* [LGRA.22.4](#LGRA-22-4)

(LGRA-22-6)=
[LGRA.22.6] **Qualified constant references.** A library-qualified constant
reference in expression position is spelled `p.NAME` (`lib.CONST`,
`config.limits.MAX_TEMP`), as a qualified schema is ([LGRA.22.4]), and is available
once the library is imported ([LIMP.1]); it needs no **selective**
`from lib import CONST`. In expression position a dotted name may also be slot
access, so the compiler resolves it by scope ([LGRA.22.9]).

*see also:* [LGRA.22.4](#LGRA-22-4), [LGRA.22.9](#LGRA-22-9), [LIMP.1](#LIMP-1)

(LGRA-22-7)=
[LGRA.22.7] **Two disjoint namespaces, selected by position.** With case removed,
a schema, a constant, and a binding may share one NFC name. The compiler must
resolve a `NAME` against exactly one of two disjoint namespaces, chosen by
grammatical position:

- The **type namespace** — the builtin types, which are the rows of [LGRA.22.8],
  unit symbols, dimension and scalar-group names ([LUNI.7.1]), schemas, and the
  kind `Schema`, which is admissible only as a service kwarg's declared type ([LADP.8.6.1]) and names a fact of any schema. It is
  used at every *type position*: a `slot: T` annotation, a `let x: T` annotation,
  a `::T` cast target ([LCST.4]), and a unit literal. **Every type position lexes
  the single `TYPE_SYM` terminal** ([LGRA.2.5.3], [LCST.4.1.2]) — the type-symbol
  class (`XID` ∪ the non-`XID` unit glyphs) — so a unit type spelled with a
  non-`XID` glyph (`slot: °C`, `x::°C`) is admitted uniformly. **Units are
  types** — a unit-typed value's static kind *is* its unit symbol — so the type
  namespace is one lattice, not a type track plus a parallel unit track.
  `Bytes` is a scalar builtin at **every** type position — a `slot: T` annotation
  (`slot: Bytes`), a `let x: T` annotation, and a `::T` cast target — like the other
  scalars, with no slot carve-out.
- The **value namespace** — pattern bindings, `let` bindings, and constants. It
  is used at expression positions.

Because the two namespaces are disjoint and position-selected, a constant named
`Float` (value namespace) does not shadow the type `Float` (type namespace), and
a `::Float` cast target resolves `Float` in the type namespace only.

**The type namespace is flat:** two type-namespace entries — any of schema, unit,
dimension, scalar group or builtin — that share one NFC name are a compile error; a schema and a unit may
not both be named `celsius`. Two schemas are `DS_VALIDATE_DUPLICATE_SCHEMA`; a
schema and a unit are `DS_VALIDATE_DUPLICATE_TYPE_NAME`. A declaration taking a
builtin's name is refused as a reserved word before it can collide ([LLEX.9.7]).

Within the value namespace the compiler must resolve an expression `NAME` in the
order in-scope binding → constant → builtin function ([LEXP.17.2]); an unresolved
`NAME` is a compile error: `DS_VALIDATE_UNKNOWN_FUNCTION` where it is called,
a library's member included, `DS_VALIDATE_UNKNOWN_QUALIFIED_CONST` where it is a
library's member that is not called, `DS_VALIDATE_UNKNOWN_CONST` where it names
an entry of the type namespace, and `DS_VALIDATE_UNKNOWN_BINDING` otherwise. A dotted name resolves by [LGRA.22.9].

**Which names an author may not declare is not this clause's to say.** The
builtin type names, the kind `Schema` and the builtin function names are
reserved words carrying rows on [LLEX.9.6], and [LLEX.9.5] is the rule that refuses them. This clause
states only how a `NAME` **resolves** once written.

The resolution order above is why the builtin function names are on that list
rather than free. A binding or constant is resolved before a builtin, so a name
left available would not merely coexist with the builtin it spells — it would
precede it, and shadow it at every call site in scope.

*ratified*  —  *checks:* `alloy×7`  —  *see also:* [LADP.8.6.1](#LADP-8-6-1), [LCST.4](#LCST-4), [LCST.4.1.2](#LCST-4-1-2), [LEXP.17.2](#LEXP-17-2), [LGRA.2.5.3](#LGRA-2-5-3), [LGRA.22.8](#LGRA-22-8), [LGRA.22.9](#LGRA-22-9), [LLEX.9.5](#LLEX-9-5), [LLEX.9.6](#LLEX-9-6), [LLEX.9.7](#LLEX-9-7), [LUNI.7.1](#LUNI-7-1)

(LGRA-22-8)=
[LGRA.22.8]

| Type     | Defined by |
|----------|------------|
| Bool     | LGRA.5.1   |
| Bytes    | LGRA.5.1   |
| Date     | LTIM.1     |
| Duration | LTIM.1     |
| Float    | LGRA.5.1   |
| Int      | LGRA.5.1   |
| Interval | LINT.1     |
| Json     | LGRA.5.8   |
| String   | LGRA.5.1   |
| Time     | LTIM.1     |

(LGRA-22-9)=
[LGRA.22.9] **A dotted name in expression position resolves by scope.** The
grammar reads `a.b.c` as one chain of `.`-separated names ([LGRA.9.6]) and does
not decide what it denotes. The compiler must resolve it by its first segment `a`,
in this order:

1. **A binding.** If `a` is a pattern binding, a regex capture ([LREG.4.6]) or a
   `let` binding in scope, the chain is access on its value.
2. **A library.** Otherwise, if a prefix of the chain is the path of a library the
   file imports, or an `as` alias of one ([LIMP.2.1.7]), the longest such prefix
   is the library, and the segment after it names a member the library exports: a
   constant ([LGRA.22.6]), or a builtin where the library is one that carries
   builtins ([LIMP.3.3.4]). That one segment is the member. Any segment after
   it is a member of the member's value, read as [LGRA.9.6] reads one on any
   value: `ha.RETRY.utc` is `.utc` of the constant `ha.RETRY`.
3. **Otherwise** the name is unresolved, and the compiler must reject it as
   [LGRA.22.7] rejects an unresolved `NAME`.

A type position ([LGRA.22.4]) and a `call` position ([LGRA.10.1.6]) are not
resolved this way: neither can hold a binding.

**A binding never shadows a library.** The compiler must reject a pattern binding,
a regex capture, a `let` binding or a constant whose NFC name equals the first segment of the path of
a library the file imports, or an `as` alias of one, with
`DS_VALIDATE_BINDING_SHADOWS_LIBRARY`. So step 1 and step 2 never both apply, and
every dotted name has at most one reading.

**Nor a member of a library that carries builtins, imported bare.** The
compiler must reject a pattern binding, a regex capture, a `let` binding or a
constant whose NFC name equals a member of such a library ([LIMP.3.3.4]) that a
selective import of that library names ([LIMP.2.1.4]), with `DS_VALIDATE_BINDING_SHADOWS_LIBRARY`. So its
bare name has one reading too.

*ratified*  —  *see also:* [LGRA.10.1.6](#LGRA-10-1-6), [LGRA.22.4](#LGRA-22-4), [LGRA.22.6](#LGRA-22-6), [LGRA.22.7](#LGRA-22-7), [LGRA.9.6](#LGRA-9-6), [LIMP.2.1.4](#LIMP-2-1-4), [LIMP.2.1.7](#LIMP-2-1-7), [LIMP.3.3.4](#LIMP-3-3-4), [LREG.4.6](#LREG-4-6)

(LGRA-23)=
## Service declarations [LGRA.23]

The syntax of a `service` declaration. What a declaration makes callable and how a
`call` resolves to one is [LADP.8].

*see also:* [LADP.8](#LADP-8)

(LGRA-23-1)=
[LGRA.23.1] Service productions:

```
service_decl    ::= 'service' service_name ':' NEWLINE
                    INDENT
                        docstring?
                        kwarg_decl*
                        response_decl
                    DEDENT

service_name    ::= NAME ('.' NAME)*

kwarg_decl      ::= 'kwarg' NAME ':' TYPE_SYM kwarg_modifier* NEWLINE
kwarg_modifier  ::= 'default' '-'? literal
                 |  'literal'
                 |  'required'

response_decl   ::= 'response' TYPE_SYM NEWLINE
                 |  'no' 'response' NEWLINE
```

*ratified*

(LGRA-23-2)=
[LGRA.23.2] **Residue the grammar does not carry ([STYL.2.15.4]).**

- **Modifiers are unordered.** A `kwarg_decl`'s modifiers may be written in any
  order; each may appear at most once, and the compiler must reject a repeated
  one (`DS_PARSE_KWARG_MODIFIER_DUPLICATE`).
- **Kwargs are unordered at the source and sorted in the artefact.** A
  service's `kwarg_decl`s may be written in any order. The compiler must emit
  them sorted by name, as it emits a call's kwargs ([RLOW.7.3.1]), so the
  artefact does not depend on the order the author wrote.
- **A `default` must fit the kwarg's declared type**, and the compiler must
  reject one that does not (`DS_VALIDATE_SERVICE_KWARG_DEFAULT_TYPE`):
  - a unit-typed kwarg takes a quantity in the unit's dimension. Where that
    dimension declares `storage int64` ([LUNI.7.2]), the quantity must also
    be a whole number of the kwarg's unit: `120 s` on a `min` kwarg is `2`,
    and `90 s` is refused;
  - a dimension-typed kwarg ([LUNI.7.1]) takes a quantity in that dimension;
  - an `Int`, `Float`, `String` or `Bool` kwarg takes a literal of its type,
    and a `Float` kwarg takes an `Int` literal too;
  - a kwarg of any other builtin type — `Bytes`, `Date`, `Duration`,
    `Interval`, `Json` or `Time` — takes no `default`;
  - a kwarg declared with a schema or with the kind `Schema` takes no
    `default` at all, because no literal has a schema type;
  - a kwarg declared with an opaque type takes no `default`, because no
    literal has an opaque type ([LOPQ.3.3]).

  A `-` before the literal is admitted only before a number or a unit
  literal. Before any other literal the compiler must reject it
  (`DS_VALIDATE_SERVICE_KWARG_DEFAULT_TYPE`). A negated unit literal has the
  value [LUNI.3.3] gives it: the literal's number is negated, then converted.

  What the service receives, from a `default` and from a written argument
  alike, is [LADP.8.5.2]. The meaning of `default`, and of `literal` and
  `required`, is [LADP.8.5.1].
- **`TYPE_SYM` in a `kwarg_decl` resolves in the type namespace** ([LGRA.22.7]):
  a scalar builtin, a unit symbol, a dimension or scalar-group name
  ([LUNI.7.1]), a schema, the kind `Schema`, or an opaque type ([LOPQ.3.2]),
  which an argument must match exactly. The compiler must refuse one
  that resolves to none of these, as it refuses a slot's
  (`DS_VALIDATE_UNKNOWN_TYPE`, [LGRA.5.7.1]), and checks no `default` against
  it. A kwarg declared with a schema or with `Schema` takes only a pattern
  binding ([LADP.8.6.1]); the compiler must reject any other argument
  (`DS_VALIDATE_FACT_KWARG_NOT_BINDING`).
- **Every `service_decl` declares its response, as its last line.** The
  grammar makes `response_decl` required; the compiler must reject a
  declaration without one (`DS_VALIDATE_SERVICE_NO_RESPONSE_DECL`), naming the
  two forms. Its meaning is [LADP.8.4.2].
- **`TYPE_SYM` in a `response_decl` resolves to a schema**: a response is a
  fact, so a scalar, a unit symbol or the kind `Schema` there is a compile
  error (`DS_VALIDATE_SERVICE_RESPONSE_NOT_SCHEMA`). The schema it names must
  meet [LCRS.4.3.2].

*ratified*  —  *see also:* [LADP.8.4.2](#LADP-8-4-2), [LADP.8.5.1](#LADP-8-5-1), [LADP.8.5.2](#LADP-8-5-2), [LADP.8.6.1](#LADP-8-6-1), [LCRS.4.3.2](#LCRS-4-3-2), [LGRA.22.7](#LGRA-22-7), [LGRA.5.7.1](#LGRA-5-7-1), [LOPQ.3.2](#LOPQ-3-2), [LOPQ.3.3](#LOPQ-3-3), [LUNI.3.3](#LUNI-3-3), [LUNI.7.1](#LUNI-7-1), [LUNI.7.2](#LUNI-7-2), [RLOW.7.3.1](#RLOW-7-3-1)

(LGRA-24)=
## The initial block [LGRA.24]

A ruleset declares its own starting state: facts in working memory and keys in
the cache, in place before any rule is evaluated. It is policy, so it travels
in the artefact with the rules that read it.

(LGRA-24-1)=
[LGRA.24.1] **Production.** The block is a top-level declaration ([LGRA.3.1]),
and its items are the `.dstest` `initial` items ([LGRA.21.1]): one grammar for
both.

```
initial_block ::= 'initial' ':' INDENT test_initial_item+ DEDENT
```

*see also:* [LGRA.21.1](#LGRA-21-1), [LGRA.3.1](#LGRA-3-1)

(LGRA-24-2)=
[LGRA.24.2] **What the production does not carry ([STYL.2.15.4]).**

- **Placement.** A file holds at most one `initial_block`, before every
  `rule_decl` in it. Any file may hold one, a library included. The compiler
  **must** reject a second block in a file, or a block after a rule, with
  `DS_VALIDATE_INITIAL_PLACEMENT`.
- **Scope.** Every fact item constructs a fact of a `scope explicit` schema
  ([LSCP.2.1]). The compiler **must** reject a fact of any other scope with
  `DS_VALIDATE_INITIAL_BAD_SCOPE`. A `logical` fact lives only while an
  activation justifies it, an `activation` fact only inside a rule's action
  list, and an `ambient` or `internal` fact only from its adapter or the engine.
- **Values.** A fact item is a construction ([LTSL.4.1]): every author-supplied
  slot given, each value a literal or the name of a `const` ([LGRA.4]) as
  [LTSL.4.1] admits them, so a `const` holding a `Time` or a `Date` is none. A
  cache item's value is the same. The compiler **must** reject any other value with
  `DS_VALIDATE_INITIAL_NOT_CONST`.
- **Dialects.** The block is a declaration, not a rule action, so no dialect
  gates it or its cache items ([NDLC.3.2]).

*ratified*  —  *see also:* [LGRA.4](#LGRA-4), [LSCP.2.1](#LSCP-2-1), [LTSL.4.1](#LTSL-4-1), [NDLC.3.2](#NDLC-3-2)

(LGRA-24-3)=
[LGRA.24.3] **Application.** After the engine loads an artefact, it **must**
apply every item of the artefact's `initial` blocks at its first step: the first
time it consumes an input or begins a pump ([LTIM.2.8.4]). It applies them under
that step's sample, before it consumes the step's input and before it evaluates
any rule, so no rule sees the starting state half built:

- within a file, in source order;
- across files, a file's block after the blocks of the files it imports, in the
  import-DAG order of [LDET.5.4], leaf libraries first. So an importer's cache
  item overwrites a library's for the same key.

Between the load and the first step, working memory and the cache hold none of
the block's items.

A fact item enters working memory with no `ts` of its own: its
entry stamp is the step's monotonic sample ([LTIM.2.8.6]), and its `ts`, where
its schema declares one, is the step's wall sample ([LFAC.9.2]). A cache item
seeds the key as the host's cache seed does ([NLFC.9.1]): it raises no cache
event and calls no write-through. It overwrites the value an earlier item of the
same application placed, but **a key the host seeded before the block applies keeps
the host's value**: the engine **must not** overwrite it with a cache item.

Applying the block records nothing in a fact stream: no item has a `FactAssert`,
an `event_id` or a `seq`. The step's sample is recorded as every sample is
([LTIM.2.8.5]). The artefact carries the block, and a replay against the same
artefact applies it at the replay's first step, under the recorded sample.

**A fault an item raises is recorded after the step's input.** A fact item whose `ts` the wall clock cannot fill is not
placed, and its `ComputationError` ([LTIM.2.8.3]) is recorded after the step's
sample and its input ([RARC.5.8.10]): the `FactAssert`, or a pump's
`PumpBoundary` ([RFCS.22]), as a bounds refusal below is. A replayer that
delivers the input re-derives the fault after it, and compares it.

**A bounds refusal refuses the step** ([LERR.1.5]). Where applying an item
would exceed a declared cap, the engine **must** apply none of the block and
none of the step's input, and evaluate no rule. The call that made the step
returns `DS_ERR_CONTRACT_BREACH`, and the engine records the step as it records
a refused assert ([RFCS.6.7]): its input, then the `BoundsError`. A pump's input
is its `PumpBoundary` ([RFCS.22]), so a refused pump records that boundary, then
the `BoundsError`, and fires no rule. A replayer meeting the boundary performs
the pump, which the engine refuses again, and compares the re-derived
`BoundsError` ([RFCS.6.7]). A refused step whose input is an external delivery
([NCBK.10.4]) records its sample and nothing else, because a stream holds only
the `ExternalAssert`s the engine admitted ([RFCS.24.1]); a replay therefore
never meets that refusal. The block stays pending, and the next step applies
it from its first item.

**Under a `.dstest`,** the test's own `initial` ([LTSL.5]) overlays the
ruleset's blocks. Its cache entries are host seeds made before the first step, so a
cache item for one of those keys leaves the test's value in place; its facts are host asserts, the first of
which is the first step, so the block applies ahead of them.

*ratified*  —  *see also:* [LDET.5.4](#LDET-5-4), [LERR.1.5](#LERR-1-5), [LFAC.9.2](#LFAC-9-2), [LTIM.2.8.3](#LTIM-2-8-3), [LTIM.2.8.4](#LTIM-2-8-4), [LTIM.2.8.5](#LTIM-2-8-5), [LTIM.2.8.6](#LTIM-2-8-6), [LTSL.5](#LTSL-5), [NCBK.10.4](#NCBK-10-4), [NLFC.9.1](#NLFC-9-1), [RARC.5.8.10](#RARC-5-8-10), [RFCS.22](#RFCS-22), [RFCS.24.1](#RFCS-24-1), [RFCS.6.7](#RFCS-6-7)

(LGRA-10-6)=
[LGRA.10.6] **A payload kwarg may take a dynamic expression.** On `call`, a
user-declared kwarg ([LGRA.10.3.3]) — a kwarg the resolved service declares —
admits any expression the action's context allows, not only a literal. A kwarg
declared with a schema or with `Schema` takes a pattern binding instead
([LADP.8.6.1]).

A `call`'s correlation is not a kwarg. It is the trailing `as <expr>` clause
([LRST.1.1]), and it is an expression too.

*ratified*  —  *see also:* [LADP.8.6.1](#LADP-8-6-1), [LGRA.10.3.3](#LGRA-10-3-3), [LRST.1.1](#LRST-1-1)

(LGRA-10-7)=
[LGRA.10.7] **A service may require a literal.** A service declaration may mark
one of its kwargs `literal`. At a `call` of that service, the value given for
such a kwarg must be a literal, and the compiler must refuse anything else with
`DS_VALIDATE_DYNAMIC_IDENT_KWARG`, naming the kwarg and the service. A literal
here is an `INT_LIT`, `FLOAT_LIT` or `UNIT_LIT`, which may be preceded by `-`
as a kwarg's `default` may ([LGRA.23.1]); a `BOOL_LIT`; or a `STRING_LIT` with
no interpolation site ([LGRA.2.9.6]), since a site is rendered at the firing.
The call's other kwargs keep [LGRA.10.6]'s freedom.

*ratified*  —  *see also:* [LGRA.10.6](#LGRA-10-6), [LGRA.2.9.6](#LGRA-2-9-6), [LGRA.23.1](#LGRA-23-1)

(LGRA-10-8)=
[LGRA.10.8] **An action's indented block.** An `emit`, `publish` or `call`
action may continue on indented lines under its head line. No other action
may: under `log`, `cache`, `cache_delete` or `withdraw` an indented block is a
syntax error, and the compiler must refuse it.

```
action_block    ::= INDENT block_line+ DEDENT

block_line      ::= action_arg+ NEWLINE                 # emit, publish, call
                 |  call_as NEWLINE                     # call only ([LGRA.10.1])
                 |  continuation                        # call only ([LCCO.2.1])
```

`action_block` follows [LGRA.10.1]'s `action` and `call_action` productions,
whose head line may carry arguments of its own.

What the productions do not say:

- Argument lines and continuations may come in any order.
- A `call` holds at most one `as`, its correlation ([LRST.1.1]): one `as` line
  in its block, or the `call_as` on its head line, and not both. After an `as`
  line the block holds only continuations ([LCRS.6.2.3]).
- **The block is layout and nothing else**, as [LGRA.6.7.4] says of `let`. The
  compiler must compile an action whose arguments are spread over block lines
  exactly as the action with the same arguments, in the order they are
  written, head line first, all on its head line; and an `as` line exactly as
  the same `as` clause at the end of the head line. Interleaving argument lines
  with continuations changes neither the arguments nor the continuations'
  order.

*ratified*  —  *see also:* [LCCO.2.1](#LCCO-2-1), [LCRS.6.2.3](#LCRS-6-2-3), [LGRA.10.1](#LGRA-10-1), [LGRA.6.7.4](#LGRA-6-7-4), [LRST.1.1](#LRST-1-1)

