---
name: lex
description: Write, format, lint, check, and evaluate Lex expressions and pure declarative .lex files (records, physical units, strict with overrides, pattern matching, pipelines, lexicons, described metadata, and pins.lex).
---

# Lex

Lex is a typed, lazy expression and declaration language with one grammar, one parser, and one bytecode VM serving two closed evaluation modes:

- **`console` mode** (single lines up to 4096 bytes): eager left-to-right evaluation, supports top-level `name = expr` assignment and host commands with effects.
- **`declaration` mode** (`.lex` files up to 16 MiB): lazy thunk graph, multi-line layout with trailing commas, refuses top-level assignment and all effects (`Effect_Refused`).

## Quick Start and CLI

```bash
lex eval file.lex [field_path] [--json]
lex eval -e '1 MiB + 512 KiB'
lex fmt file.lex
lex fmt --check file.lex
lex lint file.lex
lex check file.lex
lex version
```

Project automation (`nix develop`):

```bash
odin run tools/lextool -collection:lex=src -- check
odin run tools/lextool -collection:lex=src -- build
odin run tools/lextool -collection:lex=src -- test
odin run tools/lextool -collection:lex=src -- docs_verify
odin run tools/lextool -collection:lex=src -- site
odin run tools/lextool -collection:lex=src -- ci
```

## Syntax and Core Rules

- **Comments:** `//` to end of line only. No block comments.
- **Reserved words (10):** `_`, `let`, `in`, `with`, `if`, `then`, `else`, `true`, `false`, `match`.
- **Numbers:** signed 64-bit integers with overflow checks (no wrapping). Minimum literal: `-9223372036854775807 - 1`.
- **Physical units:** size units `bytes`, `KiB`, `pages` (4096 bytes), `MiB`, `blocks`; duration units `ns`, `us`, `ms`, `s`.
  - Compatible units in one family convert to the finer unit (`1 MiB + 512 KiB` -> `1536 KiB`, `1 s - 250 ms` -> `750 ms`).
  - Mixing incompatible families (`64 MiB + 1`, `1 MiB + 1 ms`, `1 pages + 1 blocks`) refuses with `Unit_Mismatch`.
- **Booleans:** `true`, `false`. `if`, `&&`, `||`, `!` require `Boolean` strictly; integers never coerce.
- **Text:** double-quoted UTF-8, escapes `\\`, `\"`, `\$`, `\u{XXXXXX}`, interpolation `"${expr}"`.
- **Hashes:** `blake3:<64 lowercase hex digits>`. Uppercase hex refuses with `Hash_Not_Valid`.
- **Enums & flag sets:** `.Member`, `.Read | .Write` (`|` binds tighter than arithmetic; duplicates refuse with `Set_Member_Twice`).
- **Lists:** `[1, 2, 3]`, concatenate with `++`.
- **Strict overrides (`with`):** `base with { net.port = 5010 }` checks every path against `base`'s shape before forcing values; unknown fields refuse with `Field_Unknown`. Use `extend(base, extra)` or `merge_deep(base, extra)` to add new fields.
- **Record destructuring:** `let { host, port = 8080, ... } = cfg in ...` is strict by default unless `...` is present.
- **Pattern matching:** `match v { { mode = .Verify, port = p, ... } if p > 1024 => p, _ => 8080 }`. Unmatched values refuse with `No_Matching_Arm`.
- **Safe field fallback (`??`):** `cfg.net.port ?? 8080` evaluates the right-hand side lazily only when a field in the left selection chain is absent. Lex has no `null`.
- **Pipelines (`|>`):** `x |> f(a, _, b)` passes `x` to the first argument or the explicit `_` placeholder.

## Verified Examples

<!-- lex-expect: "cache.modus.systems:5010 (66048 KiB)" -->
```lex
let
  base = { net = { host = "cache.modus.systems", port = 8080 }, mem = 64 MiB },
  cfg  = base with { net.port = 5010, mem = base.mem + 512 KiB }
in
  "${cfg.net.host}:${cfg.net.port} (${cfg.mem})"
```

<!-- lex-expect: { count = 2, total = 35 } -->
```lex
let
  nums = [1, 2, 3, 4] |> filter((x) => x > 2) |> map((x) => x * 5)
in
  { count = len(nums), total = fold(nums, 0, (a, b) => a + b) }
```

<!-- lex-expect: 42 -->
```lex
let
  fallback_port = ({ net = {} }).net.port ?? 42
in
  assert(fallback_port > 0, "positive", fallback_port)
```

<!-- lex-expect-json: {"host":"cache.modus.systems","memory":{"$integer":"64","$unit":"MiB"}} -->
```lex
{ host = "cache.modus.systems", memory = 64 MiB }
```

## Pure Standard Library (26 Built-ins)

All 26 functions work identically in console and declaration modes:

- **Lists (12):** `map(list, fn)`, `filter(list, pred)`, `fold(list, init, fn)`, `zip(a, b)`, `len(list_or_text)`, `at(list, idx)`, `slice(list, start, end)`, `any(list, pred)`, `all(list, pred)`, `flat_map(list, fn)`, `unique(list)`, `sort_by(list, key_fn)`.
- **Records (6):** `fields(rec)`, `values(rec)`, `has(rec, name)`, `extend(a, b)`, `merge_deep(a, b)`, `from_entries(list)`.
- **Text (6):** `split(text, sep)`, `join_text(list, sep)`, `starts_with(text, prefix)`, `ends_with(text, suffix)`, `contains(text, needle)`, `replace_text(text, old, new)`.
- **Diagnostics (2):** `assert(cond, msg, value)`, `trace(msg, value)`.

## Declarations, Metadata, and Pins

- `lexicon { about = "...", license = "MIT", source = here(), inputs = { ... }, outputs = { ... } }`
- `plan { ... }`
- `described(value, { about = "...", license = "MIT", subjects = .Storage, keywords = ["cache"] })`: transparent to consumers, stripped before recipe hashing, replaced whole when nested, dropped on `with`.
- `pins.lex`: canonical sorted `{ name = { address = "...", commit = "...", tree = blake3:... } }` record (or `{}` when a lexicon has no inputs).

## Common Mistakes to Avoid

1. **Using `with` to add a new key:** `with` is strict override-only; use `extend(base, extra)` or `merge_deep(base, extra)`.
2. **Mixing units and bare integers:** write `64 MiB + 16 MiB`, never `64 MiB + 16`.
3. **Treating integers as booleans:** write `if n != 0 then a else b`, never `if n then a else b`.
4. **Using `==` or block comments:** equality is `=`; comments use `//` only.
5. **Top-level assignment in `.lex` files:** use `let x = 1 in ...` instead of `x = 1` in declaration mode.
6. **Using wrong stdlib names:** use `len`, `join_text`, and `replace_text` (not `length`, `join`, or `replace`).

## Documentation Index

- Home: [https://lex.modus.systems/](https://lex.modus.systems/)
- Language Reference: [https://lex.modus.systems/language/](https://lex.modus.systems/language/)
- Standard Library & Units: [https://lex.modus.systems/stdlib/](https://lex.modus.systems/stdlib/)
- Declarations & Metadata: [https://lex.modus.systems/declarations/](https://lex.modus.systems/declarations/)
- Formatting & Linting: [https://lex.modus.systems/tools/](https://lex.modus.systems/tools/)
- CLI & Embedding: [https://lex.modus.systems/cli/](https://lex.modus.systems/cli/)
- Sources & Credits: [https://lex.modus.systems/sources.html](https://lex.modus.systems/sources.html)
