# Nurun IR

Nurun's programmable layer is a small typed expression language. It mirrors the
Core expression layer of [`../../song`](../../song) — `module`, `defn`, `let`,
`if`, application and checked integer builtins — instead of depending on
`song-bootstrap`. Song's Rust is temporary, its Core evaluator is private, and
the Song tree is moving to Iota. Nurun's mirror is self-contained and can be
extracted on its own.

The tensor IR is a separate language with its own evaluator; see
[compute.md](compute.md). This is not a mirror of the tri-cell artifact codec
or of the Iota term language. It is the expression layer that `song/src/core/geometry.core` is
written in, reduced to the subset a shader needs.

## Grammar

```text
module  ::= (module name defn*)
defn    ::= (defn name (param*) Type expr)
param   ::= (name Type)
Type    ::= Int | Bool | Cell | Face

expr    ::= integer
          | true | false
          | name
          | (if expr expr expr)
          | (let ((name expr)*) expr)
          | (name expr*)
```

`integer` is a decimal `i64` literal, with an optional `-` or `+` sign. A
module must define `main`; its parameters are the arguments to `Program::run`.
Function and parameter names start with an ASCII letter or `_` and continue
with letters, digits, `_` or `-`. Reserved words and builtin names cannot be
function names.

There are no comments, strings, lists, `data`, `match`, `lambda`, `Text`,
`Word` or `Option` in v0. Each is rejected with a named diagnostic rather than
silently ignored.

## Types and values

| type | value | representation |
|---|---|---|
| `Int` | checked 64-bit integer | `i64` |
| `Bool` | boolean | `bool` |
| `Cell` | `a + b·x` over `i64` | `apeiron::Cell<i64>` |
| `Face` | trichotomy face | `apeiron::Sigma` |

`Value` is `Copy`. The evaluator never allocates a value, and the compiled
arena has no names: a call is a function index and a variable is a frame slot.

## Builtins

| name | signature | semantics |
|---|---|---|
| `+` `-` `*` | `Int Int -> Int` | checked; overflow faults |
| `/` `%` | `Int Int -> Int` | zero divisor faults; `i64::MIN / -1` faults |
| `min` `max` | `Int Int -> Int` | total |
| `abs` | `Int -> Int` | `i64::MIN` faults |
| `bit-and` `bit-or` `bit-xor` | `Int Int -> Int` | two's-complement bits |
| `bit-shl` `bit-shr` | `Int Int -> Int` | logical over the 64-bit pattern; count 0..63 |
| `<` `<=` `>` `>=` | `Int Int -> Bool` | signed comparison |
| `=` | `T T -> Bool` | structural equality for one `T` |
| `and` `or` | `Bool Bool -> Bool` | strict; both arguments are evaluated |
| `not` | `Bool -> Bool` | |
| `classify` | `Int -> Face` | sign to `Elliptic`/`Parabolic`/`Hyperbolic` |
| `face` | `Int -> Face` | accepts only `-1`, `0`, `1` |
| `face-value` | `Face -> Int` | `-1`, `0`, `1` |
| `face-channels` | `Face -> Int` | `0`, `1`, `2` |
| `face-discards` | `Face -> Bool` | true only for `Hyperbolic` |
| `cell` | `Int Int -> Cell` | `(a, b)` |
| `cell-a` `cell-b` | `Cell -> Int` | slots |
| `cell-mul` | `Cell Cell -> Cell` | `Cell::checked_mul` with the program dial |
| `cell-norm` | `Cell -> Int` | checked `a² − σb²` |
| `cell-upper` `cell-lower` | `Cell -> Int` | checked `a + b` / `a - b`; Hyperbolic only, otherwise a fault |
| `cell-base` | `Cell -> Int` | Parabolic only; otherwise a fault |

`cell-norm`, `cell-upper` and `cell-lower` compute their formula with checked
arithmetic because Apeiron's `norm_form`, `upper` and `lower` are `Ring`
operations that wrap. They agree with Apeiron when neither overflows; on
overflow they fault instead of wrapping. `cell-base` reads `Cell::channel`,
which has no arithmetic to check.

Function arguments are evaluated left to right. `let` bindings are sequential
and may shadow. `if` evaluates only the selected branch. `and` and `or` are
strict, matching Song's host evaluator.

## Faults

A run returns a `Value` or a `Fault`.

| fault | cause |
|---|---|
| `Fuel` | the call budget is exhausted |
| `Depth` | the nested-call budget is exhausted |
| `Overflow` | checked `i64` arithmetic overflowed |
| `DivisionByZero` | `/` or `%` had a zero divisor |
| `Shift` | a shift count was outside `0..64` |
| `InvalidFace` | `face` received a code outside `-1, 0, 1` |
| `NoChannel` | `cell-upper`, `cell-lower` or `cell-base` on a face without it |
| `Arity` `Type` | `run` was given the wrong argument count or type |
| `InvalidNode` `InvalidSlot` `InvalidFunction` | a malformed arena |

The last row is unreachable through `Program::compile` because the arena fields
are private and the checker validates every reference. It is reported rather
than indexed blindly so the evaluator is total even over a corrupt program.

`DEFAULT_FUEL` is 100,000 calls and `MAX_CALL_DEPTH` is 256. A recursive shader
that exceeds either returns a fault; it does not hang or overflow the host
stack.

## The coverage shader

`crates/nurun/shaders/coverage.core` implements the same predicate as
`geom::Triangle::covers`:

```text
area2(a, b, p) = (b.x - a.x)(p.y - a.y) - (b.y - a.y)(p.x - a.x)
winding        = sign(area2(a, b, c))
covered        = winding != 0
                 and (sign(area2(a, b, p)) == winding or == 0)
                 and (sign(area2(b, c, p)) == winding or == 0)
                 and (sign(area2(c, a, p)) == winding or == 0)
```

The test runs five triangles over a grid of points and compares every result
with the Rust primitive. A second test passes coordinates near `i32::MIN` and
`i32::MAX`: the primitive returns `None` on overflow and the shader returns
`Fault::Overflow`. The shader's domain is the same as the primitive's: integer
inputs whose products fit `i64`.

## The spin shader

`shaders/spin.core` takes a center, a radius, and cos/sin scaled by `2^16`, and
returns the rotated point as a `Cell`. The demo evaluates it three times per
frame; the test pins 0°, 90° and 180°. Its domain is the host's: `r * c` and
`r * s` must fit `i64`, which screen-sized values do.

## Differences from Song Core

| Song host | Nurun |
|---|---|
| `Int` is checked `i128` | checked `i64` |
| depth 4096 | depth 256 |
| `data`, `match`, `Text`, lists, `Word`, `Option` | not in v0 |
| Cell is `data Cell (Cell Int Int)` in `geometry.core` | `Cell` is Apeiron's `Cell<i64>`, first-class |
| constructs `Channels` variants | `cell-upper`/`cell-lower`/`cell-base` return `Int` or fault |
| many functions per module | one `main` per compiled program |
| parser records cell offsets | parser records byte offsets |

The cell and face builtins are deliberate additions: the algebra is the reason
Nurun exists, so it is a type in the IR rather than an encoding of two `Int`s.

## Verification boundary

The front end is untrusted. It parses text, resolves names, checks types and
lowers to the arena. The evaluator over the arena is the body to extract with
Aeneas/Charon, together with the checked arithmetic and the `Cell<i64>` calls.

To claim `proved` for the IR, three artifacts are needed:

1. canonical Lean definitions of values, the checked operations, the face
   channels and the fuel/depth step relation;
2. extraction of the real evaluator body from this crate, with no restated
   formula in a wrapper;
3. a refinement theorem from the extracted evaluator to the canonical
   semantics, for programs produced by the checker, with every axiom within
   `propext`, `Classical.choice` and `Quot.sound`.

Type preservation of `compile` is a separate obligation: the evaluator assumes
that a `Call` has the callee's arity and that a `Local` is inside the frame.
The checker establishes both, but that theorem is not written yet.

The GPU lowering will be tested against the CPU interpreter. It will not be
proved equivalent to it, and the kernel ABI, driver, firmware and GPU are
outside every claim here.

## Not covered

- rustc and LLVM code generation;
- the kernel ABI and any GPU driver or hardware;
- any `unsafe` container (this crate forbids `unsafe_code`);
- the parser, checker and compiler beyond their tests;
- performance. No timing claim exists.
