vera-language
Write programs in the Vera programming language. Use when asked to write, edit, debug, or review Vera code (.vera files). Vera is a statically typed, purely functional language with algebraic effects, mandatory contracts, and typed slot references (`@T.n`) instead of variable names.
Safety scan
A static text scan, not a guarantee. Select the badge to see what was scanned and every finding.
Check it deeper on your machine
It has changed since its scan on 14 Nov 2026. Its scripts were only partly scanned.
As a Claude Code plugin, install it and then ask Claude Code:
/plugin marketplace add keithmackay/mackayi/plugin install scanskillsafety@mackayiDo a deep scan of https://github.com/aallan/vera with scanskillsafety
Or from a terminal, clone it and run it:
git clone https://github.com/keithmackay/scanskillsafety-skill ~/.claude/skills/scanskillsafetynode ~/.claude/skills/scanskillsafety/cli.cjs --deep 'https://github.com/aallan/vera'
It checks the exact commit: every file, its packages against OSV (api.osv.dev), how it compares with this page's scan (findsafeskills.com receives the repository's address), and, if you agree, Claude reading every file with your own Claude subscription. It never runs the code.
Badge for your README
Markdown
[](/listings/aallan--vera)HTML
<a href="/listings/aallan--vera"><img src="/api/listings/aallan--vera/badge.svg" alt="findsafeskills safety rating" /></a>Install
Install instructions from the README
As written by the repo's author. findsafeskills has not verified these steps.
Prerequisites
- Python 3.11+ - Git - Node.js 22+ *(optional, for browser runtime and parity tests)*
Installation
Install the released `veralang` distribution from PyPI:
python -m venv .venv source .venv/bin/activate # Windows: .venv\Scripts\activate python -m pip install veralang
The distribution is named `veralang`, but the installed command is `vera`, and Python code imports it as `import vera`. For editor and agent integration through the language server, install `python -m pip install "veralang[lsp]"`. Do not run `pip install vera`: that name belongs to an unrelated project on PyPI. The wheel ships the compiler and the `vera` command only; the bundled `examples/`, the conformance suite, and the specification live in the repository, not in the wheel.
**Upgrading to 0.2.0:** the checker and verifier are stricter than in 0.1.x, so 0.2.0 refuses some programs 0.1.13 accepted. The most common are a recursive function with neither `decreases` nor `Diverge` (`E137`), a `decreases` measure whose `@Nat` subtraction can underflow, such as the count-up `@Nat.1 - @Nat.0 + 1` (`E502`), or a name, type or effect the checker cannot resolve, which is an error rather than a warning. The [CHANGELOG](CHANGELOG.md) lists each new check.
The GitHub source route is the recommended environment for agents and for anyone learning the language. It provides the examples, conformance programs, and spec that [SKILL.md](SKILL.md) teaches from, alongside the toolchain, and it is the route for compiler development, unreleased changes, and testing the current `main` branch:
git clone https://github.com/aallan/vera.git cd vera python -m venv .venv source .venv/bin/activate # Windows: .venv\Scripts\activate python -m pip install -e ".[dev]"
`[dev]` includes everything (tests, linters, the language server). For a lighter source install that only adds editor/agent support to the base toolchain, use `python -m pip install -e ".[lsp]"` (see [LSP_SERVER.md](LSP_SERVER.md)).
Supported platforms
CI tests every pull request on Ubuntu x86_64 and Windows against Python 3.12, and every release, the pull request that raises the version, and main every night on:
- **macOS 15 (Sequoia) and macOS 26 (Tahoe)** on Apple Silicon, against Python 3.11, 3.12, 3.13 - **Ubuntu 24.04 LTS** on x86_64, against Python 3.11, 3.12, 3.13 - **Ubuntu 24.04 LTS** on aarch64, against Python 3.12 (an advisory job, which does not gate merges) - **Windows Server 2025** on x86_64, against Python 3.11, 3.12, 3.13
These are the supported images, pinned by name in every job that gates a merge or a release, so a label GitHub moves to a new OS release changes none of them; the nightly run also watches the floating `ubuntu-latest`, `windows-latest` and `macos-latest` labels and Ubuntu 26.04 under Python 3.12, advisory as the aarch64 cell is: a failed watched cell on a scheduled nightly run files an issue and blocks nothing.
Not tested in CI; every dependency publishes wheels for them:
- Linux x86_64 with glibc 2.27+ (Ubuntu 18.04+ / Debian 10+ / RHEL 8+) - Linux aarch64 with glibc 2.38+ on Python 3.11 / 3.13 (the 3.12 cell is CI-tested above; e.g. Ubuntu 23.10+) - macOS 15+ on Intel (x86_64)
Out of scope, neither supported nor tested in CI. Where no z3-solver wheel matches, `pip install -e .` builds z3-solver from source, and `pip install --only-binary :all: -e .` stops at a "no matching distribution" error instead:
- **macOS 14 (Sonoma) and earlier.** z3-solver's 5.x wheels are tagged `macosx_13_0`, so on macOS 13 and 14 every dependency resolves to a wheel; CI tests neither, and both are unsupported. macOS 12 and earlier match no z3-solver wheel. See [#691](https://github.com/aallan/vera/issues/691) for the decision and workarounds - **Linux aarch64 with glibc < 2.38** (for example Ubuntu 22.04 LTS aarch64); see [#701](https://github.com/aallan/vera/issues/701)
What was scanned
The files the safety scan read, as written by the repository's author and shown as plain text. Lines with a finding are marked.
SKILL.md · Manifest · 2,697 lines
- ---
- name: vera-language
- description: Write programs in the Vera programming language. Use when asked to write, edit, debug, or review Vera code (.vera files). Vera is a statically typed, purely functional language with algebraic effects, mandatory contracts, and typed slot references (`@T.n`) instead of variable names.
- ---
- # Vera Language Reference
- Vera is a programming language designed for LLMs to write. It uses typed slot references instead of variable names, requires contracts on every function, and makes all effects explicit.
- ## Installation
- Vera requires Python 3.11 or later. Node.js 22+ is optional (only needed for `vera compile --target browser` and browser parity tests).
- **Recommended: install from the GitHub source checkout.** The checkout is the full environment this file teaches from: alongside the compiler and the `vera` CLI it has the bundled `examples/`, the conformance suite in `tests/conformance/` (minimal working programs, named by spec chapter and feature), and the specification in `spec/`:
- ```bash
- git clone https://github.com/aallan/vera.git && cd vera
- python -m venv .venv && source .venv/bin/activate # Windows: .venv\Scripts\activate
- python -m pip install -e .
- ```
- For an editable source install with the language server, use `python -m pip install -e ".[lsp]"`; see [LSP_SERVER.md](LSP_SERVER.md). Verify the install end to end with the bundled example:
- ```bash
- vera check examples/hello_world.vera # prints "OK: examples/hello_world.vera"
- vera run examples/hello_world.vera # prints "Hello, World!"
- ```
- **Toolchain only: install the released `veralang` distribution from PyPI.** This installs the `vera` command and all runtime dependencies (Lark parser, Z3 solver, wasmtime), but **not** the examples, conformance programs, or specification, which exist only in the checkout:
- ```bash
- python -m venv .venv && source .venv/bin/activate # Windows: .venv\Scripts\activate
- python -m pip install veralang
- vera version
- ```
- For the language server on this route, install `python -m pip install "veralang[lsp]"`.
- If you are working on the compiler itself, install development dependencies too:
- ```bash
- python -m pip install -e ".[dev]"
- ```
- > **Platform support**: [README §Supported platforms](README.md#supported-platforms) lists the platforms and Python versions CI tests on, the ones that are out of scope (where install fails at dependency resolution), the workarounds, and the data behind the baseline.
- >
- > **For agents running in a sandbox** (Claude.ai, Code Interpreter, container-based execution environments, etc.): the steps above work. Sandboxes typically have Python, `git`, `pip`, and outbound network access, which is all Vera needs. **Run the install commands and verify with `vera run examples/hello_world.vera` before concluding that Vera "isn't available." Do not assume the sandbox lacks the toolchain; try it.**
- >
- > `pip install vera` installs a *different* package from PyPI (an ERAV citizen-science library, unrelated to this Vera). Use the `veralang` distribution or the GitHub source clone shown above; both install the `vera` command.
- ## Toolchain
- See [TOOLCHAIN.md](TOOLCHAIN.md) for the CLI cookbook: driving the toolchain to write, verify, test, run, and debug Vera, plus the `builtins`/`effects`/`errors` introspection commands.
- ```bash
- vera check file.vera # Parse and type-check (or "OK")
- vera check --json file.vera # Type-check with JSON diagnostics
- vera check --quiet file.vera # Type-check, suppress success output (errors still shown)
- vera typecheck file.vera # Same as check (explicit alias)
- vera verify file.vera # Type-check and verify contracts via Z3
- vera verify --json file.vera # Verify with JSON diagnostics
- vera verify --quiet file.vera # Verify, suppress success output (errors still shown)
- vera verify --timeout-ms 60000 file.vera # Per-query Z3 budget in ms (default 10000; env VERA_Z3_TIMEOUT_MS)
- vera compile file.vera # Compile to .wasm binary
- vera compile --wat file.vera # Print WAT text (human-readable WASM)
- vera compile --json file.vera # Compile with JSON diagnostics
- vera compile --target browser file.vera # Compile + emit browser bundle (wasm + JS + html)
- vera compile --target wasi-p2 file.vera # Emit a WASI Preview 2 component (IO+Random only)
- vera compile --target wasi-p2 --world server file.vera # wasi:http server component (wasmtime serve)
- vera run file.vera # Compile and execute (calls main)
- vera run file.vera --fn f -- 42 # Call function f with Int argument
- vera run file.vera --fn f -- 3.14 # Call function f with Float64 argument
- vera run file.vera --fn f -- true # Call function f with Bool argument
- vera run file.vera --fn f -- "hello" # Call function f with String argument
- vera run --json file.vera # Run with JSON output
- vera serve file.vera # Serve handle(Request -> Response) over HTTP (default :8000)
- vera serve --port 8080 file.vera # Serve on a specific port
- vera test file.vera # Contract-driven testing via Z3 + WASM
- vera test --json file.vera # Test with JSON output
- vera test --trials 50 file.vera # Limit trials per function (default 100)
- vera test --distrust file.vera # Also execute proved functions; a failed proved check refutes the proof (E703)
- vera test file.vera --fn f # Test a single function
- vera parse file.vera # Print the parse tree
- vera ast file.vera # Print the AST (parse + transform; no type check)
- vera ast --json file.vera # Print the AST as JSON
- vera fmt file.vera # Format to canonical form (stdout)
- vera fmt --write file.vera # Format in place
- vera fmt --check file.vera # Check if already canonical
- vera version # Print the installed version (also --version, -V)
- vera lsp # Serve LSP over stdio: live diagnostics, hover, slot goto,
- # hole completion + agent proof-delta methods (LSP_SERVER.md)
- vera builtins [--json] # List the built-in function registry (no file needed)
- vera effects [--json] # List the effect and ability registry (no file needed)
- vera errors [--json] # List the diagnostic-code registry (no file needed)
- pytest tests/ -v # Run the test suite
- ```
- Errors are natural language instructions explaining what went wrong and how to fix it. Feed them back into your context to correct the code.
- `vera test` generates Z3 inputs for `Int`, `Nat`, `Bool`, `Byte`, `String`, and `Float64` parameters. The decision is made on each parameter's **resolved** type, not its spelling: a type alias or refinement that resolves to one of those six is generated for like any other, so a parameter spelled `@Count` under `type Count = Nat;` is not skipped for its parameter type, and an alias-spelled `requires` still constrains the inputs. (Trials are what a *Tier 3* contract gets; a signature the verifier proves reports `VERIFIED (Tier 1)` instead, unless `vera test --distrust` runs it too, and one with only trivial contracts is skipped as `trivial contracts only`.) A parameter resolving to an ADT or a function type is skipped with a message naming that resolved type: `type MaybeCount = Option<Nat>` skips with `cannot generate Option<Nat> inputs`. A generic function is skipped as `generic function` before its parameter types are considered at all, so a `forall<T>` signature never reports a per-parameter reason even when every parameter is generable. A generable signature is also skipped when a `requires` conjunct, or a refined parameter's predicate, is outside the SMT layer's decidable fragment, since Z3 could not constrain the generated inputs by it; the skip names the conjunct (`cannot generate inputs satisfying `` `string_length(@String.0) > 0` ``), because running trials the precondition never shaped would report the function's own entry-guard trap as a broken contract. `string_length` over a non-literal is the usual trigger (Vera counts UTF-8 bytes and Z3's string theory has no byte-length operator), so compare a `string_length` against a literal where you want the function trialled. Float64 uses Z3's mathematical reals (NaN, ±∞, and subnormals are not generated). Strings are capped at 50 characters.
- ### Browser compilation
- `vera compile --target browser` produces a ready-to-serve browser bundle:
- ```bash
- vera compile --target browser file.vera # Output to file_browser/
- vera compile --target browser file.vera -o dist/ # Output to dist/
- ```
- This generates three files: `module.wasm` (the compiled binary), `runtime.mjs` (self-contained JavaScript runtime with all host bindings), and `index.html` (loads and runs the program). Serve the output directory with any HTTP server (`python -m http.server`) and open `index.html`; ES module imports require HTTP, not `file://`.
- The JavaScript runtime provides browser-appropriate implementations: `IO.print` writes to the page, `IO.read_line` uses `prompt()`, `IO.stderr` captures into a separate buffer, `IO.time` uses `Date.now()`, `IO.sleep` busy-waits (it blocks the main thread, so keep it short in the browser), file IO returns `Result.Err`, and `IO.read_char` returns `Result.Err`, since the browser runtime has no JSPI suspend/resume support. `Http` runs, backed by `XMLHttpRequest`; `Inference` and `DB` return `Err` from every operation, since their credentials would be readable from page source. State, contracts, JSON and Markdown work identically to the Python runtime.
- #### IO model: terminal vs browser
- The two targets differ at the IO boundary, and writing for one target without thinking about the other produces a program that compiles cleanly to both but only *runs* meaningfully on one:
- - **Terminal target** assumes a synchronous IO loop: `IO.sleep(120)` blocks the program for 120 ms, ANSI escape codes (`"\u{1B}[2J\u{1B}[H"` to clear screen + home cursor) drive cursor and colour, and the program drives its own pacing.
- - **Browser target** assumes "Vera = pure simulation core, JS = timing and rendering driver". `IO.sleep` still works numerically but busy-waits on the main thread (freezing the tab); ANSI escape codes render as literal control bytes in the DOM rather than mutating a virtual screen; `IO.print` writes to the page, but the program has no way to *yield* between writes.
- The recommended pattern for browser-targeted Vera programs is to **expose pure update functions** (`@Model, @Input -> @Model`, with `Model` and `Input` data types of your own) that JavaScript drives via `requestAnimationFrame`, with Vera computing the next state and JS handling timing + DOM updates. Two runtime gaps make the pattern harder to use; both are tracked on [#603](https://github.com/aallan/vera/issues/603):
- - implement `IO.sleep` against the WebAssembly JavaScript Promise Integration (JSPI) proposal so the WASM call suspends on `setTimeout` instead of busy-waiting.
- - interpret a minimal ANSI escape subset in the browser runtime so terminal-style programs (clear-screen, cursor-home, colour) render unchanged.
- Terminal Vera programs (animation via `IO.sleep` + cursor control via ANSI) need either a terminal target or a separate browser-shaped variant. The design point ("pure core, effects at the boundary") is unchanged; only the boundary differs between targets.
- ### WASI Preview 2 compilation
- `vera compile --target wasi-p2` emits a binary WebAssembly *component* that runs under any stock wasip2 host with no Vera bindings: `wasmtime run file.wasm` runs it. The target covers the **IO and Random host families only**; a program using any other host family (Http, Decimal, Json, Html, Md, Regex, Math, Inference, State, Async, DB) is rejected with a diagnostic naming the family. `Map` and `Set` are not host families: the module carries their operations, so both worlds run every instance code generation builds; a `Map` or `Set` with an `Array` key, value or element is refused at check (`E135`). `vera run --target wasi-p2 file.vera` executes the component under the built-in wasip2 host with the usual output/trap reporting. Divergences inherent to WASI 0.2 (exit codes collapse to 0/1; no structured trap frames) are documented in [spec chapter 13](spec/13-wasi.md). `--world server` packages a `handle(Request -> Response)` program (the `<HttpServer>` effect) as a `wasi:http/incoming-handler` component that stock `wasmtime serve` runs. Headers work via in-guest String maps; of the IO operations that world implements `IO.print`, `IO.stderr`, `IO.time` and `IO.sleep`, and rejects stdin (`IO.read_line`, `IO.read_char`), the filesystem (`IO.read_file`, `IO.write_file`, `IO.read_bytes`, `IO.write_bytes`), `IO.args`, `IO.get_env` and `IO.exit` (spec §13.7).
- To run the WASM directly in Node.js:
- ```bash
- node --experimental-wasm-exnref vera/browser/harness.mjs module.wasm
- ```
- ### JSON diagnostics
- Use `--json` on `check` or `verify` for machine-readable output:
- ```json
- {"ok": true, "file": "...", "diagnostics": [], "warnings": []}
- ```
- On error, each diagnostic includes `severity`, `description`, `location` (`file`, `line`, `column`), `source_line`, `rationale`, `fix`, `spec_ref`, and `error_code`. The `verify --json` output also includes a `verification` summary (`tier1_verified`, `tier3_runtime` and `total` counts, `assumptions` (the number of unverified `assume` statements, each a W003), and the `timeout_ms` budget the run used) and an `obligations` array, one entry per obligation with `kind`, `status`, `description`, `location` and, when present, `error_code`. The counts are derived from `status`: `verified` counts as Tier 1, `tier3` and `timeout` as Tier 3, and `violated` and `tier3_unguarded` in neither, since each surfaces as a diagnostic instead.
- ### Error codes
- Every diagnostic has a stable code grouped by compiler phase. Every `W` code is a warning; most `E` codes are errors, and a few are warnings (the Tier 3 notes `E520` to `E525`, and the disclosures `E504`, `E506`, `E539`, `E540`, `E542` and `E543`):
- - **W001**: Typed hole (`?`); reports the expected type and available bindings (warning, not error)
- - **W002**: `async()` argument evaluates eagerly: its effects fall outside the commutative set (`Http`), so the future is computed sequentially at the `async()` site rather than concurrently (warning, not error)
- - **W003**: Unverified assumption: an `assume` statement is taken on trust, not proved (warning, not error)
- - **W004**: `vera verify` found a runtime check in the compiled module that no verification record accounts for: the check still runs, and the summary omits it (warning, not error)
- - **W005**: `vera verify` did not reconcile the runtime checks, because the program holds typed holes and code generation compiles nothing until they are filled (warning, not error)
- - **E001–E009**: Parse errors (missing contracts, unexpected tokens, malformed slot references, bad string escapes)
- - **E011–E013**: Import errors (circular import, unresolvable import, a module that fails to parse)
- - **E020, E021, E023**: Malformed comments: unterminated `{-` (E020) or `/*` (E021), or a `/*` nested inside another (E023; only `{- -}` nests). Each names the delimiter at fault and how to close it.
- - **E024**: A source file that is not UTF-8: the byte that does not decode, its offset, line and column, and the `iconv` command that converts the file to UTF-8 (an imported module's E024 is located in the module)
- - **E030–E032**: Contract syntax: an `old()`/`new()` argument that is not an effect reference (E030, E031), or a contract clause written after `effects` (E032)
- - **E040**: A pipe whose right operand is not a call: `a |> b` needs `b` to be a call with an argument list, such as `a |> f()`
- - **E010**: Transform errors (internal)
- - **E1xx**: Type check: core + expressions (type mismatches, slot resolution, operators, declarations, termination)
- - **E2xx**: Type check: calls (unresolved functions, argument mismatches, module calls, ability operations)
- - **E3xx**: Type check: control flow (if/match, patterns, effect handlers)
- - **E5xx**: Verification (contract violations, undecidable fallbacks, primitive-operation safety incl. arithmetic overflow, premise satisfiability, and E541: a runtime-check claim `vera verify` found no check for in the compiled module)
- - **E6xx**: Codegen (unsupported features, name collisions, typed holes block compilation); **E699** is an internal compiler error
- - **E7xx**: Testing (contract violations, input generation, execution errors, a proof a test run refutes)
- - **E8xx**: Run: a program's own failure while it runs (**E800**, a runtime trap: its `trap_kind`, the source backtrace and the kind's fix)
- - **E9xx**: Command: the command line's own refusals, not a property of the program (a file not found, an option a command does not take or a value it does not accept, a function `--fn` cannot call, arguments that do not fit the function, a port in use, a missing optional dependency, an output path that cannot be written)
- In diagnostic messages, a `?` inside a printed type (`Array<?>`, `Map<String, ?>`) marks a component the checker could not infer. That is a rendering marker for an unknown type, not the typed-hole expression `?` (W001) you write in source.
- Common codes you'll encounter:
- - **W001**: Typed hole: fill `?` with an expression of the stated type
- - **E130**: Unresolved slot reference (`@T.n` has no matching binding)
- - **E121**: Function body type does not match return type
- - **E200**: Unresolved function call
- - **E300**: If condition is not Bool
- - **E001**: Missing contract block (requires/ensures/effects)
- - **E614**: Program contains typed holes; compile rejected until holes are filled
- ## Function Structure
- Every function has this exact structure. No part is optional except `decreases` and `where`. Visibility (`public` or `private`) is mandatory on every top-level `fn` and `data` declaration.
- <!-- vera:skip-parse category="FRAGMENT" reason="Function signature template with @ParamType placeholders" -->
- ```vera
- private fn function_name(@ParamType1, @ParamType2 -> @ReturnType)
- requires(precondition_expression)
- ensures(postcondition_expression)
- decreases(measure_expression)
- effects(effect_row)
- {
- body_expression
- }
- ```
- The order is fixed: every contract clause first (`requires`, `ensures` and `decreases`, in any order among themselves, and each may appear more than once), then exactly one `effects` clause, then the body. A contract clause
- written after `effects` is a parse error (`E032`) naming the move.
- (`invariant` is a `data` declaration's clause, not a function's.)
- Complete example:
- <!-- vera:run fn="safe_divide" args="2 10" stdout="5" -->
- ```vera
- public fn safe_divide(@Int, @Int -> @Int)
- requires(@Int.1 > 0)
- ensures(@Int.result == @Int.0 / @Int.1)
- effects(pure)
- {
- @Int.0 / @Int.1
- }
- ```
- ### Nullary and Unit-taking functions
- Vera accepts two equivalent shapes for functions that take no meaningful argument:
- <!-- vera:run fn="a" stdout="42" -->
- ```vera
- public fn a(-> @Int) requires(true) ensures(true) effects(pure) { 42 }
- public fn b(@Unit -> @Int) requires(true) ensures(true) effects(pure) { 42 }
- ```
- At every call site the arity must match the declaration: `a()` calls the nullary form, `b(())` passes a `Unit` value to the Unit-taking form. They cannot be mixed: `a(())` and `b()` are both type errors. Use the nullary form for constants and computations that have no conceptual input; use the Unit-taking form when you want to match the shape of a combinator that expects a `fn(T -> U)` (the callee side of `apply_fn`, see below). Write `main` as `main(@Unit -> @Unit)` with `effects(<IO>)`, the shape spec §5.11 requires; the toolchain does not enforce it, and runs a `main` of any signature.
- ### Stored function values and `apply_fn`
- Functions passed as arguments or stored in `let` bindings use the type form `fn(T -> U) effects(...)`: plain types, no `@`, and the `effects` clause is required. To invoke such a stored value, use `apply_fn`:
- ```vera
- type IntToInt = fn(Int -> Int) effects(pure);
- private fn use_fn(@IntToInt, @Int -> @Int)
- requires(true) ensures(true) effects(pure)
- {
- apply_fn(@IntToInt.0, @Int.0)
- }
- ```
- `apply_fn(f, x)` is the only way to call a function stored as a value; direct application syntax (`f(x)`) is reserved for declared names. The prelude uses this pattern for `option_map`, `option_and_then`, `result_map` etc., where the mapping function is a parameter. See `examples/closures.vera` and `tests/conformance/ch05_closures.vera` for worked examples.
- ## Function Visibility
- Every top-level `fn` and `data` declaration **must** have an explicit visibility modifier. There is no default visibility -- omitting it is an error.
- - `public` -- the declaration is visible to other modules that import this one. Only `public` functions are exported as WASM entry points (callable via `vera run`). Use for library APIs, exported functions, and program entry points.
- - `private` -- the declaration is only visible within the current file/module. Private functions compile but are not WASM exports. Use for internal helpers.
- <!-- vera:run fn="exported_api" args="3" stdout="3" -->
- ```vera
- public fn exported_api(@Int -> @Int)
- requires(true)
- ensures(true)
- effects(pure)
- {
- @Int.0
- }
- private fn internal_helper(@Int -> @Int)
- requires(true)
- ensures(true)
- effects(pure)
- {
- @Int.0 + 1
- }
- public data Color {
- Red,
- Green,
- Blue
- }
- private data InternalState {
- Ready,
- Done(Int)
- }
- ```
- For generic functions, visibility comes before `forall`:
- ```vera
- private forall<T> fn identity(@T -> @T)
- requires(true)
- ensures(true)
- effects(pure)
- {
- @T.0
- }
- ```
- Visibility does **not** apply to: type aliases (`type Foo = ...`), effect declarations (`effect E { ... }`), module declarations, or import statements. Functions inside `where` blocks also do not take visibility.
- Multiple `requires` and `ensures` clauses are allowed. They are conjunctive (AND'd together):
- ```vera
- private fn clamp_to_range(@Int, @Int, @Int -> @Int)
- requires(@Int.1 <= @Int.0)
- ensures(@Int.result >= @Int.1)
- ensures(@Int.result <= @Int.0)
- effects(pure)
- {
- if @Int.2 < @Int.1 then {
- @Int.1
- } else {
- if @Int.2 > @Int.0 then {
- @Int.0
- } else {
- @Int.2
- }
- }
- }
- ```
- ## Slot References (`@T.n`)
- **De Bruijn slot ordering is the most common source of bugs in Vera programs.** Before writing contracts, `ensures` clauses, or body expressions that involve multiple parameters of the same type, run `vera check --explain-slots` to confirm which index maps to which parameter. Do not rely on intuition.
- Vera has no variable names. Every binding is referenced by type and index. See [`DE_BRUIJN.md`](DE_BRUIJN.md) for the academic background, deeper examples, and the commutative-operations trap.
- ```
- @Type.index
- ```
- - `@` is the slot reference prefix (mandatory)
- - `Type` is the exact type of the binding, starting with uppercase
- - `.index` is the zero-based De Bruijn index (0 = most recent binding of that type)
- ### Parameter ordering
- Parameters bind left-to-right. The **rightmost** parameter of a given type is `@T.0`:
- ```vera
- private fn add(@Int, @Int -> @Int)
- requires(true)
- ensures(@Int.result == @Int.0 + @Int.1)
- effects(pure)
- {
- @Int.0 + @Int.1
- }
- -- @Int.0 = second parameter (rightmost Int)
- -- @Int.1 = first parameter (leftmost Int)
- ```
- ### Mixed types
- Each type has its own index counter:
- ```vera
- private fn repeat(@String, @Int -> @String)
- requires(@Int.0 >= 0)
- ensures(true)
- effects(pure)
- {
- string_repeat(@String.0, @Int.0)
- }
- -- @String.0 = first parameter (only String)
- -- @Int.0 = second parameter (only Int)
- ```
- ### Let bindings push new slots
- ```vera
- private fn example(@Int -> @Int)
- requires(true)
- ensures(true)
- effects(pure)
- {
- let @Int = @Int.0 * 2; -- @Int.0 here refers to the parameter
- let @Int = @Int.0 + 1; -- @Int.0 here refers to the first let (param * 2)
- @Int.0 -- refers to the second let (param * 2 + 1)
- }
- ```
- ### `@T.result`
- Only valid inside `ensures` clauses. Refers to the function's return value:
- ```vera
- private fn absolute(@Int -> @Nat)
- requires(true)
- ensures(@Nat.result >= 0)
- effects(pure)
- {
- if @Int.0 >= 0 then {
- @Int.0
- } else {
- -@Int.0
- }
- }
- ```
- ### Index is mandatory
- `@Int` alone is not a valid reference. Always write `@Int.0`, `@Int.1`, etc.
- ### Debugging slot indices with --explain-slots
- **Always run `vera check --explain-slots` before writing contracts or function calls that
- involve multiple parameters of the same type.** This is the single most reliable way to avoid
- De Bruijn ordering mistakes.
- ```bash
- vera check --explain-slots your_file.vera
- ```
- Output:
- ```text
- Slot environments (index 0 = last occurrence in signature):
- fn divide(@Int, @Int -> @Int)
- @Int.0 parameter 2 (last @Int)
- @Int.1 parameter 1 (first @Int)
- ```
- `where`-block helpers get their own table, indented under their parent:
- ```text
- fn is_even(@Nat -> @Bool)
- @Nat.0 parameter 1 (only @Nat)
- where fn is_odd(@Nat -> @Bool)
- @Nat.0 parameter 1 (only @Nat)
- ```
- **Read this table before writing any contract or recursive call.** The ordering only matters
- when a function has multiple parameters of the same type, and that is when bugs occur.
- Example: for `fn divide(@Int, @Int -> @Int)` with the body `@Int.0 / @Int.1`, the contract `requires(@Int.1 != 0)` guards the *first* parameter (the divisor). Confirm this by checking the table: `@Int.1 = parameter 1
- (first @Int)`.
- **Workflow:**
- 1. Write the function signature.
- 2. Run `vera check --explain-slots` to get the slot table.
- 3. Use the table to write contracts and body expressions with correct `@T.n` indices.
- 4. If `vera check` reports E130 (unresolved slot), read the `Available bindings:` table in its own fix text. It lists the slot bindings in scope *at that reference* with their `@T.n`,
- including the `let` and `match`-arm ones the signature table cannot show. The table renders
- at most twelve rows and then `; … and K more`, so a scope wider than that shows its first
- twelve bindings and names how many it withheld. `@T.result` is not a slot binding, so it
- never appears there, not even inside `ensures`.
- The `--json` flag also works: `vera check --explain-slots --json` emits a `slot_environments`
- array, useful when processing diagnostics programmatically.
- ## Types
- ### Primitive types
- - `Bool`: `true`, `false`
- - `Int`: signed 64-bit integer; `+`, `-`, `*`, `abs` and `INT_MIN / -1` trap on overflow, and each has a verifier obligation (E528). Unary negation has neither ([#1875](https://github.com/aallan/vera/issues/1875)), so `-@Int.0` with `@Int.0` at `INT_MIN` returns `INT_MIN`; write `0 - @Int.0` where the operand can reach it
- - `Nat`: natural number, the non-negative half of the 64-bit `Int` (`0` to `2^63 - 1`)
- - `Float64`: 64-bit IEEE 754 floating-point
- - `Byte`: unsigned 8-bit integer (0–255)
- - `String`: text
- - `Unit`: singleton type, value is `()`. Zero-size and **declaration-only**: a `@Unit` parameter (function or handler-clause op) is legal but reading it (`@Unit.0`) is a checker error (E182), so write the literal `()` instead; and a `let` of a zero-size type (`let @Unit = put(5);`) is a checker error (E183), so call the expression as a statement (`put(5);`). Applies to anything with no runtime representation, including `Future<Unit>`.
- - `Never`: bottom type (used for non-terminating expressions like `throw`)
- **`Int` and `Nat` are interchangeable in both directions.** `@Nat <: @Int` is a formal subtyping rule at the *type* level (use a `@Nat` anywhere `@Int` is expected, no `nat_to_int` call), and `@Int <: @Nat` is permitted by the type checker with a verifier-discharged obligation (`@Int.0 >= 0`). So `array_length` (declared `@Int`) flows into `@Nat` positions without explicit conversion; the verifier proves non-negativity from context or falls back to a runtime check. Only narrowing has a *value*-level obligation: a `@Nat` is the non-negative half of the i64 an `@Int` is, so widening is the identity, and narrowing requires `>= 0` (`E503`/`E504`). Runtime guards and verifier obligations correspond at every closure depth (nested closure returns included). Every `@Int` -> `@Nat` narrowing at a PATTERN BIND or a BOUNDARY is runtime-guarded. One ARGUMENT site is not, and is disclosed instead: `string_slice`, whose `@Nat` index arguments code generation does not guard because the builtin CLAMPS them to `[0, len]`, so a negative becomes a valid `0` and no invalid `@Nat` propagates; the disclosure is `E504`. An array element and a `Map` value take the SIGN guard at their store too. The refinement PREDICATE (`E505`/`E506`) is a different obligation over an arbitrary predicate rather than a sign, and it is guarded at every construction-position component (a constructor field, a tuple component, an array element, a `Map` value) and at the `State` write boundaries, by the same lowering the pattern binds use. It stays unguarded only where no guard can be lowered at all: a refinement whose BASE is itself a refinement (the guard would drop the inner membership predicate), or one whose base ERASES at run time. At an internal bind that is disclosed with an `E506` warning; at a function BOUNDARY it is refused outright with `E618`, because there the verifier would otherwise be promising a runtime check it cannot deliver. Every other site is guarded: the pattern binds at any depth, the function and closure boundaries, the generic-instantiated constructor field, the conversion builtins, a BUILT-IN effect operation's argument, and, of the two write boundaries, the `Exn` `throw` payload, which takes the refinement-predicate guard beside the sign guard. A user-declared effect operation's argument is never reached: a row naming the effect, and a qualified call of the operation where no row names it, are refused at check (`E340`); a bare call is `E217`. **Do not** insert `nat_to_int` defensively; `@Nat` already flows to `@Int`. Keep a value that may be negative as `@Int`, or use `int_to_nat` (which returns `Option`) when an explicit narrowing must handle the failure case. See spec §2.2.1 for the formal rule.
- ### Composite types
- <!-- vera:skip-parse category="FRAGMENT" reason="Composite type examples, bare type expressions" -->
- ```vera
- @Array<Int> -- array of ints
- @Array<Option<Int>> -- array of ADT (compound element type)
- @Array<String> -- array of strings
- @Tuple<Int, String> -- tuple
- @Option<Int> -- Option type (Some/None)
- @Map<String, Int> -- key-value map (keys: Eq + Hash)
- @Set<Int> -- unique elements, insertion order (Eq + Hash)
- @Decimal -- exact decimal arithmetic
- @Json -- JSON data (parse/query/serialize)
- @HtmlNode -- HTML document node (parse/query/serialize)
- fn(Int -> Int) effects(pure) -- function type
- { @Int | @Int.0 > 0 } -- refinement type
- ```
- ### Array literals
- Write `[1, 2, 3]` for a populated array and `[]` for an empty one. The element type is inferred from the elements when present, and from the surrounding type annotation when the literal is empty:
- <!-- vera:skip-parse category="FRAGMENT" reason="Array literal examples, bare let bindings (#513)" -->
- ```vera
- let @Array<Int> = [1, 2, 3]; -- populated: elements determine type
- let @Array<Bool> = [true, false]; -- populated, any element type
- let @Array<Int> = []; -- empty: annotation determines type
- let @Array<Array<Int>> = [[1, 2], [3, 4]]; -- nested arrays
- let @Array<Json> = [JNumber(1.0), JNull]; -- ADT elements
- ```
- Empty arrays **must** appear in a position with a known type: a `let` binding with a type annotation, a function argument whose parameter type is known, or the branch of a match arm whose type is fixed by another arm. An empty literal with no surrounding type context is a type error. When the element type is polymorphic in the context (e.g. returning `Array<T>` from a `forall<T>` function body), annotate the `let` or thread through a concrete instantiation.
- `[` and `]` are context-disambiguated: in expression position (`let @Array<Int> = []`) they delimit an array literal; in postfix position (`@Array<Int>.0[@Int.0]`) they are the index operator (see the operator precedence table at the bottom of this file). The parser resolves the two by lookahead; there is no ambiguity you need to work around.
- ### Tuples
- Tuples are constructed with the `Tuple(...)` constructor and destructured with the same shape inside `match`:
- <!-- vera:skip-parse category="FRAGMENT" reason="Tuple construction + destructuring example, bare let + match" -->
- ```vera
- let @Tuple<Int, String> = Tuple(42, "hello");
- match @Tuple<Int, String>.0 {
- Tuple(@Int, @String) -> @Int.0 -- => 42
- }
- ```
- `Tuple` is an upper-case constructor; there is no special tuple-literal syntax (no `(1, 2, 3)` form). There is no empty tuple: `Tuple<>` is a parse error, `Tuple()` is refused (`E216`), and the zero-size type is `Unit`. The name is reserved in both the data and the constructor namespace: `data Tuple { ... }` and `data Box { Tuple(Bool) }` are each rejected at `vera check` with **E158** (see below), because the compiler recognises `Tuple` by name when it renders and lays out a value. A `type Tuple = ...` alias is E158 too, as every reserved type name is.
- ### Type aliases
- ```vera
- type PosInt = { @Int | @Int.0 > 0 };
- type Name = String;
- ```
- An alias is **opaque as the head** of a slot name and **transparent inside type arguments**
- (spec §3.8.1). A parameter written `@PosInt` is referenced `@PosInt.0`, never `@Int.0`; the two are separate namespaces. A parameter written `@Option<Name>` binds `Option<String>`, so it
- is referenced `@Option<String>.0`. When in doubt, run `vera check --explain-slots`: it prints
- the resolved name of every parameter.
- ## Data Types (ADTs)
- ```vera
- private data Color {
- Red,
- Green,
- Blue
- }
- private data List<T> {
- Nil,
- Cons(T, List<T>)
- }
- ```
- > `Option<T>`, `Result<T, E>`, `Ordering`, and `UrlParts` are provided by the standard prelude and available in every program without explicit `data` declarations. Their names are reserved: a `data` declaration, a `type` alias or a type parameter named after one is refused at check (E158), so write `data Maybe<T>`, not `data Option<T>`.
- With an invariant *(not implemented; use a refinement type instead, shown below)*:
- <!-- vera:skip-check category="FUTURE" code="E130" reason="the data invariant clause is not implemented yet (#686), so vera check reports E130" -->
- ```vera
- private data Positive invariant(@Int.0 > 0) {
- MkPositive(Int)
- }
- ```
- The `invariant(...)` clause on `data` declarations is specified but does not work in the reference compiler: every documented form fails with `[E130] no <DataName> bindings in scope`. Express the same constraint with a refinement type:
- ```vera
- type Positive = { @Int | @Int.0 > 0 };
- ```
- ## Pattern Matching
- <!-- vera:skip-check category="INCOMPLETE" code="E136 E322 E322 E322" reason="matches on Color, declared in the Data Types block above" -->
- ```vera
- private fn to_int(@Color -> @Int)
- requires(true)
- ensures(true)
- effects(pure)
- {
- match @Color.0 {
- Red -> 0,
- Green -> 1,
- Blue -> 2
- }
- }
- ```
- Patterns can bind values:
- ```vera
- private fn unwrap_or(@Option<Int>, @Int -> @Int)
- requires(true)
- ensures(true)
- effects(pure)
- {
- match @Option<Int>.0 {
- None -> @Int.0,
- Some(@Int) -> @Int.0
- }
- }
- ```
- Available patterns: constructors (`Some(@Int)`), nullary constructors (`None`, `Red`), literals (`0`, `"x"`, `true`), wildcard (`_`).
- Match must be exhaustive.
- ## Conditional Expressions
- <!-- vera:skip-parse category="FRAGMENT" reason="If/else expression example" -->
- ```vera
- if @Bool.0 then {
- expr1
- } else {
- expr2
- }
- ```
- Both branches are mandatory. Braces are mandatory. Each branch is always multi-line (closing brace on its own line).
- ## Block Expressions
- Blocks contain statements followed by a final expression:
- <!-- vera:skip-parse category="FRAGMENT" reason="Block expression example" -->
- ```vera
- {
- let @Int = @Int.0 + 1;
- let @String = to_string(@Int.0);
- IO.print(@String.0);
- @Int.0
- }
- ```
- Statements end with `;`. The final expression (no `;`) is the block's value.
- ## Typed Holes
- **When you do not know the right expression to write, use `?` rather than guessing.** A typed hole tells you immediately what type is needed and what bindings are available, which is faster than writing the wrong thing and debugging the type error.
- <!-- vera:no-run category="typed-hole" reason="it holds a typed hole, which vera run refuses (E614)" -->
- ```vera
- public fn double(@Int -> @Int)
- requires(true) ensures(true) effects(pure)
- {
- ?
- }
- ```
- `vera check` reports a `W001` warning (not an error):
- ```text
- warning: [W001] Warning at double.vera, line 4, column 3:
- ?
- ^
- Typed hole: expected Int.
- ? is a placeholder for an incomplete expression. The compiler reports the expected type and available bindings so the hole can be filled in.
- Fix:
- Replace ? with an expression of type Int. Available bindings: @Int.0: Int.
- See: Chapter 4, Section 4.17 "Typed Holes"
- ```
- The program type-checks successfully (`ok: true`); holes are warnings, not errors. This means you can check the *rest* of a function for type errors while one expression is still incomplete.
- `vera check --json` includes hole warnings in the `warnings` array with the full expected type and binding context, making them machine-readable for agent workflows.
- **Programs with holes cannot be compiled.** `vera compile` and `vera run` reject any program containing `?` with an `E614` error.
- ### Workflow
- Use holes to build programs incrementally:
- <!-- vera:no-run category="typed-hole" reason="it holds a typed hole, which vera run refuses (E614)" -->
- ```vera
- public fn safe_div(@Int, @Int -> @Option<Int>)
- requires(true) ensures(true) effects(pure)
- {
- if ? then { -- W001: expected Bool. Bindings: @Int.0: Int; @Int.1: Int
- Some(?) -- W001: expected Int. Bindings: @Int.0: Int; @Int.1: Int
- } else {
- None
- }
- }
- ```
- Check this, read the `W001` fix hints, then fill in the holes:
- <!-- vera:skip-parse category="FRAGMENT" reason="Typed hole fill-in example, bare if/else expression" -->
- ```vera
- if @Int.0 != 0 then {
- Some(@Int.1 / @Int.0)
- } else {
- None
- }
- ```
- ### Multiple holes
- Multiple holes in one program each produce their own `W001` warning with independent context. You can fill them one at a time and re-check between iterations.
- ### Conformance
- See `tests/conformance/ch03_typed_holes.vera` for a minimal working example.
- ## Iteration
- Vera has no `for` or `while` loops. Iteration is always expressed as tail-recursive functions. The standard pattern for counted iteration:
- <!-- vera:skip-check category="INCOMPLETE" code="E200" reason="calls fizzbuzz, defined in the Iteration with IO example below" -->
- ```vera
- private fn loop(@Nat, @Nat -> @Unit)
- requires(@Nat.0 <= @Nat.1)
- ensures(true)
- decreases(@Nat.1 - @Nat.0)
- effects(<IO>)
- {
- IO.print(string_concat(fizzbuzz(@Nat.0), "\n"));
- if @Nat.0 < @Nat.1 then {
- loop(@Nat.1, @Nat.0 + 1)
- } else {
- ()
- }
- }
- ```
- Here `@Nat.0` is the counter (De Bruijn index 0 = most recent, i.e. the second parameter) and `@Nat.1` is the limit (the first parameter). The contract `requires(@Nat.0 <= @Nat.1)` ensures the counter never exceeds the limit, and since the recursive call passes `@Nat.0 + 1` where `@Nat.0 < @Nat.1`, the precondition is maintained at every step. The function prints, then either recurses with an incremented counter or returns `()`.
- The measure `decreases(@Nat.1 - @Nat.0)` is the number of steps left. It shrinks by one on every recursive call and never goes below zero, which is what proves the loop ends; the `requires` is what makes the subtraction safe at entry. Every recursive function needs a measure, whatever its effect row, `<IO>` included (see [decreases](#decreases-termination)). A loop that is not meant to end declares `Diverge` instead.
- Call with the limit first and counter second: `loop(100, 1)`.
- ## Closures and captured bindings
- Anonymous functions are written `fn(@ParamType1, @ParamType2 -> @ReturnType) effects(effect_row) { body_expression }`. They are first-class values and can be passed to higher-order built-ins (`array_map`, `array_filter`, `array_fold`, `array_any`, `array_find`, `array_sort_by`, …) or stored in `let` bindings.
- <!-- vera:skip-parse category="FRAGMENT" reason="Closure example, bare let bindings with array_map (#513)" -->
- ```vera
- let @Array<Int> = [1, 2, 3, 4, 5];
- let @Array<Int> = array_map(
- @Array<Int>.0,
- fn(@Int -> @Int) effects(pure) { @Int.0 * 2 }
- );
- -- Result: [2, 4, 6, 8, 10]
- ```
- Inside the closure body, `@Int.0` is the closure's own parameter (index 0 = most recent binding). This matches how slot indices work in top-level `fn` declarations.
- ### Capturing outer bindings
- **Closures can capture any outer binding**: primitives (`Int`, `Nat`, `Bool`, `Byte`, `Float64`), pair types (`String`, `Array<T>`), single-pointer ADTs (`Option<T>`, `Result<T, E>`, user-defined `data` types), and the opaque-handle ADTs (`Map<K, V>`, `Set<T>`, `Decimal`).
- Outer bindings are available at higher De Bruijn indices: the closure's own parameters are pushed on top of the slot stack, so outer `@T` bindings shift up by the number of inner `@T` parameters.
- <!-- vera:run fn="sum_plus_offset" stdout="306" -->
- ```vera
- -- WORKS: capturing a primitive @Int.
- public fn sum_plus_offset(@Unit -> @Int)
- requires(true) ensures(true) effects(pure)
- {
- let @Int = 100; -- outer binding: @Int.0 = 100
- let @Array<Int> = [1, 2, 3];
- array_fold(
- @Array<Int>.0,
- 0,
- -- array_fold's closure shape is fn(@Acc, @Elem -> @Acc) — accumulator
- -- first. By the rightmost = .0 rule, that puts the element at .0
- -- and the accumulator at .1 inside the body.
- fn(@Int, @Int -> @Int) effects(pure) {
- -- Inside this closure body, two @Int params are in scope:
- -- @Int.0 = element (most recent, the iterator's current value)
- -- @Int.1 = accumulator
- -- @Int.2 = outer `let @Int = 100` (captured — primitive, OK)
- @Int.1 + @Int.0 + @Int.2
- }
- )
- }
- -- 0+1+100 + 2+100 + 3+100 = 306
- ```
- The rule when capture IS safe: count the closure's own `@T` parameters, and the outermost captured `@T` binding sits at that index. A closure with no `@Int` parameters of its own would see the outer `let @Int` as `@Int.0`; a closure with two `@Int` parameters sees it as `@Int.2`. Types are independent: a closure's `@Int` parameter does not shift outer `@String` bindings.
- Use `vera check --explain-slots file.vera` if you need the resolved index table printed for a specific function (including closures).
- ### Capturing a pair-typed value
- Capturing a `String` or `Array<T>` works the same way as capturing any other outer binding; the closure-struct layout serialises both halves of the (ptr, len) pair, so `array_length` / `string_length` / element-access all see the captured value correctly inside the closure body.
- <!-- vera:skip-parse category="FRAGMENT" reason="Pair-type capture example (post-#535), bare let-in-closure" -->
- ```vera
- -- Capture an outer Array<Int> and read its length inside the closure.
- let @Array<Int> = [10, 20, 30]; -- captured (outer) @Array<Int>.0 = this
- let @Array<Int> = [1, 2, 3]; -- iterated (inner) @Array<Int>.0 = this
- -- outer shifts to .1
- array_fold(
- @Array<Int>.0,
- 0,
- fn(@Int, @Int -> @Int) effects(pure) {
- -- Inside the closure: @Int.0 = element, @Int.1 = acc.
- -- @Array<Int>.1 refers to the OUTER (captured) array.
- @Int.1 + @Int.0 + nat_to_int(array_length(@Array<Int>.1))
- }
- )
- -- 0+1+3 + 2+3 + 3+3 = 15
- ```
- The same applies to `String` captures. ADT captures (`Option<T>`, `Result<T, E>`, user `data` types, `Json`, `HtmlNode`, `MdBlock`, opaque handles `Map<K, V>` / `Set<T>` / `Decimal`) work too; they are single-i32 pointers that the closure-struct layout handles directly.
- ### When to use recursion instead
- Closures cover pure, self-contained transformations and simple captured constants. Prefer a top-level recursive function when any of these hold:
- - The body needs an effect row other than `pure` that does not match the combinator's expected effect signature.
- - The body needs to early-return or short-circuit in a way the combinator does not provide (`array_find` / `array_any` / `array_all` short-circuit; `array_map` / `array_fold` do not).
- - The iteration shape is not one-pass left-to-right (e.g. you need to look ahead, or process in reverse while mutating a different data structure).
- - Termination requires a `decreases` clause that proves non-trivial progress; closures cannot carry `decreases`.
- For counted iteration with IO, use the recursive `loop` pattern from the Iteration section above; for array transformations, use the array combinators with closures.
- ### Nested closures
- Closures inside closure bodies work end to end: the natural 2D `array_map(rows, fn(row) { array_map(cols, fn(col) { ... }) })` shape compiles, validates, and runs at any return type. Captures from the outer scope flow through nested closures correctly for every type that can be captured at the top level (primitives, pair types, ADTs, opaque handles). Three or more levels of nesting work the same way; the lifting pass uses a worklist that handles arbitrary depth.
- <!-- vera:run fn="build_grid" reason="returns Array, which vera run prints as a heap address" -->
- ```vera
- public fn build_grid(@Unit -> @Array<Array<Int>>)
- requires(true) ensures(true) effects(pure)
- {
- -- 2D array of products via nested array_map.
- array_map(
- array_range(0, 3),
- fn(@Int -> @Array<Int>) effects(pure) {
- array_map(
- array_range(0, 3),
- fn(@Int -> @Int) effects(pure) { @Int.0 + @Int.1 }
- )
- }
- )
- }
- ```
- ## Built-in Functions
- ### Naming convention
- All built-in functions follow predictable naming patterns. When guessing a function name you have not seen, apply these rules:
- | Pattern | When | Examples |
- |---------|------|----------|
- | `domain_verb` | Most functions | `string_length`, `array_append`, `regex_match`, `md_parse` |
- | `source_to_target` | Type conversions | `int_to_float`, `float_to_int`, `nat_to_int` |
- | `domain_is_predicate` | Boolean predicates | `float_is_nan`, `float_is_infinite` |
- | Prefix-less | Math universals and float constants only | `abs`, `min`, `max`, `floor`, `ceil`, `round`, `sqrt`, `pow`, `nan`, `infinity` |
- **String operations always use `string_` prefix**: `string_contains`, `string_starts_with`, `string_split`, `string_join`, `string_strip`, `string_upper`, `string_lower`, `string_replace`, `string_index_of`, `string_char_code`, `string_from_char_code`, `string_chars`, `string_lines`, `string_words`, `string_reverse`, `string_trim_start`, `string_trim_end`, `string_pad_start`, `string_pad_end`. **Character classifiers use `is_` prefix**: `is_digit`, `is_alpha`, `is_alphanumeric`, `is_whitespace`, `is_upper`, `is_lower`. **First-character conversion uses `char_` prefix**: `char_to_upper`, `char_to_lower`. **JSON typed accessors use `json_as_` and `json_get_` prefixes**: `json_as_string`/`number`/`bool`/`int`/`array`/`object` for Layer-1 coercions; `json_get_string`/`number`/`bool`/`int`/`array` for Layer-2 compound field accessors. **Float64 predicates use `float_` prefix**: `float_is_nan`, `float_is_infinite`. **Type conversions use `source_to_target`**: `int_to_float` (not `to_float`), `float_to_int`, `int_to_nat`. Math functions (`abs`, `min`, `max`, etc.) and float constants (`nan`, `infinity`) are the **only** exceptions; they need no prefix because they are universally understood mathematical names.
- **If `vera check` reports an unresolved function name, apply these patterns to derive the correct name before giving up.** The convention is strict and consistent, so the right name is always derivable. Do not invent names that do not follow the pattern; they will not exist.
- ### Option and Result Combinators
- The standard prelude provides `Option<T>` and `Result<T, E>` along with combinator functions that are always available:
- <!-- vera:skip-parse category="FRAGMENT" reason="Option/Result combinator usage examples, bare calls" -->
- ```vera
- -- Option: unwrap with default
- option_unwrap_or(Some(42), 0) -- returns 42
- option_unwrap_or(None, 0) -- returns 0
- -- Option: transform the value inside Some
- option_map(Some(10), fn(@Int -> @Int) effects(pure) { @Int.0 + 1 })
- -- returns Some(11)
- -- Option: chain fallible operations (flatmap)
- option_and_then(Some(5), fn(@Int -> @Option<Int>) effects(pure) {
- if @Int.0 > 0 then { Some(@Int.0 * 2) } else { None }
- })
- -- returns Some(10)
- -- Result: unwrap with default
- result_unwrap_or(Ok(42), 0) -- returns 42
- result_unwrap_or(Err("oops"), 0) -- returns 0
- -- Result: transform the Ok value
- result_map(Ok(10), fn(@Int -> @Int) effects(pure) { @Int.0 + 1 })
- -- returns Ok(11)
- ```
- These are generic functions that follow the `domain_verb` naming convention. They are automatically injected and undergo normal monomorphization. If you define a function with the same name, your definition takes precedence, inside the prelude's own bodies as well as your code: the prelude's `json_get_string` calls `json_get` by bare name, so a user `json_get` changes its answer or, with a different signature, stops the module loading. Pick a distinct name unless you mean to replace the prelude's everywhere.
- ### Array operations
- <!-- vera:skip-parse category="FRAGMENT" reason="Array built-in examples, bare calls" -->
- ```vera
- array_length(@Array<Int>.0) -- returns Int (the array length, flows to either Nat or Int positions)
- array_append(@Array<Int>.0, @Int.0) -- returns Array<Int> (new array with element appended)
- array_range(@Int.0, @Int.1) -- returns Array<Int> (integers [start, end))
- array_concat(@Array<Int>.0, @Array<Int>.1) -- returns Array<Int> (merge two arrays)
- array_slice(@Array<Int>.0, @Int.0, @Int.1) -- returns Array<Int> (elements [start, end))
- array_map(@Array<Int>.0, fn(@Int -> @Int) effects(pure) { ... }) -- returns Array<Int>
- array_filter(@Array<Int>.0, fn(@Int -> @Bool) effects(pure) { ... }) -- returns Array<Int>
- array_fold(@Array<Int>.0, 0, fn(@Int, @Int -> @Int) effects(pure) { @Int.1 + @Int.0 }) -- returns Int
- array_mapi(@Array<Int>.0, fn(@Int, @Nat -> @Int) effects(pure) { ... }) -- returns Array<Int> (map with index)
- array_reverse(@Array<Int>.0) -- returns Array<Int> (element order reversed)
- array_find(@Array<Int>.0, fn(@Int -> @Bool) effects(pure) { ... }) -- returns Option<Int> (first match)
- array_any(@Array<Int>.0, fn(@Int -> @Bool) effects(pure) { ... }) -- returns Bool (at least one match)
- array_all(@Array<Int>.0, fn(@Int -> @Bool) effects(pure) { ... }) -- returns Bool (every element matches)
- array_flatten(@Array<Array<Int>>.0) -- returns Array<Int> (one level)
- array_sort_by(@Array<Int>.0, fn(@Int, @Int -> @Ordering) effects(pure) { ... }) -- returns Array<Int>
- ```
- `array_map` / `array_mapi` are generic: the element type can change (e.g. `array_map(@Array<Int>.0, fn(@Int -> @String) ...)`).
- `array_fold` is generic: the accumulator type can differ from the element type.
- `array_mapi` passes the zero-based index as a `@Nat` second argument; use this rather than hand-rolling a recursive accumulator with an index counter.
- `array_find` short-circuits on the first match; `array_any` and `array_all` do the same and observe the standard vacuous-truth convention on empty input (`any([], _) == false`, `all([], _) == true`).
- `array_sort_by`'s comparator returns `@Ordering` (`Less` / `Equal` / `Greater`); insertion sort, stable.
- `array_sort<T> where Ord<T>`, `array_contains<T> where Eq<T>`, and `array_index_of<T> where Eq<T>` (operations that would dispatch on the element type's built-in ability) are not implemented; use `array_sort_by` with an explicit comparator, or `array_any` / `array_find` with an equality predicate.
- ### Map operations
- `Map<K, V>` is a key-value collection. Keys must satisfy `Eq` and `Hash` abilities (primitive types: `Int`, `Nat`, `Bool`, `Float64`, `String`, `Byte`). Values may be any type with a runtime representation but an `Array`: a zero-size key or value type (`Unit`, or a `Future` wrapping one) and an `Array` key or value are rejected at check time with E135. All operations are pure: insert and remove return new maps, sharing what they do not change, so an insert costs the depth of the map's trie, not its size. `map_keys` and `map_values` return the keys and values in insertion order: a key inserted again keeps its first position, and a removed key loses it. `-0.0` and `0.0` are one key, and so are any two NaNs.
- <!-- vera:skip-parse category="FRAGMENT" reason="Map built-in examples, bare calls" -->
- ```vera
- map_insert(map_new(), "hello", 42) -- returns Map<String, Nat>
- map_insert(@Map<String, Nat>.0, "world", 7) -- returns Map<String, Nat> (new map with entry added)
- map_get(@Map<String, Nat>.0, "hello") -- returns Option<Nat> (Some(42) or None)
- map_contains(@Map<String, Nat>.0, "hello") -- returns Bool
- map_remove(@Map<String, Nat>.0, "hello") -- returns Map<String, Nat> (new map without key)
- map_size(@Map<String, Nat>.0) -- returns Int (number of entries)
- map_keys(@Map<String, Nat>.0) -- returns Array<String>
- map_values(@Map<String, Nat>.0) -- returns Array<Nat>
- ```
- > `map_new()` takes no arguments. Its key and value types come from where it is used: the arguments of `map_insert(map_new(), k, v)`, or the type of a `let`. Using `option_unwrap_or(map_get(...), default)` is the idiomatic way to extract values with a fallback.
- ### Set operations
- `Set<T>` is a collection of unique elements, which `set_to_array` returns in insertion order. Elements must satisfy `Eq` and `Hash` abilities (primitive types: `Int`, `Nat`, `Bool`, `Float64`, `String`, `Byte`); a zero-size element type (`Unit`, or a `Future` wrapping one) and an `Array` element are rejected at check time with E135. All operations are pure: add and remove return new sets.
- <!-- vera:skip-parse category="FRAGMENT" reason="Set built-in examples, bare calls" -->
- ```vera
- set_add(set_add(set_new(), "hello"), "world") -- returns Set<String>
- set_contains(@Set<String>.0, "hello") -- returns Bool (true)
- set_remove(@Set<String>.0, "hello") -- returns Set<String> (new set without element)
- set_size(@Set<String>.0) -- returns Int
- set_to_array(@Set<String>.0) -- returns Array<String>
- ```
- > `set_new()` is a zero-argument generic function. Nest it inside `set_add(set_new(), elem)` so that type inference can resolve the element type. Adding a duplicate element is a no-op (sets enforce uniqueness).
- ### Decimal operations
- `Decimal` provides exact decimal arithmetic for financial and precision-sensitive applications. It is an opaque type (i32 handle) backed by the runtime's decimal implementation. All operations are pure.
- <!-- vera:skip-parse category="FRAGMENT" reason="Decimal built-in examples, bare calls" -->
- ```vera
- decimal_from_int(42) -- returns Decimal (exact conversion)
- decimal_from_float(3.14) -- returns Decimal (via str conversion)
- decimal_add(@Decimal.0, @Decimal.1) -- returns Decimal (addition)
- decimal_sub(@Decimal.0, @Decimal.1) -- returns Decimal (subtraction)
- decimal_mul(@Decimal.0, @Decimal.1) -- returns Decimal (multiplication)
- decimal_neg(@Decimal.0) -- returns Decimal (negation)
- decimal_abs(@Decimal.0) -- returns Decimal (absolute value)
- decimal_round(@Decimal.0, 2) -- returns Decimal (round to N places)
- decimal_eq(@Decimal.0, @Decimal.1) -- returns Bool (equality)
- decimal_compare(@Decimal.0, @Decimal.1) -- returns Ordering (Less/Equal/Greater)
- decimal_to_string(@Decimal.0) -- returns String
- decimal_to_float(@Decimal.0) -- returns Float64 (potentially lossy)
- ```
- `decimal_from_string` and `decimal_div` return `Option<Decimal>`; use `option_unwrap_or` or `match` to extract the value. `decimal_compare` returns `Ordering`; use `match` to dispatch on `Less`, `Equal`, `Greater`.
- ### JSON operations
- `Json` is a built-in ADT for structured data interchange. Parse JSON strings, query fields and array elements, and serialize back to strings. All operations are pure.
- The `Json` type has six constructors: `JNull`, `JBool(Bool)`, `JNumber(Float64)`, `JString(String)`, `JArray(Array<Json>)`, `JObject(Map<String, Json>)`. It is provided by the standard prelude, so no `data` declaration is needed.
- **What `json_parse` accepts.** Exactly RFC 8259-valid text that decodes to finite numbers and strings of Unicode scalar values (spec §9.7.1). Anything else is `Err`, at the parse, with the same message on the CLI and in the browser. Vera defines this domain rather than inheriting whichever one the host parser implements. Two consequences bear on the `Err` arm:
- - A **non-finite number** never parses, however it is written. The constants `NaN`, `Infinity` and `-Infinity` are not JSON at all; a number that merely *overflows*, like `1e999`, is syntactically fine and still refused, because what it decodes to is an infinity. Underflow is different: `1e-999` gives you `0` and parses. If a producer you do not control emits any of these, fix the producer or pre-process the text; there is no flag to admit them.
- - A **lone surrogate** escape (`\ud800` with no matching partner) never parses either: its decoded value is not a Unicode scalar, and a Vera `String` is. A *matched* pair is ordinary: `"\ud83d\ude00"` parses and gives you the astral character.
- Everything else that fails is a plain syntax error, and that message is the host parser's own.
- <!-- vera:skip-parse category="FRAGMENT" reason="JSON parse/stringify/get examples, bare calls" -->
- ```vera
- json_parse("{\"name\":\"Vera\"}") -- returns Result<Json, String>
- json_stringify(@Json.0) -- returns String (JSON text)
- json_get(@Json.0, "name") -- returns Option<Json> (field lookup)
- json_has_field(@Json.0, "name") -- returns Bool
- json_keys(@Json.0) -- returns Array<String> (object keys)
- json_array_get(@Json.0, 0) -- returns Option<Json> (element at index)
- json_array_length(@Json.0) -- returns Int (array length, 0 if not array)
- json_type(@Json.0) -- returns String ("null"/"bool"/"number"/"string"/"array"/"object")
- ```
- Pattern match on `Json` constructors to extract values:
- <!-- vera:skip-parse category="FRAGMENT" reason="JSON match expression example, bare expression" -->
- ```vera
- match json_parse("{\"x\":42}") {
- Err(@String) -> Err(@String.0),
- Ok(@Json) -> match json_get(@Json.0, "x") {
- None -> Err("missing x"),
- Some(@Json) -> match @Json.0 {
- JNumber(@Float64) -> Ok(float_to_int(@Float64.0)),
- _ -> Err("x is not a number")
- }
- }
- }
- ```
- #### Typed accessors (Layer 1 and Layer 2)
- For the common case of "unwrap `Option<Json>` and match on a specific constructor", use the typed accessors instead of the two-level match above:
- <!-- vera:skip-parse category="FRAGMENT" reason="JSON typed accessor examples (#366), bare calls" -->
- ```vera
- -- Layer 1: Json -> Option<T>. Some when the constructor matches.
- json_as_string(@Json.0) -- Option<String>
- json_as_number(@Json.0) -- Option<Float64>
- json_as_bool(@Json.0) -- Option<Bool>
- json_as_int(@Json.0) -- Option<Int> (truncates; None for NaN/inf/|f| >= 2^63)
- json_as_array(@Json.0) -- Option<Array<Json>>
- json_as_object(@Json.0) -- Option<Map<String, Json>>
- -- Layer 2: json_get + json_as_* composed (the common pattern).
- json_get_string(@Json.0, "name") -- Option<String>
- json_get_number(@Json.0, "score") -- Option<Float64>
- json_get_bool(@Json.0, "active") -- Option<Bool>
- json_get_int(@Json.0, "age") -- Option<Int>
- json_get_array(@Json.0, "tags") -- Option<Array<Json>>
- ```
- The Layer-2 accessors return `None` both when the field is missing AND when the field is present but of the wrong type, which is what most API-consuming code wants. The example above collapses to:
- <!-- vera:skip-parse category="FRAGMENT" reason="JSON Layer-2 compound accessor example, bare match" -->
- ```vera
- match json_parse("{\"x\":42}") {
- Err(@String) -> Err(@String.0),
- Ok(@Json) -> match json_get_int(@Json.0, "x") {
- Some(@Int) -> Ok(@Int.0),
- None -> Err("x missing or not a number")
- }
- }
- ```
- ### String operations
- <!-- vera:skip-parse category="FRAGMENT" reason="String built-in examples, bare calls" -->
- ```vera
- string_length(@String.0) -- returns Nat
- string_concat(@String.0, @String.1) -- returns String
- string_slice(@String.0, @Nat.0, @Nat.1) -- returns String (start, end)
- string_char_code(@String.0, @Int.0) -- returns Nat (ASCII code at index)
- string_from_char_code(@Nat.0) -- returns String (single char from code point)
- string_repeat(@String.0, @Nat.0) -- returns String (repeated N times)
- parse_nat(@String.0) -- returns Result<Nat, String>
- parse_int(@String.0) -- returns Result<Int, String>
- parse_float64(@String.0) -- returns Result<Float64, String>
- parse_bool(@String.0) -- returns Result<Bool, String>
- base64_encode(@String.0) -- returns String (RFC 4648)
- base64_decode(@String.0) -- returns Result<String, String>
- base64_encode_bytes(@Array<Byte>.0) -- returns String (RFC 4648, over bytes)
- base64_decode_bytes(@String.0) -- returns Result<Array<Byte>, String>
- string_to_bytes(@String.0) -- returns Array<Byte> (the string's UTF-8 bytes)
- bytes_to_string(@Array<Byte>.0) -- returns Result<String, String> (UTF-8 decode)
- url_encode(@String.0) -- returns String (RFC 3986 percent-encoding)
- url_decode(@String.0) -- returns Result<String, String>
- url_parse(@String.0) -- returns Result<UrlParts, String> (RFC 3986 decomposition)
- url_join(@UrlParts.0) -- returns String (reassemble URL from UrlParts)
- md_parse(@String.0) -- returns Result<MdBlock, String> (parse Markdown)
- md_render(@MdBlock.0) -- returns String (render to canonical Markdown)
- md_has_heading(@MdBlock.0, @Nat.0) -- returns Bool (check if heading of level exists)
- md_has_code_block(@MdBlock.0, @String.0) -- returns Bool (check if code block of language exists)
- md_extract_code_blocks(@MdBlock.0, @String.0) -- returns Array<String> (extract code by language)
- html_parse(@String.0) -- returns Result<HtmlNode, String> (parse HTML)
- html_to_string(@HtmlNode.0) -- returns String (serialize to HTML)
- html_query(@HtmlNode.0, @String.0) -- returns Array<HtmlNode> (CSS selector query)
- html_text(@HtmlNode.0) -- returns String (extract text content)
- html_attr(@HtmlNode.0, @String.0) -- returns Option<String> (get attribute value)
- regex_match(@String.0, @String.1) -- returns Result<Bool, String> (test if pattern matches)
- regex_find(@String.0, @String.1) -- returns Result<Option<String>, String> (first match)
- regex_find_all(@String.0, @String.1) -- returns Result<Array<String>, String> (all matches)
- regex_replace(@String.0, @String.1, @String.2) -- returns Result<String, String> (replace first match)
- async(@T.0) -- returns Future<T> (requires effects(<Async>))
- await(@Future<T>.0) -- returns T (requires effects(<Async>))
- to_string(@Int.0) -- returns String (integer to decimal)
- int_to_string(@Int.0) -- returns String (alias for to_string)
- bool_to_string(@Bool.0) -- returns String ("true" or "false")
- nat_to_string(@Nat.0) -- returns String (natural to decimal)
- byte_to_string(@Byte.0) -- returns String (single character)
- float_to_string(@Float64.0) -- returns String (decimal; nan/inf/-inf for non-finite; traps if finite and |x| >= 2^63)
- string_strip(@String.0) -- returns String (trim whitespace)
- ```
- #### String interpolation
- <!-- vera:skip-parse category="FRAGMENT" reason="String interpolation examples, bare expressions" -->
- ```vera
- "hello \(@String.0)" -- embeds a String value
- "x = \(@Int.0)" -- auto-converts Int to String
- "a=\(@Int.1), b=\(@Int.0)" -- multiple interpolations
- "\(@String.0)" -- interpolation-only (no literal text)
- "len=\(string_length(@String.0))" -- function call inside interpolation
- ```
- Expressions inside `\(...)` are auto-converted to String for types: Int, Nat, Bool, Byte, Float64. Other types produce error E148. Expressions cannot contain string literals (use `let` bindings instead).
- #### String search
- <!-- vera:skip-parse category="FRAGMENT" reason="String search built-in examples, bare calls" -->
- ```vera
- string_contains(@String.0, @String.1) -- returns Bool (substring test)
- string_starts_with(@String.0, @String.1) -- returns Bool (prefix test)
- string_ends_with(@String.0, @String.1) -- returns Bool (suffix test)
- string_index_of(@String.0, @String.1) -- returns Option<Nat> (first occurrence)
- ```
- `string_contains` checks whether the needle appears anywhere in the haystack. `string_starts_with` and `string_ends_with` test prefix and suffix matches. `string_index_of` returns `Some(i)` with the byte offset of the first match, or `None` if not found. An empty needle always matches (returns `true` or `Some(0)`).
- #### String transformation
- <!-- vera:skip-parse category="FRAGMENT" reason="String transformation built-in examples, bare calls" -->
- ```vera
- string_upper(@String.0) -- returns String (ASCII uppercase)
- string_lower(@String.0) -- returns String (ASCII lowercase)
- string_replace(@String.0, @String.1, @String.2) -- returns String (replace all)
- string_split(@String.0, @String.1) -- returns Array<String> (split by delimiter)
- string_join(@Array<String>.0, @String.0) -- returns String (join with separator)
- ```
- `string_upper` and `string_lower` convert ASCII letters only (a-z ↔ A-Z). `string_replace` substitutes all non-overlapping occurrences; an empty needle returns the original string unchanged. `string_split` returns an array of segments; an empty delimiter returns a single-element array. `string_join` concatenates array elements with the separator between each pair.
- #### String utilities and character classification
- <!-- vera:skip-parse category="FRAGMENT" reason="String utility / classifier signatures (#470, #471), bare calls" -->
- ```vera
- -- Splits (bridge to the array combinators)
- string_chars(@String.0) -- returns Array<String> (one byte each)
- string_lines(@String.0) -- returns Array<String> (\n, \r\n, \r)
- string_words(@String.0) -- returns Array<String> (whitespace runs)
- -- Transformations
- string_reverse(@String.0) -- returns String (byte reverse)
- string_trim_start(@String.0) -- returns String (lstrip whitespace)
- string_trim_end(@String.0) -- returns String (rstrip whitespace)
- string_pad_start(@String.0, @Nat.0, @String.1) -- returns String (left-pad to length, JS padStart)
- string_pad_end(@String.0, @Nat.0, @String.1) -- returns String (right-pad to length)
- -- Case conversion (first byte only)
- char_to_upper(@String.0) -- returns String
- char_to_lower(@String.0) -- returns String
- -- Character classifiers (first byte; false for empty)
- is_digit(@String.0) -- returns Bool ('0'..'9')
- is_alpha(@String.0) -- returns Bool ('A'..'Z', 'a'..'z')
- is_alphanumeric(@String.0) -- returns Bool
- is_whitespace(@String.0) -- returns Bool (tab, LF, VT, FF, CR, space — Python isspace() ASCII)
- is_upper(@String.0) -- returns Bool
- is_lower(@String.0) -- returns Bool
- ```
- `string_chars` is the canonical bridge from `String` to `Array<String>`; combine it with `array_map`, `array_filter`, `array_fold` to thread per-byte logic through the array combinators. `string_lines` follows Python's `splitlines()` (trailing `\n` does not add an empty segment). `string_words` follows Python's `split()` with no args (runs collapse, empty segments discarded).
- `string_pad_start` and `string_pad_end` cycle the fill left-to-right and truncate to exactly the padding length, matching JavaScript's `padStart` / `padEnd`. If the input is already at least `n` bytes, the input is returned unchanged. An empty `fill` is a no-op.
- `char_to_upper` / `char_to_lower` convert only the **first byte** of the string; remaining bytes pass through unchanged. Useful for title-casing a token. The six classifiers all inspect only the first byte and return `false` for the empty string. All sixteen are ASCII-only, with no Unicode awareness.
- String functions use the heap allocator (`$alloc`). Memory is managed automatically by a conservative mark-sweep garbage collector; there is no manual allocation or deallocation. All four parse functions return `Result<T, String>`: `parse_nat`, `parse_int`, `parse_float64`, and `parse_bool`. They return `Ok(value)` on valid input and `Err(msg)` on empty or invalid input; leading and trailing spaces are tolerated. `parse_int` accepts an optional `+` or `-` sign. `parse_bool` is strict: only `"true"` and `"false"` (lowercase) are valid. `base64_encode` encodes a string to standard Base64 (RFC 4648); `base64_decode` returns `Result<String, String>`, failing on invalid length or characters. `url_encode` percent-encodes a string for use in URLs (RFC 3986), leaving unreserved characters (`A-Z`, `a-z`, `0-9`, `-`, `_`, `.`, `~`) unchanged; `url_decode` returns `Result<String, String>`, failing on invalid `%XX` sequences. `url_parse` decomposes a URL into its RFC 3986 components, returning `Result<UrlParts, String>` where `UrlParts(scheme, authority, path, query, fragment)` is a built-in ADT with five String fields; it returns `Err("missing scheme")` if no `:` is found. `url_join` reassembles a `UrlParts` value into a URL string. `UrlParts` is in every program, so match on it directly (`UrlParts(@String, @String, @String, @String, @String) -> ...`) with no local declaration.
- #### Bytes
- An `Array<Byte>` holds bytes, one to an element. `string_to_bytes` gives a string's UTF-8 bytes, and `bytes_to_string` decodes bytes to a string: `Ok` for well-formed UTF-8, otherwise `Err("invalid UTF-8 at byte N")`, where `N` is the offset of the first byte of the first sequence that is not well formed. `base64_encode_bytes` and `base64_decode_bytes` are Base64 (RFC 4648) over bytes, so a payload that is not text, such as an image, decodes to what it is. `IO.read_bytes` and `IO.write_bytes` read and write a file's bytes unchanged.
- <!-- vera:run fn="main" stdout="6 bytes, aMOpbGxv, héllo" -->
- ```vera
- private fn decoded(@Array<Byte> -> @String)
- requires(true)
- ensures(true)
- effects(pure)
- {
- match bytes_to_string(@Array<Byte>.0) {
- Ok(@String) -> @String.0,
- Err(@String) -> @String.0
- }
- }
- public fn main(@Unit -> @Unit)
- requires(true)
- ensures(true)
- effects(<IO>)
- {
- let @Array<Byte> = string_to_bytes("héllo");
- IO.print(string_concat(int_to_string(array_length(@Array<Byte>.0)), " bytes, "));
- IO.print(string_concat(base64_encode_bytes(@Array<Byte>.0), ", "));
- match base64_decode_bytes("aMOpbGxv") {
- Ok(@Array<Byte>) -> IO.print(decoded(@Array<Byte>.0)),
- Err(@String) -> IO.print(@String.0)
- }
- }
- ```
- ### Markdown operations
- <!-- vera:skip-parse category="FRAGMENT" reason="md_parse / md_render signatures, bare calls" -->
- ```vera
- md_parse(@String.0) -- returns Result<MdBlock, String>
- md_render(@MdBlock.0) -- returns String
- md_has_heading(@MdBlock.0, @Nat.0) -- returns Bool
- md_has_code_block(@MdBlock.0, @String.0) -- returns Bool
- md_extract_code_blocks(@MdBlock.0, @String.0) -- returns Array<String>
- ```
- `md_parse` parses a Markdown string into a typed `MdBlock` document tree. Returns `Ok(MdDocument(...))` on success. `md_render` converts an `MdBlock` back to canonical Markdown text. `md_has_heading` checks whether the document contains a heading at the given level (1–6). `md_has_code_block` checks for a fenced code block with the given language tag (use `""` for untagged blocks). `md_extract_code_blocks` returns an array of code content strings for all blocks matching the language.
- Two built-in ADTs represent the Markdown document structure:
- **MdInline**: inline content within blocks:
- - `MdText(String)`: plain text
- - `MdCode(String)`: inline code
- - `MdEmph(Array<MdInline>)`: emphasis (*italic*)
- - `MdStrong(Array<MdInline>)`: strong (**bold**)
- - `MdLink(Array<MdInline>, String)`: link with text and URL
- - `MdImage(String, String)`: image with alt text and source
- **MdBlock**: block-level content:
- - `MdParagraph(Array<MdInline>)`: paragraph
- - `MdHeading(Nat, Array<MdInline>)`: heading with level (1–6)
- - `MdCodeBlock(String, String)`: fenced code block (language, code)
- - `MdBlockQuote(Array<MdBlock>)`: block quote
- - `MdList(Bool, Array<Array<MdBlock>>)`: list (ordered?, items)
- - `MdThematicBreak`: horizontal rule
- - `MdTable(Array<Array<Array<MdInline>>>)`: table (rows of cells)
- - `MdDocument(Array<MdBlock>)`: top-level document
- All Markdown functions are pure and available without imports. Pattern match on `MdBlock` and `MdInline` constructors to traverse the document tree.
- ### HTML operations
- `HtmlNode` is a built-in ADT for parsing and querying HTML documents. Parse HTML strings, query elements with CSS selectors, and extract text content. All operations are pure.
- <!-- vera:skip-parse category="FRAGMENT" reason="HTML built-in examples (html_parse/html_query/etc.), bare calls" -->
- ```vera
- html_parse(@String.0) -- returns Result<HtmlNode, String> (parse HTML)
- html_to_string(@HtmlNode.0) -- returns String (serialize to HTML)
- html_query(@HtmlNode.0, @String.0) -- returns Array<HtmlNode> (CSS selector query)
- html_text(@HtmlNode.0) -- returns String (extract text content)
- html_attr(@HtmlNode.0, @String.0) -- returns Option<String> (get attribute value)
- ```
- `html_parse` is lenient (like browsers): malformed HTML produces a best-effort tree, not an error. `html_query` supports simple CSS selectors: tag name (`div`), class (`.classname`), ID (`#id`), attribute presence (`[href]`), and descendant combinator (`div p`). `html_text` recursively concatenates all text content, excluding comments. `html_attr` returns `None` for non-element nodes or missing attributes.
- **HtmlNode constructors:**
- - `HtmlElement(String, Map<String, String>, Array<HtmlNode>)`: element (tag name, attributes, children)
- - `HtmlText(String)`: text content
- - `HtmlComment(String)`: HTML comment
- <!-- vera:skip-parse category="FRAGMENT" reason="HTML constructor match expression, bare expression" -->
- ```vera
- let @Result<HtmlNode, String> = html_parse("<div><a href=\"url\">link</a></div>");
- match @Result<HtmlNode, String>.0 {
- Ok(@HtmlNode) -> {
- let @Array<HtmlNode> = html_query(@HtmlNode.0, "a");
- IO.print(int_to_string(array_length(@Array<HtmlNode>.0)))
- },
- Err(@String) -> IO.print(@String.0)
- }
- ```
- All HTML functions are pure and available without imports. Pattern match on `HtmlNode` constructors to traverse the document tree.
- ### Regular expressions
- <!-- vera:skip-parse category="FRAGMENT" reason="Regex built-in examples, bare calls" -->
- ```vera
- regex_match(@String.0, @String.1) -- returns Result<Bool, String>
- regex_find(@String.0, @String.1) -- returns Result<Option<String>, String>
- regex_find_all(@String.0, @String.1) -- returns Result<Array<String>, String>
- regex_replace(@String.0, @String.1, @String.2) -- returns Result<String, String>
- ```
- All four regex functions take the input string as the first argument and the regex pattern as the second. `regex_replace` takes a third argument for the replacement string. All return `Result` types: `Err(msg)` for invalid patterns, `Ok(value)` on success.
- `regex_match` tests whether the pattern matches anywhere in the input (substring match, not full-string). `regex_find` returns the first matching substring wrapped in `Option`. `regex_find_all` returns all non-overlapping matches as an `Array<String>`, always the full match strings (group 0), even when the pattern contains capture groups. `regex_replace` replaces only the **first** match.
- <!-- vera:skip-parse category="FRAGMENT" reason="Regex Result matching example, bare expression" -->
- ```vera
- let @Result<Bool, String> = regex_match("hello123", "\\d+");
- match @Result<Bool, String>.0 {
- Ok(@Bool) -> if @Bool.0 then { IO.print("found digits") } else { IO.print("no digits") },
- Err(@String) -> IO.print(string_concat("Error: ", @String.0))
- }
- ```
- All regex functions are pure and implemented as host imports (Python `re` / JavaScript `RegExp`).
- ### Numeric operations
- <!-- vera:skip-parse category="FRAGMENT" reason="Numeric built-in examples, bare calls" -->
- ```vera
- abs(@Int.0) -- returns Nat (absolute value)
- min(@Int.0, @Int.1) -- returns Int (smaller of two)
- max(@Int.0, @Int.1) -- returns Int (larger of two)
- floor(@Float64.0) -- returns Int (round down)
- ceil(@Float64.0) -- returns Int (round up)
- round(@Float64.0) -- returns Int (banker's rounding)
- sqrt(@Float64.0) -- returns Float64 (square root)
- pow(@Float64.0, @Int.0) -- returns Float64 (exponentiation)
- ```
- `abs` returns `Nat` because absolute values are non-negative. `floor`, `ceil`, and `round` convert `Float64` to `Int`; they trap as `float_conversion` on NaN, an infinity, or a value outside the `Int` range `[-2^63, 2^63)`. `round` uses IEEE 754 roundTiesToEven (banker's rounding): `round(2.5)` is `2`, not `3`. `pow` takes an `Int` exponent; negative exponents produce reciprocals (`pow(2.0, -1)` is `0.5`). The integer builtins (`abs`, `min`, `max`) are fully verifiable by the SMT solver (Tier 1). The float builtins fall to Tier 3 (runtime).
- ### Logarithmic, trigonometric, and numeric utility functions
- <!-- vera:skip-parse category="FRAGMENT" reason="Math built-in examples (log/trig/constants/clamp), bare calls" -->
- ```vera
- log(@Float64.0) -- natural logarithm (base e)
- log2(@Float64.0) -- base-2 logarithm
- log10(@Float64.0) -- base-10 logarithm
- sin(@Float64.0) -- sine (radians)
- cos(@Float64.0) -- cosine (radians)
- tan(@Float64.0) -- tangent (radians)
- asin(@Float64.0) -- inverse sine, returns [-π/2, π/2]
- acos(@Float64.0) -- inverse cosine, returns [0, π]
- atan(@Float64.0) -- inverse tangent, returns (-π/2, π/2)
- atan2(@Float64.0, @Float64.1) -- quadrant-correct angle from (y, x)
- pi() -- 3.141592653589793
- e() -- 2.718281828459045
- sign(@Int.0) -- returns Int: -1, 0, or 1
- clamp(@Int.0, @Int.1, @Int.2) -- clamp(v, lo, hi) -> Int
- float_clamp(@Float64.0, @Float64.1, @Float64.2) -- Float64 clamp
- ```
- All log and trig functions follow IEEE 754 semantics: `NaN` for out-of-domain inputs (e.g. `log(-1.0)`, `asin(2.0)`), `±Infinity` for overflow. The logarithms' zero pole is not a domain error: `log(0.0)` / `log2(0.0)` / `log10(0.0)` return `-Infinity` in both runtimes. The argument order for `atan2` is `(y, x)`, matching POSIX / Python / JavaScript: `atan2(1.0, 1.0)` is `π/4`. `sign` and `clamp` are inlined as WAT (no host call). `pi()` and `e()` inline as `f64.const` constants. The log and trig functions fall to Tier 3 verification (they're uninterpreted in Z3's real-arithmetic fragment).
- ### Type conversions
- <!-- vera:skip-parse category="FRAGMENT" reason="Type conversions, bare calls" -->
- ```vera
- int_to_float(@Int.0) -- returns Float64 (int to float)
- float_to_int(@Float64.0) -- returns Int (truncation toward zero)
- nat_to_int(@Nat.0) -- returns Int (the identity: every Nat is an Int)
- int_to_nat(@Int.0) -- returns Option<Nat> (None if negative)
- byte_to_int(@Byte.0) -- returns Int (zero-extension)
- int_to_byte(@Int.0) -- returns Option<Byte> (None if out of 0..255)
- ```
- Vera has no implicit numeric conversions; use these functions to convert between numeric types. `int_to_float` and `byte_to_int` are widening conversions that always succeed (a `@Byte` is `0..255`, always in i64 range). `nat_to_int` widens `@Nat → @Int` as the identity, the same no-op as the implicit `@Nat → @Int` coercion, so it is never needed for widening. `float_to_int` truncates toward zero and traps on NaN/Infinity. `int_to_nat` and `int_to_byte` are checked narrowing conversions that return `Option`; pattern match on the result to handle the failure case. `byte_to_int` is SMT-verifiable (Tier 1); the rest are Tier 3 (runtime).
- `Byte` is excluded from arithmetic operators (`+`, `-`, `*`, `/`, `%`, unary `-`) at type-check time: `@Byte.0 + @Byte.1` produces `E140`. For byte-level math, convert to `Int` via `byte_to_int`, do the arithmetic in `@Int`, and convert back via `int_to_byte` if needed. Direct `@Byte` arithmetic (with verified underflow + overflow guards) is an open design question, [#564](https://github.com/aallan/vera/issues/564); the convention keeps the verifier's range-checking story focused on `@Nat` (where only underflow can occur).
- ### Float64 predicates
- <!-- vera:skip-parse category="FRAGMENT" reason="Float64 predicate and constant examples, bare calls" -->
- ```vera
- float_is_nan(@Float64.0) -- returns Bool (true if NaN)
- float_is_infinite(@Float64.0) -- returns Bool (true if ±infinity)
- nan() -- returns Float64 (quiet NaN)
- infinity() -- returns Float64 (positive infinity)
- ```
- `float_is_nan` and `float_is_infinite` test for IEEE 754 special values. `nan()` and `infinity()` construct them; use `0.0 - infinity()` for negative infinity. All four are Tier 3 (runtime-tested, not SMT-verifiable).
- **Float postconditions are near the solver's ceiling.** Contract predicates over `@Float64` are discharged against Z3's IEEE-754 sort, which costs roughly an order of magnitude more solver time than the integer equivalent of the same shape: a two-branch absolute difference runs to several seconds where the `@Int` version takes a fraction of one. Shapes that land near the default per-query budget (10 s) are therefore host-sensitive: the same program can report Tier 1 on a fast machine and Tier 3 on a slow or busy one. When a float contract falls to Tier 3, re-run it with a larger budget (`vera verify --timeout-ms 60000 file.vera`, or `VERA_Z3_TIMEOUT_MS` for a whole session) before concluding anything: a claim that proves with more time needed time, while one that stays Tier 3 at any budget is standing behind something the solver cannot see through at all, such as `sqrt` or `asin`. Only the second kind is a reason to restate the contract.
- **Redeclaring a built-in effect is an error (E152)**: an `effect IO { ... }` block (or `State<T>`, `Exn<E>`, `Http`, `Random`, `Inference`, `DB`, `Diverge`, `Async`, `HttpServer`) is rejected at `vera check`, whether or not its operation signatures match the built-in. The operations come with the effect row: write `effects(<IO>)` on the function and call `IO.print(...)`. Beyond one canonical form, the block cannot be honoured: code generation routes a qualified `IO.op(...)` to the fixed host import by qualifier name and never reads the declaration, so a divergent signature would compile to invalid WebAssembly that traps at `run`. Give a different effect a distinct name (e.g. `Logger`).
- **Redefining a built-in is an error (E151)**: a function whose name matches a built-in (e.g. `abs`, `array_length`, `clamp`, `to_string`) is rejected at `vera check`. Built-ins are always in scope as the single canonical definition, so a second one is both redundant (one canonical form) and, for the verifier-modelled built-ins, silently unsound: the verifier would reason with the built-in's model while codegen runs your body. Call the built-in directly (no import needed), or give your function a distinct name (e.g. `magnitude`) for different behaviour. The prelude's own functions (`option_map`, `option_and_then`, `option_unwrap_or`, `result_map`, `result_unwrap_or`, `json_*`, `html_attr`) are reserved the same way, in every file and for a `where` helper too: the prelude is a module whose names are reserved, so `fn json_get(...)` is refused and renaming it (`json_get_custom`) is the fix.
- **Declaring a data type with a built-in type's name is an error (E158)**: `data Array { ... }`, `data Map { ... }`, `data Set { ... }`, `data Decimal { ... }`, `data Future { ... }` and `data Tuple { ... }` are rejected at `vera check`, with any number of type parameters, at the entry file and inside a module alike. The compiler recognises `Future` and `Tuple` *by name* throughout code generation (how a value is rendered, compared and laid out), so a declaration of one could not be told apart from the built-in: under a `data Tuple`, `show(MkShadow(7))` would print `(7)`, dropping the constructor name. A declaration of `Array`, `Map`, `Set` or `Decimal` with the built-in's number of type parameters is the same type as the built-in to the type checker, so a built-in value would be accepted where the declaration's is expected and read through the wrong layout: `show(decimal_from_int(5))` beside a `data Decimal { MkShadow(Int) }` would print the declaration's constructor. It is the same rule that reserves built-in function names (E151) and built-in effect names (E152). For `Future` and `Tuple` it also covers a **constructor** name inside any ADT (`data Box { Tuple(Bool) }` is also E158, because code generation flattens constructor layouts by name and the user's would displace the built-in carrier's); a constructor may still be called `Array`, `Map`, `Set` or `Decimal`. The prelude's data types (`Option`, `Result`, `Ordering`, `UrlParts`, `Json`, `HtmlNode`, `MdBlock`, `MdInline`, `Request`, `Response`) and the built-in type names are reserved at every binder that declares a type name: a `data` declaration, a `type` alias (`type Decimal = Int;`) and a type parameter (`forall<Array>`) of one of those names are each E158, in the entry file and in a module. A constructor may still share a prelude constructor's name (`data Box { Less(Bool) }` is legal). Rename the declaration (`data Money`, not `data Decimal`), or use the built-in directly.
- The reserved names, in full, from `vera.prelude` (the one source):
- <!-- render_lists:begin reserved-names -->
- - A function or a `where` helper (`E151`): `html_attr`, `json_array_get`, `json_array_length`, `json_as_array`, `json_as_bool`, `json_as_int`, `json_as_number`, `json_as_object`, `json_as_string`, `json_get`, `json_get_array`, `json_get_bool`, `json_get_int`, `json_get_number`, `json_get_string`, `json_has_field`, `json_keys`, `json_type`, `option_and_then`, `option_map`, `option_unwrap_or`, `result_map`, `result_unwrap_or`.
- - A `data` declaration, a `type` alias or a type parameter (`E158`): `Array`, `Decimal`, `Future`, `HtmlNode`, `Json`, `Map`, `MdBlock`, `MdInline`, `Option`, `Ordering`, `Request`, `Response`, `Result`, `Set`, `Tuple`, `UrlParts`.
- <!-- render_lists:end reserved-names -->
- **Two declarations may not share a constructor name (E159)**: within one file, two `data` declarations may not both declare a constructor of the same name: `private data A1 { Pair(Int, Int) }` beside `private data A2 { Pair(Bool, Bool) }` is rejected at `vera check`, located at the second declaration and naming the first. Constructor names are resolved by name alone, so one namespace cannot hold two. It is the single-file sibling of E157 (two imports). Taking a *prelude* constructor's name is a different shape and stays legal (the prelude's type and function names are reserved, its constructor names are not), as is shadowing an *imported* constructor (§8.5.2).
- **Reserved function names (E153)**: four groups of identifier cannot be a function name. `old` and `new` are contract state forms, so `old(...)` / `new(...)` always parses as a reference to an effect's before/after state (Chapter 7, Section 7.9.2) and never as a call. `assert`, `assume`, `forall`, `exists`, `match`, `if`, `let`, `fn`, `true` and `false` are keywords the lexer admits as a name after `fn` but reads as the keyword everywhere else, so `match(3)` in a body does not parse as a call either. `resume` is not a keyword and a declaration does parse, but inside every handler clause body `resume` is the resumption operator, so a function of that name would give one spelling two meanings by position; writing `resume(...)` inside a handler clause is unaffected. The 21 contextual keywords (`ability`, `data`, `decreases`, `effect`, `effects`, `else`, `ensures`, `import`, `in`, `invariant`, `module`, `op`, `private`, `public`, `pure`, `requires`, `result`, `then`, `type`, `where` and `with`) would parse and run as function names, but spec §1.4 reserves them, so they are refused too. A function under any of these names (top-level, `where`-helper, or in an imported module) is rejected at `vera check`; rename it (the diagnostic suggests a name, such as `combined_with` for `with`). Only the exact identifiers are reserved: `older`, `renew`, `matched`, `resumed` and the like are ordinary function names. `handle` is the one keyword still available, because `public fn handle(@Request -> @Response)` is the entry point `vera serve` invokes from the host (Chapter 9, Section 9.5.6).
- Example:
- ```vera
- private fn greet(@String -> @String)
- requires(true)
- ensures(true)
- effects(pure)
- {
- string_concat("Hello, ", @String.0)
- }
- ```
- ## Contracts
- ### requires (preconditions)
- Conditions that must hold when the function is called:
- <!-- vera:skip-parse category="FRAGMENT" reason="Requires clause example, not full function" -->
- ```vera
- private fn safe_divide(@Int, @Int -> @Int)
- requires(@Int.1 > 0)
- ```
- ### ensures (postconditions)
- Conditions guaranteed when the function returns. Use `@T.result` to refer to the return value:
- <!-- vera:skip-parse category="FRAGMENT" reason="Ensures clause example, not full function" -->
- ```vera
- ensures(@Int.result == @Int.0 / @Int.1)
- ```
- A contract performs no effect, whatever the function's effects clause names: an effect operation in a `requires`, `ensures`, `decreases`, `assert`, `assume` or refinement predicate, or a call to a function that performs one, is refused (`E187`), so perform it in the body, bind its value with `let`, and check that value with `assert`.
- ### decreases (termination)
- Required on **every** recursive function whose effect row does not name `Diverge`, pure or effectful: the expression must strictly decrease on each recursive call so Z3 can discharge termination. A function is recursive when it lies on a cycle of calls, whether it calls itself directly, through a `where` helper, through a closure or handler clause in its own body, or through other top-level functions. Every function on the cycle that does not name `Diverge` needs its own `decreases`, and the measure must decrease on every call from one member of the cycle to another. A recursive function with neither a `decreases` clause nor `Diverge` is rejected at check time (`E137`). An `<IO>` loop that counts up to a bound takes the distance left as its measure; see the FizzBuzz loop in the [Iteration](#iteration) section. A contract cannot call back into its own function, directly or through other calls (`E138`).
- ```vera
- private fn factorial(@Nat -> @Nat)
- requires(true)
- ensures(@Nat.result >= 1)
- decreases(@Nat.0)
- effects(pure)
- {
- if @Nat.0 == 0 then {
- 1
- } else {
- @Nat.0 * factorial(@Nat.0 - 1)
- }
- }
- ```
- For nested recursion, use lexicographic ordering: `decreases(@Nat.0, @Nat.1)`.
- **A precondition no argument can satisfy is not a proof.** `requires(@Int.0 > 5 && @Int.0 < 3)` has no model, so every obligation in the function would discharge from a contradiction, and the body is never checked against a reachable state. `vera verify` reports **E538**, an ERROR, and refuses the program at the definition; the function's *proved* obligations are demoted to `tier3_unguarded` (counted in no tier). An obligation that came back anything else (`violated`, `tier3`, `tier3_unguarded`) keeps its status and its own code, because a contradiction can only manufacture a proof and that verdict was reached for some other reason. A call to such a function reports the ordinary `E501` when the callee is monomorphic; through a `forall` generic it is only disclosed. A top-level `assume` is a premise here too, because it is taken on trust rather than discharged: `assume(@Int.0 < 3); assume(@Int.0 > 5);` is the same contradiction, and the diagnostic points at the `assume` rather than at a `requires` that may be blameless. A branch or `match` arm whose guard cannot hold is *unreachable* rather than contradictory, and is not reported. The same demotion under **E539** means the premises contradict a fact derived from the program: a callee's postcondition, a refined return, a declared-type fact. Usually that is the program disagreeing with itself (an `assume` or a `requires` no callee's contract permits) and the fix is to weaken one of them; only when no such premise is at fault is the derived fact the compiler's, and worth reporting. E539 stays a warning where E538 is an error: the premise at fault there can be one you do not control, so the run declines to certify rather than refusing your program. A third code, **E540**, is neither: it means the premises could not be SHOWN satisfiable and they use arithmetic outside the decidable fragment (a product or a division of two slot references), so Tier 1 is withheld rather than claimed; raise `--timeout-ms` or replace the nonlinear premise with a linear bound. E539 also covers the case where the solver could not decide which layer is at fault: E538 refuses only on a REFUTATION of your own premises, so a budget too small to attribute the contradiction never refuses your program.
- The measure must have a well-founded ordering: `Nat`, `Int`, a data type (ordered by structural size), or a lexicographic tuple of these; a `Float64`/`String`/`Bool` measure is rejected at check time (`E127`). A measure Z3 cannot prove is checked at run time: a recursive re-entry whose measure fails to strictly decrease (or goes negative) traps with a message naming the function, instead of looping forever. Self-recursive tail calls keep tail-call optimisation (the hop is checked at the call site, so guarded iteration still runs at constant stack depth); only *mutually*-recursive tail calls between guarded functions fall back to plain calls. An ADT measure of a *parameterized* type (`List<Int>`) is not runtime-ranked, and a function declaring `Exn` gets no runtime guard (a throw would unwind past the state restores). In both cases `vera verify` still reports an unproved measure as a Tier 3 runtime check (`E525`) that nothing performs, so prove those measures statically.
- ### Workflow: writing contracts incrementally
- **Start with scaffolding, then strengthen.** A function with placeholder contracts type-checks
- and compiles:
- <!-- vera:skip-parse category="FRAGMENT" reason="Contracts scaffolding template" -->
- ```vera
- requires(true) ensures(true)
- ```
- Fill in real contracts *after* the body type-checks cleanly. Strengthen in this order:
- 1. Write `requires(true) ensures(true)` and run `vera check` to confirm the body is correct first.
- 2. Add a `requires` condition for each invariant the caller must satisfy.
- 3. Add an `ensures` condition describing what the function guarantees. Use `@T.result` for the
- return value.
- 4. Run `vera verify`, **not only `vera check`**, to confirm contracts are statically provable.
- `vera check` only type-checks; `vera verify` runs Z3.
- 5. If `vera verify` reports a contract will be checked at runtime (Tier 3), the Z3 solver could
- not prove it. Re-run with a larger budget first (`vera verify --timeout-ms 60000 file.vera`);
- if it stays Tier 3, simplify the contract expression.
- 6. Run `vera test` to find counterexamples. If `vera test` reports a failure, the contract is
- reachable and the function body is wrong.
- ### Quantified expressions
- <!-- vera:skip-parse category="FRAGMENT" reason="Quantified expression examples, bare calls" -->
- ```vera
- -- For all indices in [0, bound):
- forall(@Nat, array_length(@Array<Int>.0), fn(@Nat -> @Bool) effects(pure) {
- @Array<Int>.0[@Nat.0] > 0
- })
- -- There exists an index in [0, bound):
- exists(@Nat, array_length(@Array<Int>.0), fn(@Nat -> @Bool) effects(pure) {
- @Array<Int>.0[@Nat.0] == 0
- })
- ```
- The predicate takes exactly one parameter, the index, typed `@Nat` or `@Int` (or an alias of either), and returns `@Bool`. The index runs over every value from 0 up to the bound, so a refined parameter such as `fn(@{ @Nat | @Nat.0 < 10 } -> @Bool)` is refused (`E179`). Put the condition on the index type instead, `forall(@{ @Nat | @Nat.0 < 10 }, n, ...)`, which ranges over the values that satisfy it, or test it in the body: `P ==> Q` for `forall`, and `P && Q` for `exists`. The index type itself must be `@Nat` or `@Int`, or a refinement of one (`E186`). In a generic, a type parameter is accepted as the index type but not as the predicate's parameter or result (`E179`) or as the bound's type (`E128`), whatever the generic is instantiated at: write `@Nat`, `@Int` or `@Bool` there.
- ## Effects
- Vera is pure by default. All side effects must be declared.
- ### Declaring effects on functions
- <!-- vera:skip-parse category="FRAGMENT" reason="Effect declarations list" -->
- ```vera
- effects(pure) -- no effects
- effects(<IO>) -- performs IO
- effects(<Http>) -- network access
- effects(<State<Int>>) -- uses integer state
- effects(<State<Int>, IO>) -- multiple effects
- effects(<Http, IO>) -- network + IO
- effects(<Async>) -- async computation
- effects(<HttpServer>) -- HTTP request handler (vera serve)
- effects(<Random>) -- non-deterministic (random number generation)
- effects(<DB>) -- SQL database access
- effects(<Diverge>) -- may not terminate
- effects(<Diverge, IO>) -- divergent with IO
- ```
- `Diverge` is a built-in marker effect with no operations. Its presence in the
- effect row signals that the function may not terminate. Functions without
- `Diverge` must be proven total (via `decreases` clauses on recursion). Use it
- for a loop with no bound, such as a server or read-eval loop: a function that
- declares it needs no `decreases`, and compiles like any other; it has a
- termination guard only if it also declares `decreases`. Like any effect, it
- propagates: every function that calls a `Diverge` function must declare
- `Diverge` too (`E125`), up to `main`.
- Every entry of a row names a built-in effect. An effect variable may stand in
- a function type's row, a parameter typed `fn(A -> B) effects(<E>)`, and never
- in a function's own row: `forall<E> fn f(...) effects(<E>)` is refused at check
- (`E340`), since code generation compiles each instantiation's types and never
- its row. A user-declared effect (`effect Logger { op log(String -> Unit); }`)
- checks as a declaration, and no row may name it: nothing implements its
- operations, and a handler for it is refused too, so a row naming it, a
- function's, a closure's or a function type's, is refused at check (`E340`),
- and so is a call of one of its operations under a row that does not name it.
- `State` and `Exn` take their type argument in a row: `effects(<State<Int>>)`,
- never `effects(<State>)` (`E340`).
- An operation is held to the row in force where it is performed, as a call to a
- function is: `Random.random_int(1, 6)` in a function declared `effects(<IO>)`
- is refused at the call (`E125`), and under `effects(pure)` the function is
- refused (`E122`). A row variable names no effect, so `effects(<IO, E>)`
- permits `IO`'s operations and no others. A handler's body is checked under the
- row around it with the handled effect added. A closure's body is checked under
- the closure's own row, which a handler around the closure does not extend, so
- a closure that performs a `State` or `Exn` operation writes the handler inside
- its own body (`E340` otherwise).
- ### Effect declarations
- The IO effect is built-in, so no declaration is needed. It provides these operations:
- | Operation | Signature | Description |
- |-----------|-----------|-------------|
- | `IO.print` | `String -> Unit` | Print a string to stdout (no implicit newline; flushes per call) |
- | `IO.read_line` | `Unit -> String` | Read a line from stdin |
- | `IO.read_char` | `Unit -> Result<String, String>` | Read one character from stdin: cbreak mode on a Unix TTY, where Ctrl-D gives `Err("EOF")`; redirected input reads one character from the stdin stream and gives `Err("EOF")` at end of input. Not supported on the browser target, which would need JSPI for suspend/resume. |
- | `IO.read_file` | `String -> Result<String, String>` | Read file contents |
- | `IO.write_file` | `String, String -> Result<Unit, String>` | Write string to file |
- | `IO.read_bytes` | `String -> Result<Array<Byte>, String>` | Read a file's bytes, unchanged (no UTF-8 decoding, no newline translation) |
- | `IO.write_bytes` | `String, Array<Byte> -> Result<Unit, String>` | Write bytes to a file, unchanged |
- | `IO.args` | `Unit -> Array<String>` | Get command-line arguments |
- | `IO.exit` | `Int -> Never` | Exit with status code |
- | `IO.get_env` | `String -> Option<String>` | Read environment variable |
- | `IO.sleep` | `Nat -> Unit` | Pause execution for N milliseconds |
- | `IO.time` | `Unit -> Nat` | Current Unix time in milliseconds |
- | `IO.stderr` | `String -> Unit` | Print a string to stderr |
- Do **not** write an `effect IO { ... }` block: redeclaring a built-in effect is a compile error (`E152`), whether or not the signatures match the built-in. The same holds for `State<T>`, `Exn<E>`, `Http`, `Random`, `Inference`, `DB`, `Diverge`, `Async`, and `HttpServer`. Declaring `effects(<IO>)` on the function is all that is needed; the operations follow from the effect row, so there is exactly one way to write the program.
- **Output buffering and live writes.** Under `vera run` text mode, every `IO.print` call writes to `sys.stdout` and flushes immediately, so animations, progress bars, REPLs, and any output using ANSI escape sequences (cursor home, clear screen) render in real time. The captured transcript is *also* preserved in memory so that if the program traps, every byte printed before the trap reaches `WasmTrapError.stdout` and the JSON envelope's `stdout` field. Under `vera run --json`, live mirroring is suppressed: the transcript lives only in the JSON envelope, because writing live to stdout would corrupt the envelope for downstream consumers parsing it. Programs do not need to call any "flush" operation; per-call flushing is the contract.
- ### Performing effects
- Call the effect operations directly:
- <!-- vera:no-run category="fixture" reason="reads data.txt, which the block does not create" -->
- ```vera
- private fn greet(@String -> @Unit)
- requires(true)
- ensures(true)
- effects(<IO>)
- {
- IO.print(@String.0);
- ()
- }
- public fn main(@Unit -> @Unit)
- requires(true)
- ensures(true)
- effects(<IO>)
- {
- match IO.read_file("data.txt") {
- Ok(@String) -> IO.print(@String.0),
- Err(@String) -> IO.print(@String.0)
- };
- ()
- }
- ```
- ### State effects
- ```vera
- private fn increment(@Unit -> @Unit)
- requires(true)
- ensures(new(State<Int>) == old(State<Int>) + 1)
- effects(<State<Int>>)
- {
- let @Int = get(());
- put(@Int.0 + 1);
- ()
- }
- ```
- In `ensures` clauses, `old(State<T>)` is the state before the call and `new(State<T>)` is the state after.
- ### Exception effects
- The `Exn<E>` effect models exceptions with error type `E`. It is built-in, so no
- declaration is needed, and writing one is `E152`. Its single operation is
- `throw : E -> Never`, which never resumes.
- Throw exceptions using the qualified call syntax:
- ```vera
- private fn safe_div(@Int, @Int -> @Int)
- requires(true)
- ensures(true)
- effects(<Exn<String>>)
- {
- if @Int.1 == 0 then {
- Exn.throw("division by zero")
- } else {
- @Int.0 / @Int.1
- }
- }
- ```
- Handle exceptions with `handle[Exn<E>]`:
- <!-- vera:skip-check category="INCOMPLETE" code="E121 E200" reason="calls safe_div, defined in the block above" -->
- ```vera
- private fn try_div(@Int, @Int -> @Option<Int>)
- requires(true)
- ensures(true)
- effects(pure)
- {
- handle[Exn<String>] {
- throw(@String) -> None
- } in {
- Some(safe_div(@Int.0, @Int.1))
- }
- }
- ```
- The handler catches the exception and returns a fallback value. The `throw` handler clause receives the error value and must return the same type as the overall `handle` expression. Exception handlers do not use `resume`; throwing is non-resumable.
- ### Async effect
- The `Async` effect enables asynchronous computation with `Future<T>`:
- <!-- vera:skip-parse category="FRAGMENT" reason="Async effect row declarations, bare clauses" -->
- ```vera
- effects(<Async>) -- async computation
- effects(<IO, Async>) -- async with IO
- ```
- `async` and `await` are built-in generic functions:
- ```vera
- private fn compute(@Int, @Int -> @Int)
- requires(true)
- ensures(true)
- effects(<Async>)
- {
- let @Future<Int> = async(@Int.1 * 2);
- let @Future<Int> = async(@Int.0 * 3);
- await(@Future<Int>.0) + await(@Future<Int>.1)
- }
- ```
- `async(expr)` evaluates `expr` and wraps the result in `Future<T>`. `await(@Future<T>.n)` unwraps it.
- **Concurrency:** `async(Http.get(url))` and `async(Http.post(url, body))`, with call-free argument expressions, run **concurrently** in the native runtime: the request is issued on a worker thread at the `async(...)` point, and `await` blocks for the response. Fire several, then await them in any order to overlap network latency:
- <!-- vera:no-run category="network" reason="calls Http, so a run would reach the network" -->
- ```vera
- public fn fan_out(@String, @String -> @Bool)
- requires(true) ensures(true) effects(<Http, Async>)
- {
- let @Future<Result<String, String>> = async(Http.get(@String.1));
- let @Future<Result<String, String>> = async(Http.get(@String.0));
- let @Result<String, String> = await(@Future<Result<String, String>>.1);
- let @Result<String, String> = await(@Future<Result<String, String>>.0);
- true
- }
- ```
- Every other `async` shape evaluates eagerly (sequential), and `Future<T>` is then `T`'s representation with no overhead. The checker warns (`W002`) when the argument's effect row falls outside the commutative whitelist `{Http, Async}` (e.g. an `IO`-effectful call), marking where eager evaluation is semantically required. The browser runtime is always eager (identical values, request fires at the `async` point).
- ### HttpServer effect
- `HttpServer` is a marker effect (no operations) for **verified HTTP request handling**. Define a total handler and serve it with `vera serve prog.vera [--port N]`; the accept loop lives in the host, so no `Diverge` is involved and every contract on the handler is an ordinary obligation. `Request` / `Response` are built-in prelude ADTs:
- <!-- vera:no-run category="non-scalar-entry" reason="its exported functions take Request parameters" -->
- ```vera
- public fn handle(@Request -> @Response)
- requires(true) ensures(true) effects(<HttpServer>)
- {
- match @Request.0 {
- Request(@String, @String, @Map<String, String>, @String) ->
- Response(200, map_new(), @String.0)
- }
- }
- ```
- Request fields: method, path, headers (`Map<String, String>`), body. In the match arm above the String bindings are method (`@String.2`, oldest), path (`@String.1`), body (`@String.0`, most recent). Response fields: status (`Int`), headers, body. Each request runs on a fresh instance (State cannot leak between requests); a runtime contract violation answers 500 with the trap diagnostic. It is native-only (no browser serving).
- ### Http effect
- The `Http` effect enables network I/O. It is built-in, so no `effect Http { ... }` declaration is needed.
- | Operation | Signature | Description |
- |-----------|-----------|-------------|
- | `Http.get` | `String -> Result<String, String>` | HTTP GET request |
- | `Http.post` | `String, String -> Result<String, String>` | HTTP POST request (body as JSON; sends `Content-Type: application/json`) |
- <!-- vera:skip-parse category="FRAGMENT" reason="Http effect declarations list" -->
- ```vera
- effects(<Http>) -- network access
- effects(<Http, IO>) -- network + IO
- ```
- Both operations return `Result<String, String>`: `Ok` with the response body on success, `Err` with the error message on failure. Compose with `json_parse` for typed API responses:
- <!-- vera:no-run category="network" reason="calls Http, so a run would reach the network" -->
- ```vera
- public fn fetch_json(@String -> @Result<Json, String>)
- requires(string_length(@String.0) > 0)
- ensures(true)
- effects(<Http>)
- {
- let @Result<String, String> = Http.get(@String.0);
- match @Result<String, String>.0 {
- Ok(@String) -> json_parse(@String.0),
- Err(@String) -> Err(@String.0)
- }
- }
- ```
- Like IO, `Http` is a built-in effect. Unlike IO, it has a fixed set of two operations, so there is no need to restrict operations via an explicit declaration.
- ### Inference effect
- The `Inference` effect makes LLM calls explicit in the type system. It is built-in, so no `effect Inference { ... }` declaration is needed.
- | Operation | Signature | Description |
- |-----------|-----------|-------------|
- | `Inference.complete` | `String -> Result<String, String>` | Send a prompt, return `Ok(completion)` or `Err(message)` |
- <!-- vera:skip-parse category="FRAGMENT" reason="Inference effect declarations list" -->
- ```vera
- effects(<Inference>) -- LLM access
- effects(<Inference, IO>) -- LLM + console output
- effects(<Http, Inference>) -- fetch + LLM
- ```
- Returns `Result<String, String>`: `Ok` with the completion text on success, `Err` with the error message on failure. Provider is selected from environment variables: `VERA_ANTHROPIC_API_KEY`, `VERA_OPENAI_API_KEY`, `VERA_MOONSHOT_API_KEY` (Kimi), `VERA_MISTRAL_API_KEY`, `VERA_XAI_API_KEY` (Grok), or `VERA_DEEPSEEK_API_KEY`. Auto-detection walks the provider registry in insertion order (`anthropic`, `openai`, `moonshot`, `mistral`, `xai`, `deepseek`) and takes the first whose key is set to a non-empty value (an empty string is skipped, as if unset), so when several are set the earliest in that order wins. Setting `VERA_INFERENCE_PROVIDER` (valid values: `anthropic`, `openai`, `moonshot`, `mistral`, `xai`, `deepseek`) skips detection entirely and forces that provider; `VERA_INFERENCE_MODEL` overrides its default model. See [`ENVIRONMENT.md`](ENVIRONMENT.md) for the full env-var reference.
- ```vera
- private fn classify(@String -> @Result<String, String>)
- requires(string_length(@String.0) > 0)
- ensures(true)
- effects(<Inference>)
- {
- let @String = string_concat("Classify the sentiment as Positive, Negative, or Neutral: ", @String.0);
- Inference.complete(@String.0)
- }
- ```
- Compose with `match` to handle the `Result`:
- <!-- vera:skip-check category="INCOMPLETE" code="E200" reason="calls classify, defined in the block above" -->
- ```vera
- public fn safe_classify(@String -> @String)
- requires(string_length(@String.0) > 0)
- ensures(true)
- effects(<Inference>)
- {
- let @Result<String, String> = classify(@String.0);
- match @Result<String, String>.0 {
- Ok(@String) -> @String.0,
- Err(@String) -> "unknown"
- }
- }
- ```
- Like `Http`, `Inference` is host-backed. The browser runtime returns a detailed `Err` explaining that API keys cannot be safely embedded in client-side JavaScript; use a server-side proxy with `Http` instead.
- ### Random effect
- The `Random` effect provides non-deterministic number generation. Like `IO` and `Http`, it is built-in, so no `effect Random { ... }` declaration is needed. Functions that draw random values must declare `effects(<Random>)`, making the non-determinism visible in the type signature.
- | Operation | Signature | Description |
- |-----------|-----------|-------------|
- | `Random.random_int` | `Int, Int -> Int` | Random integer in inclusive range `[low, high]` (caller ensures `low <= high`) |
- | `Random.random_float` | `Unit -> Float64` | Uniform random in `[0.0, 1.0)` |
- | `Random.random_bool` | `Unit -> Bool` | Coin flip |
- ```vera
- private fn pick_card(@Unit -> @Int)
- requires(true)
- ensures(@Int.result >= 1 && @Int.result <= 52)
- effects(<Random>)
- {
- Random.random_int(1, 52)
- }
- ```
- The Python runtime backs Random onto the `random` module (`random.randint`, `random.random()`). The browser runtime backs all three onto `Math.random()`: fast, non-cryptographic, adequate for games and simulations. There is no seeding API (deterministic testing via `handle[Random]` is not supported).
- Functions that mix randomness with other effects compose normally:
- <!-- vera:skip-check category="INCOMPLETE" code="E200" reason="calls pick_card, defined in the block above" -->
- ```vera
- public fn print_random_card(-> @Unit)
- requires(true)
- ensures(true)
- effects(<IO, Random>)
- {
- IO.print(int_to_string(pick_card(())))
- }
- ```
- ### DB effect
- The `DB` effect executes SQL against a relational database. Like `IO` and `Http`, it is built-in, so no `effect DB { ... }` declaration is needed. Functions that read or write the database must declare `effects(<DB>)`.
- | Operation | Signature | Description |
- |-----------|-----------|-------------|
- | `DB.execute` | `String, Array<Option<String>> -> Result<Int, String>` | Runs a write (`CREATE`/`INSERT`/`UPDATE`/`DELETE`); `Ok` carries the affected-row count |
- | `DB.query` | `String, Array<Option<String>> -> Result<Array<Array<Option<String>>>, String>` | Runs a `SELECT`; `Ok` is a grid of rows, each cell an `Option<String>` (SQL `NULL` is `None`) |
- The second argument is the positional parameter list bound to the `?` placeholders: `Some(v)` binds a value, `None` binds SQL `NULL`. Bind data as parameters rather than splicing it into the SQL text; a bound value can never be parsed as SQL, the standard defence against injection.
- <!-- vera:run fn="insert_and_count" stdout="1" -->
- ```vera
- public fn insert_and_count(-> @Int)
- requires(true)
- ensures(true)
- effects(<DB>)
- {
- match DB.execute("CREATE TABLE users (name TEXT, nickname TEXT)", []) {
- Err(@String) -> -1,
- Ok(@Int) -> match DB.execute("INSERT INTO users (name, nickname) VALUES (?, ?)", [Some("Ada"), None]) {
- Err(@String) -> -1,
- Ok(@Int) -> match DB.query("SELECT name, nickname FROM users", []) {
- Err(@String) -> -1,
- Ok(@Array<Array<Option<String>>>) -> array_length(@Array<Array<Option<String>>>.0)
- }
- }
- }
- }
- ```
- A query result is `Array<Array<Option<String>>>`: rows of cells, each cell `Some(text)` or `None` for SQL `NULL`. `NULL` and `""` stay distinct; read a `NOT NULL` column with `option_unwrap_or(cell, "")`. Both operations return `Result`, so a failed statement is the `Err(String)` arm, never a trap.
- **Keep the SQL literal.** The query string must be a literal (or a `string_concat` / `let` chain of literals). A SQL string built from a runtime value (a call result, a parameter, or a `\(expr)` interpolation of one) is a **compile-time error** (`E207`): that is the injection vector. (An interpolation or concatenation whose parts are all literals stays literal, so it is accepted.) Pass every runtime value through a `?` placeholder and the params array: `DB.query("SELECT * FROM users WHERE id = ?", [Some(@String.0)])`, never `DB.query(string_concat("... id = ", @String.0), [])`. A `?`-placeholder/parameter count mismatch is `E208` when both are statically known.
- The connection is chosen by `VERA_DB_URL` (default `sqlite::memory:`, or `sqlite:///path/to/file.db`). The effect is SQLite-only, single-connection, and un-mockable (`handle[DB]` is refused at check, `E340`). The browser runtime returns `Err` for every `DB` operation, and `vera compile --target wasi-p2` rejects `<DB>`.
- ### Effect handlers
- Handlers eliminate an effect, converting effectful code to pure code. Only `State<T>` and `Exn<E>` handlers compile, and a handler for any other effect, built-in (`IO`, `Inference`) or user-declared, is refused at check (`E340`). A `State<T>` cell holds one word, so a `State<String>` or `State<Array<T>>` cell is refused too: wrap the value in a one-constructor `data` type (`private data Text { T(String) }`) and use `State<Text>`. A `State` clause ends in exactly one `resume(...)`, with any branch inside its argument (`resume(if c then { a } else { b })`).
- ```vera
- private fn run_counter(@Unit -> @Int)
- requires(true)
- ensures(true)
- effects(pure)
- {
- handle[State<Int>](@Int = 0) {
- get(@Unit) -> { resume(@Int.0) },
- put(@Int) -> { resume(()) }
- } in {
- put(42);
- get(())
- }
- }
- ```
- Handler syntax:
- <!-- vera:skip-parse category="FRAGMENT" reason="Handler with-clause pseudocode, bare expression" -->
- ```vera
- handle[EffectName<TypeArgs>](@StateType = initial_value) {
- operation(@ParamType) -> { handler_body },
- operation(@ParamType) -> { handler_body } with @StateType = new_value,
- ...
- } in {
- handled_body
- }
- ```
- Use `resume(value)` in a handler clause to continue the handled computation with the given return value.
- For `State<T>`, `put(x)` stores `x` as the new state **intrinsically**; the canonical clause `put(@T) -> { resume(()) }` needs no `with` (see `run_counter` above). A `with @T = expr` clause **overrides** that intrinsic store, letting a clause *transform* what gets written. Inside a `put` clause the state slot `@T.0` is the state **before** the store and `@T.1` is the argument being stored (operation parameters bind first, state last, and the most recent wins):
- <!-- vera:skip-parse category="FRAGMENT" reason="Handler with-clause, bare put arm expression" -->
- ```vera
- put(@Int) -> { resume(()) } with @Int = @Int.1 * 2 -- store double the argument
- ```
- Because `@T.0` is the pre-store state, `with @T = @T.0` keeps the *old* state, which silently undoes the `put`. For an ordinary "store the argument" `put`, omit `with` entirely; reach for it only to transform the stored value. The `with` expression's type must match the handler's state type.
- For the builtin `State` effect the state declaration **is** the `State<T>` cell: its declared type must structurally equal the effect's `T` after alias resolution (for refined types, predicate included), or the handle is a checker error (E336): declare `handle[State<Nat>](@Nat = ...)`, never `(@Int = ...)`. An alias that resolves to `T`, like `type Count = Nat` with `(@Count = ...)`, is fine, and scalar aliases work as the cell type: `handle[State<Count>]`. A refined cell must use a **named** refinement alias on both sides (`type Small = { @Nat | @Nat.0 < 10 }; handle[State<Small>](@Small = 0)`), never an inline refinement literal in the `State<T>` argument (not compilable) or a refinement on the declaration alone (E336: nothing would enforce it). A handler **without** a state declaration binds no state slot in its clauses; in a stateless `put` clause, `@T.0` is the operation's argument.
- ### Qualified operation calls
- When two effects have operations with the same name, qualify the call:
- <!-- vera:skip-parse category="FRAGMENT" reason="Qualified effect calls (State.put, Logger.put)" -->
- ```vera
- State.put(42);
- Logger.put("message");
- ```
- ### State handler with a loop helper
- The most common State pattern uses a `where` block to define a loop helper with `effects(<State<Int>>)`. The handler wraps the entire computation; the helper calls `get` and `put` directly.
- <!-- vera:run fn="sum_with_state" args="5" stdout="15" -->
- <!-- vera:run fn="sum_with_state" args="0" stdout="0" -->
- ```vera
- -- Sum 1..n using State<Int>
- private fn add_value(@Int, @Int -> @Int)
- requires(true)
- ensures(@Int.result == @Int.1 + @Int.0)
- effects(pure)
- {
- @Int.1 + @Int.0
- }
- public fn sum_with_state(@Nat -> @Int)
- requires(true)
- ensures(true)
- effects(pure)
- {
- handle[State<Int>](@Int = 0) {
- get(@Unit) -> { resume(@Int.0) },
- put(@Int) -> { resume(()) }
- } in {
- sum_loop(@Nat.0, 1)
- }
- }
- where {
- fn sum_loop(@Nat, @Nat -> @Int)
- requires(@Nat.0 <= @Nat.1 + 1)
- ensures(true)
- decreases(@Nat.1 + 1 - @Nat.0)
- effects(<State<Int>>)
- {
- if @Nat.0 > @Nat.1 then {
- get(())
- } else {
- put(add_value(get(()), @Nat.0));
- sum_loop(@Nat.1, @Nat.0 + 1)
- }
- }
- }
- ```
- `vera run file.vera --fn sum_with_state -- 5` prints `15`, and `-- 0` prints `0`.
- Key points:
- - The outer function `sum_with_state` is **pure**: the handler discharges the State effect
- - The `where` block helper `sum_loop` has `effects(<State<Int>>)` and uses `get`/`put` directly
- - Functions inside `where` blocks do NOT take `public`/`private` visibility
- - The `put` clause stores its argument as the new state intrinsically, so no `with` clause is needed for the common "store the value" case (a `with` clause is only for *transforming* the stored value; see the handler-syntax notes above)
- - Pure helper functions (like `add_value`) can be called from the `where` block helper (`sum_loop`)
- - The `decreases` clause on the loop helper ensures termination. The runtime guard evaluates a measure on every call, so a `@Nat` subtraction inside it needs the same bound a body would. Here the bound is `requires(@Nat.0 <= @Nat.1 + 1)`: it holds on the last call too, where the counter has passed the limit, and the measure adds before it subtracts. `decreases(@Nat.1 - @Nat.0 + 1)` computes `n - (n + 1)` on that last call and traps. A count-down loop, `decreases(@Nat.0)`, has no subtraction to bound
- ## Where Blocks (Mutual Recursion)
- ```vera
- private fn is_even(@Nat -> @Bool)
- requires(true)
- ensures(true)
- decreases(@Nat.0)
- effects(pure)
- {
- if @Nat.0 == 0 then {
- true
- } else {
- is_odd(@Nat.0 - 1)
- }
- }
- where {
- fn is_odd(@Nat -> @Bool)
- requires(true)
- ensures(true)
- decreases(@Nat.0)
- effects(pure)
- {
- if @Nat.0 == 0 then {
- false
- } else {
- is_even(@Nat.0 - 1)
- }
- }
- }
- ```
- ## Generic Functions
- ```vera
- private forall<T> fn identity(@T -> @T)
- requires(true)
- ensures(true)
- effects(pure)
Lines 2,001–2,697 are not shown. The link to the file on GitHub has every line.
README.md · README · 380 lines
- # Vera
- [](https://veralang.dev)
- [](https://github.com/aallan/vera/actions/workflows/ci.yml)
- [](https://pypi.org/project/veralang/)
- [](https://codecov.io/gh/aallan/vera)
- [](https://github.com/aallan/vera/issues/387)
- **Vera** (v-ERR-a) is a programming language designed for large language models to write. The name comes from the Latin *veritas* (truth). Programs compile to WebAssembly and run at the command line, in the browser, or on stock WASI Preview 2 hosts (the IO and Random surface).
- <!-- vera:run fn="safe_divide" args="2 10" stdout="5" -->
- ```vera
- public fn safe_divide(@Int, @Int -> @Int)
- requires(@Int.1 > 0)
- ensures(@Int.result == @Int.0 / @Int.1)
- effects(pure)
- {
- @Int.0 / @Int.1
- }
- ```
- There are no variable names. `@Int.0` is the most recent `Int` binding; `@Int.1` is the one before. The `requires` clause is a precondition `vera verify` checks at every call site. The `ensures` clause is a postcondition the SMT solver proves statically. The function is `pure`, with no side effects of any kind. If a contract is wrong, `vera verify` refuses the program with a counterexample; a contract the solver cannot decide becomes a runtime check. The compiled program checks its contracts at run time, so a proof that is wrong traps instead of returning a wrong answer. `vera verify` matches every runtime check it reports against the checks in the compiled module (`E541` for a claim with no check), and a contract code generation cannot lower, such as an `ensures` on a function that returns a `String` or an `Array`, has no check, is disclosed as a warning (`E543`) where it is not proved, and is counted as neither proved nor checked.
- ## Why?
- Programming languages have always co-evolved with their users. Assembly emerged from hardware constraints. C from operating systems. Python from productivity needs. If models become the primary authors of code, it follows that languages should adapt to that too.
- The biggest problem models face is coherence over scale, not syntax. Models struggle with maintaining invariants across a codebase, understanding the ripple effects of changes, and reasoning about state over time. They're pattern matchers optimising for local plausibility, not architects holding the entire system in mind. The [empirical literature](https://arxiv.org/abs/2307.12488) shows that models are particularly vulnerable to naming-related errors like choosing misleading names, reusing names incorrectly, and losing track of which name refers to which value.
- Vera addresses this by making everything explicit and verifiable. The model doesn't need to be right; it needs to be checkable. Names are replaced by structural references. Contracts are mandatory. Effects are typed. Every function is a specification that the compiler can verify against its implementation.
- See the **[FAQ](FAQ.md)** for deeper questions about the design: why no variable names, what gets verified, how Vera compares to Dafny/Lean/Koka/F*, and the empirical evidence behind the design choices.
- ## What Vera looks like
- Four examples follow. **[EXAMPLES.md](EXAMPLES.md)** has the full tour (contracts, refinement types, ADTs, effects, exception handling, recursion, Markdown, JSON, HTML, HTTP, SQL and LLM inference).
- ### Contracts the compiler proves
- A precondition like `requires(@Int.1 > 0)` becomes a static obligation at every call site. A call to `safe_divide` whose divisor the verifier can show may not be positive is refused with a counterexample (`E501`); a divisor it can neither prove positive nor show may not be is checked at run time (`E532`).
- <!-- vera:run fn="safe_divide" args="2 10" stdout="5" -->
- ```vera
- public fn safe_divide(@Int, @Int -> @Int)
- requires(@Int.1 > 0)
- ensures(@Int.result == @Int.0 / @Int.1)
- effects(pure)
- {
- @Int.0 / @Int.1
- }
- ```
- The compiler synthesises the same obligations for primitive operations themselves. Computing `@Int.1 / @Int.0` where the verifier finds the divisor can be zero is refused by `vera verify` (E526) rather than left to a runtime trap. A divisor it can neither prove non-zero nor witness a zero for, such as an opaque or untranslatable one, stays Tier 3, guarded at run time by the zero-divisor trap. An array index is proved in bounds where the length is statically known, refused (E527) where it is provably out of bounds, and otherwise bounds-checked at run time; `@Nat` subtraction underflow and `@Int` → `@Nat` narrowing are checked the same way. So a division or array index that `vera verify` reports as proven cannot divide by zero or index out of range for any input. `@Int` division also has an overflow obligation for `INT_MIN / -1`: the verifier proves it, refutes it (E528), or leaves it to the run-time overflow trap. Where the verifier cannot prove one (an opaque divisor, a dynamic array length, or an operation inside a closure body), the runtime guard catches it rather than produce a wrong value. Float division is exempt: dividing by zero gives inf or NaN, not a trap.
- ### Effects are explicit
- Vera is pure by default. A function that calls an LLM says so in its signature. A caller that doesn't permit `<Inference>` cannot invoke it. A caller that doesn't permit `<Http>` cannot invoke it either. Both callers must declare the full effect row.
- <!-- vera:no-run category="network" reason="calls Http, so a run would reach the network" -->
- ```vera
- public fn research_topic(@String -> @Result<String, String>)
- requires(string_length(@String.0) > 0)
- ensures(true)
- effects(<Http, Inference>)
- {
- let @Result<String, String> = Http.get(
- string_concat("https://search.example.com/?q=", @String.0));
- match @Result<String, String>.0 {
- Ok(@String) -> Inference.complete(
- string_concat("Summarise this research:\n\n", @String.0)),
- Err(@String) -> Err(@String.0)
- }
- }
- ```
- The body is six lines. The signature holds the parameter types, contracts and effect declarations, so the body reads like a pipeline. Run a real example with `VERA_ANTHROPIC_API_KEY=sk-ant-... vera run` [`examples/inference.vera`](examples/inference.vera). See [`ENVIRONMENT.md`](ENVIRONMENT.md) for all `VERA_*` environment variables (provider keys, runtime knobs, debug flags).
- ### SQL injection won't compile
- Nearly every SQL injection starts the same way: a query assembled from a value that came from outside the program. Vera makes that unwriteable. The SQL text of `DB.query` / `DB.execute` has to be written into the source, so the query is fixed when the program compiles, and outside data can only reach the database through the `?` placeholders and the params array.
- <!-- vera:no-run category="fixture" reason="queries a users table the block does not create" -->
- ```vera
- public fn find_user(@String -> @Result<Array<Array<Option<String>>>, String>)
- requires(string_length(@String.0) > 0)
- ensures(true)
- effects(<DB>)
- {
- DB.query("SELECT name, email FROM users WHERE name = ?", [Some(@String.0)])
- }
- ```
- Build the query out of the parameter instead, as `string_concat("SELECT ... WHERE name = '", @String.0)`, and the program does not compile. `E207` names string assembly as the injection vector and gives the placeholder rewrite as the fix. The type checker enforces a rule about where the string came from, with no lint to configure and no scanner to run, so the injectable form has no path to a running program. Try it: [`examples/database.vera`](examples/database.vera).
- ### Errors are instructions
- Traditional compilers produce diagnostics for humans: `expected token '{'`. Vera produces instructions for the model that wrote the code. Every error includes what went wrong, why, how to fix it with a concrete code example, and a spec reference.
- ```
- [E001] Error at main.vera, line 2, column 1:
- {
- ^
- Function is missing its contract block. Every function in Vera must declare requires(), ensures(), and effects() clauses between the signature and the body.
- Vera requires all functions to have explicit contracts so that every function's behaviour is mechanically checkable.
- Fix:
- Add a contract block after the signature:
- private fn example(@Int -> @Int)
- requires(true)
- ensures(@Int.result >= 0)
- effects(pure)
- {
- ...
- }
- See: Chapter 5, Section 5.2 "Function Declaration Syntax"
- ```
- Diagnostics carry stable codes, which `vera errors` lists, and are available as structured JSON via the `--json` flag.
- ## Getting started
- ### Prerequisites
- - Python 3.11+
- - Git
- - Node.js 22+ *(optional, for browser runtime and parity tests)*
- ### Installation
- Install the released `veralang` distribution from PyPI:
- ```bash
- python -m venv .venv
- source .venv/bin/activate # Windows: .venv\Scripts\activate
- python -m pip install veralang
- ```
- The distribution is named `veralang`, but the installed command is
- `vera`, and Python code imports it as `import vera`. For editor and agent integration through the language server, install
- `python -m pip install "veralang[lsp]"`. Do not run `pip install vera`: that
- name belongs to an unrelated project on PyPI. The wheel ships the compiler and
- the `vera` command only; the bundled `examples/`, the conformance suite, and
- the specification live in the repository, not in the wheel.
- **Upgrading to 0.2.0:** the checker and verifier are stricter than in 0.1.x, so 0.2.0 refuses some programs 0.1.13 accepted. The most common are a recursive function with neither `decreases` nor `Diverge` (`E137`), a `decreases` measure whose `@Nat` subtraction can underflow, such as the count-up `@Nat.1 - @Nat.0 + 1` (`E502`), or a name, type or effect the checker cannot resolve, which is an error rather than a warning. The [CHANGELOG](CHANGELOG.md) lists each new check.
- The GitHub source route is the recommended environment for agents and for
- anyone learning the language. It provides the examples, conformance programs,
- and spec that [SKILL.md](SKILL.md) teaches from, alongside the toolchain, and
- it is the route for compiler development, unreleased changes, and testing
- the current `main` branch:
- ```bash
- git clone https://github.com/aallan/vera.git
- cd vera
- python -m venv .venv
- source .venv/bin/activate # Windows: .venv\Scripts\activate
- python -m pip install -e ".[dev]"
- ```
- `[dev]` includes everything (tests, linters, the language server). For a lighter
- source install that only adds editor/agent support to the base toolchain, use
- `python -m pip install -e ".[lsp]"` (see [LSP_SERVER.md](LSP_SERVER.md)).
- #### Supported platforms
- CI tests every pull request on Ubuntu x86_64 and Windows against Python 3.12, and every release, the pull request that raises the version, and main every night on:
- - **macOS 15 (Sequoia) and macOS 26 (Tahoe)** on Apple Silicon, against Python 3.11, 3.12, 3.13
- - **Ubuntu 24.04 LTS** on x86_64, against Python 3.11, 3.12, 3.13
- - **Ubuntu 24.04 LTS** on aarch64, against Python 3.12 (an advisory job, which does not gate merges)
- - **Windows Server 2025** on x86_64, against Python 3.11, 3.12, 3.13
- These are the supported images, pinned by name in every job that gates a merge or a release, so a label GitHub moves to a new OS release changes none of them; the nightly run also watches the floating `ubuntu-latest`, `windows-latest` and `macos-latest` labels and Ubuntu 26.04 under Python 3.12, advisory as the aarch64 cell is: a failed watched cell on a scheduled nightly run files an issue and blocks nothing.
- Not tested in CI; every dependency publishes wheels for them:
- - Linux x86_64 with glibc 2.27+ (Ubuntu 18.04+ / Debian 10+ / RHEL 8+)
- - Linux aarch64 with glibc 2.38+ on Python 3.11 / 3.13 (the 3.12 cell is CI-tested above; e.g. Ubuntu 23.10+)
- - macOS 15+ on Intel (x86_64)
- Out of scope, neither supported nor tested in CI. Where no z3-solver wheel matches, `pip install -e .` builds z3-solver from source, and `pip install --only-binary :all: -e .` stops at a "no matching distribution" error instead:
- - **macOS 14 (Sonoma) and earlier.** z3-solver's 5.x wheels are tagged `macosx_13_0`, so on macOS 13 and 14 every dependency resolves to a wheel; CI tests neither, and both are unsupported. macOS 12 and earlier match no z3-solver wheel. See [#691](https://github.com/aallan/vera/issues/691) for the decision and workarounds
- - **Linux aarch64 with glibc < 2.38** (for example Ubuntu 22.04 LTS aarch64); see [#701](https://github.com/aallan/vera/issues/701)
- The macOS 15+ baseline follows [TelemetryDeck's macOS version distribution data](https://telemetrydeck.com/survey/apple/macOS/versions/): macOS 26 (~75%) and macOS 15 (~24%) account for ~99% of the macOS install base, and macOS 14 is ~1.4% and falling. At that share, supporting older macOS versions costs more than it returns.
- ### The workflow
- 
- ```
- $ vera check examples/absolute_value.vera
- OK: examples/absolute_value.vera
- $ vera verify examples/safe_divide.vera
- OK: examples/safe_divide.vera
- Verification: 9 verified (Tier 1)
- $ vera run examples/hello_world.vera
- Hello, World!
- ```
- `vera check` parses and type-checks. `vera verify` adds contract verification with Z3. Tier 1 contracts (decidable arithmetic, comparisons, Boolean logic, ADTs, termination) are proved automatically; contracts Z3 cannot decide become Tier 3 runtime checks, and the few sites with no runtime guard are disclosed as warnings (`E504`, `E506`, `E542`, `E543`) rather than counted in either tier. A function's premises are checked first: a `requires` or `assume` that can never hold is refused (`E538`), so a contradiction proves nothing. A query that runs out of solver time falls back to Tier 3; `--timeout-ms` raises the budget. `vera run` compiles to WebAssembly and executes; a runtime trap names its cause (`@Nat` underflow, a failed contract or `assert`, an index out of bounds, an escaped exception) with a fix.
- ```bash
- vera run file.vera --fn f -- 42 # call function f with argument 42
- vera compile --target browser file.vera # emit browser bundle
- vera compile --target wasi-p2 file.vera # emit a WASI Preview 2 component (IO and Random)
- vera run --target wasi-p2 file.vera # execute under the built-in WASI 0.2 host
- vera serve file.vera # serve handle(Request -> Response) over HTTP (default :8000)
- vera compile --target wasi-p2 --world server file.vera # wasi:http server component for wasmtime serve
- vera test file.vera # contract-driven testing via Z3 + WASM
- vera fmt file.vera # format to canonical form
- vera verify --json file.vera # JSON diagnostics for agent feedback loops
- vera verify --timeout-ms 60000 file.vera # raise the per-query Z3 budget (default 10000 ms)
- vera check --explain-slots file.vera # show slot resolution table (which @T.n maps to which param)
- vera lsp # serve the Language Server Protocol over stdio (see LSP_SERVER.md)
- vera version # print the installed version
- vera builtins --json # list the built-in function registry (no file needed)
- vera effects --json # list the effect and ability registry (no file needed)
- vera errors --json # list the diagnostic-code registry (no file needed)
- ```
- `vera compile --target browser` produces a self-contained bundle (wasm + JS runtime + HTML) that runs in any browser, with no build step and no bundler. Parity tests hold the command-line and browser runtimes to identical behaviour on the pure-language surface (arithmetic, ADTs, pattern matching, closures, contracts, effects as host imports, and so on). Two operations on that surface, `json_stringify` (spec §9.7.1) and `md_render` (§9.7.3), emit a canonical form the specification states, so their tests assert the expected string as well as cross-host equality. For `md_parse`, §9.7.3 states the grammar itself (the character classes it is written in, the order in which block constructs claim a line, the width a list continuation loses), and both parsers read one shared table of its patterns; on every pull request both hosts parse a generated corpus and the resulting ADTs are compared byte for byte. `Inference.complete`, `DB.query` and `DB.execute` return `Err` from every browser call, because the credential each needs would be readable from the page source; reach them through a server-side endpoint called with `Http`, which does run in the browser. The IO surface is the other documented exception. Terminal programs that use `IO.sleep` for animation pacing or ANSI escape codes for cursor control compile to `--target browser`, but render the escapes as literal text and freeze the tab while sleeping. The browser target expects Vera to be the pure simulation core and JavaScript to drive timing and rendering ([SKILL.md §Browser compilation](SKILL.md#browser-compilation) has the recommended pattern).
- `vera compile --target wasi-p2` targets **WASI Preview 2 for the IO and Random surface**: it emits a binary WebAssembly component whose host imports are implemented over WASI 0.2 interfaces, runnable by any stock wasip2 host (`wasmtime run` needs no flags and no Vera bindings). A program that uses a host family beyond IO and Random is rejected with a diagnostic naming the family, rather than compiled against the core target. See [spec chapter 13](spec/13-wasi.md) for the architecture, the supported surface, and the documented divergences (WASI 0.2's ok/err-only exit codes, no structured trap frames across the component boundary). With `--world server`, the same contract-verified `handle(Request -> Response)` program that `vera serve` hosts natively compiles to a `wasi:http/incoming-handler` component that stock `wasmtime serve` runs unmodified, so a verified HTTP handler deploys as a portable component. `--world server` is valid only with `--target wasi-p2`; the CLI rejects other combinations.
- ### Editor support
- Vera ships a [language server](LSP_SERVER.md) (`vera lsp`, via the optional `[lsp]` extra) that keeps a warm incremental Z3 session between keystrokes. It gives diagnostics, proofs, hover, slot go-to-definition and typed-hole completion at editor latency, and custom proof-delta methods for coding agents. See **[LSP_SERVER.md](LSP_SERVER.md)** for setup and the full protocol surface.
- - **[VS Code extension](https://marketplace.visualstudio.com/items?itemName=veralang.vera-language)**: install from the Marketplace with `code --install-extension veralang.vera-language`; starts the language server automatically, plus syntax highlighting and language configuration ([source](editors/vscode/))
- - **[Vim package](editors/vim-veralang/)**: syntax highlighting for Vim 8+ and Neovim, installed as a native package or through a plugin manager (the filetype is `veralang`, because Vim has used `vera` for an unrelated language since 2005)
- - **[TextMate bundle](editors/textmate/)**: syntax highlighting for Sublime Text and other TextMate-grammar editors (any editor with a generic LSP client can use `vera lsp` directly)
- ## For agents
- Vera ships with these files for LLM agents:
- - [`SKILL.md`](SKILL.md): the complete language reference, covering syntax, slot references, contracts, effects, common mistakes, and working examples.
- - [`AGENTS.md`](AGENTS.md): instructions for any agent system (Copilot, Cursor, Windsurf, custom), for writing Vera code and for working on the compiler.
- - [`CLAUDE.md`](CLAUDE.md): project orientation for Claude Code, with the key commands, layout, workflows and invariants.
- - [`DE_BRUIJN.md`](DE_BRUIJN.md): Vera's typed slot references in depth, covering the academic background, worked examples, the commutative-operations trap, and connections to proof assistants and LLM code-generation research.
- - [`TOOLCHAIN.md`](TOOLCHAIN.md): the CLI cookbook for driving the toolchain to write, verify, test, run, and debug Vera, plus the `builtins`/`effects`/`errors` introspection commands.
- **Claude Code** discovers `SKILL.md` and `CLAUDE.md` automatically in this repo. For other projects, install the skill manually:
- ```bash
- mkdir -p ~/.claude/skills/vera-language
- cp /path/to/vera/SKILL.md ~/.claude/skills/vera-language/SKILL.md
- ```
- **Other models** can take `SKILL.md` in the system prompt, as a file attachment, or as a retrieval document. The file is self-contained and works with any model that can read markdown.
- Every Vera example in `SKILL.md`, this README, the FAQ, `EXAMPLES.md`, the spec and the website is checked, verified and, where it names an expected output, run in CI, or carries a marker that says why it is not (a fragment, or a deliberate mistake), so an agent learns from code that passes the toolchain.
- **Essential rules** for writing Vera code:
- 1. Every function needs `requires()`, `ensures()`, and `effects()` between the signature and body
- 2. Use `@Type.index` to reference bindings: `@Int.0` is the most recent `Int`, `@Int.1` is the one before
- 3. Declare all effects: `effects(pure)` for pure functions, `effects(<IO>)` for IO, etc.
- 4. Recursive functions need a `decreases()` clause, or `Diverge` in their effect row if they may not terminate (`E137`)
- 5. Match expressions must be exhaustive
- ## Project status
- Vera is in **active development**, released to [PyPI](https://pypi.org/project/veralang/) as `veralang` with notes for each [release](https://github.com/aallan/vera/releases). **[TESTING.md](TESTING.md#overview)** counts the test suite, the conformance programs and the examples, and **[HISTORY.md](HISTORY.md)** tells how the compiler was built. Known bugs and limitations are tracked in **[KNOWN_ISSUES.md](KNOWN_ISSUES.md)**.
- The reference compiler works: parser, AST, type checker, contract verifier (Z3), WASM code generator, module system, browser runtime, and runtime contract insertion. The language specification is in draft, in [`spec/`](spec/).
- **Key features:** [typed De Bruijn indices](DE_BRUIJN.md) (`@T.n`), mandatory contracts, termination checking (`decreases`, or `Diverge` for a function that may not terminate), algebraic effects (IO, Http, HttpServer, State, Exn, Async, Inference, DB, Random, Diverge; handlers compile for `State` and `Exn` only), refinement types, constrained generics (Eq, Ord, Hash, Show), algebraic data types, pattern matching, modules, the built-in functions `vera builtins` lists (strings, arrays, maps, sets, decimals, math, JSON, HTML, Markdown, regex, base64, URL), contract-driven testing, runtime traps that name their cause, canonical formatter, browser runtime, three-tier verification design (Z3 static and runtime fallback shipped; the Z3-guided tier is specified but not implemented), a [language server](LSP_SERVER.md) with warm incremental verification and agent-facing proof-delta methods, and contract-verified HTTP handlers served natively (`vera serve`) or as wasi:http components for stock `wasmtime serve` (`--target wasi-p2 --world server`).
- **What's next:** **[ROADMAP.md](ROADMAP.md)** sets out the stages from a working language to the language agents use. The flagship goal is a verified MCP tool server where contracts guarantee tool schemas at compile time. **[VeraBench](https://github.com/aallan/vera-bench)**, a 60-problem benchmark across 5 difficulty tiers, covers 9 models across 3 providers (VeraBench v0.0.18, measured on Vera v0.1.8). Six of the nine write 100% correct Vera, a language none of them was trained on. Vera has the highest score, or level with it, for six of the nine models. The metric is **% solved** (pass@1): a refusal, a compile failure, a crash and a wrong answer all count alike as not solved. All 60 problems are graded, so a single problem moves a score by 1.7 percentage points and most gaps are one or two problems wide; the [full report](https://github.com/aallan/vera-bench) has the details.
- Known bugs and open issues are tracked on the **[issue tracker](https://github.com/aallan/vera/issues)**. See **[KNOWN_ISSUES.md](KNOWN_ISSUES.md)** for a consolidated list.
- The compiler is a seven-stage pipeline; [vera/README.md](vera/README.md) describes the architecture in depth:
- 
- <details>
- <summary><strong>Project structure</strong></summary>
- ```
- vera/
- ├── SKILL.md # Language reference for LLM agents
- ├── AGENTS.md # Instructions for any AI agent system
- ├── CLAUDE.md # Project orientation for Claude Code
- ├── FAQ.md # Design rationale and comparisons
- ├── EXAMPLES.md # Language tour with code examples
- ├── HISTORY.md # How the compiler was built
- ├── ROADMAP.md # Forward-looking language roadmap
- ├── KNOWN_ISSUES.md # Known bugs and limitations
- ├── DESIGN.md # Technical decisions and prior art
- ├── TESTING.md # Testing reference (single source of truth)
- ├── CONTRIBUTING.md # Contributor guidelines
- ├── CHANGELOG.md # Version history
- ├── LICENSE # MIT licence
- ├── spec/ # Language specification, a file per chapter
- ├── vera/ # Reference compiler (Python)
- │ ├── grammar.lark # Lark LALR(1) grammar
- │ ├── parser.py # Parser module
- │ ├── ast.py # Typed AST node definitions
- │ ├── transform.py # Lark parse tree → AST transformer
- │ ├── resolver.py # Module path resolution
- │ ├── checker/ # Type checker (mixin package)
- │ ├── verifier.py # Contract verifier (Z3)
- │ ├── codegen/ # Code generation
- │ ├── wasm/ # WASM translation
- │ ├── browser/ # Browser runtime
- │ ├── formatter.py # Canonical code formatter
- │ ├── errors.py # LLM-oriented diagnostics
- │ ├── obligations/ # Reified proof obligations + warm incremental verification
- │ ├── lsp/ # Language server (see LSP_SERVER.md)
- │ └── cli.py # Command-line interface
- ├── docs/ # GitHub Pages site (veralang.dev)
- ├── editors/ # VS Code extension (LSP client + grammar), Vim package, TextMate bundle
- ├── examples/ # Example Vera programs
- ├── tests/ # Test suite (see TESTING.md)
- └── scripts/ # CI and validation scripts
- ```
- </details>
- For compiler architecture and internals, see [`vera/README.md`](vera/README.md). For testing details, see **[TESTING.md](TESTING.md)**.
- ## Design
- See **[DESIGN.md](DESIGN.md)** for the full technical decisions table (representation, references, contracts, effects, verification, memory, target, grammar, diagnostics, data types, polymorphism, collections, error handling, recursion, naming) and **[prior art](DESIGN.md#prior-art)** (Eiffel, Dafny, F*, Koka, Liquid Haskell, Idris, SPARK/Ada, bruijn, TLA+/Alloy).
- ## Contributing
- See [CONTRIBUTING.md](CONTRIBUTING.md) for guidelines on how to contribute to Vera. For compiler internals, see [vera/README.md](vera/README.md).
- ## Citation
- If you use Vera in your research, please cite:
- ```bibtex
- @software{vera2026,
- author = {Allan, Alasdair},
- title = {Vera: a programming language designed for LLMs to write},
- year = {2026},
- url = {https://github.com/aallan/vera}
- }
- ```
- ## Licence
- Vera is licensed under the [MIT License](LICENSE).
- Every dependency Vera redistributes is under a permissive licence compatible with MIT. `scripts/check_licenses.py` enforces this for the Python side on every commit that changes `pyproject.toml` and in CI, checking installed packages transitively; the npm packages the VS Code extension bundles are listed here, and no gate checks them.
- | Dependency | Licence | Role |
- |-----------|---------|------|
- | [Lark](https://github.com/lark-parser/lark) | MIT | LALR(1) parser generator |
- | [z3-solver](https://github.com/Z3Prover/z3) | MIT | SMT solver for contract verification |
- | [wasmtime](https://github.com/bytecodealliance/wasmtime) | Apache-2.0 WITH LLVM-exception | WebAssembly runtime |
- | [pygls](https://github.com/openlawlibrary/pygls) | Apache-2.0 | Language-server framework (`[lsp]` extra) |
- | [lsprotocol](https://github.com/microsoft/lsprotocol) | MIT | LSP type definitions (`[lsp]` extra) |
- | [vscode-languageclient](https://github.com/microsoft/vscode-languageserver-node) | MIT | LSP client bundled into the VS Code extension |
- The first three are the toolchain's runtime dependencies; `pygls` and `lsprotocol` arrive with the `[lsp]` extra, which the editor integration needs. `vscode-languageclient` is bundled into the `.vsix` with its own transitive dependencies: `vscode-jsonrpc`, `vscode-languageserver-protocol`, `vscode-languageserver-types`, `vscode-languageserver-textdocument`, `brace-expansion` and `balanced-match` (MIT), `semver` (ISC), and `minimatch` (BlueOak-1.0.0). ISC and BlueOak-1.0.0 are permissive and impose no condition MIT does not.
- Copyright © 2026 Alasdair Allan
- Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
- The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
Ratings and comments
Sign in to rate this skill.
Sign inFree to use. If it’s helped, pass it on.