# Una v0.4.0: the documentation in one file # Get started In about ten minutes you install Una, write a function with a contract, watch `una check` find the input that breaks it, fix it, and build a native executable. You write `wordfreq`, a program that counts the words of a text and prints the counts as JSON. Every code block here is tested against this release, except that the outputs shown in `text` blocks are not compared with a run, and the finished program is `examples/wordfreq`. > [!NOTE] > Una runs on macOS and Linux on arm64. [More about installing](https://una-lang.org/en/install/) lists the supported systems. ## 1. Install Run the installer: ```sh curl -fsSL https://raw.githubusercontent.com/una-lang/una/main/install.sh | sh ``` It puts the release in `~/.una` and changes nothing else. Put that directory on your `PATH`: ```sh export PATH="$HOME/.una/bin:$PATH" ``` To keep it for new shells, add the same line to your shell's profile: `~/.zshrc` for zsh, the default shell on macOS, or `~/.bashrc` for bash. Check that it works: ```sh una --version ``` It prints the release, the editions it serves and the version of the prover built into it. That is everything you need to check, test and run programs. > [!TIP] > Working with an AI agent? Give it [Una, compact](https://una-lang.org/en/docs/agents/compact/): the language in one page, sized for its context. ## 2. A contract, and a proof that fails A contract says what a function needs and what it promises. Una proves it for every input, before the program runs. Make a directory `wordfreq` with two files. `una.toml` names the package and its edition, and the module `wordfreq` lives in `src/wordfreq.una`. Start with a function that takes the first letter of a word: `una.toml` ```toml [package] name = "wordfreq" version = "0.1.0" edition = "0.2" ``` `src/wordfreq.una` ```una module wordfreq --- The first letter of a word. pub initial(word: Text) -> Text ensures result.len == 1 = word.slice(start: 0, end: 1) ``` The line `ensures result.len == 1` is the promise: the result is one character long. In the `wordfreq` directory, run `una check .`: ```text [U5001] Error: precondition `0 <= 0 and 0 <= 1 and 1 <= word.len` of this call is refuted ╭─[ src/wordfreq.una:7:3 ] │ 7 │ word.slice(start: 0, end: 1) │ ──────────────┬───────────── │ ╰─────────────── precondition `0 <= 0 and 0 <= 1 and 1 <= word.len` of this call is refuted │ │ Note 2: counterexample: word = Text#0, word.len = 0 ``` The promise does not hold, and Una shows why: - **The counterexample** is `word.len = 0`: an empty word. - **The cause** is the call of `slice`, which requires its positions to lie in the text. - **The repairs** come with the diagnostic. With `una --json check`, it is a JSON document an agent can act on. The fix is to say what `initial` needs, with `requires`: `una.toml` ```toml [package] name = "wordfreq" version = "0.1.0" edition = "0.2" ``` `src/wordfreq.una` ```una module wordfreq --- The first letter of a word. pub initial(word: Text) -> Text requires word.len >= 1 ensures result.len == 1 = word.slice(start: 0, end: 1) example "a word's first letter" do initial("una") expect result == "u" ``` Now `una check .` prints nothing: every check passes. - **Every caller has to prove the `requires`**, and the body may assume it. - **The `example` is a test.** `una test .` runs it, and `una check` proves that `"una"` meets the `requires`. > [!TIP] > `una explain U5001` explains a diagnostic code, with a failing example and its fix. ## 3. A program that runs Turn the package into a program. Three files: - **`una.toml`** gains a `[run]` section: where `una run` starts, and what the program may use. - **`verification.lock`** fixes the prover's version and settings, so a check that passes on your machine passes on every other. Copy it as it is. - **`src/wordfreq.una`** gets the words of a line, and a `main` that prints how many there are. `una.toml` ```toml [package] name = "wordfreq" version = "0.1.0" edition = "0.2" [run] entry = "wordfreq" grants = ["console"] ``` `verification.lock` ```toml encoding_version = "una-smt-1" solver = "z3" solver_version = "5.1.0" logic = "QF_UFLIA" step_budget = 5000000 random_seed = 0 ``` `src/wordfreq.una` ```una module wordfreq --- The words of a line: the parts between spaces, without the empty ones. pub words(line: Text) -> List[Text] = let space = " " line.split(on: space).filter(keep: fn(part) -> part.len > 0) pub main() -> Unit uses @console: Console[print] = let text = "the cat and the hat and the bat" @console.print("{words(text).len} words") ``` Three things to notice: - **A function is an equation:** its header, then `=`, then its body. - **`split` and `filter` are prelude functions**, called with method syntax. - **`main` says what it uses:** `@console`, with the operation `print`. A function that calls another performs its effects too, so the caller's `uses` must cover them. `una contract` prints a function's header, its `uses` included. Check it and run it: ```sh una check . una run . ``` ```text 8 words ``` `una check` runs every check, the proofs included, and prints nothing when all pass. The source must also be in canonical form; `una fmt .` rewrites it so. ## 4. Maps and JSON Count the words with a `Map`, which keeps its keys in order, and write the counts as JSON. This is the whole program, with `initial` from section 2 back in: `una.toml` ```toml [package] name = "wordfreq" version = "0.1.0" edition = "0.2" [run] entry = "wordfreq" grants = ["console"] ``` `src/wordfreq.una` ```una module wordfreq --- The words of a line: the parts between spaces, without the empty ones. pub words(line: Text) -> List[Text] = let space = " " line.split(on: space).filter(keep: fn(part) -> part.len > 0) --- The first letter of a word. pub initial(word: Text) -> Text requires word.len >= 1 ensures result.len == 1 = word.slice(start: 0, end: 1) --- How often each word occurs, in ascending order of the words. pub counts(words: List[Text]) -> Map[Text, Int] = let edit counts: Map[Text, Int] = empty_map() for word in words let seen = counts.get(key: word) if none use 0 edit counts.set(key: word, value: seen + 1) counts --- The counts as one JSON object. pub report(counts: Map[Text, Int]) -> Text = let edit fields: Map[Text, Json] = empty_map() for entry in counts.entries() edit fields.set(key: entry.key, value: Number(entry.value)) Object(fields).to_json() pub main() -> Unit uses @console: Console[print] = let text = "the cat and the hat and the bat" @console.print(report(counts(words(text)))) example "a word's first letter" do initial("una") expect result == "u" example "each word is counted" do counts(words("a b a")) expect result == empty_map().with(key: "a", value: 2).with(key: "b", value: 1) ``` - **Values, not references.** `let edit` declares a binding that the code may change. `edit counts.set(...)` gives `counts` a new map, which is updated in place when nothing else holds it. - **Absence is a value.** `get` returns an `Option`: `if none use 0` handles a word not seen yet. - **One effect per line.** Each line that can fail or act is handled on the lines below it, as `if none` here. ```sh una test . una run . ``` ```text {"and":2,"bat":1,"cat":1,"hat":1,"the":3} ``` ## 5. Capabilities and grants `main` uses `Console[print]` and nothing else, and `una run` gives it exactly what `[run] grants` lists in `una.toml`. - **Without `"console"` there, the program does not start:** U3012 names the capability that is missing. - **A grant can also come from the command line:** `una run . --grant console`. The host offers these capabilities, only to `main`, which passes them to the functions it calls: | Capability | Since edition | | --- | --- | | `Console`, `Clock`, `Env`, `Files`, `Keys` | `0.1` | | `Http` | `0.2` | | `HttpServer`, for a program that serves HTTP | `0.4` | Edition `0.4` offers them to the entry functions of a driven or served module too ([Serving HTTP](https://una-lang.org/en/docs/guides/serving-http/), [Driven programs](https://una-lang.org/en/docs/guides/driven-programs/)). > [!NOTE] > Information flow is checked too. Text that comes from the outside, as `Files.read` returns, is labeled `internal`, and printing it needs a declassification policy (§9 of [the guide for agents](https://una-lang.org/en/docs/agents/)). ## 6. A native executable `una build` checks the package, then compiles `main` into a native executable, with the grants of `una.toml` built in: ```sh una build . ./target/una/wordfreq ``` ```text built target/una/wordfreq {"and":2,"bat":1,"cat":1,"hat":1,"the":3} ``` The executable prints what `una run` prints, and traces the same events: the interpreter is the reference, and the test suite runs every example program in both. > [!NOTE] > On Linux, `una build` links the executable through `cc`, against the system's C library: without `cc` it stops with "cannot run the system linker `cc`". The executable runs on the machine that built it and on systems with the same or a newer glibc, not on musl systems. ## 7. An editor `una lsp` is a language server (LSP 3.17 over stdin and stdout) for any editor that speaks the protocol: it checks as you type, proves a file when it is opened or saved, formats on request, and never runs programs. ## 8. Edition 0.4 `wordfreq` is a package of edition `0.2`, a stable edition. Edition `0.4` is a preview: a later release may still change what it accepts. It adds: - programs that run until they are stopped; - tasks and time limits; - HTTP servers; - dependencies on other packages through Itá, the package manager (in this release, path dependencies and registry packages read from a mirror directory). A package of edition `0.4` is described by `ita.una` and pinned by `ita.lock`, not by `una.toml` and `verification.lock`: `una.toml` naming `edition = "0.4"` is U7002, and `una migrate` is the repair. To move a copy of `wordfreq` to edition `0.4`: 1. Its tests are written `example`, the form of editions `0.1` and `0.2`. From edition `0.3` on they are written `test`, and `una fix` rewrites them in a package of edition `0.3` only. So first set `edition = "0.3"` in `una.toml`, then run `una fix .`, which rewrites both tests. 2. Run `una migrate .`. It writes `ita.una` and `ita.lock`, removes `una.toml` and `verification.lock`, and prints every diagnostic that the change of edition causes, none here. 3. `una check .`, `una test .` and `una run .` then work as before, in edition `0.4`. The `ita.una` it writes: ```text ita wordfreq version 0.1.0 edition 0.4 run entry wordfreq grants console ``` The pages on edition `0.4` are [Tasks and time](https://github.com/una-lang/una/blob/main/docs/guide/tasks-and-time.md), [Serving HTTP](https://github.com/una-lang/una/blob/main/docs/guide/serving-http.md), [Driven programs](https://github.com/una-lang/una/blob/main/docs/guide/driven-programs.md) and [the package manager](https://github.com/una-lang/una/blob/main/docs/guide/configure/ita/commands.md); [Known limits](https://github.com/una-lang/una/blob/main/docs/guide/known-limits.md) says what this release does not do yet. ## Where next - **With an agent:** [Una, compact](https://una-lang.org/en/docs/agents/compact/) is the language in one page, and [the guide for agents](https://una-lang.org/en/docs/agents/) is the full reference to edition `0.2`, with notes where editions `0.3` and `0.4` differ. - **A construct:** [the syntax reference](https://una-lang.org/en/docs/language/) lists the constructs of edition `0.2`, and some of what editions `0.3` and `0.4` add. - **A diagnostic:** `una explain ` explains any code, with examples. - **The definition:** [the specification](https://github.com/una-lang/una/tree/main/docs/spec) is normative. --- # At a glance Una is a verification-first language for machine-generated software. Its design follows a few visible rules: - **A function is an equation.** The header is the contract; `=` separates it from the body, the implementation. - **`@` marks direct capability operations.** Every direct interaction with the outside world goes through a capability written `@name`. A call performs the effects of the function it calls, which the caller's `uses` cover, so a header lists everything its body may do. - **Words over symbols:** `and`, `or`, `not`, `implies`, `mod`, `if error fail`. - **One canonical form:** significant indentation of 2 spaces, one formatter, and non-canonical source is an error. - **Nothing implicit.** No exceptions, no null, no implicit conversions, no ambient authority, no shared mutable state. ```una module events.seating pub kind Seats = Int in 0..5000 pub kind Availability = SoldOut | Few | Open pub kind Event name: Text remaining: Seats --- Availability bands for an event. pub availability(e: Event) -> Availability ensures e.remaining < 1 implies result is SoldOut = when e.remaining in 0..0 -> SoldOut in 1..<20 -> Few in 20..5000 -> Open ``` The compiler proves the `ensures` clause and that the three ranges cover every possible `Seats` value, before the program runs. The same package runs in the interpreter (`una run`) or compiles to a native executable (`una build`). --- --- # Lexical structure ## 1.1 Files and characters | Rule | Detail | Error | | --- | --- | --- | | Encoding | UTF-8, with no byte order mark | U0001 | | Line endings | The lexer accepts `\n` and `\r\n` (read as `\n`); a lone `\r` is rejected. Only `\n` is canonical: `una check` reports a file with `\r\n` as one U7001 at the first of them, without an edit, and `una fmt` rewrites the file with `\n` (§13). | U0001, U7001 | | One module per file | Extension `.una` | | | ASCII outside literals and comments | Identifiers, keywords and punctuation are ASCII. Other characters (accents, CJK, emoji) may appear only inside text literals and comments. | U0001 | | Control characters | U+0000 to U+001F (except tab and line feed) and U+007F are forbidden everywhere, including literals and comments | U0001 | | Bidirectional controls | U+202A to U+202E and U+2066 to U+2069 are forbidden everywhere, as a defense against "Trojan Source" attacks | U0001 | Characters that are forbidden in raw form can still appear in text through escapes: `"\u{202E}"` is valid. ## 1.2 Indentation Una uses significant indentation. - **Spaces only.** A tab in leading whitespace is an error (U0002). Tabs inside literals and comments are allowed. - **Exactly 2 spaces per level.** Any other depth is an error (U0003), and so is dedenting to a column no enclosing block uses. - **Blank and comment-only lines** do not affect indentation. - **Inside `( )` and `[ ]`**, the parser accepts line breaks and ignores the indentation of continued lines. The canonical form has no line width, so it joins continued lines into one: `una fmt` joins them, and `una check` reports the split as U7001. The only exception is a line with a comment inside its brackets, whose line breaks are kept, each continuation line one level deeper (§13). - **Brackets must be balanced** within a declaration (U0101). ```una module demo add_all(first: Int, second: Int) -> Int = first + second pub total(a: Int, b: Int) -> Int requires a >= 0 = let sum = add_all(first: a, second: b) sum ``` ## 1.3 Comments | Form | Meaning | | --- | --- | | `-- text` | Line comment | | `--- text` | Doc comment. Consecutive lines attach to the next declaration and appear in `una contract` output. | - There are no block comments. - A doc comment that is not followed by a declaration (at end of file, inside a body, or before `module`) is treated as a plain comment. ## 1.4 Identifiers and naming conventions | Token | Pattern | Used for | | --- | --- | --- | | lower identifier | `[a-z][a-z0-9_]*` | values, parameters, fields, functions, predicates, handlers, policies, module path segments, capability operations | | upper identifier | `[A-Z][A-Za-z0-9_]*` | kinds, variants, capabilities, label categories, requirement IDs | | capability reference | `@` followed by a lower identifier | `@audit`, `@console` | Naming problems fall into two cases. **Wrong case class: a parse error (U0101).** Where the grammar expects an upper identifier, a lower one is not a name at all, and the reverse: | You wrote | Message | | --- | --- | | `kind bad_kind = Int` | unexpected `bad_kind`, expected a kind name | | a variant written in lowercase, as in `kind K = \| open` | unexpected `open`, expected a variant name | | `requirement events3` | unexpected `events3`, expected a requirement identifier | **Right case class, wrong convention: U1005.** The name has the right first letter, but breaks the convention of its class: - lower identifiers use `snake_case`, without `__` and without a trailing `_` (`f__x`, `g_`); - kinds, variants, capabilities and categories use `UpperCamelCase` (`Bad_Name`); - requirement IDs use upper snake case ending in `_` and a number: `EVENTS_3`, `CHECKIN_12` (not `Events_3`). The message names the construct and suggests a fix: "kind `Bad_Name` must be UpperCamelCase, as in `BadName`". Names cannot start with `_` (U0001, with the hint "names start with a letter"). A reserved keyword cannot name a binding: `let result = ...` is U0101, and the message says what the word is reserved for (`result` names a function's result in `ensures`). ## 1.5 Keywords **Reserved in every edition.** These are never usable as names: ```text accepts and attempt capability checked confidential derived do else ensures error example expect fail fails false fn for from given handler if implies import in internal is it kind let mod module none not op opaque or pass performed policy predicate pub public reflect requirement requires restricted result secret then true trusted unit use uses when where with ``` **Keywords of edition `0.2`.** `edit`, `take` and `old` (the memory model, `spec/17`) and `together` (structured concurrency, `spec/19`). In edition `0.1`, `old` is an ordinary name and the others give the U0103 messages of the v0.1 table below. **Contextual.** These are keywords only inside `requirement` and `policy` blocks, and ordinary names elsewhere (a parameter called `status` or `source` is fine): ```text active generated human owner proposed purpose regulation source status text to via ``` `Eq`, `Ord` and `Integer` are prelude names of edition `0.2`, the built-in constraints of §3.3, and `I8` to `U64` are built-in kinds (§3.1). A kind, variant or capability with one of these names is U1002, as is one named like any other built-in type: `Int`, `Nat`, `Bool`, `Text`, `Unit`, `Hashed`, `List`, `Option`, `Result` or `Map` (ADR 0079). **Reserved for later, or deliberately absent** (U0103). The message is `` `` is `` followed by the text below, as in "`macro` is not supported (charter §6)", and names the plan or the Una alternative. In edition `0.2`: | Word | Message | | --- | --- | | `shared`, `iso`, `weak` | reserved for a later edition (aliasing) | | `parallel`, `actor` | reserved for a later version (concurrency beyond `together`) | | `simd`, `profile` | reserved for v0.2 (systems profile) | | `trait`, `impl` | reserved for a later version (user traits) | | `law`, `all` | reserved for a later edition (laws) | | `costs` | reserved for a later edition (cost contracts) | | `traced` | reserved for a later edition (provenance tracing) | | `service`, `table`, `query`, `observe`, `commit` | reserved for a later edition (platform) | | `match` | not a keyword in Una; use `when` | | `return` | not a keyword in Una; the last expression is the result | | `var` | not a keyword in Una; use `let edit` | | `while`, `loop` | not a keyword in Una; use `for` or recursion | | `region` | not a keyword in Una; the backend chooses where values live | | `type` | not a keyword in Una; use `kind` | | `unsafe` | not a keyword in Una; use a `trusted` module | | `macro` | not supported (charter §6) | | `async`, `await` | not supported; use `together` | A package of edition `0.1` keeps the table of v0.1 in every version of the compiler: there, `edit`, `take`, `region`, `shared` and `iso` are "reserved for v0.2 (memory model)", `together`, `parallel` and `actor` "reserved for v0.2 (concurrency)", `trait` and `impl` "reserved for v0.2 (constraints on generics)", `var` says "values are immutable, use `let`", `while` and `loop` say "use recursion or `fold`", and `async` and `await` "see structured concurrency in v0.2". ## 1.6 Literals **Integers** - Decimal only, with `_` allowed between digits: `0`, `42`, `1_000_000`. - Negative numbers use unary minus: `-5`. A negated literal counts as one literal, so `-128` fits `I8`. - `Int` is unbounded and never overflows. The fixed-width types of §3.1 have a range, and a literal takes the fixed-width type its context expects. - Malformed integers are U0007, with a mechanical fix when unambiguous: | Written | Problem | Fix | | --- | --- | --- | | `007` | leading zero | `7` | | `1__000` | doubled underscore | `1_000` | | `1_` | trailing underscore | `1` | **Text** - Double quotes on a single line: `"hello"`. An unterminated literal is U0004. - Escapes: `\"`, `\\`, `\n`, `\t`, `\{`, `\}`, and `\u{H}` with 1 to 6 hex digits naming a Unicode scalar value. - An unknown or invalid escape (`"C:\data"`, `\u{D800}`, `\u{110000}`, `\u0041`) is U0005. - A bare `}` outside an interpolation is U0007: write `\}`. So is a `{` that no expression can follow, a quote, a backslash or a `}` after any blanks, as in JSON written in text: write `\{`. Each comes with the edit, and the literal goes on, so one brace is one diagnostic. **Interpolation** `"{event.name}: {label}"` embeds an expression between braces. - The embedded expression cannot contain a text literal (U0006). Bind it with `let` first. - Any value that holds no function and no `Hashed` can be interpolated (U2001 otherwise). It is written in its Una form, as `una test` shows it: `Event(name: "Gala", remaining: 3)`, `[1, 2]`, `Some(3)`. A `Text` inside it is quoted. A value of a type parameter `T` needs `[T: Eq]` (U2026). In edition 0.1, only integers, `Bool` and `Text` can be interpolated (ADR 0068). - A missing closing `}` is reported as U0004 at the opening quote. - Interpolation **propagates labels**: `"id {phone}"` is as secret as `phone` (§8). ```una module demo pub kind Status = SoldOut | Few | Open pub kind Event name: Text remaining: Int --- A record is interpolated as it is, or field by field for a shorter text. pub describe(event: Event) -> Text = "{event.name} ({event.remaining} seats)" --- The whole record: `Event(name: "Gala", remaining: 3)`. pub raw(event: Event) -> Text = "{event}" pub banner(event: Event, status: Status) -> Text = let label = when status is SoldOut -> "sold out" is Few -> "few seats left" is Open -> "open" "{describe(event)}: {label}" ``` **Other literals:** `true`, `false`, and `unit`, the only value of type `Unit`. ## 1.7 Operators and precedence From highest to lowest precedence: | Level | Operators | Associativity | | --- | --- | --- | | 1 | call `f(..)`, field or method `.name`, capability operation `@c.op(..)` | left | | 2 | unary `-` | prefix | | 3 | `*` `/` `mod` | left | | 4 | `+` `-` | left | | 5 | `==` `!=` `<` `<=` `>` `>=` `is` `in` | none | | 6 | `not` | prefix | | 7 | `and` | left | | 8 | `or` | left | | 9 | `implies` | right | Nuances: - **No chained comparisons.** `0 < x < 10` is U0101; write `0 < x and x < 10`, or `x in 1..<10`. - **`not` binds looser than comparisons.** `not a == b` means `not (a == b)`. - **`implies` groups to the right.** `a implies b implies c` means `a implies (b implies c)`. - **`and`, `or` and `implies` short-circuit.** - **Division and `mod` are Euclidean,** so the remainder is never negative: `-7 / 2 == -4` and `-7 mod 2 == 1`. Division by a value the compiler cannot prove nonzero is a proof obligation (§11), never a runtime crash. - **Integer operators take operands of one type.** `a + b` with `a: U8` and `b: U16` is U2001: convert one of them (§3.1). - **Ranges:** `a..b` includes `b`; `a.. # Modules and imports A package with two modules, one importing from the other: `src/shop/prices.una` ```una module shop.prices pub kind Price = Int in 0..1_000_000 pub kind Item name: Text price: Price --- Private: other modules cannot import it (U1004). cents(item: Item) -> Int = item.price pub total(items: List[Item]) -> Int = items.map(each: fn(i) -> cents(i)).sum() ``` `src/shop/cart.una` ```una module shop.cart import shop.prices (Item, total) pub kind Cart items: List[Item] pub cart_total(cart: Cart) -> Int = total(cart.items) ``` - **Module path and file path must match** (U1008): module `shop.cart` lives in `src/shop/cart.una`. - **`trusted module`** marks a module allowed to declare policies (§8.5). It must also be listed in `una.toml`. - **Imports list names explicitly.** Kinds, functions, capabilities, handlers, policies and predicates are all imported the same way. `std.testing` is the only standard module (§12). - **The prelude is imported automatically** (§12). - **Visibility:** declarations are private unless marked `pub`. Using a private declaration from another module is U1004. Import cycles are U1003. - **Order:** declarations can appear in any order within a module. --- --- # Kinds and types ## 3.1 Built-in types | Type | Values | Notes | | --- | --- | --- | | `Int` | mathematical integers | unbounded | | `I8`, `I16`, `I32`, `I64` | `-2^(n-1)` to `2^(n-1) - 1` | edition `0.2`; overflow is a proof obligation | | `U8`, `U16`, `U32`, `U64` | `0` to `2^n - 1` | edition `0.2`; overflow is a proof obligation | | `Nat` | `Int where it >= 0` | prelude alias | | `Bool` | `true`, `false` | | | `Text` | Unicode strings | `t.len` counts Unicode scalar values; in edition `0.2`, `split`, `join`, `find`, `contains_text`, `ends_with`, `replace`, `slice`, `chars`, `bytes`, `to_upper`, `to_lower`, `trim_start`, `trim_end` and `parse_int` (`spec/22`) | | `Unit` | `unit` | | | `List[T]` or `[T]` | `[1, 2, 3]` | values; `xs.len`; changed through `set` and `append` (§5.6) | | `Map[K, V]` | `empty_map().with(key: "a", value: 1)` | edition `0.2`; keys satisfy `Ord`, in ascending order; `m.len`, `has`, `get`, `keys`, `values`, `entries`, `with`, `without`, and `edit m.set` and `edit m.remove` (`spec/21`) | | `Option[T]` | `Some(value)`, `None` | | | `Result[T, E]` | `Ok(value)`, `Err(failure)` | produced by `attempt` (§6.4) | | `Hashed` | opaque digests | produced by the `Keys` capability; only `==` and `!=` | | `fn(A, B) -> C` | lambdas and named functions | not comparable | **Fixed-width integers** (edition `0.2`, `spec/18`). They exist where an exact width matters, such as bytes, protocols and hashing. `Int` stays where it was: list lengths, indices and `Text.len` are `Int`. - **Distinct types.** `I8` to `U64` are distinct from `Int` and from one another, with no implicit conversion. An operator takes operands of one type (U2001). - **Literals** take the fixed-width type their context expects: an annotated `let`, a parameter, a field, a return, the other operand of an operator, or the field of a constructor checked against a known type, as `Some(200)` against `Option[U8]`. A literal that does not fit is U2022. - **Overflow** of `+`, `-`, `*`, `/`, `mod` and unary `-` is a proof obligation of kind `overflow` (§11), never a silent wrap. Clauses (`where`, `requires`, `ensures`) read every integer type as its mathematical value, so `requires a + b <= 255` computes exactly. - **Conversions** are built-in methods: `x.to_i8()` to `x.to_u64()` and `x.to_int()`. Widening, where every value fits, needs no proof. Narrowing carries an `overflow` obligation that the value fits. - **Wrapping and saturating arithmetic** is written out: `a.wrapping_add(by: b)`, `a.saturating_sub(by: b)` and their siblings, never by default. Bit operations are `a.bit_and(mask: m)`, `bit_or`, `bit_xor`, `bit_not()`, `a.shift_right(by: n)` and `a.wrapping_shift_left(by: n)`. ```una module demo pub kind Port = U16 where it > 0 --- Literals take the fixed-width type their context expects. pub defaults() -> List[U8] = [0, 127, 255] pub maybe_byte(flag: Bool) -> Option[U8] = if flag then Some(200) else None --- Overflow is an obligation: `a + b` must fit in `U8`. Clauses compute exactly, so `a + b <= 255` is the mathematical sum. pub add_small(a: U8, b: U8) -> U8 requires a + b <= 255 = a + b --- Wrapping arithmetic is written out, never implied. pub checksum(a: U8, b: U8) -> U8 = a.wrapping_add(by: b) --- Widening needs no proof; narrowing does. pub widen(x: U8) -> I32 = x.to_i32() pub narrow(x: I32) -> U8 requires x >= 0 and x <= 255 = x.to_u8() ``` ```una -- fails with U5001 module demo pub add(a: U8, b: U8) -> U8 = a + b ``` ```una -- fails with U2022 module demo pub too_big() -> U8 = 300 ``` ```una -- fails with U2001 module demo pub mixed(a: U8, b: U16) -> U16 = a + b ``` The overflow diagnostic proposes, in order: a guard computed on `Int`, as `if a.to_int() + b.to_int() in 0..255`; a wider type through explicit conversions; or a wrapping or saturating method, when that is the arithmetic meant. ## 3.2 Declaring kinds A `kind` declaration takes one of four forms: an alias, a refinement, a sum and a record. Any of them may take type parameters (§3.3). ```una module demo pub kind Label = Text pub kind Phone = Text where valid_phone(it) pub kind Seats = Int in 0..5000 pub kind Availability = SoldOut | Few | Open pub kind Registration name: Text phone: Phone pub kind Lookup = Found(registration: Registration) | Missing pub kind Event name: Text remaining: Seats pub kind NonEmpty[T] = List[T] where it.len > 0 pub kind PhoneError = | Malformed pub predicate opaque valid_phone(t: Text) -> Bool = t.len == 11 and is_digits(t) ``` Rules: - **Sum or alias.** A right-hand side with `|` at bracket depth zero is a sum; otherwise it is an alias or refinement. A single-variant sum needs a leading bar: `kind PhoneError = | Malformed`. - **Records and sums are nominal.** Two declarations with the same shape are different types. - **Aliases and refinements are structural over their base.** A `Seats` value can be used wherever an `Int` is expected. Using an `Int` where `Seats` is expected creates a proof obligation: the compiler must prove the value lies in `0..5000`. - **Refinements stack.** Refining a refined kind combines both predicates. Fixed-width types can be refined too: `kind Port = U16 where it > 0`. - **Range sugar:** `T in a..b` means `T where a <= it and it <= b`; `T in a.. Int = when e is Lit(value) -> value is Add(left, right) -> eval(left) + eval(right) is Neg(inner) -> -eval(inner) --- A generic recursive kind passes on only its own type parameter. pub kind Tree[T] = Leaf | Node(left: Tree[T], item: T, right: Tree[T]) pub size[T](t: Tree[T]) -> Int = when t is Leaf -> 0 is Node(left, right) -> size(left) + 1 + size(right) ``` A kind without a finite value is U2002, with a repair: ```una -- fails with U2002 module demo pub kind Stream = | Cons(head: Int, tail: Stream) ``` In edition `0.1`, a kind may contain itself only through `List` or `Option` fields: ```una -- fails with U2002 -- edition 0.1 module demo pub kind Expr = Lit(value: Int) | Add(left: Expr, right: Expr) ``` ## 3.3 Generics and constraints Kinds and functions can take type parameters, and type arguments are inferred at call sites. Without a constraint, the only operations on a type parameter are those that function parameters provide. In edition `0.2` (ADR 0066, `spec/20`), a function's type parameter can carry one built-in **constraint**: | Constraint | Allows on values of `T` | Satisfied by | | --- | --- | --- | | `Eq` | `==`, `!=` | every type whose values hold no functions | | `Ord` | what `Eq` allows, and `<`, `<=`, `>`, `>=` | `Int`, `I8` to `U64`, `Text`, and sums whose variants have no payload | | `Integer` | what `Ord` allows, and `x.to_int()` | `Int`, `I8` to `U64` | - **Written on functions only.** `Kind[T: Eq]` is U0101. Each type parameter takes at most one constraint, and an unknown name is U2027. - **Operators need the constraint** (U2026, with a repair that writes it). This includes `==` on an unconstrained type parameter. Public functions write their constraints; private ones have the least constraint their body needs inferred. - **Type arguments must satisfy it** (U2025 at the call). - **No arithmetic on `T`,** constrained or not: convert with `to_int()` and compute on `Int`. ```una module demo --- Unconstrained: only what the function parameters provide. pub first_or[T](xs: List[T], default: T) -> T = xs.first().or_else(default) --- `Ord` allows comparisons; `max` is generic over `Ord` in edition 0.2. pub largest[T: Ord](xs: List[T], floor: T) -> T = xs.fold(initial: floor, step: fn(best, x) -> max(best, b: x)) --- `Eq` allows `==` and `!=`. pub same[T: Eq](a: T, b: T) -> Bool = a == b pub has[T: Eq](xs: List[T], item: T) -> Bool = xs.contains(item) --- `Integer` adds `to_int()`; arithmetic happens on `Int`. pub total[T: Integer](xs: List[T]) -> Int = xs.map(each: fn(x) -> x.to_int()).sum() pub ranked(names: List[Text]) -> List[Text] = sort(names) ``` ```una -- fails with U2026 module demo pub same[T](a: T, b: T) -> Bool = a == b ``` ```una -- fails with U2025 module demo pub kind Shape = Circle(radius: Int) | Square(side: Int) pub biggest(shapes: List[Shape]) -> List[Shape] = sort(shapes) ``` In edition `0.1`, type parameters are unconstrained, and equality on one is allowed with an inferred bound: the function cannot be instantiated with a type whose values hold functions (U2001). ## 3.4 The refinement language (RL) `where`, `requires` and `ensures` accept only expressions the verifier can reason about: | Allowed | Examples | | --- | --- | | Integer and boolean literals | `0`, `true` | | `it`, parameters, `result`, `old(x)` of an `edit` parameter, and field access on them | `it.remaining`, `e.remaining`, `old(t).seen` | | Length of `Text` and `List` | `it.len`, `xs.len` | | Linear arithmetic | `a + b`, `a - b`, `-a`, `3 * a`; `/` and `mod` only by a nonzero literal | | Comparisons and ranges | `==`, `!=`, `<`, `<=`, `>`, `>=`, `x in 1..10` | | Variant tests, with `is` only | `result is SoldOut`, `not (result is Open)`; `==` or `!=` against a variant, as in `result != Open`, is U2014 | | Boolean connectives | `and`, `or`, `not`, `implies` | | Predicate calls | `valid_phone(it)`, `adult(age)` | Anything else, such as calls to ordinary functions, methods such as `x.to_int()`, or `a * b` with two variables, is U2014, reported on the outermost offending sub-expression. Also outside RL: the ordering of `Text`, `is` with a literal, `==` or `!=` against a variant, `unit` and interpolated text. For `x == V` the diagnostic carries an edit to `x is V`, and for `x is 1` an edit to `x == 1`. In clauses, every integer type reads as its mathematical `Int`: operators accept any mix of integer types and compute exactly, with no overflow obligation and no U2022. So `ensures result <= 300` on a `U8` result is valid. ## 3.5 Predicates Predicates are named, pure, total boolean functions usable in RL. There are two forms: | Form | Body | Seen by the solver | How a value gets the fact | | --- | --- | --- | --- | | `predicate reflect` | must be in RL and not recursive | yes, as a definition | proven statically | | `predicate opaque` | any pure, non-failing expression | no, only its name | a runtime `checked` (§6.5) or a capability operation's `ensures` (§7.1) | ```una module demo predicate reflect adult(age: Int) -> Bool = age >= 18 --- Format check only. pub predicate opaque valid_phone(t: Text) -> Bool = t.len == 11 and is_digits(t) --- A reflect body computes exactly: no overflow obligation, even on `U32`. predicate reflect large(x: U32) -> Bool = x * 4294967295 > 4294967295 pub kind Adult = Int where adult(it) ``` - **Opaque predicates** never introduce axioms, so they cannot make the logic inconsistent. They carry validation that the solver cannot reason about (formats, checksums), and the fact travels in the type once established. Their bodies are code, with overflow obligations on fixed-width arithmetic. - **`reflect` bodies compute exactly.** The body of a `reflect` predicate is typed as code that runs, so its integer types do not mix (U2001), but its arithmetic is exact, as the verifier reads it and as every engine computes it: no `overflow` obligation and no U2022. So `large(4294967295)` above holds. ## 3.6 Equality, ordering and conversions - `==` and `!=` are structural, for every type except functions. - `<`, `<=`, `>`, `>=` work on `Int`, on the fixed-width types, on `Text` (lexicographic), and on sums without payloads (declaration order). - There are **no implicit conversions**, not even between distinct kinds with the same shape, between `Int` and a fixed-width type, or between `Int` and `Text`. Integer conversions are the methods of §3.1. ## 3.7 Subtyping, in one table | Flow | Allowed when | | --- | --- | | refined value into refined position | the compiler proves the target predicate (obligation) | | labeled value into labeled position | source label ⊑ target label (§8) | | function into function position | parameters contravariant, result covariant, and its `uses` and `fails` are included in the target's | --- ## Constructs - [kind](https://una-lang.org/en/docs/language/types/kind.md) - [where and refinements](https://una-lang.org/en/docs/language/types/where.md) - [predicate: reflect and opaque](https://una-lang.org/en/docs/language/types/predicate.md) - [Constraints on generics](https://una-lang.org/en/docs/language/types/constraints.md) - [Units of measure](https://una-lang.org/en/docs/language/types/units.md) --- # Functions and contracts ## 4.1 Two forms ```una module demo requirement EVENTS_3 text "An event with no remaining seats is always shown as sold out" source policy "Box Office Handbook 2.1" owner box_office status active pub kind Seats = Int in 0..5000 pub kind Availability = SoldOut | Few | Open pub kind Event name: Text remaining: Seats --- Short form. double(x: Int) -> Int = x * 2 --- Long form. pub availability(e: Event) -> Availability ensures e.remaining < 1 implies result is SoldOut derived from EVENTS_3 = when e.remaining in 0..0 -> SoldOut in 1..<20 -> Few in 20..5000 -> Open ``` - **Short form:** no clauses, and a body that is a single-line expression. A `with` clause belongs to a statement, not an expression, so a body with `with` needs the long form (U0101 otherwise, §7.4). - **Long form:** the signature, then the indented clauses, then `=` alone on a line, then the indented body. `una fmt` converts between them: a long form with no clauses and a one-line body becomes the short form. ## 4.2 Clauses | Clause | Meaning | Checked how | | --- | --- | --- | | `requires p` | precondition over parameters | proven at every call site; assumed inside the body | | `ensures q` | postcondition over parameters, `result` and `old(x)` | proven on every normal return path; assumed by callers | | `uses @c: C[ops]` | may perform `ops` through capability `@c` | effects of the body must fit (U3003) | | `uses of p` | may perform the effects of the function argument `p` (edition `0.2`) | U3017 to U3019 for a malformed clause | | `fails E` | may fail with variants of sum kind `E` | failures of the body must be variants of `E` (U3009) | | `fails of p` | may fail as the function argument `p` does (edition `0.2`) | as `uses of p` | | `derived from R1, R2` | traceability to requirements | each requirement must exist (U1006) | Rules: - **Canonical order:** every `requires`, then every `ensures`, then every `uses` and `uses of` (one capability or parameter per clause), then at most one `fails` and one `fails of`, then at most one `derived from`. Anything else is U0102. - **`requires` and `ensures`** must be in RL (U2014). - **`result`** exists only in `ensures` clauses and example `expect` lines (U2012). **`old(x)`** exists only in `ensures`, on an `edit` parameter (§5.6). - **`ensures` covers normal returns only;** failures carry no postcondition. - **Partial correctness:** `ensures` holds if the function returns. Termination is not checked. - **Pure means no `uses`.** A function without `uses` cannot contain any `@` (U3004). - **No `fails` means it cannot fail.** ```una module demo pub kind Seats = Int in 0..5000 pub kind Event name: Text remaining: Seats pub seats_after(e: Event, count: Int) -> Seats requires count >= 1 requires count <= e.remaining ensures result == e.remaining - count = e.remaining - count ``` The compiler proves that `e.remaining - count` fits `Seats` (between 0 and 5000) using both `requires` clauses, and proves the `ensures` clause. Every caller must prove both `requires` clauses at the call site. **Effect polymorphism** (edition `0.2`, ADR 0062). `uses of p` and `fails of p` name a parameter `p` of function type, written without its own `uses` or `fails`. At each call, the callee's effects and failures are its own plus those of the argument passed for `p`. Inside the body, `p` is only called, or passed on to a parameter that the callee's `of` clause names. A callee with its own `fails E` accepts for `p` only an argument that fails with `E`, so each function keeps one error kind. ```una module demo pub kind ParseError = | NotANumber --- `each` may have effects and may fail; `apply_all` has them too, at each call. pub apply_all(xs: List[Text], each: fn(Text) -> Int) -> List[Int] uses of each fails of each = xs.map(each: each) if error pass pub parse(t: Text) -> Int fails ParseError = t.to_int() if none fail NotANumber pub parse_all(xs: List[Text]) -> List[Int] fails ParseError = apply_all(xs, each: parse) if error pass pub shout(names: List[Text]) -> Unit uses @console: Console[print] = let printed = names.map(each: fn(n) -> @console.print(n)) unit ``` ## 4.3 Visibility and inference - `pub` functions must declare every `uses`, their `fails` and the constraints of their type parameters explicitly. They are the reviewed boundary. - Private functions may omit `uses`, `fails`, `uses of`, `fails of` and constraints; the compiler infers them. `una contract ` shows the inferred header. - Parameter and result types are never inferred. ## 4.4 Calls and labeled arguments | Rule | Example | | --- | --- | | One argument: the label is optional | `double(4)` | | Two or more: the first may be unlabeled, the rest must be labeled (U2004) | `seats_after(event, count: 2)` | | Punning: from the second argument on, a bare identifier equal to the parameter name counts as labeled; the first argument always binds the first parameter (ADR 0049) | `record(key, status)` | | Argument count: too many arguments, or a parameter that receives none, is U2001. The count is checked before the labels. | `f(1, b: 2, b: 3)` for a two-parameter `f`: U2001 "`f` takes 2 arguments, but 3 are given", and no U2006 | | Unknown label: U2005 | `f(1, c: 2)` | | Duplicate argument, with the right count: U2006 | `f(a: 1, a: 2)` | | Arguments are evaluated left to right | | Constructors follow related rules: - Records and variants with two or more fields need every field labeled (punning allowed). An unlabeled field is U2004 ("`P` has 2 fields, so every argument needs its field's label"); missing or unknown fields are U2009. - Any order of labeled fields type-checks, but the canonical form is declaration order (§13): `una check` reports another order as U7001, and `una fmt` rewrites it. - A single-field constructor may omit the label: `Some(r)`, `Ok(v)`. Extra arguments to a single-field constructor, and parentheses after a variant without fields, are U2009. - A variant with fields is not a value on its own: `e == Found` is U2009, with the repair `e is Found`. ```una module demo pub kind Registration name: Text seat: Int pub kind Lookup = Found(registration: Registration) | Missing pub kind Event name: Text remaining: Int pub sample(r: Registration) -> Lookup = let e = Event(name: "Meetup", remaining: 120) let found = Found(registration: r) let maybe = Some(r) found ``` ## 4.5 Method-call syntax - `e.f(args)` calls `f(e, args)`. The receiver becomes the first, unlabeled argument. - If `e` has a field `f` of function type, `e.f(args)` calls that field instead. - `e.f` without arguments is field access, or `f(e)` when `e` has no field `f` and `f` is a function with one parameter. - `.len` is built in for `Text` and `List`, and the conversions and arithmetic methods of §3.1 for integers. - `edit xs.set(index: 0, item: v)` passes the receiver as an `edit` argument (§5.6). ```una module demo pub kind Event name: Text remaining: Int pub open_names(schedule: List[Event]) -> Int = let open_events = schedule.filter(keep: fn(e) -> e.remaining > 0) let names = open_events.map(each: fn(e) -> e.name) names.len ``` ## 4.6 Lambdas and function types ```una module demo pub increments(xs: List[Int]) -> List[Int] = xs.map(each: fn(x) -> x + 1) pub next() -> fn(Int) -> Int = fn(x: Int) -> x + 1 ``` - A lambda's parameter types come from the expected type, as in `map`'s `each`; without one, annotate them (`fn(x: Int) -> x + 1`), or it is U2010. - Function types are written `fn(A, B) -> C`, optionally with `uses` and `fails`: `fn(Text) -> Unit uses @log: Log[write]`. - A lambda is **pure** unless its expected type declares `uses` or `fails`, or is a parameter named by a `uses of` or `fails of` clause. - An effectful or fallible lambda is **second-class**: it may be passed as an argument, but not returned, stored or bound with `let` (U3006). - **A lambda body is one expression, with no room for a handling clause.** So a lambda cannot call an operation or a function that can fail: `fn(k) -> @audit.record(k)`, where `record` declares `fails`, is U3007. A lambda may still fail directly, as in `fn(k) -> if k > 0 then k else fail Bad`, when its expected type declares `fails`. Put fallible work in a named function with handling clauses, and pass the function by name, as `apply_all(xs, each: parse)` in §4.2. - Lambdas capture variables by value. A lambda captures the value an editable binding has when the lambda is created, and cannot assign it (U2019). - **The prelude's higher-order functions** (`map`, `filter`, `fold`, `first_where`) declare `uses of` and `fails of` their function parameter in edition `0.2`, so `names.map(each: fn(n) -> @console.print(n))` works (§4.2). In edition `0.1` they accept only pure, non-failing lambdas (U3004 otherwise). Prefer a `for` loop for anything that handles failures, updates bindings or takes several steps. - Inside a function, call a function parameter only where no secret condition decides the call (U4002). - A function with an `edit` or `take` parameter cannot be used as a value (U2021). ## 4.7 Recursion and the entry point - Direct and mutual recursion are allowed. There is no tail-call guarantee, and exhausting the call depth or the stack is runtime diagnostic U6003. Loops (§5.5) do not count toward the call depth. - The entry point is `pub main() -> Unit` in the module set as `entry` in `una.toml`. It can declare `uses` over host capabilities (§7.7) and a `fails` clause. - If `main` fails, the runtime prints the variant name and exits with code 1. Payload fields are printed only if they are `public`. --- ## Constructs - [requires](https://una-lang.org/en/docs/language/functions/requires.md) - [ensures](https://una-lang.org/en/docs/language/functions/ensures.md) --- # Expressions and control flow ## 5.1 Blocks, `let` and statements A block is a sequence of statements followed by a final expression, which is the block's value. ```una module demo pub kind Seats = Int in 0..5000 pub kind Availability = SoldOut | Few | Open pub kind Event name: Text remaining: Seats clamp_seats(raw: Int) -> Seats = if raw < 0 then 0 else if raw > 5000 then 5000 else raw availability(e: Event) -> Availability = if e.remaining == 0 then SoldOut else if e.remaining < 20 then Few else Open pub status(n: Text, raw: Int) -> Availability = let seats = clamp_seats(raw) let event: Event = Event(name: n, remaining: seats) availability(event) ``` - A plain `let` is immutable. An editable binding is declared `let edit` (§5.6). - A statement that is not a `let`, an assignment, a `for` loop, a `together` block or an `if` without `else` must have type `Unit` (U2011). To ignore a value, bind it. - A `let` whose right-hand side is in RL keeps an exact fact that later proofs can use: after `let half = total / 2`, the verifier knows `half == total / 2`. A `let` bound to a function call keeps only what that function's `ensures` promises. ## 5.2 `if` ```una module demo pub size(n: Int) -> Text = if n > 100 then "large" else "small" pub band(n: Int) -> Text = if n > 100 "large" else if n > 10 "medium" else "small" ``` - `if` used as an expression always has an `else`. - In edition `0.2`, a block-form `if` without `else` is a statement of type `Unit`, used to update editable bindings (§5.5). ## 5.3 `when` ```una module demo pub kind Seats = Int in 0..5000 pub kind Availability = SoldOut | Few | Open pub kind Registration name: Text pub kind Lookup = Found(registration: Registration) | Missing --- Variants. pub label(status: Availability) -> Text = when status is SoldOut -> "sold out" is Few -> "few seats left" is Open -> "open" --- A payload bound by its field name, or under another name. pub name_of(lookup: Lookup) -> Text = when lookup is Found(registration) -> registration.name is Missing -> "unknown" pub name_again(lookup: Lookup) -> Text = when lookup is Found(registration: r) -> r.name is Missing -> "unknown" --- Ranges, proven to cover every `Seats` value. pub band(remaining: Seats) -> Availability = when remaining in 0..0 -> SoldOut in 1..<20 -> Few in 20..5000 -> Open --- Literals, with `else`. pub reason(code: Int) -> Text = when code is 200 -> "ok" is 404 -> "not found" else -> "other" --- A block arm. pub greeting(status: Availability) -> Text = when status is SoldOut -> let note = "try another date" note else -> "welcome" ``` Rules: - **Variant arms** must be exhaustive, or end with `else` (U2007). - **Range and literal arms** without `else` create an obligation: the compiler must prove the arms cover every value the subject can take. With `Seats = Int in 0..5000`, the three ranges above are proven exhaustive. Arms over a fixed-width value take its type, and a bound that does not fit is U2022. - **`else` must be the last arm,** and unreachable arms are rejected (U2008). - **Single-field variants** bind their field under any name: `is Some(r)`. - **Results of `attempt`** are matched with `is Ok(value)` and `is Err(failure)` (§6.4). ## 5.4 One effect per line A capability operation, a call to a function that uses capabilities or can fail, or a call with an `edit` or `take` argument, must be the **whole expression** of a statement, a `let` or a final expression, optionally wrapped in `attempt` (U3013). It cannot be nested inside another expression. ```una module demo pub kind Availability = SoldOut | Few | Open pub kind Registration name: Text status: Availability pub kind StoreError = | Timeout pub kind CheckInError = NotRegistered | Unavailable pub capability Registrations op find(key: Text) -> Option[Registration] fails StoreError pub status_of(key: Text) -> Availability uses @registrations: Registrations[find] fails CheckInError = let registration = @registrations.find(key) if error fail Unavailable if none fail NotRegistered registration.status ``` ```una -- fails with U3013 module demo pub capability Store op get(key: Text) -> Int double(x: Int) -> Int = x * 2 pub doubled(key: Text) -> Int uses @store: Store[get] = double(@store.get(key)) ``` This fixes evaluation order, gives every failure a handling site and makes every effect visible on its own line. Pure calls nest freely. Example `do` lines are exempt (§10). ## 5.5 `for` loops (edition `0.2`) `for x in xs` visits the elements of a list in order, and `for i in a.. Int = let edit sum = 0 for x in xs sum = sum + x sum --- Over a range: `a.. List[Int] = let edit out: List[Int] = [] for i in 0.. List[U8] = let edit out: List[U8] = [] for b in low..high out = out.append(item: b) out --- An `if` without `else` is a statement. pub count_large(xs: List[Int], limit: Int) -> Int = let edit count = 0 for x in xs if x > limit count = count + 1 count ``` - **The bounds,** and the list, are evaluated once, before the first iteration. There is no `break` and no `continue`. - **The loop variable** is a plain binding (U2019 on assignment). A range's bounds are integers of one type, `Int` or a fixed-width type, and a literal bound takes the type of the other, so `for b in low..high` over `U8` bounds gives `b: U8`. An inclusive range ends at its upper bound without computing its successor, so `0..255` over `U8` does not overflow. - **As a statement,** a loop has the value `unit`. It updates `let edit` bindings declared before it. - **Verification.** The refinements of the bindings the loop updates are its invariant: the body is checked once, for any iteration, with those bindings fresh at their declared types, and no fact about their values survives the loop. Inside a range loop, `a <= i < b` (or `<= b`) holds. There is no `invariant` clause. - **Failures** inside the body end the loop and the function; the bindings it updated keep their values from before the loop (§5.6). - **Labels.** A loop over a list runs under the top label of the list, and a range loop under the labels of its bounds. In such a body, `fail` and calls that can fail are U4002 when that label is not `public`. - **Edition `0.4`** adds `stop` and `skip`, which end a loop or an iteration early, `for until c decreases m`, which runs until `c` holds, and `for ever` with `on stop` in a function that says `diverges`, which runs until it is stopped (`spec/26 §3` to `§6`). See [Loops that run until stopped](https://una-lang.org/en/docs/language/control-flow/for-ever/). ## 5.6 Mutable value semantics (edition `0.2`) Una has no references and no lifetimes: values stay values, and a binding declared editable can be rebound (ADR 0056, `spec/17`). - **`let edit x = e`** declares an editable binding, and `x = e` rebinds it. A **place** is an editable binding or a field path of one: `t.last = value` rebuilds `t` with that field changed. Assigning anything else is U2019. - **Fixed type.** An editable binding keeps its declared type, refinement and label at every rebind; each rebind carries the refinement obligation of an annotated `let`. Without an annotation, its type is that of its initial value without its refinement. - **`edit` parameters** are passed in and out: `record(edit t: Tally, ...)` receives the caller's value and returns its final value. The caller writes `edit t` at the argument (U2020 for a missing or extra marker), and the argument is a place. In `ensures`, `t` is the final value and `old(t)` the value on entry. - **`take` parameters** consume their argument: after `f(take a)`, using `a` is U2017 until an assignment gives it a new value. - **Exclusivity.** An `edit p` argument together with any other use of the root binding of `p` in the same call is U2018. - **Lists** change through `set` and `append`: `edit ys.set(index: i, item: v)`, with `requires 0 <= index and index < xs.len`. - **Transactional values.** A call that fails leaves its `edit` arguments unchanged for the caller. Effects already performed stay performed. - **Operations and handlers** cannot declare `edit` or `take` parameters (U2020). ```una module demo pub kind Tally seen: Int last: Int --- An `edit` parameter is passed in and out; `old(t)` is its value on entry. pub record(edit t: Tally, value: Int) -> Unit ensures t.seen == old(t).seen + 1 = t.seen = t.seen + 1 t.last = value pub tally(xs: List[Int]) -> Tally = let edit t = Tally(seen: 0, last: 0) for x in xs edit t.record(value: x) t --- `take` consumes its argument: the caller cannot use it afterwards. pub finish(take t: Tally) -> Int = t.seen pub summary(xs: List[Int]) -> Int = let t = tally(xs) let n = finish(take t) n --- List elements change through `set`. pub reset_first(xs: List[Int]) -> List[Int] = let edit ys = xs if ys.len > 0 edit ys.set(index: 0, item: 0) ys ``` ```una -- fails with U2017 module demo pub finish(take xs: List[Int]) -> Int = xs.len pub twice(xs: List[Int]) -> Int = let n = finish(take xs) xs.len + n ``` ```una -- fails with U2019 module demo pub bump(x: Int) -> Int = let n = x n = n + 1 n ``` A backend may update a uniquely held value in place, and reuse the memory of a value passed by `take`. None of this is observable. ## 5.7 Concurrent tasks with `together` (edition `0.2`) `together` runs independent work as concurrent tasks, and every task ends before its block does (ADR 0065, `spec/19`). A program's result and its trace are those of running the tasks one after another, in order. ```una module demo pub capability Sensor op reading() -> Int pub kind FetchError = Missing | Gone handler fixed(value: Int) for Sensor op reading() = value pub warmest() -> Int uses @north: Sensor[reading] uses @south: Sensor[reading] = together let north = reading() with @sensor = @north let south = reading() with @sensor = @south max(north, b: south) reading() -> Int uses @sensor: Sensor[reading] = @sensor.reading() fetch(id: Int) -> Int fails FetchError = if id < 0 fail Missing else id * 10 --- One task per element; the results come back in list order. pub pages(ids: List[Int]) -> List[Int] fails FetchError = let pages = together for id in ids fetch(id) if error pass pages --- Over a range, the variable takes the integer type of the bounds. pub doubled(n: U8) -> List[Int] = let out = together for i in 0.. Int = n = n + 1 n pub count(xs: List[Int]) -> Int = let edit seen = 0 together let a = xs.len let b = bump(edit seen) seen + a + b ``` ```una -- fails with U2024 module demo pub one() -> Int = together let a = 1 a ``` --- ## Constructs - [when](https://una-lang.org/en/docs/language/control-flow/when.md) - [for](https://una-lang.org/en/docs/language/control-flow/for.md) - [let edit and edit parameters](https://una-lang.org/en/docs/language/control-flow/let-edit.md) - [take](https://una-lang.org/en/docs/language/control-flow/take.md) - [together](https://una-lang.org/en/docs/language/control-flow/together.md) - [Loops that run until stopped: for ever, for until, stop and skip](https://una-lang.org/en/docs/language/control-flow/for-ever.md) --- # Errors Errors are values. There are no exceptions, no panics and no implicit propagation. ## 6.1 Error kinds and `fails` Any sum kind can serve as an error kind. A function declares at most one, with `fails E`. ```una module demo pub kind CheckInError = NotRegistered | Unavailable pub kind StoreError = Timeout | Corrupted(detail: Text) ``` ## 6.2 `fail` `fail V` or `fail V(field: value)` ends the function with a failure. `V` must be a variant of the function's error kind (U3009). ```una module demo pub kind Seats = Int in 0..5000 pub kind Event name: Text remaining: Seats pub kind BookingError = | InvalidCount pub seats_after(e: Event, count: Int) -> Seats requires count >= 1 requires count <= e.remaining = e.remaining - count pub book(e: Event, count: Int) -> Seats fails BookingError = if count < 1 or count > e.remaining fail InvalidCount else seats_after(e, count) ``` In the `else` branch the verifier knows `count >= 1` and `count <= e.remaining`, so the preconditions of `seats_after` are proven. The second argument uses punning (§4.4). ## 6.3 Handling clauses A statement whose expression can fail must be followed by an indented `if error` clause (U3007), unless it is wrapped in `attempt`. Each clause stands on its own line, one level below the statement: `fetch(id) if error pass` on one line is U0101. | Clause | Applies to | Meaning | | --- | --- | --- | | `if error fail V(...)` | any fallible expression | any failure becomes `V`; inside the arguments, `error` is the original failure | | `if error pass` | callee error kind equals the current function's | propagate the failure unchanged (U3008 if the kinds differ) | | `if error use e` | any fallible expression | recover with value `e`; `error` is in scope | | `if none fail V(...)` | an expression of type `Option[T]` | `None` becomes failure `V`; the result has type `T` | | `if none use e` | an expression of type `Option[T]` | `None` becomes `e`; the result has type `T` | - Each clause appears at most once, and `if error` comes before `if none` (U0102). - `error` is valid only inside these clauses (U2013). ```una module demo pub kind Registration name: Text pub kind StoreError = Timeout | Corrupted(detail: Text) pub kind CheckInError = NotRegistered | Unavailable pub capability Registrations op find(key: Text) -> Option[Registration] fails StoreError pub capability Store op read(path: Text) -> Text fails StoreError pub capability Cache op get(key: Text) -> Option[Text] fails StoreError pub lookup(key: Text) -> Registration uses @registrations: Registrations[find] fails CheckInError = let registration = @registrations.find(key) if error fail Unavailable if none fail NotRegistered registration pub load(path: Text) -> Text uses @store: Store[read] fails StoreError = let detail = @store.read(path) if error fail Corrupted(detail: "read failed") detail pub cached(key: Text) -> Option[Text] uses @cache: Cache[get] = let found = @cache.get(key) if error use None found ``` ## 6.4 `attempt` `attempt` turns a single fallible call into a `Result`, so you can branch on the outcome instead of failing: ```una module demo pub kind Registration name: Text pub kind StoreError = | Timeout pub capability Registrations op find(key: Text) -> Option[Registration] fails StoreError pub registered(key: Text) -> Bool uses @registrations: Registrations[find] = let outcome = attempt @registrations.find(key) when outcome is Ok(value) -> value.is_some() is Err(failure) -> false ``` The operand must be one call (U2001), and `attempt` counts as its handling site. ## 6.5 `checked` (escape hatch) `checked(v, p) else fail V` tests predicate `p` at runtime, with `it` bound to `v`. The package must allow it in its escape budget: `una.toml` ```toml [package] name = "phones" version = "0.1.0" edition = "0.2" [escape_budget] checked_per_module = 1 ``` `src/phones.una` ```una module phones pub kind Phone = Text where valid_phone(it) pub kind PhoneError = | Malformed pub predicate opaque valid_phone(t: Text) -> Bool = t.len == 11 and is_digits(t) pub parse_phone(raw: Text) -> Phone fails PhoneError = checked(raw, valid_phone(it)) else fail Malformed ``` - If the test passes, the result is `v` with its type refined by `p`. This is how opaque facts are established. - If it fails, the function fails with `V`. - `p` must be RL or an opaque predicate call, so it can run. - `checked` replaces a proof with a runtime test, so it is **budgeted**: `[escape_budget] checked_per_module` in `una.toml`, default 0 (U7003 when exceeded). Every use is listed in the build report. A narrowing integer conversion can go through `checked` too, on the same budget. ## 6.6 What is not a failure - **Proof obligations never become runtime failures.** Division by zero, overflow, refinement violations and broken preconditions are proven absent before the program runs. - **Running out of call depth, stack or memory** is runtime diagnostic U6003, not a Una failure. --- ## Constructs - [fails](https://una-lang.org/en/docs/language/errors/fails.md) - [fail](https://una-lang.org/en/docs/language/errors/fail.md) - [if error and if none](https://una-lang.org/en/docs/language/errors/if-error.md) - [attempt](https://una-lang.org/en/docs/language/errors/attempt.md) - [checked and the escape budget](https://una-lang.org/en/docs/language/errors/checked.md) --- # Capabilities and effects ## 7.1 Declaring capabilities A capability describes authority over something outside the program. Its operations are signatures, which are assumptions about the external system. ```una module demo pub kind Availability = SoldOut | Few | Open pub kind Registration name: Text status: Availability pub kind StoreError = Timeout | Corrupted pub capability Registrations op find(key: internal Hashed) -> Option[Registration] fails StoreError accepts internal pub capability Audit op record(key: internal Hashed, status: Availability) -> Unit fails StoreError accepts internal ``` | Op clause | Meaning | | --- | --- | | `requires p` | precondition on arguments, proven at each call | | `ensures q` | postcondition: an assumption callers may rely on; handlers are verified against it | | `fails E` | the operation may fail with `E` | | `accepts l` | the most sensitive label its arguments may carry (default `public`) | Canonical op clause order: every `requires`, every `ensures`, then at most one `fails` and at most one `accepts` (U0102). Operations cannot declare `edit` or `take` parameters (U2020). ## 7.2 Using capabilities ```una module demo pub kind Availability = SoldOut | Few | Open pub kind Registration name: Text status: Availability pub kind StoreError = Timeout | Corrupted pub kind CheckInError = NotRegistered | Unavailable pub capability Registrations op find(key: internal Hashed) -> Option[Registration] fails StoreError accepts internal pub capability Audit op record(key: internal Hashed, status: Availability) -> Unit fails StoreError accepts internal pub check_in(key: internal Hashed) -> Availability uses @registrations: Registrations[find] uses @audit: Audit[record] fails CheckInError = let registration = @registrations.find(key) if error fail Unavailable if none fail NotRegistered @audit.record(key, status: registration.status) if error fail Unavailable registration.status ``` - `uses @x: C[ops]` grants operations `ops` of capability `C` under the name `@x`. Omitting `[ops]` grants all of them. - `@x.op(args)` works only if `@x` is in scope (U3001) and `op` is granted (U3002). ## 7.3 Passing capabilities: by name, downward only A callee whose header says `uses @x: C[ops]` receives the caller's `@x` automatically. The caller must hold `@x` with at least those operations (U3001, U3002). Holding more is fine: the callee is limited to what it declares, so passing a capability attenuates it. ## 7.4 `with`: rebinding and handler instances ```una module demo pub kind Registration name: Text pub capability Registrations op find(key: Text) -> Option[Registration] handler in_memory(rows: List[Registration]) for Registrations op find(key) = rows.first() handler none_found() for Registrations op find(key) = None known(key: Text) -> Bool uses @registrations: Registrations[find] = let found = @registrations.find(key) found.is_some() pub check(key: Text, rows: List[Registration]) -> Bool uses @primary_store: Registrations[find] = let in_store = known(key) with @registrations = @primary_store let in_rows = known(key) with @registrations = in_memory(rows: rows) let nowhere = known(key) with @registrations = none_found() in_store or in_rows or nowhere ``` - **`@x = @y`** makes the callee's `@x` the caller's `@y`. Both must be the same capability. - **`@x = h(args)`** installs handler `h` as `@x`. The handler's own `uses` become effects of the caller. What happens when the caller lacks them depends on the caller: - a `pub` caller that does not declare them gets U3003 at the statement: "handler `h` uses `@inner: Inner[ping]`, but this code declares no `uses`, so its effects would exceed its header"; - a private caller has them inferred, and the error appears where the capability is really missing. In an example, for instance, it is U3001: "`g` needs `@inner: Inner[ping]`, which no `given` line binds". - **Scope:** the binding covers only that statement's expression. - **Statements only.** `with` is part of a statement, so it cannot appear in the short function form: `g() -> Unit = f() with @a = h()` is U0101. Use the long form, with the statement in the body. - **Several bindings** are separated by commas: `with @a = @b, @c = h()`. ## 7.5 Handlers A handler implements a capability in Una. `in_memory` and `none_found` above are handlers: - **Complete and matching.** A handler implements every operation (U3011), with the right parameter count (U3010). Types come from the capability declaration. - **Ordinary code.** Operation bodies are type-checked, flow-checked and verified against the operation's `ensures`. They may fail only with the operation's error kind. - **Parameters** (`rows` above) are captured values. - **Own authority.** A handler may declare its own `uses` before its operations. - **Not values.** Handlers are installed only through `with` or `given`. ## 7.6 The second-class rule Capability references are **not values**. `@x` cannot be: - bound with `let`; - passed as an ordinary argument; - returned; - stored in a kind; - compared or interpolated. Any of these is U3005. A bare `@x` is allowed only on either side of a `with` binding or in `given`. Effectful or fallible lambdas follow the same restrictions, except that they can be passed as arguments (U3006). Such a lambda cannot handle a failure, so it calls only operations that cannot fail (U3007 otherwise, §4.6). Second-class types are not type arguments either (U3016). Consequence: authority only flows downward through calls, and every function's reachable authority is visible in headers. ## 7.7 Host capabilities The runtime implements these; they are part of the prelude. | Capability | Operation | Fails | Accepts | | --- | --- | --- | --- | | `Console` | `print(line: Text) -> Unit` | | `public` | | `Clock` | `now() -> Int` (ms since Unix epoch) | | `public` | | `Env` | `get(name: Text) -> Option[internal Text]` | | `public` | | `Files` | `read(path: Text) -> internal Text` | `FileError` | `public` | | `Files` | `write(path: Text, content: Text) -> Unit` | `FileError` | `internal` | | `Keys` | `hmac(key_name: Text, data: Text) -> internal Hashed` | `KeyError` | `public` for `key_name`, any label for `data`; the result carries the label of `data` | | `Http` (edition `0.2`) | `get(url: Text, headers: List[Header], key_name: Option[Text]) -> internal Response` | `HttpError` | `internal` | | `Http` | `post(url: Text, headers: List[Header], body: Text, key_name: Option[Text]) -> internal Response` | `HttpError` | `internal` | | `Http` | `put(url: Text, headers: List[Header], body: Text, key_name: Option[Text]) -> internal Response` | `HttpError` | `internal` | | `Http` | `delete(url: Text, headers: List[Header], key_name: Option[Text]) -> internal Response` | `HttpError` | `internal` | - **Entry.** Host capabilities enter only through `main`'s `uses`, and only if `una run`, or the native executable, grants them. An ungranted capability is U3012 before execution starts. - **Grant syntax:** `console`, `clock`, `env`, `keys:`, `files::read`, `files::write`, and in edition `0.2` `http:` or `http::` (by default `get`). - **`Http`** (`spec/24`). `Header` has `name: Text` and `value: internal Text`, and `Response` has `status: Int`, `headers: List[Header]` and `body: Text`. A status is not a failure: `HttpError` is `Denied`, `BadUrl`, `BadRequest`, `Unreachable`, `TimedOut`, `TooLarge`, `Tls` or `Protocol`. `key_name: Some(n)` sends the key `n` of the `keys:` grants as `Authorization: Bearer `; a token another header carries goes in as a header value, through a policy to `internal` when it is `secret`. The guide for agents, §17, has an example with a stand-in handler. - **`Files` paths.** A path is relative to the grant's prefix: with `files:data:read`, `@files.read("readings.txt")` reads `data/readings.txt`, and `"data/readings.txt"` would look for `data/data/readings.txt` and fail with `NotFound`. A path stays confined to the prefix: an absolute path, or a `..` that leaves it, fails with `Denied`. `FileError` is `NotFound`, `Denied` or `Io`, and `KeyError` is `UnknownKey`. - **Tests and handlers.** You can write handlers for host capabilities, for example a fake `Keys` in tests (§17). --- ## Constructs - [capability and op](https://una-lang.org/en/docs/language/capabilities/capability.md) - [uses](https://una-lang.org/en/docs/language/capabilities/uses.md) - [@ bindings and with](https://una-lang.org/en/docs/language/capabilities/with.md) - [handler](https://una-lang.org/en/docs/language/capabilities/handler.md) - [Host capabilities and grants](https://una-lang.org/en/docs/language/capabilities/host.md) --- # Information flow ## 8.1 Labels Every type can carry a label: `secret[PII] Phone`, `internal Hashed`. A type without a label is `public`. - **Levels,** from least to most sensitive: `public` ⊏ `internal` ⊏ `confidential` ⊏ `secret` ⊏ `restricted`. - **Categories** are declared per package in `una.toml` (`[labels] categories = ["PII", "Location"]`). An undeclared category is U4007. - **Order:** a label flows into another if its level is lower or equal **and** its categories are a subset. ## 8.2 Explicit and implicit flows - **Results carry their inputs' labels.** The result of an operation is labeled with the join of its operands. - **Branches raise the program-counter label (pc).** Branching on labeled data raises the pc inside the branches, and values produced there carry it. ```una module demo pub kind Person name: Text age: secret Int --- The branch is on secret data, so the result is secret too. pub adult_flag(r: Person) -> secret Int = if r.age > 17 then 1 else 0 ``` - **Returns.** A function's result label must fit its declared return type (U4001). - **Editable bindings** keep their declared label: a rebind under a pc above it is U4001. ## 8.3 Failing and calling under a raised pc - `fail` inside a branch on secret data leaks information through the failure, so it is rejected (U4002). Return a labeled value instead. - Calling a function that performs effects or can fail is allowed under a raised pc only if every sink it reaches accepts that pc (U4002). ```una -- fails with U4002 module demo pub kind PinError = | Rejected pub check(pin: secret Int) -> secret Int fails PinError = if pin == 1234 1 else fail Rejected ``` ## 8.4 Sinks - **Operation arguments are sinks.** Every capability operation argument is a sink bounded by the operation's `accepts` label: `pc ⊔ label(args) ⊑ accepts`, otherwise U4003. - **Console is public.** `Console.print` accepts `public` only: ```una -- fails with U4003 module demo pub show(phone: secret Text) -> Unit uses @console: Console[print] = @console.print("phone {phone}") ``` - **Tests are exempt.** `expect` lines in examples observe values for the test harness and are exempt from sink checks. ## 8.5 Declassification: policies in trusted modules Labels are lowered only through a declared policy, inside a trusted module: `una.toml` ```toml [package] name = "events" version = "0.1.0" edition = "0.2" [labels] categories = ["PII"] [trusted] modules = ["events.keys"] ``` `src/events/types.una` ```una module events.types pub kind Phone = Text where valid_phone(it) pub predicate opaque valid_phone(t: Text) -> Bool = t.len == 11 and is_digits(t) ``` `src/events/keys.una` ```una trusted module events.keys import events.types (Phone) pub policy attendee_key from secret[PII] Phone to internal Hashed via hmac_phone purpose "registration lookup and audit correlation" owner privacy hmac_phone(phone: secret[PII] Phone) -> internal Hashed uses @keys: Keys[hmac] fails KeyError = @keys.hmac(key_name: "phone_pepper", data: phone) if error pass ``` - **Callable.** The policy becomes a function: `attendee_key(phone)`. Its `uses` and `fails` are those of the `via` function. - **Only entry point.** The `via` function must be private (U4005), so the policy is the only way in. Flow checks are not performed inside it; it belongs to the trusted computing base. - **Where policies live.** Policies are allowed only in trusted modules (U4004). A trusted module is declared both with `trusted module` and in `una.toml` (U7005 if either is missing). - **Reported.** Every policy call site appears in the build report with its purpose and owner. ## 8.6 What the guarantee covers Una guarantees **termination-insensitive noninterference up to declassification**. The channels in the model are values, failures, operation arguments and the occurrence of effects. Timing, termination and resource usage are outside the model, and so is the relative order of the effects of concurrent tasks (§5.7); the build report says so. --- ## Constructs - [Labels](https://una-lang.org/en/docs/language/information-flow/labels.md) - [policy: declassification](https://una-lang.org/en/docs/language/information-flow/policy.md) - [trusted modules](https://una-lang.org/en/docs/language/information-flow/trusted.md) --- # Requirements Requirements record human intent with origin and owner, so contracts can be traced to it. ```una module demo requirement EVENTS_3 text "An event with no remaining seats is always shown as sold out" source policy "Box Office Handbook 2.1" owner box_office status active pub kind Availability = SoldOut | Open pub availability(remaining: Int) -> Availability ensures remaining < 1 implies result is SoldOut derived from EVENTS_3 = if remaining < 1 then SoldOut else Open ``` | Field | Values | | --- | --- | | `text` | the statement | | `source` | `human`, `policy ""`, `regulation ""`, `generated ""` | | `owner` | accountable team or person (`snake_case`) | | `status` | `proposed` or `active` | - **IDs** are unique per package (U1002). - **Generated requirements must be `proposed`** (U1007). Agents may propose; a person activates a requirement by changing its source. - **`derived from`** in a function header links the function to requirements; `una trace EVENTS_3` shows the chain from requirement to contract to proof status. --- ## Constructs - [requirement and derived from](https://una-lang.org/en/docs/language/requirements/requirement.md) --- # Examples as tests ```una module demo import std.testing (fake_hash) pub kind Availability = SoldOut | Few | Open pub kind Registration name: Text status: Availability pub kind StoreError = Timeout | Corrupted pub kind CheckInError = NotRegistered | Unavailable pub capability Registrations op find(key: internal Hashed) -> Option[Registration] fails StoreError accepts internal pub capability Audit op record(key: internal Hashed, status: Availability) -> Unit fails StoreError accepts internal pub check_in(key: internal Hashed) -> Availability uses @registrations: Registrations[find] uses @audit: Audit[record] fails CheckInError = let registration = @registrations.find(key) if error fail Unavailable if none fail NotRegistered @audit.record(key, status: registration.status) if error fail Unavailable registration.status handler one_registration(r: Registration) for Registrations op find(key) = Some(r) handler no_registrations() for Registrations op find(key) = None handler audit_log() for Audit op record(key, status) = unit example "a registered attendee is checked in and audited" given @registrations = one_registration(Registration(name: "Ana", status: Open)) given @audit = audit_log() do check_in(fake_hash(1)) expect result is Open expect performed @audit.record example "an unknown attendee fails and is not audited" given @registrations = no_registrations() given @audit = audit_log() do check_in(fake_hash(1)) expect fails NotRegistered expect not performed @audit.record ``` | Line | Meaning | | --- | --- | | `given @x = h(args)` | install handler `h` as `@x` for this example | | `do e` | the expression under test | | `expect e` | `e` is a `Bool` over `result` and must be `true` | | `expect fails V` | `do` failed with variant `V` | | `expect performed @x.op` | the effect trace contains at least one `op` on `@x` | | `expect not performed @x.op` | the trace contains no `op` on `@x` | - **No host capabilities.** Examples cannot use them (U3014); everything comes from `given`, so examples are deterministic. - **`do` lines** may nest fallible and effectful calls, and any failure ends the example. They need no handling clauses. A `do` line has no editable binding, so a call with `edit` or `take` there is U3013: exercise it through a function that edits a local copy. - **Names** are unique per module. - **Isolation.** Each example runs in a fresh abstract machine. `una test --json` reports the outcome and the full effect trace, with labeled arguments redacted. - **`std.testing`** (`fake_hash`) is usable only in examples and in handlers installed only by `given`, and only by calling it, never as a function value (U3015). --- ## Constructs - [example](https://una-lang.org/en/docs/language/examples/example.md) - [test](https://una-lang.org/en/docs/language/examples/test.md) --- # Verification ## 11.1 What the compiler proves | Obligation | Created at | | --- | --- | | `refinement` | every point where a value flows into a refined type: arguments, returns, fields, annotated `let`, and every rebind of an editable binding | | `precondition` | every call and capability operation with `requires` | | `postcondition` | every normal return of a function or handler operation with `ensures` | | `division` | `/` and `mod` by a non-literal | | `exhaustive` | `when` with range or literal arms and no `else` | | `overflow` | each `+`, `-`, `*`, `/`, `mod` and unary `-` on a fixed-width type in code, and each narrowing conversion (edition `0.2`) | When proving an obligation, the compiler may assume: - refinements of values in scope; - the enclosing function's `requires`; - the branch conditions on the current path; - the `ensures` of functions already called; - operation `ensures`; - facts from `checked`; - the ranges of fixed-width values, and of a range loop's variable. ## 11.2 Statuses | Status | Meaning | Build | | --- | --- | --- | | `proven` | the solver proved the goal | ok | | `refuted` | a counterexample exists | error U5001, with the counterexample | | `unknown` | the solver could not decide | error U5002: unknown is never accepted | A U5001 or U5002 comes with the ranked repair candidates that apply at its site, each with an escape cost. None has a mechanical edit, and none is applied automatically. For a `refinement` or `precondition` obligation, with goal `G`, the compiler words them, in this order: | Repair | When it is proposed | Escape cost | | --- | --- | --- | | strengthen the type of the parameter `p` to a refined kind that implies `G` | the value is the parameter `p` of the enclosing function | 0 | | add `requires G` to the enclosing function; its callers then prove it | the enclosing function is not `pub`, and `G` names only its parameters | 0 | | add a guard (`if` or a `when` arm) that handles the values where `G` does not hold | always | 0 | | check the value with `checked(value, G) else fail ` | always | 1 | `checked` is an escape: its repair carries `"escape": {"kind": "checked", "cost": ...}` in `--json`, and the human output says `escape: checked` with its cost. Escapes always come after the repairs that keep the proof, and so do the other escapes, a raised `checked_per_module` (U7003) and a trusted module or policy (U4003, U4004, U7005) (ADR 0095). Inside an example there is no parameter and no `requires`, so only the guard and `checked` remain. The other kinds have their own repairs, all with escape cost 0: - a `postcondition`: add a guard or an arm so that the failing path returns a value for which the `ensures` holds, or adjust the `ensures` clause; - a `division`: guard the division with `if b != 0`; - an `exhaustive` obligation: add an `else` arm, or arms for the values the others miss; - an `overflow`: guard the operation with a test computed on `Int`, widen the values, or use a wrapping or saturating method (§3.1). A goal that names no value, such as the `0 != 0` of `x / 0`, is false whatever the values: it has no repair and no counterexample, and the code itself has to change. `checked` is the last resort: it replaces a proof with a runtime test and counts against the escape budget (§6.5). ## 11.3 Tiers | Tier | Checks | Command | | --- | --- | --- | | 0 | syntax, formatting, names, types, effects, capabilities, information flow, budgets | `una check --tier 0` | | 1 | tier 0 plus every proof obligation (Z3) | `una check` | Verification is reproducible: - the solver version is pinned in `verification.lock`; - queries are deterministic and cached; - every obligation has a stable id (`ob-…`). --- --- # Canonical form Every file has one canonical form. `una fmt` rewrites a file into it, and `una check` reports every difference as U7001, an error with a mechanical repair. Code that a program generates should go through `una fmt` before `una check`. A file with a syntax error has no canonical form: it is neither formatted nor checked for U7001. The rules, from `spec/15`: **File** - Line breaks are `\n` only. - The file ends with exactly one line break. - No line has trailing whitespace. - The file neither starts nor ends with a blank line. **Lines and indentation** - Two spaces per indentation level. - Every logical line is one line. The formatter has no maximum line width, so lines continued inside brackets are joined (§1.2). - The exception is a line with a comment inside its brackets: its line breaks are kept, and each continuation line is indented one level deeper than the line. - Every token keeps its source spelling: integer literals keep their `_` groups (`1_000`), and text literals their escapes. **Spacing.** Tokens are separated by one space, except: - no space after `(`, `[` or `.`, and none before `)`, `]`, `,`, `:` or `.`; - no space around `..` and `..<`; - no space after a unary `-`, unless another `-` follows; - no space between a name and a following `(` or `[`, and none in `fn(` and `checked(`, but one space between an import's module path and its `(`; - no space inside a text literal outside its interpolations, and none just inside the braces of an interpolation. **Functions and bodies** - Header clauses and op clauses are in canonical order (§4.2, §7.1), with one `uses` clause per capability. - A function with no clauses and a body of one plain line uses the short form (§4.1). The same holds for the body of a predicate or handler operation after its `=`, and of a `when` arm after its `->`. - A plain line has no `with` clause and no handling clause, and is not a `when` or an `if` with blocks. Otherwise the long form stays, and it also stays when a comment sits between the head and the end of the body. - Handling clauses sit on their own indented lines, directly below the statement. **Sums.** A sum with two or more variants has no leading `|`. A sum with one variant keeps it, since the grammar requires it: `kind PhoneError = | Malformed`. **Constructors** - When every argument of a record or variant constructor is labeled or punned, the arguments follow the order in which the fields are declared (§4.4). - This applies to the records and variants the file declares or imports, and to the variants of the sum kinds it imports, when the name comes from exactly one of them and is declared once in its module. - Arguments are not reordered on a line with a comment inside. **Imports** - Imports are sorted bytewise by module path, each keeping the comments that lead it: `events.keys` before `events.seating` before `std.testing`. - The names inside each import are sorted bytewise too (`Availability, Event, availability`: uppercase letters sort before lowercase), unless a comment sits inside the import. **Blank lines** - Top-level items (the module header, each import and each declaration) are separated by exactly one blank line, except consecutive imports, which have none. - Elsewhere, a run of blank lines becomes one blank line. - No blank line follows a line that opens a block, and none precedes or follows the `=` line of the long form. **Comments** - The formatter never moves a comment to another line, and it removes trailing whitespace from the comment's text. - A comment at the end of a line of code stays there, after one space. - A comment on its own line stays in place, at the indentation level nearest to its column (ties go deeper) among the levels of the lines around it. - A comment on its own line at level 0 between two top-level items belongs to the next item, and the item's blank line goes before it. **How U7001 is reported** - `una check` compares each file with its canonical form line by line, and reports one U7001 per changed region, at its first source line. - Each U7001 carries a mechanical edit that replaces the region with its canonical text, and its message names the difference: trailing whitespace, a missing or extra blank line, a missing final line break, or lines that are not in canonical form. - A file with `\r\n` line breaks gets a single U7001 at the first of them, without an edit (§1.1). Run `una fmt` to fix it. --- --- # A complete package The events package: a phone number validated at the boundary, a trusted policy that hashes it, a check-in with two capabilities and its examples, and a `main` that prints. `una check`, `una test`, `una run` and `una build` all accept it, and the native executable prints what `una run` prints. `una.toml` ```toml [package] name = "events" version = "0.1.0" edition = "0.2" [labels] categories = ["PII", "Location"] [trusted] modules = ["events.keys"] [escape_budget] checked_per_module = 1 [run] entry = "events.main" grants = ["console"] ``` `verification.lock` ```toml encoding_version = "una-smt-1" solver = "z3" solver_version = "5.1.0" logic = "QF_UFLIA" step_budget = 5000000 random_seed = 0 ``` `src/events/types.una` ```una module events.types --- A phone number of 11 digits, validated once at the boundary. pub kind Phone = Text where valid_phone(it) pub kind PhoneError = | Malformed --- Format check only. pub predicate opaque valid_phone(t: Text) -> Bool = t.len == 11 and is_digits(t) --- The only way to obtain a Phone from untrusted text. pub parse_phone(raw: Text) -> Phone fails PhoneError = checked(raw, valid_phone(it)) else fail Malformed example "malformed input is rejected" do parse_phone("123") expect fails Malformed ``` `src/events/seating.una` ```una module events.seating requirement EVENTS_3 text "An event with no remaining seats is always shown as sold out" source policy "Box Office Handbook 2.1" owner box_office status active pub kind Seats = Int in 0..5000 pub kind Availability = SoldOut | Few | Open pub kind Event name: Text remaining: Seats pub kind Registration name: Text event: Event --- Availability bands from the Box Office Handbook. pub availability(e: Event) -> Availability ensures e.remaining < 1 implies result is SoldOut derived from EVENTS_3 = when e.remaining in 0..0 -> SoldOut in 1..<20 -> Few in 20..5000 -> Open --- Clamps a raw count into the seat range. pub clamp_seats(raw: Int) -> Seats = if raw < 0 then 0 else if raw > 5000 then 5000 else raw --- Shows an event in its Una form. pub describe(e: Event) -> Text = "{e}" --- Shows a list of events in their Una forms. pub describe_many(events: List[Event]) -> Text = "{events}" example "an event with no seats is sold out" do availability(Event(name: "Launch", remaining: 0)) expect result is SoldOut example "an event record can be interpolated" do describe(Event(name: "Launch", remaining: 0)) expect result == "Event(name: \"Launch\", remaining: 0)" example "a list of event records can be interpolated" do describe_many([Event(name: "Launch", remaining: 0)]) expect result == "[Event(name: \"Launch\", remaining: 0)]" example "an event with many seats is open" do availability(Event(name: "Meetup", remaining: 120)) expect result is Open example "raw counts are clamped" do clamp_seats(9000) expect result == 5000 ``` `src/events/keys.una` ```una trusted module events.keys import events.types (Phone) pub policy attendee_key from secret[PII] Phone to internal Hashed via hmac_phone purpose "registration lookup and audit correlation" owner privacy hmac_phone(phone: secret[PII] Phone) -> internal Hashed uses @keys: Keys[hmac] fails KeyError = @keys.hmac(key_name: "phone_pepper", data: phone) if error pass ``` `src/events/checkin.una` ```una module events.checkin import events.keys (attendee_key) import events.seating (Availability, Event, Registration, availability) import events.types (Phone, parse_phone) import std.testing (fake_hash) pub kind CheckInError = NotRegistered | Unavailable pub kind StoreError = Timeout | Corrupted pub capability Registrations op find(key: internal Hashed) -> Option[Registration] fails StoreError accepts internal pub capability Audit op record(key: internal Hashed, status: Availability) -> Unit fails StoreError accepts internal --- Finds a registration by phone, reports the event's availability and audits the check-in. --- The phone number never leaves this function: only its keyed hash does. pub check_in(phone: secret[PII] Phone) -> Availability uses @registrations: Registrations[find] uses @audit: Audit[record] uses @keys: Keys[hmac] fails CheckInError = let key = attendee_key(phone) if error fail Unavailable let registration = @registrations.find(key) if error fail Unavailable if none fail NotRegistered let status = availability(registration.event) @audit.record(key, status) if error fail Unavailable status handler one_registration(r: Registration) for Registrations op find(key) = Some(r) handler no_registrations() for Registrations op find(key) = None handler audit_log() for Audit op record(key, status) = unit handler fake_keys() for Keys op hmac(key_name, data) = fake_hash(1) example "a registered attendee is checked in and audited" given @registrations = one_registration(Registration(name: "Ana", event: Event(name: "Meetup", remaining: 120))) given @audit = audit_log() given @keys = fake_keys() do check_in(parse_phone("11900000001")) expect result is Open expect performed @audit.record example "an unknown attendee fails and is not audited" given @registrations = no_registrations() given @audit = audit_log() given @keys = fake_keys() do check_in(parse_phone("11900000001")) expect fails NotRegistered expect not performed @audit.record ``` `src/events/main.una` ```una module events.main import events.seating (Availability, Event, availability, clamp_seats, describe) label(status: Availability) -> Text = when status is SoldOut -> "sold out" is Few -> "few seats left" is Open -> "open" pub main() -> Unit uses @console: Console[print] = let events = [Event(name: "Meetup", remaining: clamp_seats(120)), Event(name: "Launch", remaining: 0)] for event in events let status = availability(event) @console.print("{describe(event)}: {label(status)}") ``` Running it: ```text $ una check . $ una test . 6 examples: 6 passed, 0 failed $ una run . Meetup (120 seats): open Launch (0 seats): sold out $ una build . built target/una/events $ ./target/una/events Meetup (120 seats): open Launch (0 seats): sold out ``` --- --- # Not in this edition These are planned or deliberately absent. Using a reserved word gives U0103 (§1.5). | Area | Status | | --- | --- | | Shared and isolated references (`shared`, `iso`, `weak`), cyclic structures | not in any edition yet; the words are reserved for a later edition; use arenas and indices | | User traits and implementations (`trait`, `impl`), laws of constraints | later; edition `0.2` has `Eq`, `Ord` and `Integer` | | Task values, detached tasks, `race`, `select`, timeouts, channels, actors | in editions `0.2` and `0.3`, `together` is the only concurrency; edition `0.4` (preview) adds started tasks (`tasks` and `start`), deadlines (`within`) and races (`first of`) ([spec/27](https://una-lang.org/en/docs/spec/27-tasks-and-time/)); `select`, channels and actors are in no edition | | `break`, `continue`, an `invariant` clause for loops | not in v0.2 | | A checked left shift | not in v0.2; use `wrapping_shift_left` or a multiplication | | Cross-compilation of native executables | not in v0.2; each host builds for itself | | Units of measure | edition `0.3` preview ([spec/25](https://una-lang.org/en/docs/spec/25-units-of-measure/), [ADR 0104](https://github.com/una-lang/una/blob/v0.4.0/docs/adr/0104-units-of-measure.md)) | | Pipeline operator (`\|>`) | not added; method-call chains already cover this form ([ADR 0110](https://github.com/una-lang/una/blob/v0.4.0/docs/adr/0110-pipelines-and-shorthand-lambdas.md)) | | Foreign code and FFI | not permitted in any edition ([ADR 0121](https://github.com/una-lang/una/blob/v0.4.0/docs/adr/0121-the-terms-of-a-preview-edition.md), rule 17) | | Quantified laws and property tests | deferred: verification tiers 2 and 3 ([spec/12](https://una-lang.org/en/docs/spec/12-verification/), [backlog](https://github.com/una-lang/una/blob/v0.4.0/docs/plan/backlog.md)) | | Semantic diff | deferred; in no release yet ([availability](https://una-lang.org/en/docs/editions/availability/)) | | Cost contracts | a later release, not yet scheduled ([backlog](https://github.com/una-lang/una/blob/v0.4.0/docs/plan/backlog.md)) | | External state semantics (idempotency, delivery, `observe`), durable effect journal | not in 0.4.0, and no edition plans them yet ([ADR 0139](https://github.com/una-lang/una/blob/v0.4.0/docs/adr/0139-edition-numbering-follows-the-release-that-closes-it.md), rule 6); `observe` is only a reserved word | | Services, data access, infrastructure generation | not in 0.4.0, and no edition plans them yet; edition `0.4` (preview) has HTTP servers only ([spec/31](https://una-lang.org/en/docs/spec/31-http-servers/)) | | Exceptions, null, inheritance, operator overloading, macros, implicit conversions, global mutable state, ambient authority | never | --- # kind ## What it does `kind` declares a type. It takes one of four forms: - an **alias**, another name for a type; - a **refinement**, a type narrowed by a predicate; - a **sum**, a choice among variants, which may carry fields; - a **record**, a set of named fields. Records and sums are nominal, which means a type is known by its name: two declarations of the same shape are two types. Aliases and refinements are structural over their base, which means they are the type they rename or narrow, so a `Seats` value is an `Int` wherever an `Int` is expected. Learn more: [Records](https://una-lang.org/en/learn/kinds/records/) and [Sum kinds, and is](https://una-lang.org/en/learn/kinds/sum-kinds-and-is/). ```una module shop pub kind Seats = Int in 0..5000 pub kind Availability = SoldOut | Few | Open pub kind Lookup = Found(name: Text) | Missing pub kind Event name: Text remaining: Seats pub kind NonEmpty[T] = List[T] where it.len > 0 pub kind Count = Int ``` ## Forms In the grammar below, each rule gives a name, `=`, what the name stands for and `;`, quoted words are written as shown, NEWLINE, INDENT and DEDENT stand for a line break and for one more or one less level of indentation, `[ ]` marks an optional part, `{ }` a part that may repeat, `|` separates alternatives, `( )` groups them, and `(* *)` holds a comment. ```ebnf kind_decl = [ "pub" ] "kind" upper_ident [ type_params ] kind_body ; type_params = "[" upper_ident { "," upper_ident } "]" ; kind_body = alias_body | sum_body | record_body ; alias_body = "=" type [ "where" line_expr ] NEWLINE ; sum_body = "=" ( "|" variant { "|" variant } | variant "|" variant { "|" variant } ) NEWLINE ; record_body = NEWLINE INDENT field { field } DEDENT ; field = lower_ident ":" type NEWLINE ; variant = upper_ident [ "(" field_sig { "," field_sig } ")" ] ; field_sig = lower_ident ":" type ; ``` - **Alias:** `kind Count = Int`. - **Refinement:** `kind Phone = Text where valid_phone(it)`, or with range sugar, `kind Seats = Int in 0..5000`. `in a..b` includes `b`, and `in a.. 0`. A kind's type parameters take no constraint. ## Examples A refinement is checked where a value enters it. Here the verifier, the part of `una check` that proves what the program must keep, refutes that an arbitrary `Int` lies in `0..5000`: ```una -- fails with U5001 module shop pub kind Seats = Int in 0..5000 pub to_seats(count: Int) -> Seats = count ``` The other direction needs no proof: a `Seats` value is an `Int`: ```una module shop pub kind Seats = Int in 0..5000 pub widen(s: Seats) -> Int = s ``` A refinement of a refined kind conjoins both predicates, so the verifier knows both here: ```una module shop pub kind Stock = Int in 0..100 pub kind LowStock = Stock where it < 10 pub low_stock_level(level: LowStock) -> Int ensures result < 10 and result >= 0 = level ``` Records are nominal: the same fields do not make the same type: ```una -- fails with U2001 module shop pub kind Warehouse aisle: Int shelf: Int pub kind Bin aisle: Int shelf: Int pub as_bin(warehouse: Warehouse) -> Bin = warehouse ``` ## Edge cases **Recursive kinds.** In edition `0.2`, a kind may contain itself through any field, when it has a finite value: ```una module shop pub kind Bundle = Item(sku: Int) | Pair(left: Bundle, right: Bundle) ``` A kind with no finite value is rejected: ```una -- fails with U2002 module shop pub kind Chain = | Link(rest: Chain) ``` **Refined type arguments.** In editions `0.1` and `0.2`, a refined kind cannot be a type argument (the type in brackets, as in `List[Quantity]`), inside a kind either, since refinements are top-level: ```una -- fails with U2002 module shop pub kind Quantity = Int where it > 0 pub kind Order quantities: List[Quantity] ``` **One name per declaration.** Two declarations of a module may not share a name in one namespace, variants included: ```una -- fails with U1002 module shop pub kind Size = | Small pub kind Fit = | Small ``` Further rules: - **A single-variant sum needs its bar.** `kind Chain = Link(rest: Chain)` is a syntax error (U0101). - **Built-in names.** In edition `0.2`, a kind or variant cannot take the name of a built-in type, such as `Int`, `Text`, `List` or `Map` (U1002). In edition `0.1` such a declaration shadows the built-in type in its module. - **A refinement of a function type** is ill-formed. Refine its parameters or its result instead (U2002). ## Diagnostics - [U0101](https://una-lang.org/en/docs/errors/U0101/): a malformed declaration, such as a single-variant sum without its bar. - [U1002](https://una-lang.org/en/docs/errors/U1002/): a kind or variant name defined twice in a module. - [U2001](https://una-lang.org/en/docs/errors/U2001/): a value of one nominal kind where another is expected. - [U2002](https://una-lang.org/en/docs/errors/U2002/): an ill-formed kind, such as a recursion without a finite value or, in editions `0.1` and `0.2`, a refined type argument. - [U5001](https://una-lang.org/en/docs/errors/U5001/): a refinement refuted where a value enters the kind. ## Edition Every form is in editions `0.1` and `0.2`. Edition `0.3` accepts refined type arguments, as `List[Quantity]`: every value put into such a position must be proven to satisfy the refinement, and every value read from it carries it. Recursion differs: edition `0.1` allows a kind to contain itself only through `List` or `Option` fields. ```una -- edition 0.1 -- fails with U2002 module shop pub kind Bundle = Item(sku: Int) | Pair(left: Bundle, right: Bundle) ``` ## Normative source - `spec/03 §2`: kinds and rules 1 to 5; `spec/03 §3`: refinements, range sugar, refined type arguments and function kinds. - `spec/02 §2`: the grammar. - `spec/12 §3`: the `refinement` obligation. - `spec/03 §1`: built-in type names. - `spec/10 §11` rule 5: duplicate names; `spec/10 §12`: the formal rules of recursive kinds. - `spec/20 §2` rule 1: a kind's type parameters take no constraint. - Decision records: [ADR 0060](https://github.com/una-lang/una/blob/v0.4.0/docs/adr/0060-recursive-kinds.md), for recursive kinds; [ADR 0040](https://github.com/una-lang/una/blob/v0.4.0/docs/adr/0040-refined-type-arguments.md), for refined type arguments in editions `0.1` and `0.2`; [ADR 0103](https://github.com/una-lang/una/blob/v0.4.0/docs/adr/0103-refined-elements-of-collections.md), for refined type arguments in edition `0.3`; [ADR 0045](https://github.com/una-lang/una/blob/v0.4.0/docs/adr/0045-refined-kinds-over-function-types.md), for refined function kinds. --- # where and refinements ## What it does A refinement narrows a type by a predicate: `Text where valid_phone(it)` is the texts for which `valid_phone` holds, and `Int in 0..5000` the integers from 0 to 5000. The compiler proves, at every place a value enters the refined type, that the predicate holds. The proof happens at compile time, before the program runs, so a program that checks never holds a value outside its refinement, relative to the solver and to the `ensures` clauses of capability operations, which are assumed, not proven: a host implementation is trusted to satisfy them. Learn more: [Refined kinds and predicates](https://una-lang.org/en/learn/contracts/refined-kinds-and-predicates/). ```una module shop pub kind Seats = Int in 0..5000 pub kind Event name: Text remaining: Seats pub book(e: Event, count: Int) -> Seats requires count >= 1 requires count <= e.remaining = e.remaining - count ``` ## Forms In the grammar below, each rule gives a name, `=`, what the name stands for and `;`, quoted words are written as shown, NEWLINE, INDENT and DEDENT stand for a line break and for one more or one less level of indentation, `[ ]` marks an optional part, `{ }` a part that may repeat, `|` separates alternatives, `( )` groups them, and `(* *)` holds a comment. ```ebnf alias_body = "=" type [ "where" line_expr ] NEWLINE ; type = [ label ] type_core [ "in" range ] ; range = signed_int ( ".." | "..<" ) signed_int ; ``` - **`T where p`**, where `p` is written in the refinement language, the small set of expressions listed below that the verifier can decide, and `it` names the value. - **Range sugar:** `T in a..b` means `T where a <= it and it <= b`, and `T in a..`, `>=`, `in range`, `is Variant`; - `and`, `or`, `not`, `implies`; - calls of predicates. See [`predicate`](https://una-lang.org/en/docs/language/types/predicate/). ## Examples In the body above, the preconditions give the facts that prove `e.remaining - count` lies in `0..5000`. A caller that cannot show a value fits is refuted, with a counterexample: ```una -- fails with U5001 module shop pub kind Seats = Int in 0..5000 pub to_seats(count: Int) -> Seats = count ``` A guard is enough when it gives the facts. In the last `else` branch the verifier knows `not (raw < 0)` and `not (raw > 5000)`, so `raw` lies in `0..5000`, and in the `then` branches the literals fit: ```una module shop pub kind Seats = Int in 0..5000 pub cap_seats(raw: Int) -> Seats = if raw < 0 then 0 else if raw > 5000 then 5000 else raw ``` A predicate makes a refinement readable, and a `reflect` predicate's definition is visible to the solver, the program that decides each obligation: ```una module shop pub predicate reflect adult(age: Int) -> Bool = age >= 18 pub kind Adult = Int where adult(it) pub grow(a: Adult) -> Adult = a + 1 ``` ## Edge cases **Only the refinement language.** An expression outside it is U2014, at the outermost offending part. Outside it are the ordering of `Text`, `is` with a literal, `==` against a variant, `unit` and interpolated text: ```una -- fails with U2014 module shop pub kind Late = Text where it > "m" ``` **Refinements are top-level.** In editions `0.1` and `0.2`, a refined kind cannot be a type argument, so `List[Quantity]` is ill-formed. Refine the list itself, or check each element where it is used: ```una -- fails with U2002 module shop pub kind Quantity = Int where it > 0 pub kind Order quantities: List[Quantity] ``` Further rules: - **Structural over the base.** A refined value is a value of its base, with no conversion; only entering the refinement creates an obligation. - **Stacking.** A refinement of a refined kind conjoins both predicates. - **`it`** is valid only in `where` clauses and in the predicate of `checked` (U2013). In edition `0.3`, where an operation's condition is also written with `where`, a kind's `where` counts, not the condition on an operation. - **Unknown is not proven.** An obligation, a fact the program must be shown to keep, that the solver cannot decide is an error, U5002, never a pass. - **Opaque facts.** A refinement may name an opaque predicate, whose fact a value obtains only through `checked`. See [`checked`](https://una-lang.org/en/docs/language/errors/checked/). - **Function kinds.** `kind F = fn(Int) -> Int where good(it)` is ill-formed. Refine the parameters or the result (U2002). ## Diagnostics - [U2002](https://una-lang.org/en/docs/errors/U2002/): a refined type argument in editions `0.1` and `0.2`, or a refinement of a function type. - [U2013](https://una-lang.org/en/docs/errors/U2013/): `it` outside a `where` clause or the predicate of `checked`. - [U2014](https://una-lang.org/en/docs/errors/U2014/): a predicate outside the refinement language. - [U5001](https://una-lang.org/en/docs/errors/U5001/): a value that may not satisfy the refinement it enters, with a counterexample. - [U5002](https://una-lang.org/en/docs/errors/U5002/): an obligation the solver cannot decide. ## Edition Refinements are the same in editions `0.1` and `0.2`. In edition `0.2`, a fixed-width integer type can be refined too, as `kind Port = U16 where it > 0`. Edition `0.3` accepts refined type arguments, as `List[Quantity]`: every value put into such a position must be proven to satisfy the refinement, and every value read from it carries it. ## Normative source - `spec/03 §2`: rules 2 and 3; `spec/03 §3`: the refinement language, range sugar, refined type arguments and function kinds. - `spec/02 §2`: the grammar; `spec/02 §8`: where `it` may appear. - `spec/12 §2`: the decidable fragment; `spec/12 §3`: the `refinement` obligation; `spec/12 §6`: statuses. - `spec/03 §4`: predicates, and opaque facts. - `spec/18 §1`: refined fixed-width integers. - Decision records: [ADR 0040](https://github.com/una-lang/una/blob/v0.4.0/docs/adr/0040-refined-type-arguments.md), for refined type arguments in editions `0.1` and `0.2`; [ADR 0103](https://github.com/una-lang/una/blob/v0.4.0/docs/adr/0103-refined-elements-of-collections.md), for refined type arguments in edition `0.3`; [ADR 0092](https://github.com/una-lang/una/blob/v0.4.0/docs/adr/0092-conditions-on-allowed-effects.md), for `it` in edition `0.3`; [ADR 0045](https://github.com/una-lang/una/blob/v0.4.0/docs/adr/0045-refined-kinds-over-function-types.md), for refined function kinds. --- # predicate: reflect and opaque ## What it does A predicate is a named, pure (it acts on nothing outside the program), total (it gives a result for every input, without failing) boolean function that refinements and contracts can call. Refinements are the conditions a type adds to its values; contracts are a function's `requires` and `ensures` clauses. It comes in two forms, which differ in what the solver, the program that decides each fact the compiler must prove, knows: - **`reflect`:** its body is in the refinement language, the small set of expressions the solver can decide, and the solver sees it as a definition. A value obtains its fact by proof. - **`opaque`:** its body is any pure expression that cannot fail, and the solver sees only a name. A value obtains its fact at run time, through [`checked`](https://una-lang.org/en/docs/language/errors/checked/), or from a capability operation's `ensures`. ```una module shop pub predicate reflect adult(age: Int) -> Bool = age >= 18 pub kind Adult = Int where adult(it) pub grow(a: Adult) -> Adult = a + 1 ``` Learn more: [Refined kinds and predicates](https://una-lang.org/en/learn/contracts/refined-kinds-and-predicates/). ## Forms In the grammar below, each rule gives a name, `=`, what the name stands for and `;`, quoted words are written as shown, NEWLINE, INDENT and DEDENT stand for a line break and for one more or one less level of indentation, `[ ]` marks an optional part, `{ }` a part that may repeat, `|` separates alternatives, `( )` groups them, and `(* *)` holds a comment. ```ebnf predicate_decl = [ "pub" ] "predicate" ( "reflect" | "opaque" ) lower_ident "(" [ params ] ")" "->" type "=" inline_or_block ; ``` The kinds of predicate: | Form | Body | Visible to the solver | How a value obtains the fact | | --- | --- | --- | --- | | `predicate reflect` | In the refinement language, not recursive | Yes, as a definition | Proven statically | | `predicate opaque` | Any pure, non-failing expression | No, only as a name whose meaning it does not know | `checked` at run time, or a capability operation's `ensures` | ## Examples The solver proves `grow`'s result from `adult`'s definition: `a >= 18` implies `a + 1 >= 18`. An opaque predicate holds a test the solver cannot reason about, such as `is_digits`. A value gets its fact through [`checked`](https://una-lang.org/en/docs/language/errors/checked/), which counts against the escape budget, the number of run-time tests each module may use in place of a proof: `una.toml` ```toml [package] name = "shop" version = "0.1.0" edition = "0.2" [escape_budget] checked_per_module = 1 ``` `src/shop.una` ```una module shop pub kind Phone = Text where valid_phone(it) pub kind PhoneError = | Malformed pub predicate opaque valid_phone(t: Text) -> Bool = t.len == 11 and is_digits(t) pub parse_phone(raw: Text) -> Phone fails PhoneError = checked(raw, valid_phone(it)) else fail Malformed ``` ## A nonlinear relation checked at run time The refinement language does not let the solver derive a general nonlinear equation such as `area = side * side`. An opaque predicate can express that runtime test; `checked` establishes the refined kind only when the test succeeds. With `checked_per_module = 1`, the package spends one escape for this check. `una.toml` ```toml [package] name = "demo" version = "0.1.0" edition = "0.3" [escape_budget] checked_per_module = 1 ``` `src/demo.una` ```una module demo pub predicate opaque square_pair(value: Pair) -> Bool = value.area == value.side * value.side pub kind Pair side: Int area: Int pub kind Square = Pair where square_pair(it) pub kind ValidationError = | WrongArea pub validate(value: Pair) -> Square fails ValidationError = checked(value, square_pair(it)) else fail WrongArea test "valid" do validate(Pair(side: 3, area: 9)) expect result.side == 3 test "invalid" do validate(Pair(side: 3, area: 8)) expect fails WrongArea ``` The solver knows only the predicate's name; it does not prove or learn the square equation. Each `checked` counts against the module's budget. ## Edge cases A `reflect` predicate can also be called in code, as an ordinary function: ```una module shop pub predicate reflect adult(age: Int) -> Bool = age >= 18 pub can_vote(age: Int) -> Bool = adult(age) ``` **`reflect` bodies are in the refinement language**: ```una -- fails with U2015 module shop pub predicate reflect digits(t: Text) -> Bool = is_digits(t) ``` **`reflect` predicates do not call themselves**, directly or through others: ```una -- fails with U2015 module shop pub predicate reflect even(n: Int) -> Bool = even(n - 2) ``` **Predicates cannot fail.** A body is pure and total: ```una -- fails with U2015 module shop pub kind StockError = | Unknown pub predicate opaque restockable(n: Int) -> Bool = if n > 1 then fail Unknown else true ``` **An opaque predicate is called only in `checked`**, and in the bodies of other opaque predicates. A call anywhere else would establish its fact without counting against the escape budget: ```una -- fails with U2016 module shop pub predicate opaque valid_phone(raw: Text) -> Bool = raw.len == 11 and is_digits(raw) pub looks_valid(raw: Text) -> Bool = valid_phone(raw) ``` Further rules: - **Naming is not establishing.** The `where` clause of a kind, and the `requires` and `ensures` clauses of a capability operation, may name an opaque predicate, since they state the fact without establishing it. - **Sound by construction.** The solver knows nothing about an opaque predicate beyond facts established at run time, so it cannot introduce an inconsistency. - **Budgeted.** Each `checked` counts against the module's escape budget, U7003 beyond it. ## Diagnostics - [U2014](https://una-lang.org/en/docs/errors/U2014/): a refinement or contract outside the refinement language. - [U2015](https://una-lang.org/en/docs/errors/U2015/): an invalid predicate body: impure, failing, recursive, or outside the refinement language for `reflect`. - [U2016](https://una-lang.org/en/docs/errors/U2016/): an opaque predicate called outside `checked`. - [U7003](https://una-lang.org/en/docs/errors/U7003/): more `checked` uses than the escape budget allows. ## Edition Predicates are the same in editions `0.1` and `0.2`, and editions `0.3` and `0.4` keep the rules of edition `0.2` (`spec/13 §7`). ## Normative source - `spec/03 §4`: predicates; `spec/03 §3`: the refinement language. - `spec/02 §3`: the grammar. - `spec/06 §6`: `checked`; `spec/05 §2`: a capability operation's `ensures`. - Decision record: [ADR 0042](https://github.com/una-lang/una/blob/v0.4.0/docs/adr/0042-opaque-predicates-only-in-checked.md), for opaque predicates only in `checked`. --- # Constraints on generics ## What it does From edition `0.2`, a type parameter of a function, a placeholder such as `T` that stands for any type the caller uses, may carry one built-in constraint: `Eq`, `Ord` or `Integer`. A constraint allows operators on values of the parameter, with their built-in meaning, and restricts the types that may instantiate it. There are no user traits and no implementations (ways, in other languages, to declare your own constraints and say which types meet them): a type satisfies a constraint by what it is. Learn more: [Generic kinds and constraints](https://una-lang.org/en/learn/kinds/generic-kinds-and-constraints/). ```una module shop pub largest[T: Ord](prices: List[T], floor: T) -> T = prices.fold(initial: floor, step: fn(best, price) -> max(best, b: price)) pub total[T: Integer](prices: List[T]) -> Int = prices.map(each: fn(price) -> price.to_int()).sum() pub same[T: Eq](a: T, b: T) -> Bool = a == b ``` ## Forms In the grammar below, each rule gives a name, `=`, what the name stands for and `;`, quoted words are written as shown, NEWLINE, INDENT and DEDENT stand for a line break and for one more or one less level of indentation, `[ ]` marks an optional part, `{ }` a part that may repeat, `|` separates alternatives, `( )` groups them, and `(* *)` holds a comment. ```ebnf signature = lower_ident [ constrained_params ] "(" [ params ] ")" "->" type ; constrained_params = "[" constrained_param { "," constrained_param } "]" ; constrained_param = upper_ident [ ":" upper_ident ] ; ``` The constraints: | Constraint | Allows on values of `T` | Satisfied by | | --- | --- | --- | | `Eq` | `==`, `!=`, and interpolation | every type whose values hold no functions | | `Ord` | what `Eq` allows, and `<`, `<=`, `>`, `>=` | `Int`, `I8` to `U64`, `Text`, and sum kinds whose variants have no payload | | `Integer` | what `Ord` allows, and `x.to_int()` | `Int`, `I8` to `U64` | `Ord` includes `Eq`, and `Integer` includes `Ord`. A type parameter takes at most one constraint, and only a function's type parameters take one. ## Examples A sum without payloads satisfies `Ord`, and so does `Text`: ```una module shop pub kind Size = Small | Large pub smaller[T: Ord](a: T, b: T) -> T = if a < b then a else b pub pick(a: Size, b: Size) -> Size = smaller(a, b: b) pub texts(a: Text, b: Text) -> Text = smaller(a, b: b) ``` A private function has the least constraint its body needs inferred. A public function writes it: ```una module shop same_private[T](a: T, b: T) -> Bool = a == b pub use_it(a: Int, b: Int) -> Bool = same_private(a, b: b) ``` An operator on a parameter needs a constraint that allows it, equality included: ```una -- fails with U2026 module shop pub same[T](a: T, b: T) -> Bool = a == b ``` A generic function cannot use `+` on `T`: the built-in constraints do not include arithmetic. Pass the operation as a function value instead. This states only how to combine two values; it does not promise associativity or any other algebraic law: ```una module shop pub fold_with[T](items: List[T], initial: T, step: fn(T, T) -> T) -> T = items.fold(initial: initial, step: step) pub total(items: List[Int]) -> Int = fold_with(items, initial: 0, step: fn(acc, item) -> acc + item) ``` The runtime case [generic_fold_run](https://github.com/una-lang/una/blob/v0.4.0/tests/conformance/runtime/generic_fold_run/src/fold.una) checks that this explicit operation sums `[1, 2, 3]` to `6`. ## Edge cases **Type arguments must satisfy the constraint.** A sum whose variants carry payloads does not satisfy `Ord`: ```una -- fails with U2025 module shop pub smaller[T: Ord](a: T, b: T) -> T = if a < b then a else b pub kind Parcel = Tube(length: Int) | Envelope pub pick(a: Parcel, b: Parcel) -> Parcel = smaller(a, b: b) ``` **Only three constraints exist**: ```una -- fails with U2027 module shop pub same[T: Hashable](a: T, b: T) -> Bool = a == b ``` **Kinds take no constraint.** `Kind[T: Eq]` is a syntax error: ```una -- fails with U0101 module shop pub kind Box[T: Eq] value: T ``` **No arithmetic on `T`.** `+`, `-`, `*`, `/` and `mod` stay undefined on a type parameter, constrained or not. Convert with `to_int()` and compute on `Int`: ```una -- fails with U2001 module shop pub add[T: Integer](a: T, b: T) -> T = a + b ``` Further rules: - **Labels do not count.** `secret Int` satisfies `Integer`. - **Operators keep their meaning.** `==` is structural equality and `<` the built-in order, on every type that satisfies the constraint. - **Information flow.** A comparison on values of `T` carries the labels of its operands, the symbolic label of `T` included, a stand-in for whatever label the caller's type carries. Branching on it raises the program counter, the label of the conditions that decide whether a line runs (see [Branches and failures: implicit flows](https://una-lang.org/en/learn/information-flow/branches-and-failures-implicit-flows/)). - **Verification.** In a generic body, the verifier knows nothing about `<` on a `T: Ord` but its name, so no law such as transitivity (`a < b` and `b < c` give `a < c`) is assumed. - **The prelude.** In edition `0.2`, `min`, `max`, `contains`, `sum` and `sort` are generic over these constraints. ## Diagnostics - [U0101](https://una-lang.org/en/docs/errors/U0101/): a constraint on a kind's type parameter, or one in edition `0.1`. - [U2001](https://una-lang.org/en/docs/errors/U2001/): arithmetic on values of a type parameter. - [U2025](https://una-lang.org/en/docs/errors/U2025/): a type argument that does not satisfy its parameter's constraint. - [U2026](https://una-lang.org/en/docs/errors/U2026/): an operator that the parameter's constraint does not allow. - [U2027](https://una-lang.org/en/docs/errors/U2027/): an unknown constraint name. ## Edition Constraints exist from edition `0.2` on. In edition `0.1`, type parameters are unconstrained, equality on them keeps an inferred bound, and a written constraint is a syntax error: ```una -- edition 0.1 -- fails with U0101 module shop pub same[T: Eq](a: T, b: T) -> Bool = a == b ``` ## Normative source - `spec/20 §1`: the constraints and rules 1 to 6; `spec/20 §2`: syntax; `spec/20 §3`: static semantics; `spec/20 §4`: information flow; `spec/20 §5`: verification; `spec/20 §6`: the prelude. - `spec/03 §2` rule 4: type parameters in edition `0.1`. --- # requires ## What it does `requires p` states a precondition: what must hold of the arguments for the function to be called. It is checked at both ends: - **at every call**, the verifier (the part of `una check` that proves facts about the code) proves `p` for the arguments given, or the program does not compile; - **in the body**, `p` is a fact the verifier may assume. A precondition is proven, not tested at run time, so it costs nothing when the program runs. Learn more: [Preconditions: requires](https://una-lang.org/en/learn/contracts/preconditions-requires/). ```una module shop pub initial(name: Text) -> Text requires name.len >= 1 ensures result.len == 1 = name.slice(start: 0, end: 1) ``` ## Forms In the grammar below, each rule gives a name, `=`, what the name stands for and `;`, quoted words are written as shown, NEWLINE, INDENT and DEDENT stand for a line break and for one more or one less level of indentation, `[ ]` marks an optional part, `{ }` a part that may repeat, `|` separates alternatives, `( )` groups them, and `(* *)` holds a comment. ```ebnf clause = "requires" line_expr NEWLINE | "ensures" line_expr NEWLINE | "uses" cap_ref ":" cap_type NEWLINE | "uses" "of" lower_ident NEWLINE (* edition 0.2 *) | "fails" upper_ident NEWLINE | "fails" "of" lower_ident NEWLINE (* edition 0.2 *) | "derived" "from" upper_ident { "," upper_ident } NEWLINE ; ``` - A function may have any number of `requires` clauses. They all hold together. - They come first among the clauses: every `requires`, then every `ensures`, `uses`, `fails` and `derived from`. - The expression is in the refinement language (the expressions that a type's condition may use, which the solver can reason about), over the parameters. ## Examples Inside `initial`, `name.len >= 1` is assumed, which proves the precondition of `slice`. Every caller must prove a precondition in turn. Here a call of `half_price` with a literal argument breaks its precondition, and the diagnostic shows the refuted goal (the fact that the verifier found false): ```una -- fails with U5001 module shop pub half_price(cents: Int) -> Int requires cents >= 0 ensures result * 2 <= cents = cents / 2 pub broken_discount() -> Int = half_price(-1) ``` Several clauses describe a range of valid arguments, and the branches of a guard give the facts a caller needs: ```una module shop pub kind Seats = Int in 0..5000 pub kind Event name: Text remaining: Seats pub kind BookingError = | InvalidCount pub seats_after(e: Event, count: Int) -> Seats requires count >= 1 requires count <= e.remaining = e.remaining - count pub book(e: Event, count: Int) -> Seats fails BookingError = if count < 1 or count > e.remaining fail InvalidCount else seats_after(e, count) ``` ## Edge cases **Only the refinement language.** A precondition is decided by the solver (the program that `una check` asks to prove each fact). The ordering of `Text`, for example, is outside the refinement language: ```una -- fails with U2014 module shop pub early_name(name: Text) -> Text requires name < "b" = name ``` **`result` is not in scope.** A precondition speaks of the arguments. `result` belongs to `ensures` and `expect` lines: ```una -- fails with U2012 module shop pub restock(units: Int) -> Int requires result > 0 = units ``` **Clause order.** `requires` comes before `ensures`: ```una -- fails with U0102 module shop pub next_order(order: Int) -> Int ensures result > order requires order > 0 = order + 1 ``` Further rules: - **Counterexamples.** A refuted precondition comes with a counterexample: the values for which it fails, by name. - **Unknown is an error.** An obligation (a fact that `una check` must prove) that the solver cannot decide is U5002, never a pass. - **Repairs.** For a refuted precondition, the repairs propose a stronger parameter type, a `requires` clause when the value is a parameter of a private function, a guard, then `checked`. - **Operations.** A capability operation (an action on something outside the program, declared by a `capability`) may have `requires` too, an obligation at every call site. - **Not on `via` functions.** A policy (a declared release of labeled data to a lower label) computes its release with a `via` function, which has no `requires` clause, since a policy call checks its argument only against the policy's `from` type (U4005). ## Diagnostics - [U0102](https://una-lang.org/en/docs/errors/U0102/): a `requires` clause after another kind of clause. - [U2012](https://una-lang.org/en/docs/errors/U2012/): `result` in a precondition. - [U2014](https://una-lang.org/en/docs/errors/U2014/): a precondition outside the refinement language. - [U5001](https://una-lang.org/en/docs/errors/U5001/): a call whose precondition is refuted, with a counterexample. - [U5002](https://una-lang.org/en/docs/errors/U5002/): a precondition the solver cannot decide. ## Edition `requires` is the same in editions `0.1` and `0.2`. ## Normative source - `spec/04 §2`: clauses and rule 1. - `spec/02 §3`: the grammar, clause order and the `of` clauses of edition `0.2`; `spec/02 §8`: where `result` may appear. - `spec/03 §3`: the refinement language. - `spec/12 §3`: the `precondition` obligation and the hypotheses; `spec/12 §6`: statuses; `spec/12 §7`: counterexamples. - `spec/13 §3`: repairs. - `spec/05 §2`: operation contracts; `spec/07 §5` rule 4: `via` functions. --- # ensures ## What it does `ensures q` states a postcondition, a promise about the result: what holds of `result` and the arguments when the function returns normally. It is checked at both ends: - **in the body**, the verifier (the part of `una check` that proves facts about the code) proves `q` on every normal return path; - **at every call**, callers may assume `q` for the value they receive. So a caller can rely on a function's header alone, without reading its body. Learn more: [Postconditions: ensures and counterexamples](https://una-lang.org/en/learn/contracts/postconditions-ensures-and-counterexamples/). ```una module shop pub clamp(n: Int, low: Int, high: Int) -> Int requires low <= high ensures result >= low and result <= high ensures n >= low and n <= high implies result == n = if n < low then low else if n > high then high else n ``` ## Forms In the grammar below, each rule gives a name, `=`, what the name stands for and `;`, quoted words are written as shown, NEWLINE, INDENT and DEDENT stand for a line break and for one more or one less level of indentation, `[ ]` marks an optional part, `{ }` a part that may repeat, `|` separates alternatives, `( )` groups them, and `(* *)` holds a comment. ```ebnf clause = "requires" line_expr NEWLINE | "ensures" line_expr NEWLINE | "uses" cap_ref ":" cap_type NEWLINE | "uses" "of" lower_ident NEWLINE (* edition 0.2 *) | "fails" upper_ident NEWLINE | "fails" "of" lower_ident NEWLINE (* edition 0.2 *) | "derived" "from" upper_ident { "," upper_ident } NEWLINE ; ``` - A function may have any number of `ensures` clauses. They all hold together. - They come after every `requires` and before `uses`, `fails` and `derived from`. - The expression is in the refinement language (the expressions that a type's condition may use, which the solver can reason about), over the parameters and `result`. - **`old(x)`** (edition `0.2`): for an [Passing a value in and out: edit](https://una-lang.org/en/learn/memory/passing-a-value-in-and-out-edit/) `x` (one the function may change for its caller), `x` in `ensures` denotes its final value, and `old(x)` its value on entry. ## Examples A postcondition the body does not keep is refuted, with a counterexample (the values for which it fails): ```una -- fails with U5001 module shop pub next_price(cents: Int) -> Int ensures result > cents = cents ``` Callers assume what they are promised. `attempt` keeps the promise for its `Ok` arm (the `is Ok` line of the `when`), so `add_or_keep` is proven from `add_units`'s header alone: ```una module shop pub kind OrderError = | TooMany pub add_units(units: Int) -> Int ensures result > units fails OrderError = if units > 100 then fail TooMany else units + 1 pub add_or_keep(units: Int) -> Int ensures result >= units = let outcome = attempt add_units(units) when outcome is Ok(value) -> value is Err -> units ``` In edition `0.2`, an `edit` parameter's postcondition relates its final value to `old`: ```una module shop pub kind Visits seen: Int pub record_visit(edit visits: Visits) -> Unit ensures visits.seen == old(visits).seen + 1 = visits.seen = visits.seen + 1 ``` ## Promise versus coverage A contract is a promise the implementation must prove; it does not establish that the promise captures the product requirement. This example is valid but weak: the body returns `SoldOut` for every input, and its single postcondition says nothing about positive inventory. `una.toml` ```toml [package] name = "demo" version = "0.1.0" edition = "0.3" ``` `src/demo.una` ```una module demo pub kind Availability = SoldOut | Few | Open pub classify(seats: Int) -> Availability requires seats >= 0 ensures seats == 0 implies result is SoldOut = SoldOut ``` A complete contract states each intended band, and the implementation must prove them: ```una module demo pub kind Availability = SoldOut | Few | Open pub classify(seats: Int) -> Availability requires seats >= 0 ensures seats == 0 implies result is SoldOut ensures seats > 0 and seats < 20 implies result is Few ensures seats >= 20 implies result is Open = if seats == 0 then SoldOut else if seats < 20 then Few else Open example "zero" do classify(0) expect result is SoldOut example "lower band" do classify(1) expect result is Few example "upper band" do classify(20) expect result is Open ``` The examples give concrete runtime checks; the proof obligation is the contract. This deliberately broken implementation is refuted with U5001: ```una -- fails with U5001 module demo pub kind Availability = SoldOut | Few | Open pub classify(seats: Int) -> Availability requires seats >= 0 ensures seats == 0 implies result is SoldOut ensures seats > 0 and seats < 20 implies result is Few ensures seats >= 20 implies result is Open = SoldOut ``` Neither passing examples nor proving postconditions establishes that they capture the complete business requirement. Review `requires` and `ensures` against the requirement and its owner. The report can mark a trivial `ensures` such as `ensures true`; it does not infer semantic completeness. ## Edge cases **Only the refinement language.** `*` needs a literal operand, so `side * side` cannot be stated: ```una -- fails with U2014 module shop pub tile_area(side: Int) -> Int ensures result == side * side = side * side ``` Further rules: - **Normal returns only.** `ensures` holds when the function returns. A failure carries no postcondition, so `add_units` above proves `result > units` only on its `units + 1` path. - **Partial correctness.** `ensures` holds if the function returns, a promise only for the runs that finish; whether a function finishes is not checked. - **`result`** appears only in `ensures` clauses and `expect` lines (U2012). - **Unknown is an error.** A postcondition the solver (the program that `una check` asks to prove each fact) cannot decide is U5002, never a pass. - **Operations.** A capability operation's `ensures` (the promise of an action on something outside the program) is an assumption about the external system. Callers rely on it, handlers (Una code that implements a capability, such as a fake for tests) are verified against it, and the runtime's own implementations are trusted to satisfy it. - **Clause order.** An `ensures` before a `requires` is U0102. ## Diagnostics - [U0102](https://una-lang.org/en/docs/errors/U0102/): an `ensures` clause out of order. - [U2012](https://una-lang.org/en/docs/errors/U2012/): `result` outside `ensures` or `expect`. - [U2014](https://una-lang.org/en/docs/errors/U2014/): a postcondition outside the refinement language. - [U5001](https://una-lang.org/en/docs/errors/U5001/): a postcondition refuted on a return path, with a counterexample. - [U5002](https://una-lang.org/en/docs/errors/U5002/): a postcondition the solver cannot decide. ## Edition `ensures` is the same in editions `0.1` and `0.2`. Edition `0.2` adds `edit` parameters, and `old(x)` with them. Editions `0.3` and `0.4` keep the rules of edition `0.2` (`spec/13 §7`). ## Normative source - `spec/04 §2`: clauses and rules 1 to 3. - `spec/02 §3`: the grammar, clause order and the `of` clauses of edition `0.2`; `spec/02 §8`: where `result` may appear. - `spec/03 §3`: the refinement language. - `spec/12 §3`: the `postcondition` obligation and the hypotheses; `spec/12 §6`: statuses; `spec/12 §7`: counterexamples. - `spec/05 §2`: operation contracts. - `spec/17 §3`: parameter conventions and `old`. --- # when ## What it does `when v` chooses an arm, one of the lines below it that each say what to do for some values, by the value of `v`. An arm can match: - a variant of a sum, one of the alternatives a sum kind lists, binding its payload fields, the values the variant carries; - a literal; - a range; - anything, with `else`. Variant arms must cover every variant (U2007). Range and literal arms without `else` must be proven to cover every value. `when` is Una's only pattern match: `match` is not a keyword. Learn more: [Taking a sum apart: when](https://una-lang.org/en/learn/kinds/taking-a-sum-apart-when/). ```una module shop pub kind Seats = Int in 0..5000 pub kind Availability = SoldOut | Few | Open pub kind Lookup = Found(name: Text) | Missing pub label(status: Availability) -> Text = when status is SoldOut -> "sold out" is Few -> "few seats left" is Open -> "open" pub name_of(lookup: Lookup) -> Text = when lookup is Found(name) -> name is Missing -> "unknown" pub band(remaining: Seats) -> Availability = when remaining in 0..0 -> SoldOut in 1..<20 -> Few in 20..5000 -> Open ``` ## Forms In the grammar below, each rule gives a name, `=`, what the name stands for and `;`, quoted words are written as shown, NEWLINE, INDENT and DEDENT stand for a line break and for one more or one less level of indentation, `[ ]` marks an optional part, `{ }` a part that may repeat, `|` separates alternatives, `( )` groups them, and `(* *)` holds a comment. ```ebnf when_expr = "when" line_expr NEWLINE INDENT arm { arm } DEDENT ; arm = pattern "->" ( line_expr NEWLINE | NEWLINE INDENT block DEDENT ) ; pattern = "is" upper_ident [ "(" bind { "," bind } ")" ] | "is" literal | "in" range | "else" ; bind = lower_ident [ ":" lower_ident ] ; (* field, or field: local name *) ``` - **`is V`** or **`is V(field)`**: a variant, binding its fields by name, or under another name with `field: name`. - **`is 200`**: a literal of the value's type. A pattern's literal is a constant, so a text literal there cannot interpolate a value: `is "{s}"` is U4008. Compare with `==` instead. - **`in a..b`** or **`in a.. Text = when lookup is Found(registration: r) -> r.name is Missing -> "unknown" pub reason(code: Int) -> Text = when code is 200 -> "ok" is 404 -> "not found" else -> "other" pub greeting(found: Lookup) -> Text = when found is Missing -> let note = "try another name" note else -> "welcome" ``` A missing variant is rejected: ```una -- fails with U2007 module shop pub kind Availability = SoldOut | Few | Open pub label(status: Availability) -> Text = when status is SoldOut -> "sold out" is Few -> "few" ``` Ranges that leave a gap are refuted: here `20` is not covered, and the counterexample shows it: ```una -- fails with U5001 module shop pub kind Seats = Int in 0..5000 pub kind Availability = SoldOut | Few | Open pub band(remaining: Seats) -> Availability = when remaining in 0..0 -> SoldOut in 1..<20 -> Few in 21..5000 -> Open ``` ## Edge cases **`else` is last, and every arm is reachable**: ```una -- fails with U2008 module shop pub kind Availability = SoldOut | Few | Open pub label(status: Availability) -> Text = when status else -> "other" is SoldOut -> "sold out" ``` **No nested patterns.** Bind the field, then match it in a second `when` inside the arm: ```una -- fails with U0101 module shop pub kind Parcel = Tube(length: Int) | Box(width: Int) pub tube_length(parcel: Option[Parcel]) -> Int = when parcel is Some(Tube(length)) -> length else -> 0 ``` **Variant arms need a sum.** A record has no variants to match: ```una -- fails with U2001 module shop pub kind Address number: Int pub house_number(address: Address) -> Int = when address is Address(number) -> number ``` **Labeled values raise the program counter** (the label of the conditions that decide whether a line runs; see [Branches and failures: implicit flows](https://una-lang.org/en/learn/information-flow/branches-and-failures-implicit-flows/)). Every arm runs under the label of the value, so an arm cannot `fail` on `secret` data: ```una -- fails with U4002 module shop pub kind CreditError = | Frozen pub spendable(balance: secret Int) -> secret Int fails CreditError = when balance is 0 -> fail Frozen else -> balance ``` Further rules: - **A single-field variant** binds its field under any name: `is Some(r)`. - **Results of `attempt`** are matched with `is Ok(value)` and `is Err(failure)`. See [`attempt`](https://una-lang.org/en/docs/language/errors/attempt/). - **An arm may `fail`,** so a binding takes the value of the arms that do not. See [`fail`](https://una-lang.org/en/docs/language/errors/fail/). - **Fixed-width values.** In edition `0.2`, arms over a fixed-width integer take its type, and a bound that does not fit it is U2022. - **Facts in arms.** Inside an arm the verifier, the part of `una check` that proves what the program must keep, knows the arm's condition, and the payload's fields. ## Diagnostics - [U0101](https://una-lang.org/en/docs/errors/U0101/): a nested pattern. - [U2001](https://una-lang.org/en/docs/errors/U2001/): variant arms on a value that is not of a sum kind. - [U2007](https://una-lang.org/en/docs/errors/U2007/): variant arms that miss a variant, without `else`. - [U2008](https://una-lang.org/en/docs/errors/U2008/): an unreachable arm, or an `else` that is not last. - [U2022](https://una-lang.org/en/docs/errors/U2022/): a range bound that does not fit a fixed-width type. - [U4002](https://una-lang.org/en/docs/errors/U4002/): a failure in an arm under a labeled value. - [U4008](https://una-lang.org/en/docs/errors/U4008/): a text literal with interpolation in a pattern. - [U5001](https://una-lang.org/en/docs/errors/U5001/): range or literal arms that do not cover every value. ## Edition `when` is the same in editions `0.1` and `0.2`. Edition `0.2` adds fixed-width integer types, whose arms take the value's type. ## Normative source - `spec/01 §5`: keywords; `spec/02 §6`: the grammar; `spec/02 §8`: the place of `else`. - `spec/10 §4`: T-Case and exhaustiveness over variants; `spec/10 §12` rule 1: variant arms on a value that is not of a sum kind (U2001), and rule 3: unreachable and repeated arms (U2008). - `spec/12 §3`: hypotheses in arms and the `exhaustive` obligation; `spec/12 §4`: its encoding. - `spec/07 §3` rule 3: failures under the program counter; `spec/07 §7` rule 3: a text literal with interpolation in a pattern (U4008). - `spec/18 §2`: literals of fixed-width types. --- # for ## What it does From edition `0.2`, `for x in xs` runs its body once for each element of a list, in order, and `for i in a.. Int = let edit cents = 0 for price in prices cents = cents + price cents pub shelf_slots(shelves: Int) -> List[Int] = let edit slots: List[Int] = [] for i in 0.. Int = let edit count = 0 for price in prices if price > limit count = count + 1 count pub bin_codes(low: U8, high: U8) -> List[U8] = let edit codes: List[U8] = [] for code in low..high codes = codes.append(item: code) codes ``` The loop variable is not editable: ```una -- fails with U2019 module shop pub order_total(prices: List[Int]) -> Int = let edit cents = 0 for price in prices price = price + 1 cents ``` ## A bounded loop is not a general cost proof A precondition can bound a particular range. The function below accepts at most 1,000 iterations and returns the count for this input: ```una module demo pub count_up(limit: Int) -> Nat requires limit >= 0 and limit <= 1000 = let edit count: Nat = 0 for i in 0.. Basket = let edit items: Basket = 0 for price in prices items = items + 1 items ``` The diagnostic's reason says what the loop forgets, and what to do: "guard the use with an `if`, or move the update into a helper with an `edit` parameter whose `ensures` states what the use needs". **A labeled list raises the program counter** (the label of the conditions that decide whether a line runs; see [Branches and failures: implicit flows](https://una-lang.org/en/learn/information-flow/branches-and-failures-implicit-flows/)). The body runs under the top label of the list, or of a range's bounds, since how often it runs depends on them. There, `fail` and calls that can fail are U4002: ```una -- fails with U4002 module shop pub kind AuditError = | NegativePrice pub audit(prices: secret List[Int]) -> Int fails AuditError = for price in prices if price < 0 fail NegativePrice 0 ``` **A binding taken in the body** is taken in every later iteration: ```una -- fails with U2017 module shop pub ship(take items: List[Int]) -> Int = items.len pub ship_batches(items: List[Int], batches: List[Int]) -> Int = let edit shipped = 0 for batch in batches let sent = ship(take items) shipped = shipped + sent shipped ``` Further rules: - **Evaluated once.** The list, or the range's bounds, are evaluated before the first iteration. - **Facts inside.** In a range loop the body knows `a <= i < b`, or `a <= i <= b`. In a loop over a list, the list has at least one element. In edition `0.3`, the loop variable also carries the refinement of the list's elements, as `List[Pos]` gives `Pos`. - **The length frame.** A list binding that the body only changes through `set` keeps its length, and the verifier knows it. - **Failures.** A failure that leaves the body ends the loop and the function. The bindings it updated keep their values from before the loop, and effects already performed stay performed. - **No overflow at the end.** An inclusive range stops at its upper bound without computing its successor, so `0..255` over `U8` does not overflow. - **Termination** is not checked. ## Diagnostics - [U0101](https://una-lang.org/en/docs/errors/U0101/): a `for` loop in edition `0.1`, where `for` appears only in `handler h for K`. - [U0103](https://una-lang.org/en/docs/errors/U0103/): `edit`, a reserved word of edition `0.2`, in edition `0.1`. - [U2017](https://una-lang.org/en/docs/errors/U2017/): a binding taken in every iteration. - [U2019](https://una-lang.org/en/docs/errors/U2019/): an assignment to the loop variable, or to another binding that is not editable. - [U4002](https://una-lang.org/en/docs/errors/U4002/): a failure in a body under a labeled list or range. - [U5002](https://una-lang.org/en/docs/errors/U5002/): a fact the loop forgets, needed in its body or after it. ## Edition `for` loops exist from edition `0.2` on. In edition `0.1`, a `for` loop is a syntax error, since `for` appears only in `handler h for K`: ```una -- edition 0.1 -- fails with U0101 module shop pub first_count(prices: List[Int]) -> Int = for price in prices unit 0 ``` The loops of edition `0.2` usually update a `let edit` binding, and `edit` is a reserved word in edition `0.1`: ```una -- edition 0.1 -- fails with U0103 module shop pub order_total(prices: List[Int]) -> Int = let edit cents = 0 for price in prices cents = cents + price cents ``` ## Normative source - `spec/17 §1`: syntax; `spec/17 §2`: editable bindings; `spec/17 §3` rule 3: `take` in loops; `spec/17 §4`: desugaring and ranges. - `spec/17 §5` rules 3 and 5: the loop invariant, facts and termination; `spec/17 §6` rule 3: labels; `spec/17 §7`: failures. - `spec/01 §5`: reserved words. - `spec/12 §6`: what an unknown obligation's reason says about a loop. - Decision record: [ADR 0071](https://github.com/una-lang/una/blob/v0.4.0/docs/adr/0071-a-length-frame-for-loops.md), for the length frame; [ADR 0103](https://github.com/una-lang/una/blob/v0.4.0/docs/adr/0103-refined-elements-of-collections.md), for refined elements in edition `0.3`. --- # let edit and edit parameters ## What it does From edition `0.2`, values stay values: there are no references (names that share one value, so that a change through one shows through the other) and no lifetimes (rules for how long such a sharing name stays valid), and an editable binding can be rebound, which means the name is given a new value. Learn more: [Passing a value in and out: edit](https://una-lang.org/en/learn/memory/passing-a-value-in-and-out-edit/). - **`let edit x = e`** declares a binding that assignments may rebind: `x = e`. - **A place**, an editable binding or a path of fields inside one, as `t.last`, can be assigned too: `t.last = value` rebuilds `t` with that field changed. - **An `edit` parameter** is passed in and out. The function receives the caller's value, and the caller's place receives its final value. ```una module shop pub kind Visits seen: Int last: Int pub record(edit t: Visits, value: Int) -> Unit ensures t.seen == old(t).seen + 1 = t.seen = t.seen + 1 t.last = value pub visits_of(stamps: List[Int]) -> Visits = let edit t = Visits(seen: 0, last: 0) for stamp in stamps edit t.record(value: stamp) t ``` ## Forms In the grammar below, each rule gives a name, `=`, what the name stands for and `;`, quoted words are written as shown, NEWLINE, INDENT and DEDENT stand for a line break and for one more or one less level of indentation, `[ ]` marks an optional part, `{ }` a part that may repeat, `|` separates alternatives, `( )` groups them, and `(* *)` holds a comment. ```ebnf param = [ "edit" | "take" ] lower_ident ":" type ; arg = [ lower_ident ":" ] ( "edit" place | "take" lower_ident | line_expr ) ; place = lower_ident { "." lower_ident } ; let_stmt = "let" [ "edit" ] lower_ident [ ":" type ] "=" ( handled | block_expr ) ; assign_stmt = place "=" ( handled | block_expr ) ; postfix = [ "edit" ] primary { "." lower_ident [ call_args ] | call_args } ; ``` - **`let edit x = e`**, or `let edit x: T = e` with a type that fixes a refinement as an invariant. - **`p = e`**, where `p` is an editable binding or a field path of one. - **`edit x: T`** in a parameter list, and **`edit p`** at the matching argument. A method receiver is written `edit t.record(...)`. - **`old(x)`** in an `ensures` clause: the value of the `edit` parameter `x` on entry. ## Examples A list's elements change through `set`, never by assignment: ```una module shop pub clear_first(prices: List[Int]) -> List[Int] = let edit updated = prices if updated.len > 0 edit updated.set(index: 0, item: 0) updated ``` Only an editable binding can be assigned: ```una -- fails with U2019 module shop pub next_order(last: Int) -> Int = let order = last order = order + 1 order ``` The caller writes `edit` exactly where the parameter is declared `edit`: ```una -- fails with U2020 module shop pub kind Visits seen: Int pub record(edit t: Visits) -> Unit = t.seen = t.seen + 1 pub log_visit(t: Visits) -> Visits = let edit copy = t record(copy) copy ``` ## A failed call rolls back edits, not completed effects An `edit` argument is transactional for the caller: if the call fails, its local value is unchanged. An effect already performed through a capability is external and remains performed. This example uses a test handler to make that distinction visible: ```una module demo pub kind StoreError = | Rejected pub capability Store op write(value: Int) -> Unit pub update(edit current: Int) -> Unit uses @store: Store[write] fails StoreError = current = current + 1 @store.write(current) fail Rejected pub scenario() -> Int uses @store: Store[write] = let edit value = 10 update(edit value) if error use unit value handler store() for Store op write(value) = unit example "local rollback preserves an already performed effect" given @store = store() do scenario() expect result == 10 expect performed @store.write ``` Only the caller's `edit` arguments are restored (`spec/17 §7` rules 1 and 2). An operation performed before the failure stays performed, and the trace records it; Una rolls back nothing in an external system. Undoing it takes another operation, which can fail in turn. ## Edge cases **Exclusivity.** An `edit p` argument excludes every other use of `p`'s root binding in the same call, even of a disjoint field: ```una -- fails with U2018 module shop pub kind Visits seen: Int last: Int pub record(edit t: Visits, value: Int) -> Unit = t.seen = t.seen + 1 t.last = value pub record_own_count(edit t: Visits) -> Unit = record(edit t, value: t.seen) ``` **Not a value.** A function with an `edit` or `take` parameter can only be called, not passed or returned: ```una -- fails with U2021 module shop pub kind Visits seen: Int pub record(edit t: Visits) -> Unit = t.seen = t.seen + 1 pub recorder() -> fn(Visits) -> Unit = record ``` Further rules: - **Fixed type.** An editable binding keeps its declared type, refinement and label at every rebind. Each rebind carries the obligation of an annotated `let`. Without an annotation, its type is its initial value's without the refinement. In edition `0.3`, it also drops the refinements of nested positions, as `let edit xs = [p]` is a `List[Int]`, and an annotation such as `let edit out: List[Pos] = []` keeps them. - **Fields of records only.** A place's fields are fields of record kinds; a field of a variant payload is not a place. - **No compound assignment**, and no assignment to a list element: elements change through `set`. - **Lambdas capture values.** A lambda captures an editable binding's value when it is created, and cannot edit it (U2019). - **Transactional.** A call that fails leaves its `edit` arguments unchanged for the caller. Effects already performed stay performed. - **Labels are fixed.** A rebind under a program counter (the label of the conditions that decide whether the line runs; see [Branches and failures: implicit flows](https://una-lang.org/en/learn/information-flow/branches-and-failures-implicit-flows/)) above the binding's label is U4001, never a silent raise. - **Not on operations.** Capability operations and handlers cannot declare `edit` or `take` parameters (U2020). - **One effect per line.** A call with an `edit` argument is the whole expression of a statement or `let` (U3013). ## Diagnostics - [U0103](https://una-lang.org/en/docs/errors/U0103/): `edit` in edition `0.1`, where it is reserved. - [U2018](https://una-lang.org/en/docs/errors/U2018/): an `edit` argument used again in the same call. - [U2019](https://una-lang.org/en/docs/errors/U2019/): an assignment to a binding that is not editable. - [U2020](https://una-lang.org/en/docs/errors/U2020/): a missing or extra `edit` marker, or an `edit` argument that is not a place. - [U2021](https://una-lang.org/en/docs/errors/U2021/): a function with conventions used as a value. - [U3013](https://una-lang.org/en/docs/errors/U3013/): a call with an `edit` argument inside a larger expression. - [U4001](https://una-lang.org/en/docs/errors/U4001/): a rebind under a program counter above the binding's label. ## Edition `let edit`, assignments and `edit` parameters exist from edition `0.2` on. In edition `0.1`, `edit` is reserved: ```una -- edition 0.1 -- fails with U0103 module shop pub next_order(last: Int) -> Int = let edit order = last order = order + 1 order ``` ## Normative source - `spec/17 §1`: syntax; `spec/17 §2`: places and editable bindings; `spec/17 §3`: parameter conventions. - `spec/17 §5`: static semantics; `spec/17 §6`: information flow; `spec/17 §7`: dynamic semantics. - `spec/04 §2`: `old` in `ensures`. - Decision record: [ADR 0056](https://github.com/una-lang/una/blob/v0.4.0/docs/adr/0056-memory-model.md), for the memory model of edition `0.2`; [ADR 0103](https://github.com/una-lang/una/blob/v0.4.0/docs/adr/0103-refined-elements-of-collections.md), for nested refinements in edition `0.3`. --- # take ## What it does From edition `0.2`, a parameter declared `take` consumes its argument, which means the caller gives the value away: after `f(take a)`, the caller cannot use `a` until an assignment gives it a new value. This lets the backend (the part of the compiler that produces the running program) reuse the memory of the value passed instead of copying it. That reuse is never observable, so the meaning stays that of values. Learn more: [Giving a value up: take](https://una-lang.org/en/learn/memory/giving-a-value-up-take/). ```una module shop pub kind Cart items: Int pub checkout(take cart: Cart) -> Int = cart.items pub close(cart: Cart) -> Int = let count = checkout(take cart) count ``` ## Forms In the grammar below, each rule gives a name, `=`, what the name stands for and `;`, quoted words are written as shown, NEWLINE, INDENT and DEDENT stand for a line break and for one more or one less level of indentation, `[ ]` marks an optional part, `{ }` a part that may repeat, `|` separates alternatives, `( )` groups them, and `(* *)` holds a comment. ```ebnf param = [ "edit" | "take" ] lower_ident ":" type ; arg = [ lower_ident ":" ] ( "edit" place | "take" lower_ident | line_expr ) ; ``` - **`take x: T`** in a parameter list. - **`take a`** at the matching argument, where `a` is a binding, not a field. ## Examples A `let edit` binding can be given a new value after it was taken, and is usable again: ```una module shop pub ship(take items: List[Int]) -> Int = items.len pub ship_and_refill(items: List[Int]) -> Int = let edit stock = items let shipped = ship(take stock) stock = [1, 2] stock.len + shipped ``` Using a binding after it was taken is rejected: ```una -- fails with U2017 module shop pub ship(take items: List[Int]) -> Int = items.len pub ship_twice(items: List[Int]) -> Int = let shipped = ship(take items) items.len + shipped ``` ## Edge cases **The marker is required**: ```una -- fails with U2020 module shop pub ship(take items: List[Int]) -> Int = items.len pub ship_unmarked(items: List[Int]) -> Int = ship(items) ``` **A binding, not a field**: ```una -- fails with U2020 module shop pub kind Order items: List[Int] pub ship(take items: List[Int]) -> Int = items.len pub ship_order(order: Order) -> Int = let shipped = ship(take order.items) shipped ``` Further rules: - **Branches and loops.** A binding taken in one branch of an `if` or a `when` counts as taken after it. A binding taken in a loop body is taken in every later iteration, so it is assigned before the end of the body, or declared inside it (U2017). - **Any local binding** can be taken: a plain `let`, a `let edit` or a parameter. Only an assignment revives it, so a plain binding stays taken. - **Exclusivity.** Another use of a binding after its `take`, even in the same call, is U2017. A `take` together with an `edit` of the same binding in one call is U2018. - **Not a value.** A function with a `take` parameter can only be called (U2021). - **Not on operations.** Capability operations and handlers cannot declare `take` parameters (U2020). ## Diagnostics - [U0103](https://una-lang.org/en/docs/errors/U0103/): `take` in edition `0.1`, where it is reserved. - [U2017](https://una-lang.org/en/docs/errors/U2017/): a binding used after it was taken, in a later line or later in the same call. - [U2018](https://una-lang.org/en/docs/errors/U2018/): a `take` together with an `edit` of the same binding in one call. - [U2020](https://una-lang.org/en/docs/errors/U2020/): a missing or extra `take` marker, or a field given to `take`. - [U2021](https://una-lang.org/en/docs/errors/U2021/): a function with a `take` parameter used as a value. ## Edition `take` exists from edition `0.2` on. In edition `0.1` it is reserved: ```una -- edition 0.1 -- fails with U0103 module shop pub ship(take items: List[Int]) -> Int = items.len ``` ## Normative source - `spec/17 §1`: syntax. - `spec/17 §3`: parameter conventions, rules 1 to 8. - `spec/17 §7` rule 3: backend freedom. - Decision record: [ADR 0056](https://github.com/una-lang/una/blob/v0.4.0/docs/adr/0056-memory-model.md), for the memory model of edition `0.2`. --- # together ## What it does From edition `0.2`, `together` runs independent work as concurrent tasks, pieces of work that may run at the same time, and every task ends before its block does. The result is that of running the tasks one after another, in order, stopping at the first failure, and the reported trace (the record of what the program did outside itself) lists each task's events in index order, whatever the interleaving, the order in which the tasks' steps happened to mix. Learn more: [Running work at the same time: together](https://una-lang.org/en/learn/concurrency/running-work-at-the-same-time-together/). - **`together`** with two or more `let` branches runs each branch as a task. The branches' bindings are in scope after the block. - **`together for x in xs`** runs one task per element, and gives the list of their results in element order. ```una module shop pub capability Warehouse op stock_level() -> Int pub largest_stock() -> Int uses @east: Warehouse[stock_level] uses @west: Warehouse[stock_level] = together let east = stock_level() with @warehouse = @east let west = stock_level() with @warehouse = @west max(east, b: west) stock_level() -> Int uses @warehouse: Warehouse[stock_level] = @warehouse.stock_level() ``` ## Forms In the grammar below, each rule gives a name, `=`, what the name stands for and `;`, quoted words are written as shown, NEWLINE, INDENT and DEDENT stand for a line break and for one more or one less level of indentation, `[ ]` marks an optional part, `{ }` a part that may repeat, `|` separates alternatives, `( )` groups them, and `(* *)` holds a comment. ```ebnf statement = let_stmt | assign_stmt | for_stmt | if_stmt | together_stmt | handled ; together_stmt = "together" NEWLINE INDENT let_stmt let_stmt { let_stmt } DEDENT ; block_expr = when_expr | if_block | together_for ; together_for = "together" "for" lower_ident "in" ( line_expr | range_expr ) NEWLINE INDENT block DEDENT ; ``` - **`together`** is a statement: its body holds only `let` statements, at least two. Each `let`, with its `with` bindings and handling clauses, is a branch. - **`together for`** stands where a block expression can: as the value of a `let` or of an assignment, or as the last line of a block. Its body is a block whose final expression is the element's result. ## Examples One task per element, with failures passed on: ```una module shop pub kind FetchError = Missing | Gone fetch_price(sku: Int) -> Int fails FetchError = if sku < 0 fail Missing else sku * 10 pub prices(skus: List[Int]) -> List[Int] fails FetchError = let found = together for sku in skus fetch_price(sku) if error pass found ``` A `together` with one branch is rejected: write a plain `let`: ```una -- fails with U2024 module shop pub prepare(units: Int) -> Int = together let boxes = units + 1 boxes ``` ## Edge cases **A task cannot change outer bindings.** It captures the values it reads, as a lambda does. Assigning a binding declared outside it, or passing one as `edit` or `take`, is rejected; return the new value from the task instead: ```una -- fails with U2023 module shop pub sum_skus(skus: List[Int]) -> Int = let edit total = 0 let copies = together for sku in skus total = total + sku sku total ``` The outer code may update its own bindings after the block, from the branches' results: ```una module shop pub prepare(units: Int) -> Int = let edit total = 0 together let boxes = units + 1 let labels = units + 2 total = boxes + labels total ``` Further rules: - **Scope.** A branch sees the bindings in scope before the block, and none of its siblings'. - **Failure and cancellation.** When a task fails, every task after it is canceled, and the block fails with the failure of the lowest-indexed task that failed. Cancellation is cooperative, which means a task is never stopped in the middle of a step: a canceled task stops at its next call, operation or loop iteration, and effects already performed stay. - **The trace** of a block is the traces of its tasks in index order, whatever the interleaving. - **Verification.** Each branch is verified with the facts known before the block and none of its siblings'. - **Labels.** Each branch runs under the block's program counter (the label of the conditions that decide whether a line runs; see [Branches and failures: implicit flows](https://una-lang.org/en/learn/information-flow/branches-and-failures-implicit-flows/)). A `together for` over a labeled list, or a range with labeled bounds, runs its body under that label, so `fail` and calls that can fail are U4002 there. - **Timing.** The relative order of the effects of different tasks, and how far a canceled task got, depend on timing. In editions `0.2` and `0.3` timing is out of the model. Edition `0.4` adds time limits and races, and gives each of their sites a timing label that the checker enforces (see [Tasks and time](https://una-lang.org/en/docs/guides/tasks-and-time/#timing-labels-what-the-checker-refuses-and-why)). - **No task values.** No value stands for a task, to keep or pass on: every task ends before its block does. In editions `0.2` and `0.3` there are no other tasks, no races, no timeouts and no channels. Edition `0.4` adds tasks that only have effects (`tasks` and `start`), a time limit (`within`) and a race (`first of`), described in [Tasks and time](https://una-lang.org/en/docs/guides/tasks-and-time/). - **A statement, not an expression.** `let x = together` with branches is U0101: write `together for` to build a list. ## Diagnostics - [U0101](https://una-lang.org/en/docs/errors/U0101/): `together` with branches written as an expression. - [U0103](https://una-lang.org/en/docs/errors/U0103/): `together` in edition `0.1`, where it is reserved. - [U2023](https://una-lang.org/en/docs/errors/U2023/): a task that assigns, edits or takes a binding declared outside it. - [U2024](https://una-lang.org/en/docs/errors/U2024/): a `together` body with a statement other than `let`, or fewer than two branches. - [U4002](https://una-lang.org/en/docs/errors/U4002/): a failure in a task under a labeled program counter. ## Edition `together` exists from edition `0.2` on. In edition `0.1` it is reserved: ```una -- edition 0.1 -- fails with U0103 module shop pub hash_skus(skus: List[Int]) -> List[Int] = let codes = together for sku in skus sku * sku codes ``` ## Normative source - `spec/19 §1`: syntax and rules 1 to 6; `spec/19 §2`: static semantics; `spec/19 §3`: information flow; `spec/19 §4`: verification. - `spec/19 §6`: dynamic semantics; `spec/19 §7`: traces. - `spec/17 §5` rule 4: captures, as for lambdas. - Decision record: [ADR 0065](https://github.com/una-lang/una/blob/v0.4.0/docs/adr/0065-structured-concurrency.md), for structured concurrency. --- # fails ## What it does `fails E` is the header clause (a line between a function's signature and its body) that declares a function's error kind: the one sum kind (a kind whose values are each one of several named variants) whose variants the function may fail with. A function without `fails` cannot fail. Callers see the clause in the header, and must handle every failure at the line of the call. Learn more: [Declaring a failure: fails and fail](https://una-lang.org/en/learn/failure/declaring-a-failure-fails-and-fail/). ```una module shop pub kind OrderError = | TooMany pub add_units(units: Int) -> Int fails OrderError = if units > 100 then fail TooMany else units + 1 ``` ## Forms In the grammar below, each rule gives a name, `=`, what the name stands for and `;`, quoted words are written as shown, NEWLINE, INDENT and DEDENT stand for a line break and for one more or one less level of indentation, `[ ]` marks an optional part, `{ }` a part that may repeat, `|` separates alternatives, `( )` groups them, and `(* *)` holds a comment. ```ebnf clause = "requires" line_expr NEWLINE | "ensures" line_expr NEWLINE | "uses" cap_ref ":" cap_type NEWLINE | "uses" "of" lower_ident NEWLINE (* edition 0.2 *) | "fails" upper_ident NEWLINE | "fails" "of" lower_ident NEWLINE (* edition 0.2 *) | "derived" "from" upper_ident { "," upper_ident } NEWLINE ; ``` Edition `0.2` adds `fails of p` and `uses of p`. `of` is not a keyword: it is read as part of the clause only right after `fails` or `uses`. - **`fails E`**, where `E` names a sum kind. Any sum kind can be an error kind, with or without payloads. - **`fails of p`** (edition `0.2`): the function fails as its parameter `p`, a function value, fails. A header has at most one `fails E` and at most one `fails of p`. - **No clause.** A `pub` function then cannot fail. A private function may omit the clause, and the compiler infers its error kind. Clauses of a header come in a fixed order: every `requires`, every `ensures`, every `uses`, then at most one `fails E` and one `fails of p`, then `derived from`. ## Examples An error kind with payloads, and a function that fails with each variant: ```una module shop pub kind QuantityError = TooMany(limit: Int) | Negative pub quantity(units: Int) -> Int fails QuantityError = if units > 100 then fail TooMany(limit: 100) else if units < 0 then fail Negative else units ``` A private function's error kind is inferred, and a `pub` caller passes it on with `if error pass`, since the kinds are equal: ```una module shop pub kind OrderError = | TooMany check_units(units: Int) -> Int = if units > 100 then fail TooMany else units pub order_units(units: Int) -> Int fails OrderError = check_units(units) if error pass ``` In edition `0.2`, `fails of p` lets a higher-order function (one that takes another function as a parameter) fail as the function it is given: ```una module shop pub apply_discount(cents: Int, discount: fn(Int) -> Int) -> Int fails of discount = discount(cents) if error pass ``` A `pub` function that fails without a `fails` clause is rejected: ```una -- fails with U3009 module shop pub kind OrderError = | TooMany pub add_units(units: Int) -> Int = if units > 100 then fail TooMany else units ``` An error kind is a sum kind, never a record: ```una -- fails with U2002 module shop pub kind Address street: Text pub ship(units: Int) -> Int fails Address = units ``` ## Edge cases **One error kind per function.** A second `fails` clause is U0102: ```una -- fails with U0102 module shop pub kind OrderError = | TooMany pub kind PaymentError = | Declined pub checkout(units: Int) -> Int fails OrderError fails PaymentError = units ``` **One kind for an inferred function too.** A private function without `fails` still has one error kind: failing with variants of two kinds is U3009: ```una -- fails with U3009 module shop pub kind OrderError = | TooMany pub kind PaymentError = | Declined charge(units: Int) -> Int = if units > 100 then fail TooMany else if units < 0 then fail Declined else units ``` **Declared, never raised.** A function may declare `fails E` and never fail. Its callers still handle the failure, since they read the header: ```una -- fails with U3007 module shop pub kind OrderError = | TooMany pub reserve(units: Int) -> Int fails OrderError = units pub checkout(units: Int) -> Int fails OrderError = reserve(units) ``` Further rules: - **Passing needs equal kinds.** `if error pass` propagates a failure only when the callee's kind is the caller's (U3008). Otherwise convert it with `if error fail V`. - **`of` names an open function parameter.** The name in `fails of p` or `uses of p` must be one of the function's own parameters (U3017), of a function type (U3018), whose type writes no `uses` or `fails` of its own (U3019). - **`fails of` keeps one kind.** A callee with both `fails E` and `fails of p` accepts for `p` only an argument that fails with `E` (U3009 at the argument). - **No postconditions on failure.** `ensures` describes normal returns only. ## Diagnostics - [U0101](https://una-lang.org/en/docs/errors/U0101/): `fails of` in edition `0.1`, where the clause names an error kind. - [U0102](https://una-lang.org/en/docs/errors/U0102/): a repeated or misplaced `fails` clause. - [U2002](https://una-lang.org/en/docs/errors/U2002/): `fails` names a kind that is not a sum kind. - [U3007](https://una-lang.org/en/docs/errors/U3007/): a call of the function whose failure is not handled. - [U3008](https://una-lang.org/en/docs/errors/U3008/): `if error pass` across different error kinds. - [U3009](https://una-lang.org/en/docs/errors/U3009/): a failure outside the declared error kind, or a failure in a function without `fails`. - [U3017](https://una-lang.org/en/docs/errors/U3017/): an `of` clause that names no parameter. - [U3018](https://una-lang.org/en/docs/errors/U3018/): an `of` clause that names a parameter not of function type. - [U3019](https://una-lang.org/en/docs/errors/U3019/): an `of` clause that names a function type with its own `uses` or `fails`. ## Edition `fails E` is in editions `0.1` and `0.2`. `fails of p` is in edition `0.2` and later; in edition `0.1` the clause takes an error kind, so `fails of` is a syntax error (U0101): ```una -- edition 0.1 -- fails with U0101 module shop pub apply_discount(cents: Int, discount: fn(Int) -> Int) -> Int fails of discount = discount(cents) if error pass ``` ## Normative source - `spec/06 §1`: error kinds; `spec/06 §2`: failing with a variant; `spec/06 §3`: handling at the call, and `if error pass` between equal kinds; `spec/06 §4`: no postcondition on failure. - `spec/04 §2`: the clause, rule 2 (normal returns only) and rule 4 (no clause, no failure); `spec/04 §5`: rule 2, a `pub` function declares its failure, and rule 3, a private function's kind is inferred. - `spec/02 §3`: the grammar, the order of clauses, and the `of` clauses of edition `0.2`. - `spec/05 §9` rule 9: `fails of` and `uses of`, and what they may name. - `spec/10 §1`: one error kind for an inferred function. - Decision record: [ADR 0062](https://github.com/una-lang/una/blob/v0.4.0/docs/adr/0062-effect-polymorphism.md), for `fails of`. --- # fail ## What it does `fail V` ends the current function with a failure: the value `V`, a variant (one of the named alternatives of a kind) of the function's error kind (the kind that lists the ways the function may fail). There is no implicit propagation: the caller receives the failure at the line of the call, and must handle it there. Learn more: [Declaring a failure: fails and fail](https://una-lang.org/en/learn/failure/declaring-a-failure-fails-and-fail/). ```una module shop pub kind OrderError = | TooMany pub add_units(units: Int) -> Int fails OrderError = if units > 100 then fail TooMany else units + 1 ``` ## Forms In the grammar below, each rule gives a name, `=`, what the name stands for and `;`, quoted words are written as shown, NEWLINE, INDENT and DEDENT stand for a line break and for one more or one less level of indentation, `[ ]` marks an optional part, `{ }` a part that may repeat, `|` separates alternatives, `( )` groups them, and `(* *)` holds a comment. ```ebnf fail_expr = "fail" variant_expr ; variant_expr = upper_ident [ call_args ] ; ``` - **`fail V`**, for a variant without payload (the values a variant carries). - **`fail V(field: value)`**, for a variant with payload fields, labeled like any constructor. - **`fail V` in a handling clause**: `if error fail V(...)` and `if none fail V(...)`. See [`if error` and `if none`](https://una-lang.org/en/docs/language/errors/if-error/). - **`else fail V` of `checked`**. See [`checked`](https://una-lang.org/en/docs/language/errors/checked/). `fail` is an expression, so it may stand where a value is expected: a branch of `if`, an arm of `when`, or a block's final expression. The other branches give the value. ## Examples A variant with a payload: ```una module shop pub kind QuantityError = TooMany(limit: Int) | Negative pub quantity(units: Int) -> Int fails QuantityError = if units > 100 then fail TooMany(limit: 100) else if units < 0 then fail Negative else units ``` An arm of `when` may fail, so a binding takes the value of the arms that do not: ```una module shop pub kind Unreadable = | NotANumber --- The price in cents that a JSON value holds. pub price(j: Json) -> Int fails Unreadable = let cents = when j is Number(value) -> value else -> fail NotANumber cents ``` In the branch that does not fail, the verifier (the part of `una check` that proves facts about the code) knows the negation of the condition, so a guard with `fail` can establish a precondition (a condition that must hold when a function is called): ```una module shop pub kind Seats = Int in 0..5000 pub kind Event name: Text remaining: Seats pub kind BookingError = | InvalidCount pub seats_after(e: Event, count: Int) -> Seats requires count >= 1 requires count <= e.remaining = e.remaining - count pub book(e: Event, count: Int) -> Seats fails BookingError = if count < 1 or count > e.remaining fail InvalidCount else seats_after(e, count) ``` A function without `fails` cannot fail: ```una -- fails with U3009 module shop pub kind OrderError = | TooMany pub add_units(units: Int) -> Int = if units > 100 then fail TooMany else units ``` ## Edge cases **The variant must belong to the function's error kind**: ```una -- fails with U3009 module shop pub kind OrderError = | TooMany pub kind PaymentError = | Declined pub add_units(units: Int) -> Int fails OrderError = if units > 100 then fail Declined else units ``` **No failure that depends on labeled data.** `fail` is allowed only when the [Branches and failures: implicit flows](https://una-lang.org/en/learn/information-flow/branches-and-failures-implicit-flows/) (the label of the conditions that decided whether this line runs) is `public`, since whether a function fails is observable. Code that must decide on labeled data returns a labeled value instead: ```una -- fails with U4002 module shop pub kind CreditError = | OverLimit pub spend(balance: secret Int) -> secret Int fails CreditError = if balance > 100 then fail OverLimit else balance ``` Further rules: - **Payload labels.** A failure's payload follows the normal flow rules: a failure raised in a labeled context carries that label. - **No postcondition.** `ensures`, the postcondition (a promise about the result), holds on normal returns only. A failing path has no postcondition to prove. - **What is not a failure.** Division by zero, and violations of a refinement (a condition attached to a type, such as `Int in 0..5000`) or of a precondition, are proof obligations (facts that `una check` must prove before the program may run), never runtime failures. Exceeding the call depth or the memory limit is runtime diagnostic U6003, not a failure. - **A failure of `main`** stops `una run` with U6001 and exit code 1. ## Diagnostics - [U3009](https://una-lang.org/en/docs/errors/U3009/): a variant outside the function's error kind, or a failure in a function without `fails`. - [U4002](https://una-lang.org/en/docs/errors/U4002/): a failure under a program counter above `public`. - [U6001](https://una-lang.org/en/docs/errors/U6001/): at run time, `main` failed. - [U6003](https://una-lang.org/en/docs/errors/U6003/): at run time, the call depth or the memory limit was exceeded, which is not a failure. ## Edition `fail` is the same in editions `0.1` and `0.2`. ## Normative source - `spec/06 §2`: failing, and payloads; `spec/06 §3`: handling at the call; `spec/06 §4`: failures at the boundary and their labels; `spec/06 §6`: `checked`; `spec/06 §7`: what is not a failure. - `spec/02 §7`: the grammar of `fail_expr`, and `fail` as an expression. - `spec/04 §2`: rule 2, no postcondition on a failing path, and rule 4, a function without `fails` cannot fail; `spec/04 §8`: the entry point. - `spec/07 §3` rule 3: failures under the program counter. - `spec/12 §3`: what the verifier knows after a guard. --- # if error and if none ## What it does A statement whose expression can fail is followed by a handling clause, which says what the failure becomes at that line. There is no implicit propagation, so every failure is visible where it can occur. `if none` handles an `Option` (a value that is either `Some` of something or `None`) the same way, at the same place. Learn more: [Handling a failure: the clauses](https://una-lang.org/en/learn/failure/handling-a-failure-the-clauses/). ```una module shop pub kind Registration name: Text pub kind StoreError = Timeout | Corrupted(detail: Text) pub kind CheckInError = NotRegistered | Unavailable pub capability Registrations op find(key: Text) -> Option[Registration] fails StoreError pub lookup(key: Text) -> Registration uses @registrations: Registrations[find] fails CheckInError = let registration = @registrations.find(key) if error fail Unavailable if none fail NotRegistered registration ``` ## Forms In the grammar below, each rule gives a name, `=`, what the name stands for and `;`, quoted words are written as shown, NEWLINE, INDENT and DEDENT stand for a line break and for one more or one less level of indentation, `[ ]` marks an optional part, `{ }` a part that may repeat, `|` separates alternatives, `( )` groups them, and `(* *)` holds a comment. ```ebnf handled = line_expr [ with_clause ] NEWLINE [ INDENT handling { handling } DEDENT ] ; handling = "if" "error" ( "fail" variant_expr | "pass" | "use" line_expr ) NEWLINE | "if" "none" ( "fail" variant_expr | "use" line_expr ) NEWLINE ; ``` The clauses and their meaning, where a fallible expression is one that can fail: | Clause | Applies to | Meaning | | --- | --- | --- | | `if error fail V(...)` | Any fallible expression | Any failure becomes `V`. Inside the arguments, `error` names the original failure value. | | `if error pass` | Callee error kind equals the current function's | Propagate the failure unchanged | | `if error use e` | Any fallible expression | Recover with value `e` of the expression's type; `error` is in scope in `e` | | `if none fail V(...)` | Expression of type `Option[T]` | `None` becomes failure `V`; the result has type `T` | | `if none use e` | Expression of type `Option[T]` | `None` becomes `e`; the result has type `T` | A clause stands on its own line, one level below the statement it handles. A statement may be a `let`, a bare statement or a block's final expression. ## Examples `if error pass` propagates a failure of the same kind, and `if error use` recovers with a value: ```una module shop pub kind OrderError = | TooMany pub add_units(units: Int) -> Int fails OrderError = if units > 100 then fail TooMany else units + 1 pub add_twice(units: Int) -> Int fails OrderError = let once = add_units(units) if error pass add_units(once) if error pass pub add_or_zero(units: Int) -> Int = add_units(units) if error use 0 ``` `error` names the original failure inside `if error fail`, so it can travel as a payload: ```una module shop pub kind StockError = | OutOfStock pub kind CheckoutError = Stock(cause: StockError) | Declined reserve(units: Int) -> Int = if units > 10 then fail OutOfStock else units pub checkout(units: Int) -> Int fails CheckoutError = reserve(units) if error fail Stock(cause: error) ``` `if none use` gives a default for an `Option`, and an operation's failure can be recovered at the same line. Here `if error use None` turns a failure of `get` into `None`, and `if none use ""` then turns any `None`, from a failure or from a missing key, into the empty text: ```una module shop pub kind StoreError = | Timeout pub capability Cache op get(key: Text) -> Option[Text] fails StoreError pub cached(key: Text) -> Text uses @cache: Cache[get] = let found = @cache.get(key) if error use None if none use "" found ``` Inside `if error use`, `error` names the failure too, so the recovered value can come from it: ```una module shop pub kind StockError = | OutOfStock(left: Int) reserve(units: Int) -> Int = if units > 10 then fail OutOfStock(left: 10) else units left_of(failure: StockError) -> Int = when failure is OutOfStock(left) -> left pub reserve_what_is_left(units: Int) -> Int = reserve(units) if error use left_of(error) ``` A fallible call without a clause is rejected: ```una -- fails with U3007 module shop pub kind OrderError = | TooMany pub add_units(units: Int) -> Int fails OrderError = if units > 100 then fail TooMany else units + 1 pub add_twice(units: Int) -> Int fails OrderError = let once = add_units(units) add_units(once) if error pass ``` ## Edge cases **`if error pass` needs equal error kinds.** A function has one error kind, so a failure of another kind is converted with `if error fail`: ```una -- fails with U3008 module shop pub kind StockError = | OutOfStock pub kind CheckoutError = | Declined reserve(units: Int) -> Int = if units > 10 then fail OutOfStock else units pub checkout(units: Int) -> Int fails CheckoutError = reserve(units) if error pass ``` **Order and repetition.** Each clause appears at most once, and `if error` comes before `if none`: ```una -- fails with U0102 module shop pub kind StoreError = | Timeout pub kind LookupError = | Missing price_of(sku: Int) -> Option[Int] = if sku > 999 then fail Timeout else Some(sku) pub price(sku: Int) -> Int fails LookupError = let found = price_of(sku) if none fail Missing if error fail Missing found ``` **A clause on its own line.** A clause written on the statement's line is a syntax error: ```una -- fails with U0101 module shop pub kind StockError = | OutOfStock reserve(units: Int) -> Int = if units > 10 then fail OutOfStock else units pub checkout(units: Int) -> Int fails StockError = reserve(units) if error pass ``` **`if none` needs an `Option`**: ```una -- fails with U2001 module shop pub kind LookupError = | Missing pub price(cents: Int) -> Int fails LookupError = let found = cents if none fail Missing found ``` **The recovered value has the expression's type**: ```una -- fails with U2001 module shop pub kind StockError = | OutOfStock reserve(units: Int) -> Int = if units > 10 then fail OutOfStock else units pub reserved(units: Int) -> Int = reserve(units) if error use "none" ``` **`error` only inside a clause.** `error` is valid only in the `fail` or `use` part of an `if error` clause: ```una -- fails with U2013 module shop pub kind StockError = | OutOfStock pub reserve(units: Int) -> Int fails StockError = if units > 10 then fail OutOfStock else error ``` Further rules: - **One effect per line.** A fallible call is the whole expression of its statement, `let` or final expression, so that its clause has one site (U3013). Bind its result with `let` first. - **The `fail` of a clause** obeys the rules of `fail`: its variant belongs to the function's error kind (U3009), and it is allowed only when the [Branches and failures: implicit flows](https://una-lang.org/en/learn/information-flow/branches-and-failures-implicit-flows/), the label of the conditions that decided whether this line runs, is `public` (U4002). - **Labeled failures.** A failure decided by labeled data (data marked with a label above `public`, such as `internal` or `secret`), such as an `Http` request's, carries that label. `if error use` then runs under it, and `if error pass` and `if error fail` are U4002 when it is above `public`. - **An `if error` clause on a statement that cannot fail.** In edition `0.3`, an `if error` clause after a statement that cannot fail, such as `let x = n + 1`, is U3025, and `una fix` deletes it. Only `if error` is judged: on an `Option` that cannot fail, such as `let first = codes.first()`, an `if none` clause stays. Editions `0.1` and `0.2` accept the `if error` clause. - **Alternative.** `attempt` handles a failure by turning it into a `Result` value instead. See [`attempt`](https://una-lang.org/en/docs/language/errors/attempt/). ## Diagnostics - [U0101](https://una-lang.org/en/docs/errors/U0101/): a clause on the statement's own line. - [U0102](https://una-lang.org/en/docs/errors/U0102/): a repeated clause, or `if error` after `if none`. - [U2001](https://una-lang.org/en/docs/errors/U2001/): `if none` on a value that is not an `Option`, or a recovered value of the wrong type. - [U2013](https://una-lang.org/en/docs/errors/U2013/): `error` outside a handling clause. - [U3007](https://una-lang.org/en/docs/errors/U3007/): a fallible statement without a clause. - [U3008](https://una-lang.org/en/docs/errors/U3008/): `if error pass` across error kinds. - [U3009](https://una-lang.org/en/docs/errors/U3009/): the variant of `if error fail` or `if none fail` outside the function's error kind. - [U3013](https://una-lang.org/en/docs/errors/U3013/): a fallible call nested inside another expression. - [U3025](https://una-lang.org/en/docs/errors/U3025/): in edition `0.3`, an `if error` clause on an expression that cannot fail. - [U4002](https://una-lang.org/en/docs/errors/U4002/): the `fail` of a clause under a program counter above `public`, or `if error pass` or `if error fail` on a failure labeled above `public`. ## Edition The handling clauses are the same in editions `0.1` and `0.2`. Edition `0.3` adds U3025 for an `if error` clause on an expression that cannot fail. ## Normative source - `spec/06 §3`: handling clauses, their order, and, in edition `0.3`, a clause on a statement that cannot fail; `spec/06 §1`: one error kind per function; `spec/06 §2`: the variant of a `fail`; `spec/06 §5`: `attempt`. - `spec/02 §6`: the grammar of `handled` and `handling`; `spec/02 §8`: where `error` may appear. - `spec/04 §4`: one effect per line. - `spec/07 §3` rule 3: failures under the program counter; `spec/07 §7` rule 4: labeled failures of operations. - Decision record: [ADR 0100](https://github.com/una-lang/una/blob/v0.4.0/docs/adr/0100-failure-handling-on-code-that-cannot-fail.md), for U3025. --- # attempt ## What it does `attempt f(args)` evaluates one fallible call (a call that can fail) and returns a `Result[T, E]` instead of failing: `Ok(value)` on a normal return, `Err(failure)` on a failure. The caller then branches on the outcome. `attempt` is the call's handling site, so the call needs no `if error` clause (U3007). Learn more: [Failures as values: attempt and Result](https://una-lang.org/en/learn/failure/failures-as-values-attempt-and-result/). ```una module shop pub kind Registration name: Text pub kind StoreError = | Timeout pub capability Registrations op find(key: Text) -> Option[Registration] fails StoreError pub registered(key: Text) -> Bool uses @registrations: Registrations[find] = let outcome = attempt @registrations.find(key) when outcome is Ok(value) -> value.is_some() is Err(failure) -> false ``` ## Forms In the grammar below, each rule gives a name, `=`, what the name stands for and `;`, quoted words are written as shown, NEWLINE, INDENT and DEDENT stand for a line break and for one more or one less level of indentation, `[ ]` marks an optional part, `{ }` a part that may repeat, `|` separates alternatives, `( )` groups them, and `(* *)` holds a comment. ```ebnf attempt_expr = "attempt" postfix ; ``` The operand is one call of a function or of a capability operation. `attempt` stands as the whole expression of a statement, a `let` or a final expression, as any fallible call does. ## Examples After `let x = attempt f(...)`, the arm (one `is` line of a `when`) `is Ok(value)` knows what a normal return of `f` guarantees, its `ensures` included; the arm `is Err` knows nothing more. Here the verifier (the part of `una check` that proves facts about the code) proves `result >= units` from `add_units`'s `ensures`: ```una module shop pub kind OrderError = | TooMany pub add_units(units: Int) -> Int ensures result > units fails OrderError = if units > 100 then fail TooMany else units + 1 pub add_or_keep(units: Int) -> Int ensures result >= units = let outcome = attempt add_units(units) when outcome is Ok(value) -> value is Err -> units ``` The `Result` is a value like any other, so a function may return it to its caller: ```una module shop pub kind StockError = | OutOfStock reserve(units: Int) -> Int = if units > 10 then fail OutOfStock else units pub try_reserve(units: Int) -> Result[Int, StockError] = attempt reserve(units) ``` The operand must be a call: ```una -- fails with U2001 module shop pub try_reserve(units: Int) -> Result[Int, Int] = attempt units ``` ## Edge cases **One effect per line.** `attempt` does not let a fallible call sit inside a larger expression. Bind the `Result` with `let` first: ```una -- fails with U3013 module shop pub kind StockError = | OutOfStock reserve(units: Int) -> Int = if units > 10 then fail OutOfStock else units pub can_reserve(units: Int) -> Bool = (attempt reserve(units)).is_ok() ``` Further rules: - **One call, not a block.** `attempt` covers a single call; a sequence of fallible calls takes one `attempt` or one clause each. - **Labeled failures.** When a failure is decided by labeled data (data marked with a label above `public`, such as `internal` or `secret`), the `Result` carries that label. This holds for the requests of `Http` and a policy call's failure, labeled by its `to` label joined with the program counter (see [`policy`](https://una-lang.org/en/docs/language/information-flow/policy/)). Branching on it raises the [Branches and failures: implicit flows](https://una-lang.org/en/learn/information-flow/branches-and-failures-implicit-flows/), the label of the conditions that decided whether a line runs, and under a raised one a `fail` is U4002. - **An operand that cannot fail.** In edition `0.3`, `attempt` of a call that cannot fail is U3026: use the value of the call directly, and unwrap the uses of the `Result`. Editions `0.1` and `0.2` accept it, and the error type of its `Result` is then not constrained. - **Alternative.** To convert, propagate or recover at the line itself, use a handling clause. See [`if error` and `if none`](https://una-lang.org/en/docs/language/errors/if-error/). ## Diagnostics - [U2001](https://una-lang.org/en/docs/errors/U2001/): the operand of `attempt` is not one call. - [U3007](https://una-lang.org/en/docs/errors/U3007/): a fallible call with neither a clause nor `attempt`. - [U3013](https://una-lang.org/en/docs/errors/U3013/): `attempt` nested inside another expression. - [U3026](https://una-lang.org/en/docs/errors/U3026/): in edition `0.3`, `attempt` of a call that cannot fail. - [U4002](https://una-lang.org/en/docs/errors/U4002/): a failure decided under a labeled program counter, such as a `fail` in an arm that branches on a labeled `Result`. ## Edition `attempt` is the same in editions `0.1` and `0.2`. Edition `0.3` adds U3026 for `attempt` of a call that cannot fail. ## Normative source - `spec/06 §5`: `attempt`, its operand and, in edition `0.3`, an operand that cannot fail; `spec/06 §3`: its role as the handling site, and one handling per call. - `spec/02 §7`: the grammar; `spec/02 §8`: where a fallible call may stand. - `spec/04 §4`: one effect per line. - `spec/12 §3`: the facts after `attempt`. - `spec/07 §3` rule 3, `spec/07 §7` rule 4 and `spec/07 §5` rule 6: labeled failures. - Decision record: [ADR 0100](https://github.com/una-lang/una/blob/v0.4.0/docs/adr/0100-failure-handling-on-code-that-cannot-fail.md), for U3026. --- # checked and the escape budget ## What it does `checked(v, p) else fail V` tests the predicate `p` (a condition on `it` that is true or false) at run time, with `it` bound to `v`: - when `p` holds, the result is `v`, with its type refined by `p` (its type now carries the condition `p`); - otherwise the function fails with `V`. This is how a value obtains an opaque fact, one the solver (the program that `una check` asks to prove each fact) cannot prove. `checked` replaces a proof made before the program runs with a test while it runs, so it is an escape hatch. Each module may use it only as many times as its package's escape budget (a count set in `una.toml`) allows, and every use is listed in the build report (what `una report` prints about a build). Learn more: [When no proof can decide: checked and opaque predicates](https://una-lang.org/en/learn/failure/when-no-proof-can-decide-checked-and-opaque-predicates/). `una.toml` ```toml [package] name = "shop" version = "0.1.0" edition = "0.2" [escape_budget] checked_per_module = 1 ``` `src/shop.una` ```una module shop pub kind Phone = Text where valid_phone(it) pub kind PhoneError = | Malformed pub predicate opaque valid_phone(t: Text) -> Bool = t.len == 11 and is_digits(t) pub parse_phone(raw: Text) -> Phone fails PhoneError = checked(raw, valid_phone(it)) else fail Malformed ``` ## Forms In the grammar below, each rule gives a name, `=`, what the name stands for and `;`, quoted words are written as shown, NEWLINE, INDENT and DEDENT stand for a line break and for one more or one less level of indentation, `[ ]` marks an optional part, `{ }` a part that may repeat, `|` separates alternatives, `( )` groups them, and `(* *)` holds a comment. ```ebnf checked_expr = "checked" "(" line_expr "," line_expr ")" "else" "fail" variant_expr ; ``` - The first argument is the value tested. - The second is the predicate, with `it` naming the value. It is written in the refinement language (the expressions that a type's condition may use, which the solver can reason about), or is a call of an opaque predicate (one whose body the solver never sees), so that it can run. - `else fail V` names the variant the function fails with when the test fails. `V` belongs to the function's error kind. The budget is the key `checked_per_module` of the `[escape_budget]` table of `una.toml`, an integer of at least 0 that defaults to 0. ## Examples A predicate in the refinement language refines a plain value. Here `Shelf`'s refinement holds for the result because the test established it: `una.toml` ```toml [package] name = "shop" version = "0.1.0" edition = "0.2" [escape_budget] checked_per_module = 1 ``` `src/shop.una` ```una module shop pub kind Shelf = Int in 0..9 pub kind ShelfError = | NoSuchShelf pub shelf(n: Int) -> Shelf fails ShelfError = checked(n, it >= 0 and it <= 9) else fail NoSuchShelf ``` Without a budget, `checked` is rejected. The default is 0, and a file checked on its own has the default: ```una -- fails with U7003 module shop pub kind Phone = Text where valid_phone(it) pub kind PhoneError = | Malformed pub predicate opaque valid_phone(t: Text) -> Bool = t.len == 11 and is_digits(t) pub parse_phone(raw: Text) -> Phone fails PhoneError = checked(raw, valid_phone(it)) else fail Malformed ``` ## Edge cases **The predicate must run.** A call of a function that is not a predicate is outside the refinement language: `una.toml` ```toml [package] name = "shop" version = "0.1.0" edition = "0.2" [escape_budget] checked_per_module = 1 ``` `src/shop.una` ```una -- fails with U2014 module shop pub kind SkuError = | NotDigits pub digits_only(sku: Text) -> Text fails SkuError = checked(sku, is_digits(it)) else fail NotDigits ``` **Opaque predicates are called only in `checked`**, and in the bodies of other opaque predicates. A call anywhere else would establish the fact without counting against the budget: ```una -- fails with U2016 module shop pub predicate opaque valid_phone(t: Text) -> Bool = t.len == 11 and is_digits(t) pub looks_valid(raw: Text) -> Bool = valid_phone(raw) ``` **The variant belongs to the function's error kind**: `una.toml` ```toml [package] name = "shop" version = "0.1.0" edition = "0.2" [escape_budget] checked_per_module = 1 ``` `src/shop.una` ```una -- fails with U3009 module shop pub kind StockError = | Negative pub kind PaymentError = | Declined pub stock_level(units: Int) -> Int fails StockError = checked(units, it >= 0) else fail Declined ``` **No test that depends on labeled data** (data marked with a label above `public`, such as `internal` or `secret`). A failure of `checked` reveals whether the predicate holds. So `checked` is U4002 on a labeled value, on a predicate that reads a labeled value, or under a raised [Branches and failures: implicit flows](https://una-lang.org/en/learn/information-flow/branches-and-failures-implicit-flows/) (the label of the conditions that decided whether this line runs): `una.toml` ```toml [package] name = "shop" version = "0.1.0" edition = "0.2" [escape_budget] checked_per_module = 1 ``` `src/shop.una` ```una -- fails with U4002 module shop pub kind CreditError = | Negative pub balance(cents: secret Int) -> secret Int fails CreditError = checked(cents, it >= 0) else fail Negative ``` The same holds when the operand is public but the predicate reads labeled data, here an `internal` bound: `una.toml` ```toml [package] name = "shop" version = "0.1.0" edition = "0.2" [escape_budget] checked_per_module = 1 ``` `src/shop.una` ```una -- fails with U4002 module shop pub kind LimitError = | OverLimit pub within_limit(cents: Int, limit: internal Int) -> Int fails LimitError = checked(cents, it < limit) else fail OverLimit ``` Further rules: - **Counting.** The first use beyond the budget is U7003, with the later uses as related locations. The budget counts per module, not per package. - **`it`** is valid only in the predicate of `checked` and in `where` clauses (U2013). In edition `0.3`, only the `where` of a kind counts, not the condition on an operation. - **Repairs prefer proofs.** When a proof is refuted (the solver finds a case where the fact is false), the repairs list a stronger type, a `requires` clause or a guard before `checked`, which they mark as an escape with a cost. - **Reported.** Every use of `checked` is listed in the build report, so reviewers see each run-time test that replaces a proof. - **Narrowing integers.** In edition `0.2`, a narrowing conversion of an integer (to a type with fewer values) carries an `overflow` obligation (a fact `una check` must prove), or narrows through `checked` on the same budget. ## Diagnostics - [U2013](https://una-lang.org/en/docs/errors/U2013/): `it` outside the predicate of `checked` or a `where` clause. - [U2014](https://una-lang.org/en/docs/errors/U2014/): a predicate outside the refinement language. - [U2016](https://una-lang.org/en/docs/errors/U2016/): an opaque predicate called outside `checked`. - [U3009](https://una-lang.org/en/docs/errors/U3009/): the variant of `else fail` outside the function's error kind. - [U4002](https://una-lang.org/en/docs/errors/U4002/): `checked` of a labeled value, with a predicate that reads one, or under a raised program counter. - [U7003](https://una-lang.org/en/docs/errors/U7003/): more uses in a module than its escape budget allows. ## Edition `checked` and the escape budget are the same in editions `0.1` and `0.2`. Edition `0.2` keeps them and adds fixed-width integers, whose narrowing conversions may go through `checked`. ## Normative source - `spec/06 §6`: `checked`, its predicate, the budget and its counting per module; `spec/06 §2`: the variant belongs to the error kind. - `spec/02 §7`: the grammar; `spec/02 §8`: where `it` may appear. - `spec/03 §3`: the refinement language; `spec/03 §4`: opaque predicates. - `spec/13 §3`: repairs; `spec/13 §6`: the build report; `spec/13 §7`: `[escape_budget]`. - `spec/10 §7`: T-Checked and its label rule; `spec/10 §13.2`: the predicate's other reads. - `spec/07 §3` rule 3: failures under the program counter. - `spec/18 §4` rule 4: narrowing conversions. - Decision record: [ADR 0089](https://github.com/una-lang/una/blob/v0.4.0/docs/adr/0089-checked-predicate-labels.md), for the labels a predicate reads. --- # capability and op ## What it does A capability is unforgeable authority (no code can make one up: a function gets it from its caller, and `main` from the runtime) over something outside the program, such as a store, a clock or a network. `capability C` declares the operations that authority allows, each with `op`: an operation is one action on the outside world, such as reading a key. Code acts outside the program only through an operation of a capability it holds, written `@name.op(...)`. Every such call is an effect (an action outside the program), recorded in the program's trace (the list of effects a run performed, in order). Learn more: [Your own capabilities and handlers](https://una-lang.org/en/learn/capabilities/your-own-capabilities-and-handlers/). Related pages: [`uses`](https://una-lang.org/en/docs/language/capabilities/uses/), [handlers](https://una-lang.org/en/docs/language/capabilities/handler/) and [`with`](https://una-lang.org/en/docs/language/capabilities/with/). ```una module shop pub kind StoreError = | Timeout pub capability Store op get(key: Text) -> Option[Text] fails StoreError op put(key: Text, value: Text) -> Unit fails StoreError pub read(key: Text) -> Text uses @store: Store[get] fails StoreError = let found = @store.get(key) if error pass if none use "" found ``` ## Forms In the grammar below, each rule gives a name, `=`, what the name stands for and `;`, quoted words are written as shown, NEWLINE, INDENT and DEDENT stand for a line break and for one more or one less level of indentation, `[ ]` marks an optional part, `{ }` a part that may repeat, `|` separates alternatives, `( )` groups them, and `(* *)` holds a comment. ```ebnf capability_decl = [ "pub" ] "capability" upper_ident NEWLINE INDENT op_decl { op_decl } DEDENT ; op_decl = "op" lower_ident "(" [ params ] ")" "->" type NEWLINE [ INDENT op_clause { op_clause } DEDENT ] ; op_clause = "requires" line_expr NEWLINE | "ensures" line_expr NEWLINE | "fails" upper_ident NEWLINE | "accepts" label NEWLINE ; ``` An operation's clauses mean: | Op clause | Meaning | | --- | --- | | `requires p` | Precondition over arguments; an obligation (a fact the checker must prove) at every call site | | `ensures q` | Postcondition (a promise about the result) over arguments and `result`. It is an assumption about the external system: callers may rely on it, handlers (code that implements the capability in Una) are verified against it, host implementations are trusted to satisfy it | | `fails E` | The operation may fail with variants of `E` | | `accepts l` | Upper bound on the labels of arguments (the sink label: how sensitive the data an operation receives may be). Default: `public` | Operation clauses come in a fixed order: every `requires`, every `ensures`, at most one `fails`, at most one `accepts`. ## Examples An operation's `ensures` is a fact for its callers. A handler of the capability must keep it, so a handler that cannot is refuted: ```una -- fails with U5001 module shop pub capability Store op get(key: Text) -> Text ensures result.len > 0 handler blank() for Store op get(key) = "" ``` A function uses only the operations its `uses` clause lists: ```una -- fails with U3002 module shop pub capability Store op get(key: Text) -> Text op put(key: Text, value: Text) -> Unit pub save(key: Text) -> Unit uses @store: Store[get] = @store.put(key, value: "Desk lamp") ``` ## Edge cases **One name per declaration.** A capability shares the upper-case namespace of kinds and their variants, and a name defined twice in a module is rejected: ```una -- fails with U1002 module shop pub kind Store = | Empty pub capability Store op get(key: Text) -> Text ``` Further rules: - **Assumed, and reported.** Every capability the package declares is listed under `assumptions` in `una report`, with its operations and their `ensures`, since those describe a system outside the program. - **Sinks.** A sink is a place where data leaves the program. `accepts` bounds the labels of the arguments, so an operation that accepts only `public` cannot receive `secret` data. - **Host capabilities** such as `Console` and `Files` are declared in the module `std.host` and implemented by the runtime. See [host capabilities and grants](https://una-lang.org/en/docs/language/capabilities/host/). ## Diagnostics - [U1002](https://una-lang.org/en/docs/errors/U1002/): a capability whose name is already defined in the module. - [U3002](https://una-lang.org/en/docs/errors/U3002/): an operation that the `uses` clause does not permit. - [U5001](https://una-lang.org/en/docs/errors/U5001/): a handler operation that does not keep the operation's `ensures`. ## Edition Capabilities are the same in editions `0.1` and `0.2`. Edition `0.2` adds the host capability `Http`. ## Normative source - `spec/05 §1`: the model; `spec/05 §2`: declarations; `spec/05 §3`: using capabilities; `spec/05 §5`: handlers. - `spec/02 §4`: the grammar. - `spec/07 §4`: sinks; `spec/13 §6`: the build report and its `assumptions`. - `spec/10 §11` rule 1: the upper-case namespace of kinds, variants and capabilities; rule 5: duplicate names. - `spec/14 §3`: the host capabilities, and `Http` from edition `0.2`. --- # uses ## What it does `uses @x: C[ops]` is the header clause that gives a function authority (the right to act outside the program): inside its body, `@x` names a [capability](https://una-lang.org/en/docs/language/capabilities/capability/) `C`, and the body may perform the operations `ops` on it. There is no ambient authority (no power that code has just by existing, such as a global file system), so a function's capability context is exactly its `uses` clauses. A line acts outside the program only through an `@` operation, or through a call of a function that has `uses`. Learn more: [Declaring what a function may do: uses in full](https://una-lang.org/en/learn/capabilities/declaring-what-a-function-may-do-uses-in-full/). ```una module shop pub capability Log op write(line: Text) -> Unit pub note(line: Text) -> Unit uses @log: Log[write] = @log.write(line) ``` A call may perform an effect even when its line has no `@`. Here, `emit` performs `@console.print`, and `main` calls it. Both public headers declare `Console[print]`. A public caller that leaves it out is U3003, as an example below shows. ```una module shop pub emit() -> Unit uses @console: Console[print] = @console.print("hello") pub main() -> Unit uses @console: Console[print] = emit() ``` ## Forms In the grammar below, each rule gives a name, `=`, what the name stands for and `;`, quoted words are written as shown, NEWLINE, INDENT and DEDENT stand for a line break and for one more or one less level of indentation, `[ ]` marks an optional part, `{ }` a part that may repeat, `|` separates alternatives, `( )` groups them, and `(* *)` holds a comment. ```ebnf clause = "requires" line_expr NEWLINE | "ensures" line_expr NEWLINE | "uses" cap_ref ":" cap_type NEWLINE | "fails" upper_ident NEWLINE | "derived" "from" upper_ident { "," upper_ident } NEWLINE ; cap_type = upper_ident [ "[" lower_ident { "," lower_ident } "]" ] ; ``` - **`uses @x: C[op1, op2]`** permits the listed operations. - **`uses @x: C`**, without brackets, permits every operation of `C`. - A function may have several `uses` clauses, one per reference. They come after `requires` and `ensures`, and before `fails`. - **`uses of p`** (from edition `0.2` on): the function performs the effects (actions outside the program) of its parameter `p`, a function value. ## Examples Capabilities pass downward by name. A callee that needs `@log` gets the caller's `@log`, with at least the operations it needs: ```una module shop pub capability Log op write(line: Text) -> Unit note(line: Text) -> Unit uses @log: Log[write] = @log.write(line) pub twice(line: Text) -> Unit uses @log: Log = note(line) note(line) ``` An operation outside the clause's list is rejected: ```una -- fails with U3002 module shop pub capability Store op get(key: Text) -> Text op put(key: Text, value: Text) -> Unit pub save(key: Text) -> Unit uses @store: Store[get] = @store.put(key, value: "Desk lamp") ``` ## Edge cases **A reference must be in scope**: ```una -- fails with U3001 module shop pub capability Log op write(line: Text) -> Unit pub note(line: Text) -> Unit uses @log: Log[write] = @other.write(line) ``` **A public function without `uses` is pure** (it does nothing outside the program). In a `pub` function, which declares its `uses`, an `@` is rejected: ```una -- fails with U3004 module shop pub capability Log op write(line: Text) -> Unit pub note(line: Text) -> Unit = @log.write(line) ``` **A call with effects needs the caller's `uses`.** A pure `pub` function cannot call a function with effects: ```una -- fails with U3003 module shop pub capability Log op write(line: Text) -> Unit note(line: Text) -> Unit uses @log: Log[write] = @log.write(line) pub caller(line: Text) -> Unit = note(line) ``` **One clause per reference**: ```una -- fails with U1002 module shop pub capability Log op write(line: Text) -> Unit pub note(line: Text) -> Unit uses @log: Log[write] uses @log: Log[write] = @log.write(line) ``` Further rules: - **Inferred for private functions.** A private function without `uses` gets the least set that covers its operations and its callees' requirements. A `pub` function declares every `uses`. - **Attenuation** (narrowing what a callee may do). Passing a capability with more operations than the callee needs is allowed, and the callee can use only its own list. - **Rebinding.** A caller can give a callee another reference, or a handler, with `with`. See [`@` bindings and `with`](https://una-lang.org/en/docs/language/capabilities/with/). - **Host capabilities** reach a program only through `main`'s `uses`, from the runtime's grants. See [host capabilities and grants](https://una-lang.org/en/docs/language/capabilities/host/). ## Diagnostics - [U1002](https://una-lang.org/en/docs/errors/U1002/): a reference bound twice in one header. - [U3001](https://una-lang.org/en/docs/errors/U3001/): a reference that is not in scope, or of another capability than the callee needs. - [U3002](https://una-lang.org/en/docs/errors/U3002/): an operation that the clause does not permit, or a callee that needs more operations. - [U3003](https://una-lang.org/en/docs/errors/U3003/): a call whose effects exceed the caller's header. - [U3004](https://una-lang.org/en/docs/errors/U3004/): an `@` in code whose header declares no `uses`. ## Edition `uses` is the same in editions `0.1` and `0.2`. Edition `0.2` adds `uses of p`. Edition `0.3`, a preview, adds conditions on operations, as `Catalog[price, set_price where not dry_run]`, which the checker proves wherever the operation may run, and lets `una.toml` lock the `uses` of public functions under `[contracts]`, so that a header granting more than its lock is an error. See [Conditions on operations](https://una-lang.org/en/learn/authority/conditions-on-operations-edition-0-3/). ## Normative source - `spec/05 §1`: the model; `spec/05 §3`: using capabilities, and in edition `0.3` rules 4 and 5, conditions on operations and locked contracts; `spec/05 §4`: passing capabilities; `spec/05 §9`: reporting. - `spec/04 §2` rule 4: pure functions; `spec/04 §5`: inference. - `spec/02 §3`: the grammar and clause order. - Decision records: [ADR 0062](https://github.com/una-lang/una/blob/v0.4.0/docs/adr/0062-effect-polymorphism.md), for `uses of`; [ADR 0092](https://github.com/una-lang/una/blob/v0.4.0/docs/adr/0092-conditions-on-allowed-effects.md), for conditions on operations and locked contracts. --- # @ bindings and with ## What it does A capability reference, `@name`, is a name for authority (the right to act outside the program), not a value. Capabilities pass downward by name: a callee that says [`uses @x: C[ops]`](https://una-lang.org/en/docs/language/capabilities/uses/) gets the caller's `@x`. `with` changes what the callee's name refers to, for one statement: - **`with @x = @y`** gives the callee the caller's `@y` under the name `@x`; - **`with @x = h(args)`** installs a [handler](https://una-lang.org/en/docs/language/capabilities/handler/) `h`, written in Una, as the callee's `@x`. Learn more: [Passing authority: with, rebinding and narrowing](https://una-lang.org/en/learn/capabilities/passing-authority-with-rebinding-and-narrowing/). ```una module shop pub capability Log op write(line: Text) -> Unit note(line: Text) -> Unit uses @log: Log[write] = @log.write(line) pub caller(line: Text) -> Unit uses @audit: Log[write] = note(line) with @log = @audit ``` ## Forms In the grammar below, each rule gives a name, `=`, what the name stands for and `;`, quoted words are written as shown, NEWLINE, INDENT and DEDENT stand for a line break and for one more or one less level of indentation, `[ ]` marks an optional part, `{ }` a part that may repeat, `|` separates alternatives, `( )` groups them, and `(* *)` holds a comment. ```ebnf handled = line_expr [ with_clause ] NEWLINE [ INDENT handling { handling } DEDENT ] ; with_clause = "with" cap_binding { "," cap_binding } ; cap_binding = cap_ref "=" ( cap_ref | handler_call ) ; ``` - A `with` clause ends a statement, a `let` or a final expression, and scopes over that expression only. - One clause may bind several references, separated by commas. ## Examples A handler installed for one call. The handler's operations run in place of a real store: ```una module shop pub capability Store op get(key: Text) -> Text handler fixed(value: Text) for Store op get(key) = value read(key: Text) -> Text uses @store: Store[get] = @store.get(key) pub preview_name() -> Text = let name = read("LAMP-01") with @store = fixed(value: "Desk lamp") name ``` Both sides of a rebinding have the same capability: ```una -- fails with U3001 module shop pub capability Log op write(line: Text) -> Unit pub capability Ticker op now() -> Int note(line: Text) -> Unit uses @log: Log[write] = @log.write(line) pub caller(line: Text) -> Unit uses @ticker: Ticker[now] = note(line) with @log = @ticker ``` ## Edge cases **References are second-class** (usable only in the few places the language allows, never as ordinary data). A capability reference cannot be bound with `let`, passed as an ordinary argument, returned, stored, compared or interpolated: ```una -- fails with U3005 module shop pub capability Log op write(line: Text) -> Unit pub keep() -> Unit uses @log: Log[write] = let saved = @log unit ``` **So are effectful function values** (function values that act outside the program or can fail). A function value with `uses` or `fails` may only be called, or passed directly as an argument. It never outlives the `with` scope it was created in: ```una -- fails with U3006 module shop pub capability Log op write(line: Text) -> Unit pub keep(writer: fn() -> Unit uses @log: Log[write]) -> Unit uses @log: Log[write] = let later = writer later() ``` **Handlers are not values.** A handler is installed with `with`, or with `given` in an example: ```una -- fails with U2001 module shop pub capability Store op get(key: Text) -> Text handler fixed(value: Text) for Store op get(key) = value pub keep() -> Unit = let catalog = fixed(value: "Desk lamp") unit ``` Further rules: - **Attenuation** (narrowing what a callee may do). A caller may give a reference with more operations than the callee needs. The callee uses only its own. - **The handler's own `uses`** must be held where it is installed. - **A handler for the right capability.** `with @x = h(...)` needs `h` to implement the capability the callee expects at `@x` (U3010). - **One binding per reference** in a clause (U1002). - **No type argument holds an effectful function type,** so such a value cannot be stored in a list either (U3016). - **Why.** Authority moves only downward, along calls, through `uses` and `with`. So every function's reachable authority is visible in its header, and capability confinement holds (no code can act through a capability it was not given) without an escape analysis (a compiler pass that tracks where values may travel). - **A bare reference**, not followed by `.op(...)`, appears only on either side of a `with` binding or after `given @x =` (U3005). ## Diagnostics - [U1002](https://una-lang.org/en/docs/errors/U1002/): a reference bound twice in one `with` clause. - [U2001](https://una-lang.org/en/docs/errors/U2001/): a handler used as a value. - [U3001](https://una-lang.org/en/docs/errors/U3001/): a rebinding to a reference of another capability, or one not in scope. - [U3005](https://una-lang.org/en/docs/errors/U3005/): a capability reference used as a value. - [U3006](https://una-lang.org/en/docs/errors/U3006/): an effectful or failing function value that escapes. - [U3010](https://una-lang.org/en/docs/errors/U3010/): a handler for another capability than the one expected. - [U3016](https://una-lang.org/en/docs/errors/U3016/): a type argument that holds an effectful or failing function type. - [U3020](https://una-lang.org/en/docs/errors/U3020/): from edition `0.3`, a call into a boundary that gets a capability by name instead of through `with`. - [U3024](https://una-lang.org/en/docs/errors/U3024/): from edition `0.3`, a call into a boundary from which a policy call is reachable. ## Edition `with` and the second-class rule are the same in editions `0.1` and `0.2`. From edition `0.3`, a preview, the language adds the narrowed rebinding `with @x = @y[ops]`, which gives the callee the caller's `@y` restricted to `ops`, and checks each call into a boundary (a group of modules whose authority `una.toml`, or from edition `0.4` `ita.una`, caps) against that cap. A call into a boundary gets no capability by name, so each one it needs is passed with `with` (U3020), and no policy call may be reachable from it (U3024). See [Granting less at the call](https://una-lang.org/en/learn/authority/a-ceiling-for-a-module-boundaries/#granting-less-at-the-call-with-x-yops) and [`[boundaries]`](https://una-lang.org/en/docs/configure/boundaries/). ## Normative source - `spec/05 §4`: passing capabilities and `with`, and from edition `0.3` rules 4 and 5, narrowed rebindings and calls into a boundary; `spec/05 §6`: the second-class rule; `spec/05 §9`: reporting. - `spec/02 §6`: the grammar; `spec/02 §8`: where a bare reference may appear. - `spec/10 §6`: the typing of `with`; `spec/10 §10` T4: confinement. - `spec/05 §5` rule 4: handlers are not values. - Decision record: [ADR 0093](https://github.com/una-lang/una/blob/v0.4.0/docs/adr/0093-authority-at-module-boundaries.md), for narrowed rebindings and boundaries. --- # handler ## What it does A handler implements a [capability](https://una-lang.org/en/docs/language/capabilities/capability/) in Una: it gives a body to each operation. A caller installs it for one statement with `with`, or an example (a test written next to the code) installs it with `given`, so code that needs the capability runs against the handler instead of the outside world, as a fake store does in a test. Handler bodies are ordinary Una code, fully checked and verified (their contracts proved by the checker). Learn more: [Your own capabilities and handlers](https://una-lang.org/en/learn/capabilities/your-own-capabilities-and-handlers/). ```una module shop pub capability Store op get(key: Text) -> Text handler fixed(value: Text) for Store op get(key) = value read(key: Text) -> Text uses @store: Store[get] = @store.get(key) pub preview_name() -> Text = let name = read("LAMP-01") with @store = fixed(value: "Desk lamp") name ``` ## Forms In the grammar below, each rule gives a name, `=`, what the name stands for and `;`, quoted words are written as shown, NEWLINE, INDENT and DEDENT stand for a line break and for one more or one less level of indentation, `[ ]` marks an optional part, `{ }` a part that may repeat, `|` separates alternatives, `( )` groups them, and `(* *)` holds a comment. ```ebnf handler_decl = [ "pub" ] "handler" lower_ident "(" [ params ] ")" "for" upper_ident NEWLINE INDENT { "uses" cap_ref ":" cap_type NEWLINE } handler_op { handler_op } DEDENT ; handler_op = "op" lower_ident "(" [ lower_ident { "," lower_ident } ] ")" "=" inline_or_block ; ``` - **Parameters** of the handler are captured values, given where it is installed: `fixed(value: "Desk lamp")`. - **`for C`** names the capability the handler implements. - **`uses`** lines give the handler capabilities of its own. - **`op name(params) = body`** implements one operation. Its parameters are written without types: they come from the capability's declaration. ## Examples A handler implements every operation of its capability: ```una -- fails with U3011 module shop pub capability Store op get(key: Text) -> Text op put(key: Text, value: Text) -> Unit handler fixed(value: Text) for Store op get(key) = value ``` A handler body must keep the operation's `ensures`, which callers rely on: ```una -- fails with U5001 module shop pub capability Store op get(key: Text) -> Text ensures result.len > 0 handler blank() for Store op get(key) = "" ``` ## Edge cases **Only the capability's operations**: ```una -- fails with U3010 module shop pub capability Store op get(key: Text) -> Text handler fixed(value: Text) for Store op get(key) = value op extra(key) = value ``` **`for` names a capability**: ```una -- fails with U3010 module shop pub kind Address street: Text handler shipping() for Address op get(key) = key ``` **Failures of the operation's kind only.** An operation body fails only with its operation's error kind, and passes only an equal kind (U3008): ```una -- fails with U3009 module shop pub kind StoreError = | Timeout pub kind PaymentError = | Declined pub capability Store op get(key: Text) -> Text fails StoreError handler broken() for Store op get(key) = fail Declined ``` Further rules: - **Not a value.** A handler is installed only with `with` or `given`. Binding it with `let` is U2001. - **Worst caller.** An operation body is checked for the worst caller its operation allows, the caller that passes the most sensitive data the operation accepts: every parameter is raised to the operation's `accepts` label (how sensitive its data may be). So a handler of an operation that accepts `internal` data cannot print it, while a fake store that fails or returns fixed values stays valid. - **Its own authority.** A handler's `uses` must be held where it is installed. - **Host capabilities** may have user handlers too, such as a fake `Keys` in examples. The host implementations are used only by `una run` and by an executable that `una build` makes. ## Diagnostics - [U2001](https://una-lang.org/en/docs/errors/U2001/): a handler used as a value. - [U3008](https://una-lang.org/en/docs/errors/U3008/): an operation body that passes a failure of another kind. - [U3009](https://una-lang.org/en/docs/errors/U3009/): an operation body that fails outside its operation's error kind. - [U3010](https://una-lang.org/en/docs/errors/U3010/): `for` that names no capability, or an operation the capability lacks. - [U3011](https://una-lang.org/en/docs/errors/U3011/): a handler that misses an operation. - [U5001](https://una-lang.org/en/docs/errors/U5001/): an operation body that does not keep the operation's `ensures`. ## Edition Handlers are the same in editions `0.1` and `0.2`. ## Normative source - `spec/05 §5`: handlers, rules 1 to 5; `spec/05 §4`: installing with `with`; `spec/05 §9` rules 3 and 4: reporting. - `spec/02 §4`: the grammar. - `spec/08 §2`: `given` in examples. - `spec/12 §3`: obligations of handler operations. - `spec/14 §3`: host capabilities. --- # Host capabilities and grants ## What it does Host capabilities are the ones the runtime implements: `Console`, `Clock`, `Env`, `Files` and `Keys`, from edition `0.2` on also `Http`, and from edition `0.4` on also `HttpServer`, which a module imports from `std.host` (see [Serving HTTP](https://una-lang.org/en/docs/guides/serving-http/)). They enter a program only through `main`'s `uses` clauses, and the runtime provides them only when they are granted (allowed by whoever runs the program), in `una.toml` or with `--grant`. Other functions receive them from their callers by name, like any [capability](https://una-lang.org/en/docs/language/capabilities/capability/). Learn more: [The host's capabilities and grants](https://una-lang.org/en/learn/capabilities/the-hosts-capabilities-and-grants/). `una.toml` ```toml [package] name = "shop" version = "0.1.0" edition = "0.2" [run] entry = "shop" grants = ["console"] ``` `src/shop.una` ```una module shop pub main() -> Unit uses @console: Console[print] = @console.print("The shop is open") ``` ## Forms The host capabilities: | Capability | Operation | Fails | Accepts | | --- | --- | --- | --- | | `Console` | `print(line: Text) -> Unit` | | `public` | | `Clock` | `now() -> Int` | | `public` | | `Env` | `get(name: Text) -> Option[internal Text]` | | `public` | | `Files` | `read(path: Text) -> internal Text` | `FileError` | `public` | | `Files` | `write(path: Text, content: Text) -> Unit` | `FileError` | `internal` | | `Keys` | `hmac(key_name: Text, data: Text) -> internal Hashed` | `KeyError` | `public` for `key_name`, any label for `data` | | `Http` (edition `0.2`) | `get(url: Text, headers: List[Header], key_name: Option[Text]) -> internal Response` | `HttpError` | `internal` | | `Http` (edition `0.2`) | `post(url: Text, headers: List[Header], body: Text, key_name: Option[Text]) -> internal Response` | `HttpError` | `internal` | | `Http` (edition `0.2`) | `put(url: Text, headers: List[Header], body: Text, key_name: Option[Text]) -> internal Response` | `HttpError` | `internal` | | `Http` (edition `0.2`) | `delete(url: Text, headers: List[Header], key_name: Option[Text]) -> internal Response` | `HttpError` | `internal` | `internal` is a label: a mark on data that says how sensitive it is, which the checker follows wherever the data goes (see [labels](https://una-lang.org/en/docs/language/information-flow/labels/)). The grant specs: - `console`, `clock` and `env`; - `keys:`; - `files::read`, `files::write` and `files::read,write`; - from edition `0.2` on, `http:` and `http::`. They are given in `[run] grants` of `una.toml`, or as `--grant` flags of `una run`. ## Examples A host operation of `main` that no grant allows is reported by `una check`, before the program runs: `una.toml` ```toml [package] name = "shop" version = "0.1.0" edition = "0.2" [run] entry = "shop" grants = ["console"] ``` `src/shop.una` ```una -- fails with U3012 module shop pub main() -> Unit uses @console: Console[print] uses @clock: Clock[now] = let opened = @clock.now() @console.print("opened at {opened}") ``` What `Env.get` and `Files.read` return is `internal`, so printing it to the console, which accepts only `public`, is rejected. Lowering a label takes a [policy](https://una-lang.org/en/docs/language/information-flow/policy/), a declared and reviewed release of data: `una.toml` ```toml [package] name = "shop" version = "0.1.0" edition = "0.2" [run] entry = "shop" grants = ["console", "env"] ``` `src/shop.una` ```una -- fails with U4003 module shop pub main() -> Unit uses @console: Console[print] uses @env: Env[get] = let name = @env.get("SHOP_NAME") if none use "" @console.print(name) ``` ## Edge cases Further rules: - **Files stay inside the grant.** A `Files` path is resolved against the grant's prefix (the directory the grant names). An absolute path, a `..` that leaves the prefix, or a final component that is a symbolic link (a file that points to another file) fails with `Denied`; path resolution never escapes the prefix. - **Keys stay outside values.** `Keys` loads its keys from the grant's file, and key material never enters Una values. The result of `hmac` is labeled `internal`, joined with every label of the type of `data`, and lowering it takes a policy. `key_name` accepts only `public`, so a labeled key name, or a call under a raised program counter (when the conditions that decided whether this line runs read labeled data; see [Branches and failures: implicit flows](https://una-lang.org/en/learn/information-flow/branches-and-failures-implicit-flows/)), is U4003. - **Labeled failures.** Whether a host operation fails is labeled by the arguments that decide it: the path of `Files`, not the content; the key name of `Keys.hmac`, not the data; and every argument of `Http`, so its failures are `internal`. A `Files.write` to an `internal` path fails `internal`, and every `Files` failure also carries the package's file-state label: the labels that decide where the package's writes land and whether they run. - **Host text.** When `Files.read` or `Env.get` meets bytes that are not valid UTF-8, the run aborts with U6005. - **Out of the model.** Races on a path, hard links, resource limits and other processes are outside what the checker reasons about, and `una report` lists such channels under `out_of_model`. - **User handlers.** Code may implement a host capability with its own handler, such as a fake `Keys` in examples. The host implementations are used only by `una run` and by an executable that `una build` makes. - **Declared in `std.host`.** A user capability with the same name is a different declaration. ## Diagnostics - [U3012](https://una-lang.org/en/docs/errors/U3012/): a host operation of `main` that no grant allows, or a `uses` of `main` that no grant can provide. - [U4003](https://una-lang.org/en/docs/errors/U4003/): labeled data sent to an operation that does not accept its label. - [U6005](https://una-lang.org/en/docs/errors/U6005/): at run time, host text that is not valid UTF-8. ## Edition The five host capabilities of v0.1 are in every edition. Edition `0.2` adds `Http`, with its grants `http:` and `http::`. Edition `0.4`, a preview, adds `HttpServer`, imported from `std.host` and granted by a `serve:` grant (`spec/31 §1`, `spec/31 §2`), lets an `http` grant carry limits, and moves a package's grants to `ita.una`. ## Normative source - `spec/05 §7`: host capabilities, rules 1 to 4. - `spec/14 §3`: the operations, `Files` paths, `Keys`, labels and host text. - `spec/13 §5`: grant specs and `una run`; `spec/13 §7`: `[run] grants`. - `spec/07 §4`: sinks; `spec/07 §7` rule 4: labeled failures. - `spec/24 §1`: the `Http` operations; `spec/24 §2`: `Http` grants; `spec/24 §5` rule 3: the labels of `Http` failures. - `spec/31 §1`: `HttpServer`; `spec/31 §2`: `serve:` grants (edition `0.4`). - Decision record: [ADR 0039](https://github.com/una-lang/una/blob/v0.4.0/docs/adr/0039-labels-of-keys-hmac.md), for the labels of `Keys.hmac`. --- # Labels ## What it does A label classifies data by how sensitive it is: a level, and optional categories (named kinds of data, such as personal data). The checker follows labels through every computation and every branch, and rejects any flow of data to a place that its label does not allow. The guarantee is termination-insensitive noninterference (data can influence what a reader sees only through a declared release, leaving aside whether the program finishes at all): an observer at a label sees the same values and effects in two runs that differ only in data labeled above it, unless a [policy](https://una-lang.org/en/docs/language/information-flow/policy/) released it. It covers the channels the model observes: timing, termination, resource use and the other channels it leaves out are listed under `out_of_model` by `una report`, and flows inside the `via` functions of a trusted module are, but for one timing rule of edition `0.4`, not checked. The checker enforces it by its rules; the formal model in Lean proves it for a fragment of the language only (see [Known limits](https://una-lang.org/en/docs/known-limits/)). Learn more: [Labels and how they follow data](https://una-lang.org/en/learn/information-flow/labels-and-how-they-follow-data/), and [Sinks: where labeled data may go](https://una-lang.org/en/learn/information-flow/sinks-where-labeled-data-may-go/). ```una module shop pub keep(balance: secret Int) -> secret Int = balance + 1 pub flag(age: secret Int) -> secret Int = if age > 17 then 1 else 0 ``` ## Forms In the grammar below, each rule gives a name, `=`, what the name stands for and `;`, quoted words are written as shown, NEWLINE, INDENT and DEDENT stand for a line break and for one more or one less level of indentation, `[ ]` marks an optional part, `{ }` a part that may repeat, `|` separates alternatives, `( )` groups them, and `(* *)` holds a comment. ```ebnf type = [ label ] type_core [ "in" range ] ; label = level [ "[" upper_ident { "," upper_ident } "]" ] ; level = "public" | "internal" | "confidential" | "secret" | "restricted" ; ``` - **Levels**, in order: `public` < `internal` < `confidential` < `secret` < `restricted`. A type without a label is `public`. - **Categories**, in brackets: `secret[PII] Phone`. They are declared per package in `una.toml`, under [`[labels] categories`](https://una-lang.org/en/docs/configure/labels/categories/). - **Order.** A label is below another when its level is not higher and its categories are a subset. - **Position.** A label covers one position of a type: `internal Option[internal Int]` labels the option and its payload; a flow compares the labels at every position. ## Examples A value flows only upward. Returning `secret` data as `public` is rejected: ```una -- fails with U4001 module shop pub show_balance(balance: secret Int) -> Int = balance ``` Branching raises the program counter (the label of the conditions that decided whether a line runs; see [Branches and failures: implicit flows](https://una-lang.org/en/learn/information-flow/branches-and-failures-implicit-flows/)). A value chosen by a `secret` condition is `secret`, even when the branches are constants: ```una -- fails with U4001 module shop pub flag(age: secret Int) -> Int = if age > 17 then 1 else 0 ``` A capability operation is a sink (a place where data leaves the program), and accepts arguments only up to its label: `Console.print` accepts `public`. Interpolation keeps the label of what it interpolates: ```una -- fails with U4003 module shop pub print_balance(balance: secret Int) -> Unit uses @console: Console[print] = @console.print("{balance}") ``` Categories are declared in the package: `una.toml` ```toml [package] name = "shop" version = "0.1.0" edition = "0.2" [labels] categories = ["PII"] ``` `src/shop.una` ```una module shop pub tagged(birth_year: secret[PII] Int) -> secret[PII] Int = birth_year pub wider(birth_year: secret[PII] Int) -> restricted[PII] Int = birth_year ``` ## Validating sensitive data without revealing validity A validator can return a `Result` whose success payload and outer result are labeled `internal`, while keeping the error variant public. This lets a caller process the result without making a secret-dependent failure observable: ```una -- edition 0.3 module demo pub kind Positive = Int where it > 0 pub kind ValidationError = | NonPositive pub validate(value: internal Int) -> internal Result[internal Positive, ValidationError] = if value > 0 then Ok(value) else Err(NonPositive) test "valid" do validate(3) expect result is Ok test "invalid" do validate(0) expect result is Err ``` The success payload is constrained at its own position; the error type stays public, and the enclosing `Result` is internal. Returning `Err` on the invalid branch avoids a secret-dependent `fail`. The contrasting implementation below fails with U4002 because failure itself reveals the internal condition: ```una -- fails with U4002 module demo pub kind Positive = Int where it > 0 pub kind ValidationError = | NonPositive pub validate(value: internal Int) -> internal Positive fails ValidationError = if value > 0 then value else fail NonPositive ``` ## Edge cases **An undeclared category** is rejected: ```una -- fails with U4007 module shop pub tagged(birth_year: secret[PII] Int) -> secret[PII] Int = birth_year ``` **No failure that reveals.** Whether a function fails is observable, so `fail` is allowed only under a `public` program counter: ```una -- fails with U4002 module shop pub kind CreditError = | OverLimit pub spend(balance: secret Int) -> secret Int fails CreditError = if balance > 100 then fail OverLimit else balance ``` Further rules: - **Raising is free.** An `internal` value may flow where `secret` is expected. - **Lowering needs a policy** in a trusted module. See [`policy`](https://una-lang.org/en/docs/language/information-flow/policy/) and [trusted modules](https://una-lang.org/en/docs/language/information-flow/trusted/). - **Fields.** Reading a field joins the record's label with the field's declared label. - **Effects under the program counter.** A call is allowed under a raised program counter only when every effect it may perform accepts that label, and the function cannot fail (U4002). - **Examples are exempt.** `expect` lines observe values for the test harness and are not sinks. - **Outside the model.** Timing, termination, resource consumption and the order of effects across concurrent tasks, among others, are not covered, and `una report` lists them under `out_of_model`. The normative source gives the full list. ## Diagnostics - [U4001](https://una-lang.org/en/docs/errors/U4001/): a flow from a higher label to a lower one. - [U4002](https://una-lang.org/en/docs/errors/U4002/): a failure, or a call that may fail or act, under a labeled program counter. - [U4003](https://una-lang.org/en/docs/errors/U4003/): an argument above the label its operation accepts. - [U4007](https://una-lang.org/en/docs/errors/U4007/): a category not declared in `una.toml`. ## Edition Labels are the same in editions `0.1` and `0.2`, except at calls of generic functions: edition `0.2` raises only the positions of the result that can carry each type argument's labels, and edition `0.1` raises every position. Editions `0.3`, `0.4` and `0.5` keep the rules of edition `0.2` and add rules of their own, among them: from edition `0.3`, the answer of an operation carries the label that its header's `gives` names, and a boundary module never releases (`spec/13 §7`); from edition `0.4`, deadlines and races have timing labels, and a deadline or race outcome reaches the result of a `via` function only when its concurrent label is `public`. ## Normative source - `spec/07 §1`: the guarantee and its scope; `spec/07 §2`: labels; `spec/07 §3`: typing rules; `spec/07 §4`: sinks. - `spec/07 §7` rule 2: flows at every position; `spec/03 §5`: labeled types. - `spec/02 §2`: the grammar; `spec/13 §7`: `[labels] categories`. - Decision record: [ADR 0067](https://github.com/una-lang/una/blob/v0.4.0/docs/adr/0067-position-precise-result-labels-of-user-generic-functions.md), for the labels of a generic function's result. --- # policy: declassification ## What it does [Labels](https://una-lang.org/en/docs/language/information-flow/labels/) only rise, except through a `policy`: a declared, named release of data from one label to a lower one, through a function that the policy names. Lowering a label this way is called declassification. A policy lives in a [trusted module](https://una-lang.org/en/docs/language/information-flow/trusted/) (a module that `una.toml` lists as allowed to declare policies, and that `una report` lists for review), and every call of it is listed by `una report` with its purpose and owner. So every place where data goes down is visible and reviewed. Learn more: [Releasing data: policies and trusted modules](https://una-lang.org/en/learn/information-flow/releasing-data-policies-and-trusted-modules/). `una.toml` ```toml [package] name = "shop" version = "0.1.0" edition = "0.2" [labels] categories = ["Private"] [trusted] modules = ["shop.release"] ``` `src/shop/release.una` ```una trusted module shop.release pub policy length_band from confidential[Private] Text to public Nat via hundreds purpose "show how long a customer note is without showing it" owner support hundreds(text: confidential[Private] Text) -> public Nat = text.len / 100 ``` `src/shop/notes.una` ```una module shop.notes import shop.release (length_band) pub note_size(note: confidential[Private] Text) -> Nat = length_band(note) ``` ## Forms In the grammar below, each rule gives a name, `=`, what the name stands for and `;`, quoted words are written as shown, NEWLINE, INDENT and DEDENT stand for a line break and for one more or one less level of indentation, `[ ]` marks an optional part, `{ }` a part that may repeat, `|` separates alternatives, `( )` groups them, and `(* *)` holds a comment. ```ebnf policy_decl = [ "pub" ] "policy" lower_ident NEWLINE INDENT "from" type NEWLINE "to" type NEWLINE "via" lower_ident NEWLINE "purpose" text_lit NEWLINE "owner" lower_ident NEWLINE DEDENT ; ``` - **`from`** and **`to`**: the types before and after the release. The `via` function takes a `from` and returns a `to`, with the same types except for labels. - **`via`**: the private function of the trusted module that computes the release. - **`purpose`** and **`owner`**: why the release exists and who answers for it. `una report` lists them at every call. A policy `p` is called as a function, `p(v)`, with the `uses` and `fails` of its `via` function. ## Examples Above, `note_size` hands its caller a `public` number computed from `confidential` text: only the length band leaves, through `length_band`, and the note stays labeled. A policy is allowed only in a trusted module: `una.toml` ```toml [package] name = "shop" version = "0.1.0" edition = "0.2" [labels] categories = ["Private"] ``` `src/shop/release.una` ```una -- fails with U4004 module shop.release pub policy length_band from confidential[Private] Text to public Nat via hundreds purpose "show how long a customer note is without showing it" owner support hundreds(text: confidential[Private] Text) -> public Nat = text.len / 100 ``` ## Edge cases **The `via` function is private.** The policy is its only entry point, so no other code can call it with labeled data: `una.toml` ```toml [package] name = "shop" version = "0.1.0" edition = "0.2" [labels] categories = ["Private"] [trusted] modules = ["shop.release"] ``` `src/shop/release.una` ```una -- fails with U4005 trusted module shop.release pub policy length_band from confidential[Private] Text to public Nat via hundreds purpose "show how long a customer note is without showing it" owner support pub hundreds(text: confidential[Private] Text) -> public Nat = text.len / 100 ``` **No `requires` on `via`.** A policy call checks its argument against `from` only, so the `via` body may assume nothing more: `una.toml` ```toml [package] name = "shop" version = "0.1.0" edition = "0.2" [labels] categories = ["Private"] [trusted] modules = ["shop.release"] ``` `src/shop/release.una` ```una -- fails with U4005 trusted module shop.release pub policy length_band from confidential[Private] Text to public Nat via hundreds purpose "show how long a customer note is without showing it" owner support hundreds(text: confidential[Private] Text) -> public Nat requires text.len > 0 = text.len / 100 ``` **No release under a labeled program counter.** At a call `p(v)`, the program counter (the label of the conditions that decided whether this line runs; see [Branches and failures: implicit flows](https://una-lang.org/en/learn/information-flow/branches-and-failures-implicit-flows/)) must be below the `to` label. Choosing whether to release by a `secret` condition would reveal it: `una.toml` ```toml [package] name = "shop" version = "0.1.0" edition = "0.2" [labels] categories = ["Private"] [trusted] modules = ["shop.release"] ``` `src/shop/release.una` ```una trusted module shop.release pub policy length_band from confidential[Private] Text to public Nat via hundreds purpose "show how long a customer note is without showing it" owner support hundreds(text: confidential[Private] Text) -> public Nat = text.len / 100 ``` `src/shop/notes.una` ```una -- fails with U4002 module shop.notes import shop.release (length_band) pub note_size(note: confidential[Private] Text, flag: secret Bool) -> secret Nat = if flag then length_band(note) else 0 ``` Further rules: - **Inside `via`, labels are not checked.** The `via` function is part of the trusted code that `una report` lists under `tcb`; its refinements, preconditions and postconditions are still proven. - **Only through its policy.** Any use of a `via` function other than through its policy is U4005. - **Labeled failures.** The failure of a policy call is labeled by its `to` label joined with the program counter, so `if error pass` and `if error fail` on it are U4002 when that label is above `public`. One exception: a `via` function whose only failures are `Keys.hmac` calls with a literal key name, at the top level of its body and handled by `if error pass` or `if error fail` without a payload, decides nothing from the released value, so its policy's failure is labeled by the program counter alone. - **Keys.** The result of `Keys.hmac` is labeled `internal` joined with every label of its data; lowering it further takes a policy, such as one from `secret[PII] Phone` to `internal Hashed` whose `via` function computes the HMAC of a phone number. ## Diagnostics - [U4002](https://una-lang.org/en/docs/errors/U4002/): a policy call under a program counter above its `to` label, or `if error pass` or `if error fail` on a policy failure labeled above `public`. - [U4004](https://una-lang.org/en/docs/errors/U4004/): a policy outside a trusted module. - [U4005](https://una-lang.org/en/docs/errors/U4005/): a `via` function that is public, has a `requires` clause, is used other than through its policy, or whose types do not match the policy's. ## Edition Policies are the same in editions `0.1` and `0.2`. ## Normative source - `spec/07 §5`: declassification policies, rules 1 to 6; `spec/07 §6`: trusted modules. - `spec/02 §4`: the grammar. - `spec/13 §6`: the build report. - `spec/14 §3`: `Keys.hmac` and its labels. - `spec/10 §13.4`: a `via` function whose failure reveals nothing. - Decision record: [ADR 0039](https://github.com/una-lang/una/blob/v0.4.0/docs/adr/0039-labels-of-keys-hmac.md), for the labels of `Keys.hmac`. --- # trusted modules ## What it does A trusted module may hold declassification [policies](https://una-lang.org/en/docs/language/information-flow/policy/): declared releases of data to a lower [label](https://una-lang.org/en/docs/language/information-flow/labels/), the only code that lowers a label (marks data as less sensitive). A module is trusted only when two places agree: its header says `trusted module`, and the package lists it under [`[trusted] modules`](https://una-lang.org/en/docs/configure/trusted/modules/) in `una.toml`. The rest of its code is checked as usual. `una report` lists trusted modules and their line counts under `tcb` (the trusted computing base: the parts the guarantees rely on, which people review), so reviewers know exactly what to read. Learn more: [Releasing data: policies and trusted modules](https://una-lang.org/en/learn/information-flow/releasing-data-policies-and-trusted-modules/). `una.toml` ```toml [package] name = "shop" version = "0.1.0" edition = "0.2" [labels] categories = ["Private"] [trusted] modules = ["shop.release"] ``` `src/shop/release.una` ```una trusted module shop.release pub policy length_band from confidential[Private] Text to public Nat via hundreds purpose "show how long a customer note is without showing it" owner support hundreds(text: confidential[Private] Text) -> public Nat = text.len / 100 ``` `src/shop/notes.una` ```una module shop.notes import shop.release (length_band) pub note_size(note: confidential[Private] Text) -> Nat = length_band(note) ``` ## Forms In the grammar below, each rule gives a name, `=`, what the name stands for and `;`, quoted words are written as shown, NEWLINE, INDENT and DEDENT stand for a line break and for one more or one less level of indentation, `[ ]` marks an optional part, `{ }` a part that may repeat, `|` separates alternatives, `( )` groups them, and `(* *)` holds a comment. ```ebnf module_header = [ "trusted" ] "module" module_path NEWLINE ; ``` In `una.toml`, `[trusted] modules` is an array of module paths, each one of the package whose header says `trusted module`. ## Examples The header alone does not make a module trusted: `una.toml` ```toml [package] name = "shop" version = "0.1.0" edition = "0.2" [labels] categories = ["Private"] ``` `src/shop/release.una` ```una -- fails with U7005 trusted module shop.release pub policy length_band from confidential[Private] Text to public Nat via hundreds purpose "show how long a customer note is without showing it" owner support hundreds(text: confidential[Private] Text) -> public Nat = text.len / 100 ``` Without both, a policy has no place to live: `una.toml` ```toml [package] name = "shop" version = "0.1.0" edition = "0.2" [labels] categories = ["Private"] ``` `src/shop/release.una` ```una -- fails with U4004 module shop.release pub policy length_band from confidential[Private] Text to public Nat via hundreds purpose "show how long a customer note is without showing it" owner support hundreds(text: confidential[Private] Text) -> public Nat = text.len / 100 ``` ## Edge cases Further rules: - **Everything else is checked.** Only the `via` functions of policies skip label checks; every other declaration of a trusted module is checked normally, and every obligation of a `via` function is proven. - **Reported.** `una report` lists each trusted module with its line count under `tcb`. ## Reading the trust report Read the report fields separately: - `proven` gives the number of proven obligations as `semantic`; `security` and `authority` are `"by typing"`. A proof shows that the program keeps its contracts, not that the contracts capture the whole requirement or that an external system behaves as declared. - `assumptions` lists every capability the package declares, with its operations and their `ensures` clauses; those clauses are assumed of the implementation, not proven. - `escapes.checked` lists every module that uses `checked`, with its count and its budget. - `tcb` lists the trusted modules with their line counts, the host capabilities, the solver and the proof cache with its key. Line counts locate the code to review; they do not say whether a policy's purpose is appropriate. - `out_of_model` lists the channels outside the information-flow guarantee, such as timing, termination and divergence, resource consumption, hard links, and external systems beyond their declared signatures. A review of the report still compares each policy's purpose and owner with the requirement, and reads the assumptions and the excluded channels. These fields are defined in `spec/13 §6`; the information-flow scope is in `spec/07 §1`. ## Diagnostics - [U4004](https://una-lang.org/en/docs/errors/U4004/): a policy in a module that is not trusted. - [U7005](https://una-lang.org/en/docs/errors/U7005/): a module trusted in its header or in `una.toml`, but not in both. ## Edition Trusted modules are the same in editions `0.1` and `0.2`. From edition `0.3`, a preview, the language adds boundaries (groups of modules whose authority `una.toml`, or from edition `0.4` `ita.una`, caps): a module inside a boundary is never trusted, and a call into a boundary that could reach a policy call is rejected. See [`[boundaries]`](https://una-lang.org/en/docs/configure/boundaries/) and [A ceiling for a module: boundaries](https://una-lang.org/en/learn/authority/a-ceiling-for-a-module-boundaries/). ## Normative source - `spec/07 §6`: trusted modules, and from edition `0.3`, boundary modules that are never trusted; `spec/07 §5`: policies. - `spec/02 §1`: the module header. - `spec/13 §6`: the build report and its `tcb`; `spec/13 §7`: `[trusted] modules`. - Decision record: [ADR 0093](https://github.com/una-lang/una/blob/v0.4.0/docs/adr/0093-authority-at-module-boundaries.md), for boundaries. --- # requirement and derived from ## What it does A `requirement` records a human or business statement, with its source and its owner, so contracts (the conditions a function states with `requires` and `ensures`) can be traced to intent. A function names the requirements it implements with `derived from`. `una trace` then lists, for one requirement, every function derived from it, with its contract and the status of each proof. Learn more: [What the verifier proves, and what examples show](https://una-lang.org/en/learn/testing/what-the-verifier-proves-and-what-examples-show/). ```una module shop requirement EVENTS_3 text "An event with no remaining seats is always shown as sold out" source policy "Box Office Handbook 2.1" owner box_office status active pub kind Availability = SoldOut | Few | Open pub availability(remaining: Int) -> Availability requires remaining >= 0 ensures remaining == 0 implies result is SoldOut derived from EVENTS_3 = if remaining == 0 then SoldOut else if remaining < 20 then Few else Open ``` ## Forms In the grammar below, each rule gives a name, `=`, what the name stands for and `;`, quoted words are written as shown, NEWLINE, INDENT and DEDENT stand for a line break and for one more or one less level of indentation, `[ ]` marks an optional part, `{ }` a part that may repeat, `|` separates alternatives, `( )` groups them, and `(* *)` holds a comment. ```ebnf requirement_decl = "requirement" upper_ident NEWLINE INDENT "text" text_lit NEWLINE "source" source NEWLINE "owner" lower_ident NEWLINE "status" ( "proposed" | "active" ) NEWLINE DEDENT ; source = "human" | ( "policy" | "regulation" | "generated" ) text_lit ; ``` The fields: | Field | Values | | --- | --- | | `text` | The statement, as written by its source | | `source` | `human`, `policy ""`, `regulation ""`, `generated ""` | | `owner` | Team or person accountable (lower snake case) | | `status` | `proposed` or `active` | A requirement's identifier is upper snake case ending in `_` and a number, as `SHOP_1` or `EVENTS_3`; another form is U1005. **`derived from R1, R2`** is the last clause of a function header, at most once. ## Examples The function above proves the requirement's intent as a contract: `ensures remaining == 0 implies result is SoldOut`. The requirement says what people want; the contract says what the code guarantees, and the verifier (the part of `una check` that proves facts about the code) checks the contract. A requirement written by an agent is only proposed. A person activates it by changing its source: ```una -- fails with U1007 module shop requirement GEN_1 text "Seats are counted" source generated "task 42" owner agents status active ``` ## Edge cases **The identifier follows its convention**: ```una -- fails with U1005 module shop requirement Shipping text "Orders ship within two days" source human owner warehouse status active ``` **`derived from` names declared requirements**: ```una -- fails with U1006 module shop pub seats_left(remaining: Int) -> Int derived from NOPE_1 = remaining ``` **Identifiers are unique per package**: ```una -- fails with U1002 module shop requirement SHOP_1 text "Prices include sales tax" source human owner team status active requirement SHOP_1 text "Prices show sales tax apart" source human owner team status active ``` Further rules: - **Proposed requirements** do not block a build: functions derived from them compile normally, and the build report flags them. - **`una trace R`** checks the package at tier 1 (with the solver's proofs, as `una check` does by default), then prints the requirement and each function derived from it, with its `requires`, `ensures` and the status of each obligation (a fact that `una check` must prove). With `--json` it prints `una.trace/1`. - **Evidence is separate.** A requirement states intent, a contract guarantees it, and examples show it running. See [`example`](https://una-lang.org/en/docs/language/examples/example/), written [`test`](https://una-lang.org/en/docs/language/examples/test/) in edition `0.3`. ## Diagnostics - [U1002](https://una-lang.org/en/docs/errors/U1002/): a requirement identifier defined twice in a package. - [U1005](https://una-lang.org/en/docs/errors/U1005/): a requirement identifier that is not upper snake case ending in `_` and a number. - [U1006](https://una-lang.org/en/docs/errors/U1006/): `derived from` names an undeclared requirement. - [U1007](https://una-lang.org/en/docs/errors/U1007/): a requirement with source `generated` and status `active`. ## Edition Requirements are the same in editions `0.1` and `0.2`. ## Normative source - `spec/08 §1`: requirements, rules 1 to 4, and `una trace`. - `spec/02 §5`: the grammar; `spec/02 §3`: the `derived from` clause. - `spec/13 §5`: the command line; `spec/13 §6`: the build report. - `spec/01 §4`: the naming convention of requirement identifiers. - `spec/12 §1`: tiers of verification. --- # example ## What it does An `example` is executable evidence of behavior: a small test written beside the code it exercises, which `una test` runs. This is the declaration of editions `0.1` and `0.2`; edition `0.3` writes it [`test`](https://una-lang.org/en/docs/language/examples/test/), with the same lines and rules, and rejects `example` with a rewrite that `una fix` applies. Edition `0.4` writes it `test` as well, and there `example` is an ordinary name. Learn more: [Examples: do and expect](https://una-lang.org/en/learn/testing/examples-do-and-expect/), [Fakes: given, expect performed and expect not performed](https://una-lang.org/en/learn/testing/fakes-given-expect-performed-and-expect-not-performed/) and [Testing failures: expect fails](https://una-lang.org/en/learn/testing/testing-failures-expect-fails/). Its lines: - **`given`** lines install handlers (Una code that stands in for a capability, such as a fake store) for the capabilities (named authority over something outside the program, such as the console or a store) the code needs; - **`do`** runs the expression under test; - **`expect`** lines state what must hold: of its result, of its failure, or of the effects (actions outside the program, such as printing) it performed. ```una module shop pub kind OrderError = | TooMany pub add_units(units: Int) -> Int fails OrderError = if units > 100 then fail TooMany else units + 1 example "adding a unit" do add_units(1) expect result == 2 example "too many units" do add_units(101) expect fails TooMany ``` ## Forms In the grammar below, each rule gives a name, `=`, what the name stands for and `;`, quoted words are written as shown, NEWLINE, INDENT and DEDENT stand for a line break and for one more or one less level of indentation, `[ ]` marks an optional part, `{ }` a part that may repeat, `|` separates alternatives, `( )` groups them, and `(* *)` holds a comment. ```ebnf example_decl = "example" text_lit NEWLINE INDENT { "given" cap_ref "=" handler_call NEWLINE } "do" line_expr NEWLINE expectation { expectation } DEDENT ; handler_call = lower_ident "(" [ args ] ")" ; expectation = "expect" ( "fails" upper_ident | [ "not" ] "performed" cap_ref "." lower_ident | line_expr ) NEWLINE ; ``` The lines mean: | Line | Meaning | | --- | --- | | `given @x = h(args)` | Install handler `h` as capability `@x` for this example | | `do e` | The expression under test. It may have effects or fail; it needs no handling clauses | | `expect e` | `e` is a `Bool` expression over `result`; it must evaluate to `true` | | `expect fails V` | `do` failed with variant `V` | | `expect performed @x.op` | The trace (the record, in order, of the effects the run performed) contains at least one completed or failed `op` on binding `@x` | | `expect not performed @x.op` | The trace contains no `op` on binding `@x` | An example has at least one `expect` line. ## Examples A handler stands in for a capability, and the trace shows what the code did: ```una module shop pub capability Log op write(line: Text) -> Unit pub note(line: Text) -> Unit uses @log: Log[write] = @log.write(line) handler quiet() for Log op write(line) = unit example "notes once" given @log = quiet() do note("order 42 shipped") expect performed @log.write ``` Examples cannot use host capabilities, so they are deterministic. A capability the code needs comes from `given`: ```una -- fails with U3014 module shop pub greet(name: Text) -> Unit uses @console: Console[print] = @console.print("hi {name}") example "greets" do greet("ann") expect result == unit ``` ## Edge cases **Every capability `do` needs has a `given`**: ```una -- fails with U3001 module shop pub capability Log op write(line: Text) -> Unit pub note(line: Text) -> Unit uses @log: Log[write] = @log.write(line) example "missing handler" do note("order 42 shipped") expect result == unit ``` **`expect performed` names a declared operation**: ```una -- fails with U1001 module shop pub capability Log op write(line: Text) -> Unit pub note(line: Text) -> Unit uses @log: Log[write] = @log.write(line) handler quiet() for Log op write(line) = unit example "notes" given @log = quiet() do note("order 42 shipped") expect performed @log.erase ``` **Names are unique per module**: ```una -- fails with U1002 module shop pub double_price(cents: Int) -> Int = cents * 2 example "doubles" do double_price(2) expect result == 4 example "doubles" do double_price(3) expect result == 6 ``` Further rules: - **Checked like code.** Examples are type-checked, checked for where labeled data flows, and verified like any other code. Only `expect` lines are exempt from sink checks (the checks that labeled data reaches only places that accept it), since they observe values for the test harness. - **`do` lines may nest calls.** The one-effect-per-line rule does not apply to them: calls that can fail or have effects are evaluated left to right, and any failure ends the example. - **Order of expectations.** They are checked in order, and the first that does not hold fails the example. An `expect` over `result` after a failed `do` fails it with the failure shown; a `do` that failed with no `expect fails` line fails it too. An `expect` line that does not mention `result` still runs after a failed `do`, and an example whose run aborts fails. - **Fresh runs.** Each example runs in a fresh abstract machine (the model of a run that the specification defines), with nothing left from another example. `una test --json` reports, per example, the outcome, the failed expectation if any, and the full effect trace. ## Diagnostics - [U1001](https://una-lang.org/en/docs/errors/U1001/): `expect performed` names an operation the capability does not declare. - [U1002](https://una-lang.org/en/docs/errors/U1002/): an example name used twice in a module. - [U3001](https://una-lang.org/en/docs/errors/U3001/): a capability `do` needs that no `given` binds. - [U3014](https://una-lang.org/en/docs/errors/U3014/): an example that needs a host capability. - [U3020](https://una-lang.org/en/docs/errors/U3020/): in edition `0.3`, a `do` line that calls a boundary function that needs a capability; a `do` line takes no `with`, so it grants nothing. - [U3021](https://una-lang.org/en/docs/errors/U3021/): in edition `0.3`, a `given` handler of an example of a boundary module beyond the module's ceiling. ## Edition Examples are the same in editions `0.1` and `0.2`. In edition `0.3` the declaration is written [`test`](https://una-lang.org/en/docs/language/examples/test/) (ADR 0105): an `example` declaration there is U0103 with the exact rewrite of the keyword, which `una fix` applies. In edition `0.4` `example` is an ordinary name, with no U0103 and no rewrite (ADR 0105, amendment of 2026-11-05). Edition `0.3` also adds boundaries (modules whose authority `una.toml` limits, see [`[boundaries]`](https://una-lang.org/en/docs/configure/boundaries/)): the `given` handlers of an example of a boundary module count against its ceiling (U3021), and a `do` line that calls into a boundary from outside it grants it nothing by name (U3020). Learn more: [A ceiling for a module: boundaries](https://una-lang.org/en/learn/authority/a-ceiling-for-a-module-boundaries/). ## Normative source - `spec/08 §2`: examples, rules 1 to 7. - `spec/02 §5`: the grammar. - `spec/05 §9` rule 5: operations named in examples, and, in edition `0.3`, examples of boundary modules. - `spec/07 §4`: the sink exemption; `spec/04 §4`: one effect per line. - `spec/11 §5`: traces; `spec/13 §5`: `una test`. - Decision record: [ADR 0032](https://github.com/una-lang/una/blob/v0.4.0/docs/adr/0032-runtime-details-left-open.md), for the order of expectations after a failed `do`. --- # Loops that run until stopped: for ever, for until, stop and skip ## What it does A [`for`](https://una-lang.org/en/docs/language/control-flow/for/) loop over a list or a range runs a number of times that is known when it starts. Some programs need a loop whose end is not known in advance: - a loop that runs until a condition holds, such as "halve the number until it reaches 1"; - a loop that leaves early, such as "add up the orders until the total passes a limit"; - a loop that runs until someone stops the program, such as a worker that takes jobs, a poller or a game loop. Edition `0.4` (a preview) adds four things for these cases: - **`stop` and `skip`** end a loop early, or end one iteration (one run of the body) early. They work in every `for` loop. - **`for until c decreases m`** runs until the condition `c` holds. The measure `m` is a number that gets smaller in each iteration, so the verifier (the part of `una check` that proves facts about the program) can prove that the loop ends. - **`for ever`** runs its body again and again, with no end of its own. It ends by `stop`, by a failure of its body, or when the host (the program that runs yours: `una run`, or the operating system for an executable that `una build` wrote) asks it to stop. - **`on stop`**, a block after a `for ever`, runs once when the loop has ended, to clean up or report. A function that holds a `for ever` may never return, so it must say so in its header with the clause `diverges`. Every reader, and every caller, then sees that a call may run forever. ```una -- edition 0.4 module heartbeat pub main() -> Unit uses @console: Console[print] diverges = let edit beats = 0 for ever stop when beats == 3 @console.print("beat {beats}") beats = beats + 1 on stop @console.print("stopped after {beats} beats") @console.print("goodbye") ``` `una run`, and the executable that `una build` writes, both print: ```text beat 0 beat 1 beat 2 stopped after 3 beats goodbye ``` The run ends with exit code 0. The loop started a fourth iteration, `stop when beats == 3` held there, the loop ended, `on stop` ran with `beats` at 3, and execution went on after the loop. ## Forms In the grammar below, each rule gives a name, `=`, what the name stands for and `;`, quoted words are written as shown, NEWLINE, INDENT and DEDENT stand for a line break and for one more or one less level of indentation, `[ ]` marks an optional part, `|` separates alternatives, and `(* *)` holds a comment. ```ebnf stop_stmt = "stop" [ "when" line_expr ] NEWLINE ; skip_stmt = "skip" NEWLINE ; until_stmt = "for" "until" line_expr "decreases" add_expr NEWLINE INDENT block DEDENT ; ever_stmt = "for" "ever" [ "within" add_expr ] NEWLINE INDENT block DEDENT [ on_stop ] ; on_stop = "on" "stop" NEWLINE INDENT block DEDENT ; clause = ... | "diverges" NEWLINE ; (* after "fails" *) ``` - **`stop`** ends the innermost `for` loop around it. **`stop when c`** ends it when `c`, a `Bool`, holds, and does nothing otherwise. - **`skip`** ends the current iteration, and the loop goes on with the next one. It takes no `when`: write an `if` around it. - **`for until c decreases m`** checks `c` at the start of each iteration and ends the loop when it holds. `m` is an integer expression that the verifier reads and the program never evaluates. - **`for ever`** runs its body until something ends it. **`for ever within d`** gives each iteration a time limit `d` (see Edge cases). - **`on stop`** may follow only a `for ever`. - **`diverges`** is a clause of a function header, after `fails`. It is never inferred: a function that may run forever says it. The bindings that a loop updates (the `let edit` names declared before it) keep the values they have at the point where the loop or the iteration ends. After `stop`, those are the loop's final values; after `skip`, the next iteration starts with them. ## Examples **`stop` and `skip` in a loop over a list.** The total of the orders, leaving out the canceled ones, until it passes `limit`: ```una -- edition 0.4 module orders pub kind Order amount: Int cancelled: Bool pub total(orders: List[Order], limit: Int) -> Int = let edit total = 0 for order in orders if order.cancelled skip stop when total > limit total = total + order.amount total pub main() -> Unit uses @console: Console[print] = let first = Order(amount: 10, cancelled: false) let second = Order(amount: 99, cancelled: true) let third = Order(amount: 30, cancelled: false) let fourth = Order(amount: 5, cancelled: false) @console.print("total {total(orders: [first, second, third, fourth], limit: 35)}") ``` Both engines print `total 40`: 10 is added, the canceled 99 is skipped, 30 is added, and at the fourth order the total, 40, is over 35, so the loop stops before adding 5. `main` here does not say `diverges`: `stop` and `skip` need no clause, since a loop over a list always ends. **`for until` with a measure.** How many times a number can be halved before it reaches 1: ```una -- edition 0.4 module halving pub halvings(n: Int) -> Int requires n >= 1 = let edit value = n let edit steps = 0 for until value <= 1 decreases value value = value / 2 steps = steps + 1 steps pub main() -> Unit uses @console: Console[print] = @console.print("halvings of 100: {halvings(100)}") @console.print("halvings of 1: {halvings(1)}") ``` Both engines print `halvings of 100: 6` and `halvings of 1: 0`. For `halvings(1)` the condition holds before the first iteration, so the body never runs. The verifier proves two facts about the measure `value`: it is at least 0 wherever the loop goes on (there `value <= 1` is false, so `value >= 2`), and each iteration makes it smaller (`value / 2 < value` when `value >= 2`). A number that is never negative and always gets smaller cannot do so forever, so the loop ends. **A worker stopped by the host.** A `for ever` with no `stop` runs until the host asks it to end: ```una -- edition 0.4 module worker pub main() -> Unit uses @console: Console[print] diverges = let edit jobs = 0 for ever @console.print("job {jobs}") jobs = jobs + 1 on stop @console.print("finished {jobs} jobs") ``` The flag `--stop-after-iterations 3` gives each `for ever` a budget of three iterations. Here `una run . --stop-after-iterations 3`, and the executable run with the same flag, both print: ```text job 0 job 1 job 2 finished 3 jobs ``` and end with exit code 0. Without the flag, this program runs until it gets SIGINT (Ctrl-C in a terminal) or SIGTERM, or until the time given by `--deadline ` has passed. Each of those is a **host stop request**: the loop ends at the start of its next iteration, `on stop` runs, and the run ends with exit code 0. With `--deadline 1`, both engines print one line per job for about one second, then `finished N jobs`, where `N` depends on the speed of the machine, and end with exit code 0. **A test of a loop that never ends by itself.** A test (`una test`) may end with the line `stop after N`: each `for ever` of its run stops at the start of iteration `N + 1`. Time in a test is virtual, so `elapse` moves the clock at once and the test does not wait: ```una -- edition 0.4 module poller import std.testing (elapse) import std.time (Millisecond, millisecond, minute) pub capability Store op get(key: Text) -> Text pub kind Delay = Int of Millisecond where it >= 0 pub handler slow_store(delay: Delay) for Store op get(key) = elapse(delay) "v" pub poll(key: Text) -> Int uses @store: Store[get] diverges = let edit reads = 0 for ever let value = @store.get(key) reads = reads + 1 reads test "the loop reads the store three times, then stops" given @store = slow_store(delay: 60 * minute) do poll("k") expect result == 3 stop after 3 ``` `una test` reports `1 test: 1 passed, 0 failed`. Each read takes an hour of virtual time, and the test takes no time on the wall clock. ## Host stops A host stop is how a program that runs forever is ended from outside, while still getting to clean up. These are the requests: | Request | How it is made | |---|---| | SIGINT or SIGTERM | Ctrl-C, `kill`, a service manager stopping the program | | `--deadline ` | the run asks itself to stop that many seconds after it started (1 to 31,536,000) | After the first request: 1. Every `for ever` that reaches the start of an iteration ends there, as if by `stop`, keeping its bindings, and its `on stop` runs. A loop entered after the request ends at its first iteration start. 2. An `Http` operation that is waiting in the body of a `for ever` fails with `HttpError.Interrupted`, so a loop blocked on the network does not hold the stop up. 3. Code outside every `for ever`, the `on stop` blocks included, runs on normally. A request is sticky: once one has arrived, it stays for the rest of the run. **Grace and the hard stop.** The cleanup is given a limited time. `--stop-grace ` (1 to 86,400, 10 when not given) is how long the run may go on after the first request. At the end of that time, or at a second request, whichever comes first, the **hard stop** cancels the run at its next call or loop iteration, `on stop` blocks included. The run then ends with U6007 and exit code 1. This `on stop` takes far longer than one second: ```una -- edition 0.4 module slow_cleanup pub main() -> Unit uses @console: Console[print] diverges = let edit rounds = 0 for ever rounds = rounds + 1 on stop @console.print("cleaning up") let edit left = 0 for i in 0..<2_000_000_000 left = left + 1 @console.print("cleaned up") ``` Run with `--deadline 1 --stop-grace 1`, it prints `cleaning up` and then, in both engines, never `cleaned up` but: ```text [U6007] Error: the host stopped the run before it finished, after the grace period of 1 second ``` Sending SIGINT twice gives the same error, ending "at a second host stop request". A third request ends the process with SIGTERM even when it is stuck in an operation that cannot be interrupted. **Only programs that can run forever take signals this way.** A run installs its handlers of SIGINT and SIGTERM only when its `main` says `diverges` or the host runs its loop (the `drive` section of `spec/26 §2`). Every other run keeps the default actions, so a signal ends it at once, as before. **The iteration budget is not a request.** `--stop-after-iterations `, and a test's `stop after N`, give each loop instance (each entry into a `for ever`) its own budget of `n` iterations, counted from 0. Reaching it ends that loop alone: it interrupts no operation, reaches no other loop and starts no grace period. Two loops in a row each run `n` iterations. This keeps the number of iterations one loop ran, maybe under a `secret` branch, from changing where another loop stops. **`--virtual-time`** gives a run the clock that tests have: it starts at 0, never waits on the wall clock, and moves only when the run waits on time. It is accepted for a package of any edition, and both engines then give the same output and trace, the readings of `Clock.now` included. It matters most for a program whose loop the host drives, whose ticks it delivers at once. ## Edge cases **`for ever` needs `diverges`.** A `for ever` in a function whose header does not say `diverges` is refused, and so is a call of a function that says it: ```una -- edition 0.4 -- fails with U3027 module sites pub spin() -> Unit = for ever stop ``` The message is "`for ever` may run forever here: its function does not say `diverges`; add `diverges` to the header of a function that may run forever". `for ever`, and calls of a `diverges` function, are also refused inside a lambda, a `together` task, an `on stop` block and the body of another `for ever`: each iteration must end, so only the code around the loop may run forever. A test may call a `diverges` function only on its `do` line and only when it ends with `stop after N`. **A `diverges` function is not a value.** It can only be called by name, never stored or passed, since a call through a value would hide that it may run forever: ```una -- edition 0.4 -- fails with U3028 module values pub spin() -> Unit diverges = for ever stop pub held() -> Int = let f = spin 1 ``` **A failure of the body.** When the body of a `for ever` fails, `on stop` still runs, with the bindings at their values from before the loop, and then the failure goes on to the caller. With `strokes` counting from 0 and `fail Jammed` when it reaches 2, `main` prints `stroke 0`, `stroke 1` and `on stop sees 0 strokes`, then ends with U6001, "`main` failed with `Jammed`", exit code 1, in both engines. **`on stop` must not fail.** It runs when the loop has already ended, and maybe in the middle of a stop, so there is nobody left to hand a failure to. Each fallible call in it is handled where it is: ```una -- edition 0.4 -- fails with U3029 module tidy pub kind TidyError = | Busy pub tidy(n: Int) -> Unit fails TidyError = if n > 5 fail Busy unit pub run() -> Unit fails TidyError diverges = let edit n = 0 for ever stop when n == 3 n = n + 1 on stop tidy(n) ``` Writing `tidy(n)` with `if error use unit` on the next line handles the failure, and the module checks. **`on stop` follows only a `for ever`.** A loop over a list or a range always ends by itself, so the statements after it do the same work: ```una -- edition 0.4 -- fails with U2034 module tally pub count(xs: List[Int]) -> Int = let edit n = 0 for x in xs n = n + 1 on stop n = 0 n ``` **`stop` and `skip` belong to a loop body.** Outside every loop they are U2034. The body of a `together for` and a branch of `together` are tasks, not loops, so a `stop` there cannot reach a loop around them either. **Code after `stop` or `skip` never runs.** A statement after an unconditional `stop` or `skip` in the same block is refused: ```una -- edition 0.4 -- fails with U2040 module dead pub count(xs: List[Int]) -> Int = let edit n = 0 for x in xs skip n = n + 1 n ``` Statements after `stop when c`, or after an `if` that holds the `stop`, are legal, since they run when the condition is false. **`for until` needs a measure that decreases.** Without `decreases` the loop is a syntax error, U0101, "`for until` needs a `decreases` measure". A measure that the verifier cannot show to get smaller is U5001: ```una -- edition 0.4 -- fails with U5001 module countdown pub count_down(n: Int) -> Int requires n >= 0 = let edit value = n for until value <= 0 decreases value value = value + 1 value ``` The message is "the measure `value` may not decrease in this iteration". A path that ends at `stop` needs neither fact, since it ends the loop. **Whether a loop stops must not reveal a secret.** If `stop when c` depends on a `secret` value, the number of iterations, and so everything printed after the loop, would show it: ```una -- edition 0.4 -- fails with U4002 module limits pub count(xs: List[Int], limit: secret Int) -> Int = let edit n = 0 for x in xs stop when x > limit n = n + 1 n ``` A `skip` under a branch on a labeled value is legal: the rest of the body is then checked under that label. **`for ever within d`.** Each iteration gets the deadline `d` after its start, an `Int of Millisecond` from `std.time`. An `Http` operation still waiting when it passes fails with `HttpError.TimedOut`, the iteration runs on to its end, and the next iteration gets a new deadline. A plain number is U2028, "the deadline of `for ever within` is an `Int of Millisecond` from `std.time`, found `Int`": ```una -- edition 0.4 -- fails with U2028 module paced pub run() -> Unit diverges = let edit n = 0 for ever within 100 stop when n == 2 n = n + 1 ``` Written `within 100 * millisecond`, with `import std.time (millisecond)`, it checks. A body that reads `secret` data and calls `Http` under a deadline is refused (U4001 at the loop), since whether a request times out depends on how long the iteration took. **Termination and correctness.** A `for ever` body must end each iteration: its other loops are bounded or are `for until` loops the verifier proves, and recursion is bounded by `--max-depth`. A function that says `diverges` keeps its `ensures`: the fact holds whenever it returns, and nothing is claimed when it does not. **When to use which.** Use a `for` over a list or a range when the number of iterations is known, with `stop` and `skip` to leave early. Use `for until` when the loop ends on a condition you can measure. Use `for ever` with `diverges` only for a program, or a part of one, that should run until it is stopped: a server, a worker, a poller. Use the [`drive` section](https://una-lang.org/en/docs/spec/26-long-running-programs/#s2) instead when the loop runs on a fixed tick, such as a game. ## Diagnostics - [U0101](https://una-lang.org/en/docs/errors/U0101/): `for until` without `decreases`, or `stop when`, `for ever` and `diverges` before edition `0.4`. - [U2028](https://una-lang.org/en/docs/errors/U2028/): the deadline of `for ever within` is not an `Int of Millisecond`. - [U2034](https://una-lang.org/en/docs/errors/U2034/): `stop` or `skip` outside a loop body, or `on stop` after a loop other than `for ever`. - [U2040](https://una-lang.org/en/docs/errors/U2040/): a statement after an unconditional `stop` or `skip`. - [U3027](https://una-lang.org/en/docs/errors/U3027/): `for ever`, or a call of a `diverges` function, where it may not run forever. - [U3028](https://una-lang.org/en/docs/errors/U3028/): a `diverges` function named other than as a callee. - [U3029](https://una-lang.org/en/docs/errors/U3029/): a statement of `on stop` that can fail. - [U4002](https://una-lang.org/en/docs/errors/U4002/): a `stop` whose condition, or whose branch, depends on labeled data. - [U5001](https://una-lang.org/en/docs/errors/U5001/): a measure of `for until` that may not decrease, or may be negative. - [U6001](https://una-lang.org/en/docs/errors/U6001/): `main` failed, also when the failure came from the body of a `for ever`. - [U6007](https://una-lang.org/en/docs/errors/U6007/): the hard stop canceled the run. ## Edition These forms exist only in editions `0.4` and `0.5`, previews, which a package names in `ita.una`. In edition `0.3`, `stop`, `skip`, `ever` and `until` are identifiers, and `diverges` and `within` are names too, so the forms do not parse: ```una -- edition 0.3 -- fails with U0101 module olds pub count(xs: List[Int]) -> Int = let edit n = 0 for x in xs stop when x > 3 n = n + 1 n ``` In edition `0.4`, `diverges` and `within` are reserved words and cannot be names. `stop`, `skip`, `ever`, `until` and `decreases` stay names where they do not start these forms, so `for ever in xs` is a loop over `xs` whose variable is `ever`. ## Normative source - `spec/26 §1`: the edition and its reserved words. - `spec/26 §3`: `stop` and `skip`; `spec/26 §4`: `for until c decreases m`. - `spec/26 §5`: `diverges`, `for ever` and `on stop`. - `spec/26 §6`: host stops, the flags, signal handlers, grace and the hard stop. - `spec/26 §7`: `for ever within d`; `spec/26 §8`: `stop after N` and virtual time. - `spec/26 §2`: the host-driven step, for a loop the host runs. - Decision record: [ADR 0116](https://github.com/una-lang/una/blob/v0.4.0/docs/adr/0116-long-running-programs.md). - Conformance cases: `tests/conformance/runtime/for_ever_on_stop`, `tests/conformance/runtime/for_ever_failure_on_stop`, `tests/conformance/runtime/loop_stop_and_skip`, `tests/conformance/runtime/stop_after_per_loop`, `tests/conformance/runtime/test_stop_after`, `tests/conformance/authority/diverges_sites`, `tests/conformance/authority/diverges_not_a_value`. --- # test ## What it does A `test` is executable evidence of behavior: a small test written beside the code it exercises, which `una test` runs. It is the declaration of editions `0.3` to `0.5`; editions `0.1` and `0.2` write it [`example`](https://una-lang.org/en/docs/language/examples/example/), with the same lines and rules. Learn more: [Examples: do and expect](https://una-lang.org/en/learn/testing/examples-do-and-expect/), [Fakes: given, expect performed and expect not performed](https://una-lang.org/en/learn/testing/fakes-given-expect-performed-and-expect-not-performed/) and [Testing failures: expect fails](https://una-lang.org/en/learn/testing/testing-failures-expect-fails/). Its lines: - **`given`** lines install handlers (Una code that stands in for a capability, such as a fake store) for the capabilities (named authority over something outside the program, such as the console or a store) the code needs; - **`do`** runs the expression under test; - **`expect`** lines state what must hold: of its result, of its failure, or of the effects (actions outside the program, such as printing) it performed. ```una -- edition 0.3 module shop pub kind OrderError = | TooMany pub add_units(units: Int) -> Int fails OrderError = if units > 100 then fail TooMany else units + 1 test "adding a unit" do add_units(1) expect result == 2 test "too many units" do add_units(101) expect fails TooMany ``` ## Forms In the grammar below, each rule gives a name, `=`, what the name stands for and `;`, quoted words are written as shown, NEWLINE, INDENT and DEDENT stand for a line break and for one more or one less level of indentation, `[ ]` marks an optional part, `{ }` a part that may repeat, `|` separates alternatives, `( )` groups them, and `(* *)` holds a comment. ```ebnf test_decl = "test" text_lit NEWLINE INDENT { "given" cap_ref "=" handler_call NEWLINE } "do" line_expr NEWLINE expectation { expectation } DEDENT ; handler_call = lower_ident "(" [ args ] ")" ; expectation = "expect" ( "fails" upper_ident | [ "not" ] "performed" cap_ref "." lower_ident | line_expr ) NEWLINE ; ``` The lines mean: | Line | Meaning | | --- | --- | | `given @x = h(args)` | Install handler `h` as capability `@x` for this test | | `do e` | The expression under test. It may have effects or fail; it needs no handling clauses | | `expect e` | `e` is a `Bool` expression over `result`; it must evaluate to `true` | | `expect fails V` | `do` failed with variant `V` | | `expect performed @x.op` | The trace (the record, in order, of the effects the run performed) contains at least one completed or failed `op` on binding `@x` | | `expect not performed @x.op` | The trace contains no `op` on binding `@x` | A test has at least one `expect` line. ## Examples A handler stands in for a capability, and the trace shows what the code did: ```una -- edition 0.3 module shop pub capability Log op write(line: Text) -> Unit pub note(line: Text) -> Unit uses @log: Log[write] = @log.write(line) handler quiet() for Log op write(line) = unit test "notes once" given @log = quiet() do note("order 42 shipped") expect performed @log.write ``` Examples cannot use host capabilities, so they are deterministic. A capability the code needs comes from `given`: ```una -- fails with U3014 -- edition 0.3 module shop pub greet(name: Text) -> Unit uses @console: Console[print] = @console.print("hi {name}") test "greets" do greet("ann") expect result == unit ``` ## Edge cases **Every capability `do` needs has a `given`**: ```una -- fails with U3001 -- edition 0.3 module shop pub capability Log op write(line: Text) -> Unit pub note(line: Text) -> Unit uses @log: Log[write] = @log.write(line) test "missing handler" do note("order 42 shipped") expect result == unit ``` **`expect performed` names a declared operation**: ```una -- fails with U1001 -- edition 0.3 module shop pub capability Log op write(line: Text) -> Unit pub note(line: Text) -> Unit uses @log: Log[write] = @log.write(line) handler quiet() for Log op write(line) = unit test "notes" given @log = quiet() do note("order 42 shipped") expect performed @log.erase ``` **Names are unique per module**: ```una -- fails with U1002 -- edition 0.3 module shop pub double_price(cents: Int) -> Int = cents * 2 test "doubles" do double_price(2) expect result == 4 test "doubles" do double_price(3) expect result == 6 ``` Further rules: - **Checked like code.** Examples are type-checked, checked for where labeled data flows, and verified like any other code. Only `expect` lines are exempt from sink checks (the checks that labeled data reaches only places that accept it), since they observe values for the test harness. - **`do` lines may nest calls.** The one-effect-per-line rule does not apply to them: calls that can fail or have effects are evaluated left to right, and any failure ends the example. - **Order of expectations.** They are checked in order, and the first that does not hold fails the example. An `expect` over `result` after a failed `do` fails it with the failure shown; a `do` that failed with no `expect fails` line fails it too. An `expect` line that does not mention `result` still runs after a failed `do`, and an example whose run aborts fails. - **Fresh runs.** Each example runs in a fresh abstract machine (the model of a run that the specification defines), with nothing left from another example. `una test --json` reports, per example, the outcome, the failed expectation if any, and the full effect trace. ## Diagnostics - [U1001](https://una-lang.org/en/docs/errors/U1001/): `expect performed` names an operation the capability does not declare. - [U1002](https://una-lang.org/en/docs/errors/U1002/): an example name used twice in a module. - [U3001](https://una-lang.org/en/docs/errors/U3001/): a capability `do` needs that no `given` binds. - [U3014](https://una-lang.org/en/docs/errors/U3014/): an example that needs a host capability. - [U3020](https://una-lang.org/en/docs/errors/U3020/): in edition `0.3`, a `do` line that calls a boundary function that needs a capability; a `do` line takes no `with`, so it grants nothing. - [U3021](https://una-lang.org/en/docs/errors/U3021/): in edition `0.3`, a `given` handler of an example of a boundary module beyond the module's ceiling. ## Edition In edition `0.3` the declaration is written `test`, and `test` is a keyword there: a local named `test` is renamed by `una fix` to `test_value`, and a function, field, handler or module named `test` needs another name (U0101). An `example` declaration in an edition `0.3` package is U0103, "`example` is written `test` in edition 0.3", and `una fix` rewrites the keyword; the body does not change. Editions `0.1` and `0.2` keep [`example`](https://una-lang.org/en/docs/language/examples/example/) and `test` as a name. In edition `0.4` the declaration is `test` too, and `example` is an ordinary name: a function, a local, a field or a module may be called `example`, and a line `example "..."` is a plain syntax error (U0101) with no rewrite, since `una fix` rewrites `example` in edition `0.3` packages only (ADR 0105, amendment of 2026-11-05). `una test` prints `test "" ... ok` and ` tests: ...` for an edition `0.3` package, and its `--json` is `una.test/2`, with the key `tests` where `una.test/1` has `examples`. Edition `0.3` also adds boundaries (modules whose authority `una.toml` limits, see [`[boundaries]`](https://una-lang.org/en/docs/configure/boundaries/)): the `given` handlers of an example of a boundary module count against its ceiling (U3021), and a `do` line that calls into a boundary from outside it grants it nothing by name (U3020). Learn more: [A ceiling for a module: boundaries](https://una-lang.org/en/learn/authority/a-ceiling-for-a-module-boundaries/). ## Normative source - `spec/08 §2`: tests, rules 1 to 7; `spec/01 §5`: the keyword `test` and `example` in edition `0.3`. - `spec/02 §5`: the grammar. - `spec/05 §9` rule 5: operations named in examples, and, in edition `0.3`, examples of boundary modules. - `spec/07 §4`: the sink exemption; `spec/04 §4`: one effect per line. - `spec/11 §5`: traces; `spec/13 §5`: `una test`. - Decision records: [ADR 0105](https://github.com/una-lang/una/blob/v0.4.0/docs/adr/0105-the-test-declaration.md), the declaration is written `test` in edition `0.3`; [ADR 0032](https://github.com/una-lang/una/blob/v0.4.0/docs/adr/0032-runtime-details-left-open.md), for the order of expectations after a failed `do`. --- # Units of measure ## What it does A unit is part of an integer type. `Int of Meter` and `Int of Second` are distinct, so the checker rejects mixing them before the program runs. Units exist only during checking: they are erased from runtime values and outputs. Use `measure` declarations for base units and derived scales, then write `of` on an integer type. ```una -- edition 0.3 module shop pub measure Meter pub measure Kilometer = 1000 * Meter pub measure Second pub kind Speed = Int of Meter / Second in 0..300 pub distance(km: Int of Kilometer) -> Int of Meter = km.convert() ``` ## Forms ```ebnf measure_decl = [ "pub" ] "measure" upper_ident [ "=" unit_expr ] NEWLINE ; type = [ label ] type_core [ "of" unit_expr ] [ "in" range ] ; unit_expr = unit_term { ( "*" | "/" ) unit_term } ; unit_term = upper_ident | "(" unit_expr ")" | integer_literal ; ``` - A declaration without `=` introduces a base unit. A declaration with `=` defines a derived unit using declared units and positive integer factors. - `of` follows an integer type, including fixed-width integer types. For example, `Int of Meter`, `I64 of Second`, and `Int of Meter / Second`. - `+`, `-`, `mod`, the comparisons and `in` need one unit on both sides. `*` multiplies the operands' units, and `/` divides them. - `measured()` gives a unitless integer the unit required by its expected type. `magnitude()` deliberately drops a measured value's unit. `convert()` converts to the expected unit when it has the same dimension and the ratio of the scales, source over target, is a positive integer. ## Examples Conversions use the expected return type. The unit remains part of the result type: ```una -- edition 0.3 module shop pub measure Meter pub measure Kilometer = 1000 * Meter pub kilometers_to_meters(km: Int of Kilometer) -> Int of Meter = km.convert() pub meters_from_raw(value: Int) -> Int of Meter = value.measured() pub display_magnitude(distance: Int of Meter) -> Int = distance.magnitude() ``` Adding matching units is accepted, while a unitless literal takes the other operand's unit: ```una -- edition 0.3 module shop pub measure Meter pub add(distance: Int of Meter) -> Int of Meter = distance + 5 ``` ## Edge cases **Different dimensions do not mix.** Convert only between units of the same dimension. `magnitude()` removes the dimensional guarantee and should be used only when the raw count is intended: ```una -- edition 0.3 -- fails with U2028 module shop pub measure Meter pub measure Second pub add(distance: Int of Meter, elapsed: Int of Second) -> Int of Meter = distance + elapsed ``` **Conversions need a target type.** Without an expected unit, the checker cannot choose the converted scale. A conversion from meters to kilometers also is not exact; make any division explicit through `magnitude()` and `measured()` where appropriate: ```una -- edition 0.3 -- fails with U2030 module shop pub measure Meter pub measure Kilometer = 1000 * Meter pub convert_without_target(distance: Int of Kilometer) -> Bool = let value = distance.convert() true ``` **Units are compile-time only.** Interpolation and JSON expose the magnitude, without a unit name. `magnitude()` has the same effect in the type system: it returns an ordinary integer. ## Diagnostics - [U2028](https://una-lang.org/en/docs/errors/U2028/): values of different units meet, or a measured and unitless value meet. - [U2030](https://una-lang.org/en/docs/errors/U2030/): `measured()` or `convert()` lacks an expected unit, or a conversion is not exact. ## Edition Edition `0.3`, a preview. In editions `0.1` and `0.2`, a `measure` declaration and `of` after a type are syntax errors (U0101). Edition `0.4` has every construct of edition `0.3` (`spec/13 §7`). ## Normative source - `spec/25 §1`: declarations; `§2`: measured types; `§3`: arithmetic and comparison; `§5`: conversions; `§8`: diagnostics. - `spec/02 §1`: the grammar of `measure` and `of`; `spec/03 §2`: kinds; `spec/18`: the fixed-width integer types, which may carry a unit. - Decision record: [ADR 0104](https://github.com/una-lang/una/blob/v0.4.0/docs/adr/0104-units-of-measure.md), which targets units to edition `0.3` as a preview construct. --- # Diagnostics Every diagnostic code of the compiler, with the same explanation that `una explain ` prints: what it means, a failing example and a fixed one. 121 codes at v0.4.0. ## U0xx | Code | Meaning | | --- | --- | | [U0001](https://una-lang.org/en/docs/errors/U0001/) | Invalid character, byte order mark or lone carriage return | | [U0002](https://una-lang.org/en/docs/errors/U0002/) | Tab in indentation | | [U0003](https://una-lang.org/en/docs/errors/U0003/) | Inconsistent indentation | | [U0004](https://una-lang.org/en/docs/errors/U0004/) | Unterminated text literal | | [U0005](https://una-lang.org/en/docs/errors/U0005/) | Invalid escape sequence | | [U0006](https://una-lang.org/en/docs/errors/U0006/) | Text literal inside interpolation | | [U0007](https://una-lang.org/en/docs/errors/U0007/) | Malformed literal | | [U0101](https://una-lang.org/en/docs/errors/U0101/) | Unexpected token | | [U0102](https://una-lang.org/en/docs/errors/U0102/) | Clause out of order or repeated | | [U0103](https://una-lang.org/en/docs/errors/U0103/) | Reserved keyword not available in the package's edition | ## U1xx | Code | Meaning | | --- | --- | | [U1001](https://una-lang.org/en/docs/errors/U1001/) | Unresolved name | | [U1002](https://una-lang.org/en/docs/errors/U1002/) | Duplicate definition | | [U1003](https://una-lang.org/en/docs/errors/U1003/) | Import cycle | | [U1004](https://una-lang.org/en/docs/errors/U1004/) | Use of a private declaration from another module | | [U1005](https://una-lang.org/en/docs/errors/U1005/) | Naming convention violation | | [U1006](https://una-lang.org/en/docs/errors/U1006/) | Undeclared requirement in `derived from` | | [U1007](https://una-lang.org/en/docs/errors/U1007/) | Generated requirement marked active | | [U1008](https://una-lang.org/en/docs/errors/U1008/) | Module path does not match file path | | [U1009](https://una-lang.org/en/docs/errors/U1009/) | Reserved module name | | [U1010](https://una-lang.org/en/docs/errors/U1010/) | A module whose first path segment is a dependency's local name | ## U2xx | Code | Meaning | | --- | --- | | [U2001](https://una-lang.org/en/docs/errors/U2001/) | Type mismatch | | [U2002](https://una-lang.org/en/docs/errors/U2002/) | Unknown or ill-formed type | | [U2003](https://una-lang.org/en/docs/errors/U2003/) | Wrong number of type arguments | | [U2004](https://una-lang.org/en/docs/errors/U2004/) | Missing argument label | | [U2005](https://una-lang.org/en/docs/errors/U2005/) | Unknown argument label | | [U2006](https://una-lang.org/en/docs/errors/U2006/) | Duplicate argument | | [U2007](https://una-lang.org/en/docs/errors/U2007/) | Non-exhaustive `when` over variants | | [U2008](https://una-lang.org/en/docs/errors/U2008/) | Unreachable arm or misplaced `else` | | [U2009](https://una-lang.org/en/docs/errors/U2009/) | Missing or unknown field in constructor | | [U2010](https://una-lang.org/en/docs/errors/U2010/) | Cannot infer lambda parameter type | | [U2011](https://una-lang.org/en/docs/errors/U2011/) | Statement value is not `Unit` | | [U2012](https://una-lang.org/en/docs/errors/U2012/) | `result` outside `ensures` or `expect` | | [U2013](https://una-lang.org/en/docs/errors/U2013/) | `it` or `error` outside its allowed position | | [U2014](https://una-lang.org/en/docs/errors/U2014/) | Expression outside the refinement language | | [U2015](https://una-lang.org/en/docs/errors/U2015/) | Invalid predicate body (impure, failing, recursive or outside RL for `reflect`) | | [U2016](https://una-lang.org/en/docs/errors/U2016/) | Opaque predicate called outside `checked` | | [U2017](https://una-lang.org/en/docs/errors/U2017/) | Use of a binding after it was passed by `take` | | [U2018](https://una-lang.org/en/docs/errors/U2018/) | An `edit` argument together with another use of its binding in the same call | | [U2019](https://una-lang.org/en/docs/errors/U2019/) | Assignment to a binding that is not editable | | [U2020](https://una-lang.org/en/docs/errors/U2020/) | A parameter convention (`edit`, `take`) not matched at the call site, or declared where none is allowed | | [U2021](https://una-lang.org/en/docs/errors/U2021/) | A function with `edit` or `take` parameters used as a value | | [U2022](https://una-lang.org/en/docs/errors/U2022/) | Integer literal does not fit its type | | [U2023](https://una-lang.org/en/docs/errors/U2023/) | A binding declared outside a `together` branch assigned, or passed as `edit` or `take`, inside it | | [U2024](https://una-lang.org/en/docs/errors/U2024/) | A `together` body with a statement other than `let`, or fewer than two branches | | [U2025](https://una-lang.org/en/docs/errors/U2025/) | A type argument does not satisfy the constraint of its parameter | | [U2026](https://una-lang.org/en/docs/errors/U2026/) | An operation on a type parameter that its constraint does not allow | | [U2027](https://una-lang.org/en/docs/errors/U2027/) | An unknown constraint name | | [U2028](https://una-lang.org/en/docs/errors/U2028/) | Values of different units meet, or a measured and a unitless value | | [U2029](https://una-lang.org/en/docs/errors/U2029/) | An invalid unit declaration or unit expression | | [U2030](https://una-lang.org/en/docs/errors/U2030/) | A unit conversion without an expected unit, or not exact | | [U2031](https://una-lang.org/en/docs/errors/U2031/) | A float literal rounds to an infinity, or is not zero and rounds to zero | | [U2032](https://una-lang.org/en/docs/errors/U2032/) | A float literal other than zero, or a float range, as a pattern | | [U2033](https://una-lang.org/en/docs/errors/U2033/) | A comparison of an `F64` with a float literal zero | | [U2034](https://una-lang.org/en/docs/errors/U2034/) | `stop` or `skip` outside a loop body, or across a task boundary | | [U2035](https://una-lang.org/en/docs/errors/U2035/) | `first of` with fewer than two branches, or a line that is not an expression; `start` outside the block of a `tasks`, inside a task within it, or with a `with` clause | | [U2037](https://una-lang.org/en/docs/errors/U2037/) | A decimal scale out of place | | [U2038](https://una-lang.org/en/docs/errors/U2038/) | A tensor shape, index, permutation or axis out of place | | [U2039](https://una-lang.org/en/docs/errors/U2039/) | A `map`, `zip_map` or `update` in a function with `simd required` whose lambda cannot be vectorized for a listed target | | [U2040](https://una-lang.org/en/docs/errors/U2040/) | A statement after `stop` or `skip` in the same block, which never runs | ## U3xx | Code | Meaning | | --- | --- | | [U3001](https://una-lang.org/en/docs/errors/U3001/) | Capability not in scope | | [U3002](https://una-lang.org/en/docs/errors/U3002/) | Operation not permitted by capability type | | [U3003](https://una-lang.org/en/docs/errors/U3003/) | Effects exceed declared `uses` | | [U3004](https://una-lang.org/en/docs/errors/U3004/) | Capability used in a pure function | | [U3005](https://una-lang.org/en/docs/errors/U3005/) | Capability reference used as a value | | [U3006](https://una-lang.org/en/docs/errors/U3006/) | Effectful or failing lambda escapes | | [U3007](https://una-lang.org/en/docs/errors/U3007/) | Fallible expression without handling | | [U3008](https://una-lang.org/en/docs/errors/U3008/) | `if error pass` with a different error kind | | [U3009](https://una-lang.org/en/docs/errors/U3009/) | Failure variant not in the declared error kind | | [U3010](https://una-lang.org/en/docs/errors/U3010/) | Handler does not match its capability | | [U3011](https://una-lang.org/en/docs/errors/U3011/) | Handler missing an operation | | [U3012](https://una-lang.org/en/docs/errors/U3012/) | Host capability in `main` not granted by `una run` | | [U3013](https://una-lang.org/en/docs/errors/U3013/) | Effectful or fallible call nested inside an expression | | [U3014](https://una-lang.org/en/docs/errors/U3014/) | Host capability used in an example | | [U3015](https://una-lang.org/en/docs/errors/U3015/) | `std.testing` used outside a handler or example | | [U3016](https://una-lang.org/en/docs/errors/U3016/) | Second-class type used as a type argument | | [U3017](https://una-lang.org/en/docs/errors/U3017/) | `of` clause that names no parameter | | [U3018](https://una-lang.org/en/docs/errors/U3018/) | `of` clause that names a parameter not of function type | | [U3019](https://una-lang.org/en/docs/errors/U3019/) | `of` clause that names a function type with its own `uses` or `fails` | | [U3020](https://una-lang.org/en/docs/errors/U3020/) | Call into a boundary module whose capability is not granted with `with` | | [U3021](https://una-lang.org/en/docs/errors/U3021/) | Call that grants a boundary module more than its ceiling | | [U3022](https://una-lang.org/en/docs/errors/U3022/) | Labeled operation passed to code that reads it lower | | [U3023](https://una-lang.org/en/docs/errors/U3023/) | Header that grants more than its lock in `una.toml` | | [U3024](https://una-lang.org/en/docs/errors/U3024/) | Call into a boundary module from which a release is reachable | | [U3025](https://una-lang.org/en/docs/errors/U3025/) | `if error` clause on an expression that cannot fail | | [U3026](https://una-lang.org/en/docs/errors/U3026/) | `attempt` of a call that cannot fail | | [U3027](https://una-lang.org/en/docs/errors/U3027/) | Code that may run forever where it is not allowed to | | [U3028](https://una-lang.org/en/docs/errors/U3028/) | A function that says `diverges`, used as a value | | [U3029](https://una-lang.org/en/docs/errors/U3029/) | A failure that must be handled where it is not | | [U3032](https://una-lang.org/en/docs/errors/U3032/) | A `simd required` clause outside a `systems` package of edition `0.5` | | [U3033](https://una-lang.org/en/docs/errors/U3033/) | An operation of `HttpServer` in the effect set of a `together` branch, a `together for` body, a `first of` branch, or `handle` or `on_stop` of a `serve` module | ## U4xx | Code | Meaning | | --- | --- | | [U4001](https://una-lang.org/en/docs/errors/U4001/) | Flow to a lower label | | [U4002](https://una-lang.org/en/docs/errors/U4002/) | Implicit flow through control, failure or call under raised pc | | [U4003](https://una-lang.org/en/docs/errors/U4003/) | Sink label exceeded | | [U4004](https://una-lang.org/en/docs/errors/U4004/) | `policy` outside a trusted module | | [U4005](https://una-lang.org/en/docs/errors/U4005/) | Invalid policy (public `via`, or type mismatch) | | [U4007](https://una-lang.org/en/docs/errors/U4007/) | Unknown label category | | [U4008](https://una-lang.org/en/docs/errors/U4008/) | A text literal with interpolation in a pattern | ## U5xx | Code | Meaning | | --- | --- | | [U5001](https://una-lang.org/en/docs/errors/U5001/) | Obligation refuted | | [U5002](https://una-lang.org/en/docs/errors/U5002/) | Obligation unknown | | [U5003](https://una-lang.org/en/docs/errors/U5003/) | Solver missing or version mismatch | ## U6xx | Code | Meaning | | --- | --- | | [U6001](https://una-lang.org/en/docs/errors/U6001/) | `main` failed | | [U6003](https://una-lang.org/en/docs/errors/U6003/) | Call depth or memory limit exceeded | | [U6004](https://una-lang.org/en/docs/errors/U6004/) | A header value contains a control character | | [U6005](https://una-lang.org/en/docs/errors/U6005/) | A host value is not valid UTF-8 | | [U6006](https://una-lang.org/en/docs/errors/U6006/) | The floating-point environment of the platform is not the default one | | [U6007](https://una-lang.org/en/docs/errors/U6007/) | The host stopped the run before it finished | | [U6009](https://una-lang.org/en/docs/errors/U6009/) | The host gave no random bytes for keyed hashing | ## U7xx | Code | Meaning | | --- | --- | | [U7001](https://una-lang.org/en/docs/errors/U7001/) | Non-canonical formatting | | [U7002](https://una-lang.org/en/docs/errors/U7002/) | Invalid `una.toml` | | [U7003](https://una-lang.org/en/docs/errors/U7003/) | Escape budget exceeded | | [U7004](https://una-lang.org/en/docs/errors/U7004/) | Missing or invalid `verification.lock` | | [U7005](https://una-lang.org/en/docs/errors/U7005/) | Trusted module not declared in both header and `una.toml` | | [U7008](https://una-lang.org/en/docs/errors/U7008/) | Invalid `ita.una` or `itaty.una` | | [U7009](https://una-lang.org/en/docs/errors/U7009/) | Missing, invalid or inconsistent `ita.lock` | | [U7010](https://una-lang.org/en/docs/errors/U7010/) | A package, archive, statement, root, checkpoint or log proof that fails verification | | [U7011](https://una-lang.org/en/docs/errors/U7011/) | A locked package that is neither in the vendor directory nor in Itaoca | | [U7012](https://una-lang.org/en/docs/errors/U7012/) | A dependency the root may not use as written | | [U7013](https://una-lang.org/en/docs/errors/U7013/) | No resolution: no release meets a need, or a bound of resolution is exceeded | | [U7014](https://una-lang.org/en/docs/errors/U7014/) | A locked release yanked, under an advisory or signed after a stated compromise, or a pending recovery, a key change or a transfer of its owner | | [U7015](https://una-lang.org/en/docs/errors/U7015/) | The executable cannot be laid out: a branch beyond its target's range, or a section larger than its format allows | ## U8xx | Code | Meaning | | --- | --- | | [U8001](https://una-lang.org/en/docs/errors/U8001/) | Internal compiler error (always a bug) | --- # U0001: Invalid character, byte order mark or lone carriage return U0001 reports a character that cannot appear where it is, a byte sequence that is not valid UTF-8, a byte order mark at the start of the file, and a carriage return not followed by a line feed. Lexing continues after the error, so later problems in the file are still reported. ## Why Una rejects it Every source file is UTF-8 text without a byte order mark, and its lines end with `\n` or `\r\n`. - Identifiers, keywords and punctuation are ASCII. Any other character, such as an accented letter, may appear only inside text literals and comments. - Control characters other than tab and line feed, and Unicode bidirectional controls, are rejected everywhere, including literals and comments, so that reviewed code always reads as it runs. ## How to fix it Write control characters and Unicode bidirectional controls in text with `\u{...}` escapes. ## The repair at a glance ```diff module demo - pub café() -> Text = "coffee" + pub cafe() -> Text = "coffee" ``` ## Failing example ```una module demo pub café() -> Text = "coffee" ``` ## Fixed example ```una module demo pub cafe() -> Text = "coffee" ``` --- # U0002: Tab in indentation U0002 reports a tab in the leading whitespace of a line. Tabs inside text literals and comments are not indentation and are allowed. ## Why Una rejects it Una uses significant indentation made of spaces only, two per level (`spec/01 §2`). A tab in the leading whitespace of a line is rejected, because its width depends on the editor and would make the block structure ambiguous. ## How to fix it The diagnostic carries a mechanical edit that replaces the indentation with spaces. ## The repair at a glance ```diff module demo pub double(x: Int) -> Int requires x >= 0 = - x * 2 + x * 2 ``` ## Failing example The body line starts with a tab. ```una module demo pub double(x: Int) -> Int requires x >= 0 = x * 2 ``` ## Fixed example ```una module demo pub double(x: Int) -> Int requires x >= 0 = x * 2 ``` --- # U0003: Inconsistent indentation Each indentation level is exactly two spaces deeper than the enclosing one, and a line that closes blocks must return to the indentation of an enclosing level (`spec/01 §2`). U0003 reports a line indented by an odd number of spaces relative to its block, a line more than one level deeper than the line before it, and a line dedented to a column that no enclosing block uses. The diagnostic proposes mechanical edits that re-indent the line to the nearest valid levels. ## The repair at a glance ```diff module demo pub double(x: Int) -> Int requires x >= 0 = - x * 2 + x * 2 ``` ## Failing example ```una module demo pub double(x: Int) -> Int requires x >= 0 = x * 2 ``` ## Fixed example ```una module demo pub double(x: Int) -> Int requires x >= 0 = x * 2 ``` --- # U0004: Unterminated text literal A text literal starts and ends with `"` on the same line; it cannot span lines (`spec/01 §6`). U0004 reports a literal whose closing quote is missing before the end of the line or of the file, including a literal whose interpolation is missing its `}`. Write a quote inside text as `\"` and a line break as `\n`. ## The repair at a glance ```diff module demo - pub greeting() -> Text = "hello + pub greeting() -> Text = "hello" ``` ## Failing example ```una module demo pub greeting() -> Text = "hello ``` ## Fixed example ```una module demo pub greeting() -> Text = "hello" ``` --- # U0005: Invalid escape sequence U0005 reports a backslash in a text literal that does not start a valid escape sequence. ## Why Una rejects it Inside a text literal, a backslash starts an escape sequence. The valid escapes are `\"`, `\\`, `\n`, `\t`, `\{`, `\}` and `\u{H}`, where `H` is one to six hexadecimal digits naming a Unicode scalar value (`spec/01 §6`). U0005 reports: - any other character after a backslash, - a `\u` escape without braces or digits, - a code point that is a surrogate or above `10FFFF`. ## How to fix it Write a backslash itself as `\\`. ## The repair at a glance ```diff module demo - pub folder() -> Text = "C:\data" + pub folder() -> Text = "C:\\data" ``` ## Failing example ```una module demo pub folder() -> Text = "C:\data" ``` ## Fixed example ```una module demo pub folder() -> Text = "C:\\data" ``` --- # U0006: Text literal inside interpolation Interpolation embeds an expression in a text literal, as in `"seats {e.remaining}"` (`spec/01 §6`). The embedded expression must not contain another text literal, which keeps every literal on one level and easy to read and edit. Bind the inner text with `let` and interpolate the name instead. ## The repair at a glance ```diff module demo - pub greeting() -> Text = "hello {trim(" world ")}" + pub greeting() -> Text + = + let name = trim(" world ") + "hello {name}" ``` ## Failing example ```una module demo pub greeting() -> Text = "hello {trim(" world ")}" ``` ## Fixed example ```una module demo pub greeting() -> Text = let name = trim(" world ") "hello {name}" ``` --- # U0007: Malformed literal U0007 reports: - an integer literal with a leading zero, a doubled underscore, or an underscore at its start or end, - an unescaped `}` in text, - an unescaped `{` that no expression can follow, a quote, a backslash or a `}`, as in JSON written in text (`"{\"id\": 7}"` is `"\{\"id\": 7\}"`). ## Why Una rejects it - An integer literal is written in decimal digits, with `_` allowed only between two digits to group them, and without leading zeros except for `0` itself (`spec/01 §6`). - Inside a text literal, `{` starts an interpolation and `}` ends it, so a `}` outside an interpolation must be escaped as `\}`. ## How to fix it When the intended spelling is unambiguous, the diagnostic carries a mechanical edit. ## The repair at a glance ```diff module demo - pub timeout() -> Int = 030 + pub timeout() -> Int = 30 ``` ## Failing example ```una module demo pub timeout() -> Int = 030 ``` ## Fixed example ```una module demo pub timeout() -> Int = 30 ``` --- # U0101: Unexpected token The parser found a token that the grammar of `spec/02` does not allow at that point. The message names the token found and what was expected. After the error, parsing resumes at the next declaration, so the rest of the file is still checked. ## Why Una rejects it U0101 also reports: - brackets left unbalanced within a declaration, - chained comparisons such as `a < b < c` (`spec/01 §7`), - keywords such as `if` used as names, - nested patterns such as `is Some(Circle(radius))`, which no edition supports, - literal patterns such as `is Some(0)`, - nesting deeper than 256 levels, where each chained operator counts as one level (ADR 0019). ## How to fix it - For a nested pattern such as `is Some(Circle(radius))`, bind the field to a name, then match that name in a second `when` inside the arm. - For a literal pattern such as `is Some(0)`, bind the field to a name, then match it in a second `when` with a literal arm and `else`, or compare it inside the arm. ## The repair at a glance ```diff module demo - pub between(x: Int) -> Bool = 0 < x < 10 + pub between(x: Int) -> Bool = 0 < x and x < 10 ``` ## Failing example ```una module demo pub between(x: Int) -> Bool = 0 < x < 10 ``` ## Fixed example ```una module demo pub between(x: Int) -> Bool = 0 < x and x < 10 ``` --- # U0102: Clause out of order or repeated U0102 reports a clause placed after a clause that must follow it, and a repeated `fails`, `derived from`, `accepts`, `if error` or `if none` clause. ## Why Una rejects it - The clauses of a function header follow one canonical order: every `requires`, then every `ensures`, then every `uses`, then at most one `fails`, then at most one `derived from` (`spec/02 §3`). - Capability operations follow the same idea: every `requires`, then every `ensures`, then at most one `fails`, then at most one `accepts` (`spec/02 §4`). - The handling clauses of a statement come in the order `if error`, then `if none`, each at most once (`spec/06 §3`). A fixed order lets people and tools find each part of a contract at a glance. A `fails` or `derived from` clause is not repeated: a function or operation fails with a single error kind (ADR 0006), and one `derived from` lists all its requirements. ## The repair at a glance ```diff module demo pub double(x: Int) -> Int - ensures result == x * 2 requires x >= 0 + ensures result == x * 2 = x * 2 ``` ## Failing example ```una module demo pub double(x: Int) -> Int ensures result == x * 2 requires x >= 0 = x * 2 ``` ## Fixed example ```una module demo pub double(x: Int) -> Int requires x >= 0 ensures result == x * 2 = x * 2 ``` --- # U0103: Reserved keyword not available in the package's edition A reserved word is used as a keyword or as a name. The message names the planned area, "reserved for a later edition (laws)" for example, or the Una construct to use instead. ## Why Una rejects it Some words are reserved for features planned in later versions of Una, and others name constructs from other languages that Una expresses differently. Using one as a keyword or as a name is rejected (`spec/01 §5`). For example, Una has no `return`: the last expression of a body is its result. In edition 0.3 the test declaration is written `test` (ADR 0105), so `example` at the start of a declaration is U0103 there, "`example` is written `test` in edition 0.3". The declaration's body is read as a test's, and editions 0.1 and 0.2 keep `example`. ## How to fix it - A word reserved for a later version, such as `table` or `all`, comes with a repair that renames it, the same way at every occurrence in every module of the package, the names an `import` line lists included: `the_table`, or `Table` where a kind or capability name is expected, with a number added when any module of the package already has that name (`the_table_2`). So applying every edit never makes a name refer to another declaration. - In a module path the repair is advice, since the module's file must move too. - In edition 0.3, `example` at the start of a declaration comes with the exact rewrite of the keyword that `una fix` applies. ## The repair at a glance ```diff module demo - pub double(x: Int) -> Int = return x * 2 + pub double(x: Int) -> Int = x * 2 ``` ## Failing example ```una module demo pub double(x: Int) -> Int = return x * 2 ``` ## Fixed example ```una module demo pub double(x: Int) -> Int = x * 2 ``` --- # U1001: Unresolved name U1001 reports a name that refers to nothing visible where it is used, whether it names a value, a type, a capability, a handler, a module or an imported declaration. ## Why Una rejects it Every name must refer to something visible where it is used (ADR 0023): - a local binding (a parameter, a `let`, a pattern binding or a lambda parameter), - a declaration of the module, - a name the module imports, - the prelude. U1001 reports a name that none of these holds. An import names a module of the package or one of the standard modules that its edition can import: - `std.host`, with the host capabilities and their failure kinds, in every edition, - `std.testing`, with the helpers for examples, in every edition, - `std.time`, `std.drive` and `std.limit`, from edition `0.4`, - `std.collections`, from edition `0.5`. The prelude is always in scope and is not imported. A variant in a `when` pattern, an `is` test or after `fail` takes its kind from the context, and is checked against that kind instead. An operation that a capability does not declare is unresolved too, after `@x.` in a call and after `expect performed` or `expect not performed` in an example. ## How to fix it For an operation that a capability does not declare, the diagnostic offers the closest operation as an edit (ADR 0082). ## The repair at a glance ```diff module demo + double(x: Int) -> Int = x * 2 + pub total(x: Int) -> Int = double(x) ``` ## Failing example ```una module demo pub total(x: Int) -> Int = double(x) ``` ## Fixed example ```una module demo double(x: Int) -> Int = x * 2 pub total(x: Int) -> Int = double(x) ``` --- # U1002: Duplicate definition U1002 reports a name that is defined more than once in its scope. ## Why Una rejects it A name is defined once in its scope: - the declarations of a module (kinds, variants and capabilities share one namespace; functions, predicates, handlers and policies another), - the parameters, fields and operations of one declaration, - the requirements of a package, - the examples of a module (the tests, written `test` in edition 0.3). A local binding cannot rebind another local that is still in scope, so every use of a name inside a function means one binding. A module may reuse a prelude name, and a local may reuse any name that is not local: the inner one wins. In edition 0.2, a kind, a variant or a capability cannot take the name of a built-in type (`Int`, `Nat`, `Bool`, `Text`, `Unit`, `Hashed`, `List`, `Option`, `Result`, the fixed-width integer types, `Map` and `Entry`): `pub kind Text = Short | Long` is U1002, since it would silently replace `Text` in its module (ADR 0079). ## The repair at a glance ```diff module demo pub double(x: Int) -> Int = - let x = x * 2 - x + let doubled = x * 2 + doubled ``` ## Failing example ```una module demo pub double(x: Int) -> Int = let x = x * 2 x ``` ## Fixed example ```una module demo pub double(x: Int) -> Int = let doubled = x * 2 doubled ``` --- # U1003: Import cycle Modules form a graph through their imports, and that graph has no cycle: a module cannot import, directly or through other modules, a module that imports it. U1003 is reported once per cycle, at the first import of the cycle's first module in path order, and names every module of the cycle. Move the declarations that both sides need into a module that both import. ## Failing example `src/a.una` ```una module a import b (two) pub one() -> Int = 1 pub three() -> Int = two() + 1 ``` `src/b.una` ```una module b import a (one) pub two() -> Int = one() + 1 ``` ## Fixed example `src/a.una` ```una module a import b (two) pub three() -> Int = two() + 1 ``` `src/b.una` ```una module b import c (one) pub two() -> Int = one() + 1 ``` `src/c.una` ```una module c pub one() -> Int = 1 ``` --- # U1004: Use of a private declaration from another module An import names a declaration that is not public. The diagnostic points at the imported name and shows the declaration. ## Why Una rejects it Declarations are private to their module unless they are marked `pub` (`spec/04 §5`), and an import can name only public declarations. ## How to fix it - The diagnostic carries an edit that adds `pub` to the declaration. The edit is marked as a widening of visibility, since every module may then use the declaration (ADR 0097). - The other fix, which keeps the module's interface, is to import a public declaration instead. ## The repair at a glance `src/a.una` ```diff module a - helper() -> Int = 1 + pub helper() -> Int = 1 ``` ## Failing example `src/a.una` ```una module a helper() -> Int = 1 ``` `src/main.una` ```una module main import a (helper) pub two() -> Int = helper() + 1 ``` ## Fixed example `src/a.una` ```una module a pub helper() -> Int = 1 ``` `src/main.una` ```una module main import a (helper) pub two() -> Int = helper() + 1 ``` --- # U1005: Naming convention violation Names follow fixed conventions (`spec/01 §4`): kinds, variants, capabilities, type parameters and label categories are UpperCamelCase; all other names are lower snake case, without `__` and without a trailing `_`; requirement identifiers are upper snake case ending with `_` and a number, as in `EVENTS_3`. The convention is checked where a name is defined, and the message suggests a name that follows it; rename the uses too. ## The repair at a glance ```diff module demo - pub kind Seat_Count = Int in 0..5000 + pub kind SeatCount = Int in 0..5000 ``` ## Failing example ```una module demo pub kind Seat_Count = Int in 0..5000 ``` ## Fixed example ```una module demo pub kind SeatCount = Int in 0..5000 ``` --- # U1006: Undeclared requirement in `derived from` A `derived from` clause traces a function to the requirements it implements (`spec/08 §1`). Every identifier it lists must be declared by a `requirement` somewhere in the package, so that `una trace` can connect the contract to its origin. Declare the requirement, with its text, source, owner and status, or correct the identifier. ## The repair at a glance ```diff module demo + requirement EVENTS_3 + text "An event with no remaining seats is always shown as sold out" + source policy "Box Office Handbook 2.1" + owner box_office + status active + pub sold_out(remaining: Int) -> Bool derived from EVENTS_3 = remaining < 1 ``` ## Failing example ```una module demo pub sold_out(remaining: Int) -> Bool derived from EVENTS_3 = remaining < 1 ``` ## Fixed example ```una module demo requirement EVENTS_3 text "An event with no remaining seats is always shown as sold out" source policy "Box Office Handbook 2.1" owner box_office status active pub sold_out(remaining: Int) -> Bool derived from EVENTS_3 = remaining < 1 ``` --- # U1007: Generated requirement marked active Agents may propose requirements with `source generated`, but only a person can activate one (`spec/08 §1`): a requirement whose source is `generated` must have `status proposed`. To activate it, a person changes its source to `human`, `policy` or `regulation`. The diagnostic carries an edit that marks the requirement proposed. ## The repair at a glance ```diff module demo requirement EVENTS_3 text "An event with no remaining seats is always shown as sold out" source generated "task 41" owner box_office - status active + status proposed ``` ## Failing example ```una module demo requirement EVENTS_3 text "An event with no remaining seats is always shown as sold out" source generated "task 41" owner box_office status active ``` ## Fixed example ```una module demo requirement EVENTS_3 text "An event with no remaining seats is always shown as sold out" source generated "task 41" owner box_office status proposed ``` --- # U1008: Module path does not match file path A package keeps each module at the path its name gives: module `a.b.c` lives in `src/a/b/c.una` (`spec/13 §7`), so a reader and a tool find a module from its name. The diagnostic carries an edit that makes the header match the file; moving the file is the other fix. A file checked on its own is exempt. ## The repair at a glance `src/events/seating.una` ```diff - module events.seats + module events.seating pub one() -> Int = 1 ``` ## Failing example `src/events/seating.una` ```una module events.seats pub one() -> Int = 1 ``` ## Fixed example `src/events/seating.una` ```una module events.seating pub one() -> Int = 1 ``` --- # U1009: Reserved module name Module paths whose first segment is `std` or `prelude` belong to the standard library (`spec/10 §11` rule 8): the prelude and the standard modules: `std.host` and `std.testing` in every edition, `std.time`, `std.drive` and `std.limit` from edition `0.4`, and `std.collections` from edition `0.5`. A declaration is identified by its module path and its name, so a user module with such a path could pass its own declarations off as standard ones. The diagnostic points at the `module` header; give the module a path of its own, and move the file to match it in a package. ## The repair at a glance ```diff - module prelude + module keys pub kind KeyError = UnknownKey | Revoked | Expired ``` ## Failing example ```una module prelude pub kind KeyError = UnknownKey | Revoked | Expired ``` ## Fixed example ```una module keys pub kind KeyError = UnknownKey | Revoked | Expired ``` --- # U1010: A module whose first path segment is a dependency's local name From edition `0.4`, a package's modules import a dependency's modules under the dependency's local name: the module `text` of the dependency `util` is `util.text` in the importing package (ADR 0122 rule 47, `spec/30`). A module of the package whose path starts with that local name could be mistaken for one of the dependency's, so it is U1010 at its header. The repair is to give the need another local name with `as`, or to rename the module. ## The repair at a glance `ita.una` ```diff ita demo version 0.1.0 edition 0.4 needs - util from path "deps/util" + util as strings from path "deps/util" accept name ``` `src/util.una` ```diff module util - import util.text (shout) + import strings.text (shout) pub greet() -> Text = shout("hello") ``` ## Failing example `ita.una` ```una ita demo version 0.1.0 edition 0.4 needs util from path "deps/util" accept name ``` `ita.lock` ```una lock 1 solver encoding "una-smt-1" name "z3" version "5.1.0" logic "QF_UFLIA" steps 5000000 seed 0 package util 0.1.0 from path "deps/util" digest "sha256:0000000000000000000000000000000000000000000000000000000000000000" ``` `deps/util/ita.una` ```una ita util version 0.1.0 edition 0.4 ``` `deps/util/src/text.una` ```una module text pub shout(word: Text) -> Text = word ``` `src/util.una` ```una module util import util.text (shout) pub greet() -> Text = shout("hello") ``` ## Fixed example `ita.una` ```una ita demo version 0.1.0 edition 0.4 needs util as strings from path "deps/util" accept name ``` `ita.lock` ```una lock 1 solver encoding "una-smt-1" name "z3" version "5.1.0" logic "QF_UFLIA" steps 5000000 seed 0 package util 0.1.0 from path "deps/util" digest "sha256:0000000000000000000000000000000000000000000000000000000000000000" ``` `deps/util/ita.una` ```una ita util version 0.1.0 edition 0.4 ``` `deps/util/src/text.una` ```una module text pub shout(word: Text) -> Text = word ``` `src/util.una` ```una module util import strings.text (shout) pub greet() -> Text = shout("hello") ``` --- # U2001: Type mismatch An expression does not have the type expected where it appears. The message names the type expected and the type found. ## Why Una rejects it Every expression has a type, and where a type is expected, by a declaration, a parameter, an operator or the other branches of an `if` or `when`, the expression must have that type (`spec/10`). Types are compared by their base: a refined kind such as `Seats` is its base `Int`, so its refinement becomes a proof obligation rather than a mismatch (`spec/03 §6`). U2001 also reports: - values that `==` cannot compare because they hold functions, - `<` on a type without an order, - interpolation, in edition `0.1`, of a type other than `Int`, `Bool` and `Text`, and from edition `0.2`, of a value whose type holds a function or a `Hashed`, - a call with the wrong number of arguments, - `attempt` on something other than one call, - a type that inference cannot determine, such as the element type of an unused empty list. ## The repair at a glance ```diff module demo - pub label(count: Int) -> Text = count + pub label(count: Int) -> Text = "{count}" ``` ## Failing example ```una module demo pub label(count: Int) -> Text = count ``` ## Fixed example ```una module demo pub label(count: Int) -> Text = "{count}" ``` --- # U2002: Unknown or ill-formed type U2002 reports a written type that is unknown or ill-formed. ## Why Una rejects it A written type names a built-in type, a kind or a type parameter (`spec/03`). U2002 reports: - a name that denotes something else, such as a variant or a capability; - range sugar on a type other than `Int`; - a `fails` clause that names anything but a sum kind without type parameters; - an alias defined in terms of itself; - a record or sum kind that contains itself other than through `List` or `Option` fields, since every value must be finite (`spec/03 §2` rule 5). A refined kind or a range written as a type argument, as `List[Pos]`, is U2002 in editions `0.1` and `0.2` (ADR 0040). Edition `0.3` accepts it and proves the refinement of every element where values are built (ADR 0103). ## How to fix it For a recursive field, the diagnostic carries an edit that makes the field optional. ## The repair at a glance ```diff module demo pub kind Node value: Int - next: Node + next: Option[Node] ``` ## Failing example ```una module demo pub kind Node value: Int next: Node ``` ## Fixed example ```una module demo pub kind Node value: Int next: Option[Node] ``` --- # U2003: Wrong number of type arguments A type takes exactly as many type arguments as it has type parameters (`spec/03 §2`): `List[T]` and `Option[T]` take one, `Result[T, E]` takes two, and `Int` takes none, as does a type parameter. The message gives both counts. ## The repair at a glance ```diff module demo - pub size(xs: List) -> Int = 0 + pub size(xs: List[Int]) -> Int = xs.len ``` ## Failing example ```una module demo pub size(xs: List) -> Int = 0 ``` ## Fixed example ```una module demo pub size(xs: List[Int]) -> Int = xs.len ``` --- # U2004: Missing argument label A call with two or more arguments may omit the label of its first argument only; every other argument names its parameter, as in `max(x, b: 10)`, or is a bare name equal to the parameter's name, which counts as labeled (`spec/04 §3`). A constructor with two or more fields labels every argument, the first included. The diagnostic carries an edit that labels the argument with the parameter at its position. ## The repair at a glance ```diff module demo - pub larger(x: Int) -> Int = max(x, 10) + pub larger(x: Int) -> Int = max(x, b: 10) ``` ## Failing example ```una module demo pub larger(x: Int) -> Int = max(x, 10) ``` ## Fixed example ```una module demo pub larger(x: Int) -> Int = max(x, b: 10) ``` --- # U2005: Unknown argument label A label names a parameter of the function, operation or handler that is called (`spec/04 §3`). Function values, such as parameters of function type and lambdas, take their arguments by position and without labels, since a function type has no parameter names; so does a policy, which takes one argument (ADR 0024). The diagnostic suggests the closest parameter name when there is one. ## The repair at a glance ```diff module demo - pub larger(x: Int) -> Int = max(x, c: 10) + pub larger(x: Int) -> Int = max(x, b: 10) ``` ## Failing example ```una module demo pub larger(x: Int) -> Int = max(x, c: 10) ``` ## Fixed example ```una module demo pub larger(x: Int) -> Int = max(x, b: 10) ``` --- # U2006: Duplicate argument Each parameter receives exactly one argument, whether by position, by label or by punning (`spec/04 §3`). Likewise, a constructor gives each field once, and a pattern binds each field once. ## The repair at a glance ```diff module demo - pub larger(x: Int) -> Int = max(a: x, a: 10) + pub larger(x: Int) -> Int = max(a: x, b: 10) ``` ## Failing example ```una module demo pub larger(x: Int) -> Int = max(a: x, a: 10) ``` ## Fixed example ```una module demo pub larger(x: Int) -> Int = max(a: x, b: 10) ``` --- # U2007: Non-exhaustive `when` over variants A `when` whose arms test variants matches every variant of the sum kind, or ends with an `else` arm, so that every value takes an arm (`spec/10 §4`). The message lists the variants that no arm matches. For range and literal arms, exhaustiveness is a proof obligation instead (`spec/12 §3`). ## The repair at a glance ```diff module demo pub kind Level = Low | Mid | High pub rank(level: Level) -> Int = when level is Low -> 0 + is Mid -> 1 is High -> 2 ``` ## Failing example ```una module demo pub kind Level = Low | Mid | High pub rank(level: Level) -> Int = when level is Low -> 0 is High -> 2 ``` ## Fixed example ```una module demo pub kind Level = Low | Mid | High pub rank(level: Level) -> Int = when level is Low -> 0 is Mid -> 1 is High -> 2 ``` --- # U2008: Unreachable arm or misplaced `else` An `else` arm is the last arm of a `when` (`spec/02 §8`), since any arm after it is never reached. U2008 also reports the other arms that no value reaches: an arm that tests a variant or a literal that an earlier arm already tests, and an `else` after arms that match every variant of the kind (ADR 0024). The diagnostic points at the unreachable arm and at the arm that makes it unreachable. ## The repair at a glance ```diff module demo pub kind Level = Low | High pub rank(level: Level) -> Int = when level - else -> 0 is High -> 2 + else -> 0 ``` ## Failing example ```una module demo pub kind Level = Low | High pub rank(level: Level) -> Int = when level else -> 0 is High -> 2 ``` ## Fixed example ```una module demo pub kind Level = Low | High pub rank(level: Level) -> Int = when level is High -> 2 else -> 0 ``` --- # U2009: Missing or unknown field in constructor A record or variant constructor gives every field of the kind, labeled when there are two or more, in any order (`spec/04 §3` rule 4); a constructor with fields must be applied to them, since constructors are not values (ADR 0024). U2009 reports a missing field, a label that names no field, a variant without fields called with parentheses, and a pattern that binds a field its variant does not have. The diagnostic suggests the closest field name when there is one. ## The repair at a glance ```diff module demo pub kind Point x: Int y: Int - pub origin() -> Point = Point(x: 0) + pub origin() -> Point = Point(x: 0, y: 0) ``` ## Failing example ```una module demo pub kind Point x: Int y: Int pub origin() -> Point = Point(x: 0) ``` ## Fixed example ```una module demo pub kind Point x: Int y: Int pub origin() -> Point = Point(x: 0, y: 0) ``` --- # U2010: Cannot infer lambda parameter type A lambda takes the types of its parameters from the function type expected where it appears, such as the parameter `each` of `map` (`spec/03 §7`). Where no function type is expected, as on the right of a `let`, each parameter needs an annotation. ## The repair at a glance ```diff module demo pub two() -> Int = - let add_one = fn(x) -> x + 1 + let add_one = fn(x: Int) -> x + 1 add_one(1) ``` ## Failing example ```una module demo pub two() -> Int = let add_one = fn(x) -> x + 1 add_one(1) ``` ## Fixed example ```una module demo pub two() -> Int = let add_one = fn(x: Int) -> x + 1 add_one(1) ``` --- # U2011: Statement value is not `Unit` A statement that is not the last line of its block runs for its effect, so its value must be `Unit` (`spec/02 §6`); a value of another type would be silently discarded. Bind the value with `let`, or remove the statement. ## The repair at a glance ```diff module demo pub twice(x: Int) -> Int = - x + x - x + let doubled = x + x + doubled ``` ## Failing example ```una module demo pub twice(x: Int) -> Int = x + x x ``` ## Fixed example ```una module demo pub twice(x: Int) -> Int = let doubled = x + x doubled ``` --- # U2012: `result` outside `ensures` or `expect` `result` names the value that a function returns, so it has a meaning only in an `ensures` clause and, for examples, in an `expect` line (`spec/02 §8`). In a body, the returned value is the last expression; a `requires` clause states a condition over the parameters. ## The repair at a glance ```diff module demo pub positive(x: Int) -> Int - requires result > 0 + requires x > 0 + ensures result > 0 = x ``` ## Failing example ```una module demo pub positive(x: Int) -> Int requires result > 0 = x ``` ## Fixed example ```una module demo pub positive(x: Int) -> Int requires x > 0 ensures result > 0 = x ``` --- # U2013: `it` or `error` outside its allowed position `it` names the value being refined, so it appears only in a `where` clause and in the predicate of `checked`; `error` names the failure being handled, so it appears only in the `fail` or `use` part of an `if error` clause (`spec/02 §8`). ## The repair at a glance ```diff module demo pub kind Small = Int where it < 100 - pub bound(x: Small) -> Int = it + pub bound(x: Small) -> Int = x ``` ## Failing example ```una module demo pub kind Small = Int where it < 100 pub bound(x: Small) -> Int = it ``` ## Fixed example ```una module demo pub kind Small = Int where it < 100 pub bound(x: Small) -> Int = x ``` --- # U2014: Expression outside the refinement language A clause or a predicate of `checked` holds an expression outside the refinement language. The diagnostic points at the outermost sub-expression outside the language. ## Why Una rejects it `where`, `requires` and `ensures` clauses, and the predicate of `checked`, are written in the refinement language, which the verifier decides (`spec/03 §3`). The language has: - integer, boolean and text literals; - parameters, `it`, `result`, field access, `.len`; - `+`, `-`, `*` with a literal operand, `/` and `mod` by a nonzero literal; - comparisons, `in`, `is` with a variant; - `and`, `or`, `not`, `implies`; - calls of predicates. ## How to fix it - When the fix is mechanical, such as `x is V` for `x == V` or `x == 1` for `x is 1`, the diagnostic carries an edit. - To use a function in a contract, state what it computes in the contract, or as a predicate. ## The repair at a glance ```diff module demo pub shift(x: Int) -> Int - requires abs(x) < 100 + requires x > -100 and x < 100 = x ``` ## Failing example ```una module demo pub shift(x: Int) -> Int requires abs(x) < 100 = x ``` ## Fixed example ```una module demo pub shift(x: Int) -> Int requires x > -100 and x < 100 = x ``` --- # U2015: Invalid predicate body (impure, failing, recursive or outside RL for `reflect`) The body of a predicate is not valid for its kind of predicate. ## Why Una rejects it A predicate is a pure, total function that returns `Bool` (`spec/03 §4`). - The body of a `reflect` predicate, which the verifier sees, is written in the refinement language. - An `opaque` predicate may use any pure expression, but cannot perform operations, fail, or call functions that do. - No predicate calls itself, directly or through other predicates and functions. ## The repair at a glance ```diff module demo - predicate reflect even(n: Int) -> Bool = n == 0 or even(n - 2) + predicate reflect even(n: Int) -> Bool = n mod 2 == 0 ``` ## Failing example ```una module demo predicate reflect even(n: Int) -> Bool = n == 0 or even(n - 2) ``` ## Fixed example ```una module demo predicate reflect even(n: Int) -> Bool = n mod 2 == 0 ``` --- # U2016: Opaque predicate called outside `checked` A call of an opaque predicate appears somewhere other than the predicate of `checked` or the body of another opaque predicate. ## Why Una rejects it The solver knows an opaque predicate only as an uninterpreted symbol. So a value obtains an opaque fact only through `checked`, which counts against the module's escape budget and is listed in the build report, or through a capability operation's `ensures` (`spec/03 §4`, `spec/06 §6`, ADR 0042). An opaque predicate is therefore called only as the predicate of `checked` and in the bodies of other opaque predicates. A call anywhere else is U2016: - in code; - in a `requires` or `ensures` clause of a function; - in a `reflect` body; - in an example. The `where` clause of a kind and the clauses of a capability operation name the predicate without establishing its fact, so they may use it. ## How to fix it Two fixes keep the escape budget. - In code, when it needs only the test and not the fact, test with a function, not a predicate, that has the same body: an `if` on it establishes nothing for the solver. This works only when the body calls no other opaque predicate. The function's result type must not be a kind whose `where` names the predicate, whose fact the solver could not prove. - When the predicate's body is in the refinement language and does not call itself, declare it `predicate reflect`, as the fixed example does. The solver then knows its definition, and a guard proves the fact. A body outside the refinement language is U2015. If the predicate appears in a capability operation's clauses, or in a kind of an operation's signature, those contracts are assumptions, and with `reflect` they give their callers the predicate's whole definition: verify each such operation against a handler. Otherwise, `checked(value, p(it)) else fail ` establishes the fact at run time. It is the last repair, marked as an escape (ADR 0095): it counts against the module's escape budget and is listed in the build report. ## The repair at a glance ```diff module demo pub kind SlugError = | Malformed - predicate opaque valid_slug(t: Text) -> Bool = t.len >= 3 + predicate reflect valid_slug(t: Text) -> Bool = t.len >= 3 pub kind Slug = Text where valid_slug(it) pub parse_slug(raw: Text) -> Slug fails SlugError = if valid_slug(raw) then raw else fail Malformed ``` ## Failing example ```una module demo pub kind SlugError = | Malformed predicate opaque valid_slug(t: Text) -> Bool = t.len >= 3 pub kind Slug = Text where valid_slug(it) pub parse_slug(raw: Text) -> Slug fails SlugError = if valid_slug(raw) then raw else fail Malformed ``` ## Fixed example ```una module demo pub kind SlugError = | Malformed predicate reflect valid_slug(t: Text) -> Bool = t.len >= 3 pub kind Slug = Text where valid_slug(it) pub parse_slug(raw: Text) -> Slug fails SlugError = if valid_slug(raw) then raw else fail Malformed ``` --- # U2017: Use of a binding after it was passed by `take` The code uses a binding after it was passed by `take`. ## Why Una rejects it In edition 0.2, a parameter declared `take` consumes its argument, and the caller writes `take a` (`spec/17 §3`). After `take a`, every use of `a` is U2017, until an assignment gives `a` a new value. Only a `let edit` binding can be reassigned. A binding taken in one branch of an `if` or a `when` counts as taken after the construct. ## How to fix it - Use the value before passing it. - Keep a copy of what you need. - Assign the binding again. ## The repair at a glance `src/demo.una` ```diff module demo pub drain(take items: List[Int]) -> Int = items.len pub count() -> Int = let items = [1, 2, 3] + let size = items.len let n = drain(take items) - n + items.len + n + size ``` ## Failing example `una.toml` ```toml [package] name = "demo" version = "0.1.0" edition = "0.2" ``` `src/demo.una` ```una module demo pub drain(take items: List[Int]) -> Int = items.len pub count() -> Int = let items = [1, 2, 3] let n = drain(take items) n + items.len ``` ## Fixed example `una.toml` ```toml [package] name = "demo" version = "0.1.0" edition = "0.2" ``` `src/demo.una` ```una module demo pub drain(take items: List[Int]) -> Int = items.len pub count() -> Int = let items = [1, 2, 3] let size = items.len let n = drain(take items) n + size ``` --- # U2018: An `edit` argument together with another use of its binding in the same call A call that passes `edit p` may not use the root binding of `p` anywhere else: not in another argument, not as another `edit` or `take` argument, and not through a disjoint field, so `f(edit r.x, y: r.y)` is U2018 too (`spec/17 §3` rule 4). The callee changes the place while the other argument is read, and exclusivity keeps the order of the two from mattering. Bind the other value with `let` before the call. ## The repair at a glance `src/demo.una` ```diff module demo pub kind Point x: Int y: Int pub shift(edit p: Point, by: Int) -> Unit = p.x = p.x + by pub step() -> Point = let edit p = Point(x: 1, y: 2) - shift(edit p, by: p.y) + let dy = p.y + shift(edit p, by: dy) p ``` ## Failing example `una.toml` ```toml [package] name = "demo" version = "0.1.0" edition = "0.2" ``` `src/demo.una` ```una module demo pub kind Point x: Int y: Int pub shift(edit p: Point, by: Int) -> Unit = p.x = p.x + by pub step() -> Point = let edit p = Point(x: 1, y: 2) shift(edit p, by: p.y) p ``` ## Fixed example `una.toml` ```toml [package] name = "demo" version = "0.1.0" edition = "0.2" ``` `src/demo.una` ```una module demo pub kind Point x: Int y: Int pub shift(edit p: Point, by: Int) -> Unit = p.x = p.x + by pub step() -> Point = let edit p = Point(x: 1, y: 2) let dy = p.y shift(edit p, by: dy) p ``` --- # U2019: Assignment to a binding that is not editable The code assigns to a binding that is not editable. ## Why Una rejects it Only a binding declared `let edit`, or a parameter declared `edit`, can be assigned, have a field assigned, or be passed as `edit` (`spec/17 §2`). A plain `let` and a plain or `take` parameter are fixed. A lambda captures the value a binding has when the lambda is created. So inside a lambda a captured binding is not editable either (`spec/17 §5` rule 4). ## How to fix it - Declare the binding `let edit`. - Or bind the new value to a new name. ## The repair at a glance `src/demo.una` ```diff module demo pub total(xs: List[Int]) -> Int = - let sum = 0 + let edit sum = 0 sum = xs.sum sum ``` ## Failing example `una.toml` ```toml [package] name = "demo" version = "0.1.0" edition = "0.2" ``` `src/demo.una` ```una module demo pub total(xs: List[Int]) -> Int = let sum = 0 sum = xs.sum sum ``` ## Fixed example `una.toml` ```toml [package] name = "demo" version = "0.1.0" edition = "0.2" ``` `src/demo.una` ```una module demo pub total(xs: List[Int]) -> Int = let edit sum = 0 sum = xs.sum sum ``` --- # U2020: A parameter convention (`edit`, `take`) not matched at the call site, or declared where none is allowed A call does not match a parameter convention (`edit`, `take`), or a declaration has a convention where none is allowed. ## Why Una rejects it A caller writes `edit p` exactly where the parameter is declared `edit`, and `take a` exactly where it is declared `take` (`spec/17 §3`). Each of these is U2020: - a marker on a plain parameter; - a missing marker; - the other marker. A method receiver follows the same rule, as in `edit total.add(by: 1)`. The argument of `edit` is a place, a binding or a field path of one, and the argument of `take` is a binding. Operations and handlers cannot declare conventions, and neither can predicates: they are U2020 at the declaration. ## The repair at a glance `src/demo.una` ```diff module demo pub kind Tally count: Int pub add(edit t: Tally, by: Int) -> Unit = t.count = t.count + by pub run() -> Int = let edit t = Tally(count: 0) - add(t, by: 2) + add(edit t, by: 2) t.count ``` ## Failing example `una.toml` ```toml [package] name = "demo" version = "0.1.0" edition = "0.2" ``` `src/demo.una` ```una module demo pub kind Tally count: Int pub add(edit t: Tally, by: Int) -> Unit = t.count = t.count + by pub run() -> Int = let edit t = Tally(count: 0) add(t, by: 2) t.count ``` ## Fixed example `una.toml` ```toml [package] name = "demo" version = "0.1.0" edition = "0.2" ``` `src/demo.una` ```una module demo pub kind Tally count: Int pub add(edit t: Tally, by: Int) -> Unit = t.count = t.count + by pub run() -> Int = let edit t = Tally(count: 0) add(edit t, by: 2) t.count ``` --- # U2021: A function with `edit` or `take` parameters used as a value Function types have no conventions, so a function with an `edit` or `take` parameter cannot be used as a value: naming it anywhere but in the callee position of a call is U2021 (`spec/17 §3` rule 7). Call it directly, or wrap the call in a function or lambda without conventions. ## The repair at a glance `src/demo.una` ```diff module demo - pub drain(take items: List[Int]) -> Int = items.len + pub size(items: List[Int]) -> Int = items.len - pub sizes(groups: List[List[Int]]) -> List[Int] = groups.map(each: drain) + pub sizes(groups: List[List[Int]]) -> List[Int] = groups.map(each: size) ``` ## Failing example `una.toml` ```toml [package] name = "demo" version = "0.1.0" edition = "0.2" ``` `src/demo.una` ```una module demo pub drain(take items: List[Int]) -> Int = items.len pub sizes(groups: List[List[Int]]) -> List[Int] = groups.map(each: drain) ``` ## Fixed example `una.toml` ```toml [package] name = "demo" version = "0.1.0" edition = "0.2" ``` `src/demo.una` ```una module demo pub size(items: List[Int]) -> Int = items.len pub sizes(groups: List[List[Int]]) -> List[Int] = groups.map(each: size) ``` --- # U2022: Integer literal does not fit its type An integer literal is outside the range of the type it takes. ## Why Una rejects it In edition 0.2, an integer literal takes the fixed-width type its context expects, such as an annotated `let`, a parameter, a field, a return or the other operand of an operator (`spec/18 §2`). A literal outside that type's range is U2022: `U8` holds `0` to `255`, `I8` holds `-128` to `127`, and so on. A computed value that may leave the range is not U2022 but an `overflow` obligation (`spec/18 §3`). In `requires`, `ensures` and `where` clauses, literals are mathematical integers, so U2022 does not apply there. ## How to fix it - Write a literal that fits. - Or give the value a wider type. ## The repair at a glance `src/demo.una` ```diff module demo - pub port() -> U16 = 70000 + pub port() -> U16 = 8080 ``` ## Failing example `una.toml` ```toml [package] name = "demo" version = "0.1.0" edition = "0.2" ``` `src/demo.una` ```una module demo pub port() -> U16 = 70000 ``` ## Fixed example `una.toml` ```toml [package] name = "demo" version = "0.1.0" edition = "0.2" ``` `src/demo.una` ```una module demo pub port() -> U16 = 8080 ``` --- # U2023: A binding declared outside a `together` branch assigned, or passed as `edit` or `take`, inside it The branches of a `together` block, and the body of a `together for`, run as concurrent tasks (`spec/19`). A task captures the values of the bindings declared before it, as a lambda does, and cannot change them: inside a task, a binding declared outside it cannot be assigned, passed as `edit`, or passed as `take` (`spec/19 §2` rule 3). Return the new value from the branch instead, and use it after the block, where every task has finished. ## The repair at a glance `src/demo.una` ```diff module demo pub both(a: Int, b: Int) -> Int = let edit total = 0 together - let x = bump(edit total, by: a) + let x = a * 2 let y = b + 1 - total + x + y - - bump(edit n: Int, by: Int) -> Int - = - n = n + by - n + total = total + x + total + y ``` ## Failing example `una.toml` ```toml [package] name = "demo" version = "0.1.0" edition = "0.2" ``` `src/demo.una` ```una module demo pub both(a: Int, b: Int) -> Int = let edit total = 0 together let x = bump(edit total, by: a) let y = b + 1 total + x + y bump(edit n: Int, by: Int) -> Int = n = n + by n ``` ## Fixed example `una.toml` ```toml [package] name = "demo" version = "0.1.0" edition = "0.2" ``` `src/demo.una` ```una module demo pub both(a: Int, b: Int) -> Int = let edit total = 0 together let x = a * 2 let y = b + 1 total = total + x total + y ``` --- # U2024: A `together` body with a statement other than `let`, or fewer than two branches The body of a `together` block holds its branches: two or more `let` statements, each run as a concurrent task, whose bindings are in scope after the block (`spec/19 §1`). Any other statement in the body, or fewer than two branches, is U2024. Put the work of a branch in a function and call it from the branch's `let`; with one branch, write a plain `let`. ## The repair at a glance `src/demo.una` ```diff module demo - pub one(a: Int) -> Int + pub two(a: Int, b: Int) -> Int = together let x = a + 1 - x + let y = b + 1 + x + y ``` ## Failing example `una.toml` ```toml [package] name = "demo" version = "0.1.0" edition = "0.2" ``` `src/demo.una` ```una module demo pub one(a: Int) -> Int = together let x = a + 1 x ``` ## Fixed example `una.toml` ```toml [package] name = "demo" version = "0.1.0" edition = "0.2" ``` `src/demo.una` ```una module demo pub two(a: Int, b: Int) -> Int = together let x = a + 1 let y = b + 1 x + y ``` --- # U2025: A type argument does not satisfy the constraint of its parameter A type argument does not satisfy the constraint of its type parameter. ## Why Una rejects it A type parameter written with a constraint, as `T: Ord`, can only be instantiated with a type that satisfies it (`spec/20 §1`, `§3` rule 3). - `Eq` takes every type whose values hold no functions. - `Ord` takes `Int`, the fixed-width integer types, `Text` and sums whose variants have no payload. - `Integer` takes `Int` and the fixed-width integer types. A type parameter of the caller satisfies the constraint written on it, so a generic caller writes the constraint its callees need. ## How to fix it - Pass a value of a type that satisfies the constraint. - Or compare by a field that does. ## The repair at a glance `src/demo.una` ```diff module demo pub kind Box size: Int - pub largest(a: Box, b: Box) -> Box = max(a, b: b) + pub largest(a: Box, b: Box) -> Int = max(a.size, b: b.size) ``` ## Failing example `una.toml` ```toml [package] name = "demo" version = "0.1.0" edition = "0.2" ``` `src/demo.una` ```una module demo pub kind Box size: Int pub largest(a: Box, b: Box) -> Box = max(a, b: b) ``` ## Fixed example `una.toml` ```toml [package] name = "demo" version = "0.1.0" edition = "0.2" ``` `src/demo.una` ```una module demo pub kind Box size: Int pub largest(a: Box, b: Box) -> Int = max(a.size, b: b.size) ``` --- # U2026: An operation on a type parameter that its constraint does not allow On values of a type parameter, `==` and `!=` need the constraint `Eq`, the orderings `<`, `<=`, `>` and `>=` need `Ord`, and `x.to_int()` needs `Integer` (`spec/20 §3`). A public function writes the constraint on the parameter, as `[T: Ord]`; a private one gets it inferred when none is written. Arithmetic is never defined on a type parameter: convert with `to_int()` under `Integer` (`spec/20 §1` rule 6). ## The repair at a glance `src/demo.una` ```diff module demo - pub same[T](a: T, b: T) -> Bool = a == b + pub same[T: Eq](a: T, b: T) -> Bool = a == b ``` ## Failing example `una.toml` ```toml [package] name = "demo" version = "0.1.0" edition = "0.2" ``` `src/demo.una` ```una module demo pub same[T](a: T, b: T) -> Bool = a == b ``` ## Fixed example `una.toml` ```toml [package] name = "demo" version = "0.1.0" edition = "0.2" ``` `src/demo.una` ```una module demo pub same[T: Eq](a: T, b: T) -> Bool = a == b ``` --- # U2027: An unknown constraint name A type parameter takes one of the built-in constraints `Eq`, `Ord` or `Integer` (`spec/20 §1`, `§2` rule 3). There are no user traits: a type satisfies a constraint by what it is. ## The repair at a glance `src/demo.una` ```diff module demo - pub same[T: Equal](a: T, b: T) -> Bool = a == b + pub same[T: Eq](a: T, b: T) -> Bool = a == b ``` ## Failing example `una.toml` ```toml [package] name = "demo" version = "0.1.0" edition = "0.2" ``` `src/demo.una` ```una module demo pub same[T: Equal](a: T, b: T) -> Bool = a == b ``` ## Fixed example `una.toml` ```toml [package] name = "demo" version = "0.1.0" edition = "0.2" ``` `src/demo.una` ```una module demo pub same[T: Eq](a: T, b: T) -> Bool = a == b ``` --- # U2028: Values of different units meet, or a measured and a unitless value Values of different units meet, or a measured value meets a unitless one. ## Why Una rejects it In edition 0.3, a unit is part of a number type (ADR 0104, ADR 0114 rule 12, ADR 0120 rules 61 to 65): `Int of Meter` is neither `Int` nor `Int of Second`, and `F64 of Meter` is neither `F64` nor `F64 of Second`. These agree on their unit: - the operands of `+`, `-`, `mod` and of a comparison; - an argument and its parameter; - a result and its declared type. A value changes unit only through `convert()`, which multiplies by an exact integer ratio between units of one dimension, or leaves or takes a unit through `magnitude()` and `measured()`. The host of a `drive` section (edition 0.4 preview, `spec/26 §2` rule 2) hands the state of the driven module from `init` to `step` and from `init` and `step` to `on_stop` unchanged, so that hand-off is such a flow too. The units of the result type of `init` and of the state parameters of `step` and `on_stop` MUST be the same at every position, at the top and in each type argument, as `Option[Int of Second]`. `init() -> Int of Second` with `step(edit state: Int of Millisecond, input: Tick)` is U2028 at the type of `state`. `una run` and `una build` refuse such a module too. A unit with no base unit and a scale other than 1, as `Kilometer / Meter`, stays a unit, and its `magnitude()` counts in steps of that scale. ## The repair at a glance `src/demo.una` ```diff module demo pub measure Meter pub measure Kilometer = 1000 * Meter - pub total(a: Int of Meter, b: Int of Kilometer) -> Int of Meter = a + b + pub total(a: Int of Meter, b: Int of Kilometer) -> Int of Meter = a + b.convert() ``` ## Failing example `una.toml` ```toml [package] name = "demo" version = "0.1.0" edition = "0.3" ``` `src/demo.una` ```una module demo pub measure Meter pub measure Kilometer = 1000 * Meter pub total(a: Int of Meter, b: Int of Kilometer) -> Int of Meter = a + b ``` ## Fixed example `una.toml` ```toml [package] name = "demo" version = "0.1.0" edition = "0.3" ``` `src/demo.una` ```una module demo pub measure Meter pub measure Kilometer = 1000 * Meter pub total(a: Int of Meter, b: Int of Kilometer) -> Int of Meter = a + b.convert() ``` --- # U2029: An invalid unit declaration or unit expression A unit declaration or a unit expression is invalid. ## Why Una rejects it A unit is declared with `measure` (ADR 0104): - a base unit by its name; - a derived unit by an expression of declared units and positive integer factors, as `measure Kilometer = 1000 * Meter`. A unit expression names only declared units, a derived unit does not refer to itself, and one with no base unit and scale 1 is refused, since it would be no unit at all. `of` follows only a number type: an integer type or `F64`, and in edition `0.5` (preview) `F32`, `Decimal[s]`, `Complex[F64]` and `Complex[F32]`. ## The repair at a glance `src/demo.una` ```diff module demo pub measure Meter - pub distance(d: Int of Meters) -> Int of Meter = d + pub distance(d: Int of Meter) -> Int of Meter = d ``` ## Failing example `una.toml` ```toml [package] name = "demo" version = "0.1.0" edition = "0.3" ``` `src/demo.una` ```una module demo pub measure Meter pub distance(d: Int of Meters) -> Int of Meter = d ``` ## Fixed example `una.toml` ```toml [package] name = "demo" version = "0.1.0" edition = "0.3" ``` `src/demo.una` ```una module demo pub measure Meter pub distance(d: Int of Meter) -> Int of Meter = d ``` --- # U2030: A unit conversion without an expected unit, or not exact A unit conversion has no expected unit, or is not exact. ## Why Una rejects it `measured()` and `convert()` take the unit they produce from the type their context expects (ADR 0104). `measured()` takes a unitless value, and `convert()` a measured one. `convert()` moves between units of one dimension only by a positive integer ratio that fits the magnitude's integer type: from `Kilometer` to `Meter` it multiplies by 1000. The way down is written out, `(d.magnitude() / 1000).measured()`, so that the truncation of the division shows. - On an `F64` the ratio may be k or 1/k with k at most 2^53, and in edition `0.5` (preview) on an `F32` at most 2^24. - In edition `0.5` (preview), on a decimal only k, since 1/k would round. - In edition `0.5` (preview), a complex or a dense value does not convert as a whole. ## The repair at a glance `src/demo.una` ```diff module demo pub measure Meter pub measure Kilometer = 1000 * Meter - pub coarse(d: Int of Meter) -> Int of Kilometer = d.convert() + pub coarse(d: Int of Meter) -> Int of Kilometer = (d.magnitude() / 1000).measured() ``` ## Failing example `una.toml` ```toml [package] name = "demo" version = "0.1.0" edition = "0.3" ``` `src/demo.una` ```una module demo pub measure Meter pub measure Kilometer = 1000 * Meter pub coarse(d: Int of Meter) -> Int of Kilometer = d.convert() ``` ## Fixed example `una.toml` ```toml [package] name = "demo" version = "0.1.0" edition = "0.3" ``` `src/demo.una` ```una module demo pub measure Meter pub measure Kilometer = 1000 * Meter pub coarse(d: Int of Meter) -> Int of Kilometer = (d.magnitude() / 1000).measured() ``` --- # U2031: A float literal rounds to an infinity, or is not zero and rounds to zero A float literal would round to an infinity, or is not zero and would round to zero. ## Why Una rejects it A float literal denotes the `F64` nearest its exact decimal value (`spec/29`, ADR 0114). - A literal beyond the largest finite `F64`, `1.7976931348623157e308`, would round to an infinity. - A literal that is not zero but below half the smallest positive `F64`, `5.0e-324`, would round to zero. Either way the program would compute with a value other than the one written, so the checker refuses the literal. A literal that rounds to a subnormal value is accepted. ## How to fix it - Write `infinity()` when an infinity is meant. - Write `0.0` when zero is meant. - Or write a value in range. ## The repair at a glance `src/demo.una` ```diff module demo - pub tiny() -> F64 = 1.0e-400 + pub tiny() -> F64 = 0.0 ``` ## Failing example `una.toml` ```toml [package] name = "demo" version = "0.1.0" edition = "0.3" ``` `src/demo.una` ```una module demo pub tiny() -> F64 = 1.0e-400 ``` ## Fixed example `una.toml` ```toml [package] name = "demo" version = "0.1.0" edition = "0.3" ``` `src/demo.una` ```una module demo pub tiny() -> F64 = 0.0 ``` --- # U2032: A float literal other than zero, or a float range, as a pattern A `when` arm or an `is` test does not match an `F64` against a float literal (`spec/29`, ADR 0114). A computed float rarely equals a literal exactly, and the test hides which equality is meant: the identity of `==`, under which `-0.0` and `0.0` differ, or IEEE equality. Compare in an `if`, with `==` for identity or an IEEE method such as `x.ieee_eq(other: 0.5)`. ## The repair at a glance `src/demo.una` ```diff module demo - pub is_half(x: F64) -> Bool = x is 0.5 + pub is_half(x: F64) -> Bool = x == 0.5 ``` ## Failing example `una.toml` ```toml [package] name = "demo" version = "0.1.0" edition = "0.3" ``` `src/demo.una` ```una module demo pub is_half(x: F64) -> Bool = x is 0.5 ``` ## Fixed example `una.toml` ```toml [package] name = "demo" version = "0.1.0" edition = "0.3" ``` `src/demo.una` ```una module demo pub is_half(x: F64) -> Bool = x == 0.5 ``` --- # U2033: A comparison of an `F64` with a float literal zero The code compares an `F64` with a float literal zero. ## Why Una rejects it `==` on `F64` is identity, and `<` is IEEE totalOrder (`spec/29`, ADR 0114): `-0.0` and `0.0` are two values, and `-0.0 < 0.0`. So `x == 0.0` is false and `x < 0.0` is true when `x` is `-0.0`, which ordinary arithmetic produces (`0.0 * -5.0`). Every mainstream language says the opposite. The checker refuses every comparison of an `F64` with a literal zero, `0.0` or `-0.0`, in code and in clauses: `==`, `!=`, `is`, a `when` arm, `<`, `<=`, `>` and `>=`. A clamp written with the prelude's `min` and `max` maps NaN to its upper bound; `x.clamp(lo: a, hi: b)` keeps NaN. Under totalOrder, NaN is the greatest `F64`, so `x > c` and `x >= c` are true for NaN for every literal `c`, and `contains(xs, item: 0.0)` finds only the positive zero. ## How to fix it The repairs say which test is meant: - for an equality, `x.is_zero()` accepts both zeros, and `x.is_positive_zero()` or `x.is_negative_zero()` one of them; - for an ordering, the IEEE methods `x.ieee_lt(other: 0.0)`, `x.ieee_le(other: 0.0)`, `x.ieee_gt(other: 0.0)` and `x.ieee_ge(other: 0.0)` treat the zeros as equal; `x.is_sign_negative()` tests the sign bit. ## The repair at a glance `src/demo.una` ```diff module demo - pub safe_ratio(n: F64, d: F64) -> F64 = if d == 0.0 then 0.0 else n / d + pub safe_ratio(n: F64, d: F64) -> F64 = if d.is_zero() then 0.0 else n / d ``` ## Failing example `una.toml` ```toml [package] name = "demo" version = "0.1.0" edition = "0.3" ``` `src/demo.una` ```una module demo pub safe_ratio(n: F64, d: F64) -> F64 = if d == 0.0 then 0.0 else n / d ``` ## Fixed example `una.toml` ```toml [package] name = "demo" version = "0.1.0" edition = "0.3" ``` `src/demo.una` ```una module demo pub safe_ratio(n: F64, d: F64) -> F64 = if d.is_zero() then 0.0 else n / d ``` --- # U2034: `stop` or `skip` outside a loop body, or across a task boundary A `stop` or `skip` is outside a loop body, or across a task boundary from its loop. ## Why Una rejects it In edition 0.4, `stop` ends the innermost `for` loop around it, `stop when c` does so when `c` holds, and `skip` ends the current iteration and goes on to the next (`spec/26 §3`, ADR 0116 rule 6). Each belongs to the body of its innermost loop. It is an error: - outside any loop body; - when the innermost loop lies outside the nearest enclosing task: the body of a `together for`, or a branch of `together`, is not a loop for them, so they cannot end an iteration of a loop that runs the task. A loop inside the task is a loop for them. ## How to fix it To end a task's work early: - Give its block a value with `if`. - Or put a `for` loop inside the task. ## The repair at a glance `src/demo.una` ```diff module demo pub doubled(xs: List[Int]) -> List[Int] = together for x in xs if x < 0 - skip - x + x + 0 + else + x + x ``` ## Failing example `ita.una` ```una ita demo version 0.1.0 edition 0.4 ``` `ita.lock` ```una lock 1 solver encoding "una-smt-1" name "z3" version "5.1.0" logic "QF_UFLIA" steps 5000000 seed 0 ``` `src/demo.una` ```una module demo pub doubled(xs: List[Int]) -> List[Int] = together for x in xs if x < 0 skip x + x ``` ## Fixed example `ita.una` ```una ita demo version 0.1.0 edition 0.4 ``` `ita.lock` ```una lock 1 solver encoding "una-smt-1" name "z3" version "5.1.0" logic "QF_UFLIA" steps 5000000 seed 0 ``` `src/demo.una` ```una module demo pub doubled(xs: List[Int]) -> List[Int] = together for x in xs if x < 0 0 else x + x ``` --- # U2035: `first of` with fewer than two branches, or a line that is not an expression; `start` outside the block of a `tasks`, inside a task within it, or with a `with` clause A `first of` or a `start` is written in a form or a place that is an error. ## Why Una rejects it In edition 0.4, `first of` races its branches: each line of its body is a branch, an expression with its `with` bindings, its deadline and its handling clauses, and each branch runs as a task (`spec/27 §6`, ADR 0117 rule 6). The first branch to return gives the value, and the others are canceled. It is an error: - when the body has fewer than two branches, since there is nothing to race; - when a line of the body is not an expression, such as a `let`, a loop or a `when`. `start` starts a task in the block of a `tasks` statement, which waits for every task it starts (`spec/27 §7`, ADR 0117 rule 7). It is an error: - outside the block of a `tasks` statement, where nothing would wait for the task; - inside a task within that block, a branch of `together` or `first of` or the body of a `together for`, or inside a lambda, since the task could then outlive what waits for it; - with a `with` clause, since a `with` scopes over its statement and the task outlives the statement. ## How to fix it For `first of`: - With one branch, write the expression alone. - For more steps in a branch, put them in a function and call it from the branch. For `start` with a `with` clause, install the handler around the call of the function that holds the `tasks` statement, or inside the started function. ## The repair at a glance `src/demo.una` ```diff module demo primary(n: Int) -> Int = n + 1 + replica(n: Int) -> Int = n + 1 + pub quote(n: Int) -> Int = let price = first of primary(n) + replica(n) price ``` ## Failing example `ita.una` ```una ita demo version 0.1.0 edition 0.4 ``` `ita.lock` ```una lock 1 solver encoding "una-smt-1" name "z3" version "5.1.0" logic "QF_UFLIA" steps 5000000 seed 0 ``` `src/demo.una` ```una module demo primary(n: Int) -> Int = n + 1 pub quote(n: Int) -> Int = let price = first of primary(n) price ``` ## Fixed example `ita.una` ```una ita demo version 0.1.0 edition 0.4 ``` `ita.lock` ```una lock 1 solver encoding "una-smt-1" name "z3" version "5.1.0" logic "QF_UFLIA" steps 5000000 seed 0 ``` `src/demo.una` ```una module demo primary(n: Int) -> Int = n + 1 replica(n: Int) -> Int = n + 1 pub quote(n: Int) -> Int = let price = first of primary(n) replica(n) price ``` --- # U2037: A decimal scale out of place In edition `0.5` (preview), a decimal scale is in a place where it would not fit. ## Why Una rejects it A `Decimal[s]` holds an exact number with s digits after the point, and its scale is part of the type (`spec/29 §16`, ADR 0120). The scale is an integer literal from 0 to 38. A value never loses a digit silently, so the checker refuses every place where a scale would not fit: - a scale above 38, or a `Decimal` type without its scale in brackets; - a float literal with a nonzero digit beyond the scale it takes, such as `19.995` as a `Decimal[2]`, also as the other operand of `+`, `-` or `*`, where the literal takes that operand's scale and never widens it; - a literal whose coefficient would have more than 4,300 digits, the language's digit cap; - a product whose scale, the sum of its operands' scales, is above 38; - `widen` to a smaller scale, and `rescale` or `rescale_exact` to a scale that is not smaller; - a scale argument, `scale:`, that is not an integer literal. ## How to fix it - Give the literal its own type (`let fee: Decimal[3] = 0.005`). - Write fewer digits. - Rescale an operand first. - Or use the method that matches the direction of the change: `widen` adds digits, `rescale` drops them with a written rounding mode. ## The repair at a glance `src/demo.una` ```diff module demo - pub price() -> Decimal[2] = 19.995 + pub price() -> Decimal[3] = 19.995 ``` ## Failing example `ita.una` ```una ita demo version 0.1.0 edition 0.5 ``` `ita.lock` ```una lock 1 solver encoding "una-smt-1" name "z3" version "5.1.0" logic "QF_UFLIA" steps 5000000 seed 0 ``` `src/demo.una` ```una module demo pub price() -> Decimal[2] = 19.995 ``` ## Fixed example `ita.una` ```una ita demo version 0.1.0 edition 0.5 ``` `ita.lock` ```una lock 1 solver encoding "una-smt-1" name "z3" version "5.1.0" logic "QF_UFLIA" steps 5000000 seed 0 ``` `src/demo.una` ```una module demo pub price() -> Decimal[3] = 19.995 ``` --- # U2038: A tensor shape, index, permutation or axis out of place In edition `0.5` (preview), a tensor shape, index, permutation or axis is out of place. ## Why Una rejects it A `Tensor[T]` has a rank from 1 to 8 and a length along each axis (`spec/29 §17`, ADR 0120). The checker reads a tensor's shapes, indices, permutations and axes from the source, so that each call gets the contract of its rank and the verifier proves its shapes with linear facts. So each is written as a literal: - the `shape:` of `tensor` and `tensor_filled`, the `at:` of `get`, `at` and `set`, and the `shape:` of `reshape`, are list literals of 1 to 8 elements, whose elements may be any `Int` expressions: `shape: [rows, 3]`; - the `axes:` of `permute` is a list literal of integer literals that is a permutation of 0 to r - 1, where r is its length: `axes: [1, 0]`; - the `axis:` of `dim` and `sum`, and the `axis:` and `other:` of `contract`, are integer literals from 0 to 7; - `tensor` and `tensor_filled` are not function values, since a function value's shape would be a run-time list; a lambda that calls one with a list literal is. ## How to fix it - Write the literal. - Or, for a computed shape, write a list literal of computed lengths: `tensor_filled(shape: [n, n], value: 0.0)`. ## The repair at a glance `src/demo.una` ```diff module demo - pub zeros(shape: List[Int]) -> Tensor[F64] = tensor_filled(shape: shape, value: 0.0) + pub zeros(n: Int) -> Tensor[F64] + requires n >= 0 + = + tensor_filled(shape: [n, n], value: 0.0) ``` ## Failing example `ita.una` ```una ita demo version 0.1.0 edition 0.5 ``` `ita.lock` ```una lock 1 solver encoding "una-smt-1" name "z3" version "5.1.0" logic "QF_UFLIA" steps 5000000 seed 0 ``` `src/demo.una` ```una module demo pub zeros(shape: List[Int]) -> Tensor[F64] = tensor_filled(shape: shape, value: 0.0) ``` ## Fixed example `ita.una` ```una ita demo version 0.1.0 edition 0.5 ``` `ita.lock` ```una lock 1 solver encoding "una-smt-1" name "z3" version "5.1.0" logic "QF_UFLIA" steps 5000000 seed 0 ``` `src/demo.una` ```una module demo pub zeros(n: Int) -> Tensor[F64] requires n >= 0 = tensor_filled(shape: [n, n], value: 0.0) ``` --- # U2039: A `map`, `zip_map` or `update` in a function with `simd required` whose lambda cannot be vectorized for a listed target Not reported by 0.4.0: reserved for the `simd required` clause, which this release does not read. ## Why Una rejects it A function of a `systems` package of edition `0.5` (preview) may require that its loops use the processor's vector instructions, with the clause `simd required target neon, avx2` after its `ensures` clauses: the `simd required` clause of ADR 0120 rule 58. Every `map`, `zip_map` and `update` with an inline lambda in its body, on a dense value of a float, complex or fixed-width element type, must then be vectorizable for each listed target. A lambda is vectorizable when: - its parameters, its captured values and its result have raw types (`F64`, `F32`, `I8` to `U64`), and - its body uses only `let`, an `if` on a raw condition, literals, and operators and methods that have a vector instruction on each listed target. It calls no function, performs no effect and cannot fail. U2039 names the construct, the target and the reason when one is not. Vectorization never changes a result: the lambda means the scalar loop it equals, and its checks and obligations stay (ADR 0120 rule 55, ADR 0109 rule 5). The clause lands with its slice of ADR 0120. Until then the release reads no `simd required` clause, so no program reports U2039, and this text has no example of its own. ## How to fix it - Remove the operation that has no vector instruction from the lambda, such as a call or a float `rem`. - Compute it outside the loop. - Or drop the target that lacks the instruction from the clause. --- # U2040: A statement after `stop` or `skip` in the same block, which never runs A statement comes after `stop` or `skip` in the same block, so it never runs. ## Why Una rejects it In edition 0.4, `stop` ends the innermost loop and `skip` ends the current iteration (`spec/26 §3`, ADR 0116 rule 6). A statement after an unconditional `stop` or `skip` in the same block can never run, which is almost always a mistake: the statement was meant to come before the exit, or under a condition. The checker refuses it, at the first such statement. `stop when c` is conditional, so statements after it run whenever `c` is false and stay legal. Statements after the block that holds the `stop` or `skip`, such as those after an `if` whose block ends in `skip`, run on the other paths and stay legal too. ## How to fix it The repair removes the statements after the exit. ## The repair at a glance `src/demo.una` ```diff module demo pub positives(xs: List[Int]) -> Int = let edit count = 0 for x in xs if x <= 0 skip - count = count - 1 count = count + 1 count ``` ## Failing example `ita.una` ```una ita demo version 0.1.0 edition 0.4 ``` `ita.lock` ```una lock 1 solver encoding "una-smt-1" name "z3" version "5.1.0" logic "QF_UFLIA" steps 5000000 seed 0 ``` `src/demo.una` ```una module demo pub positives(xs: List[Int]) -> Int = let edit count = 0 for x in xs if x <= 0 skip count = count - 1 count = count + 1 count ``` ## Fixed example `ita.una` ```una ita demo version 0.1.0 edition 0.4 ``` `ita.lock` ```una lock 1 solver encoding "una-smt-1" name "z3" version "5.1.0" logic "QF_UFLIA" steps 5000000 seed 0 ``` `src/demo.una` ```una module demo pub positives(xs: List[Int]) -> Int = let edit count = 0 for x in xs if x <= 0 skip count = count + 1 count ``` --- # U3001: Capability not in scope The code refers to a capability that no binding in scope holds. ## Why Una rejects it A capability operation `@c.op(...)` acts through the binding `@c` of the current capability context (`spec/05 §1, §3`): - a `uses` clause of the header; - a `with` binding of the statement; - a `given` line of an example; - the `uses` of the function type a lambda is written for. U3001 reports a reference that no binding in scope holds. It also reports: - a call whose callee needs `@x: C[ops]` when the caller holds no `@x`, or holds a capability other than `C` under that name (`spec/05 §4`); - a `do` line that needs a capability no `given` line binds (`spec/08 §2`); - a private function whose inferred reference cannot be given one capability, because no caller binds it or callers bind it to different capabilities (`spec/04 §5`). ## How to fix it - Bind it with `with` from a binding in scope, or install a handler with `given`. These keep the code's authority. - Declaring the capability with `uses` widens the header, and its repair says so (ADR 0097). ## The repair at a glance ```diff module demo capability Log op write(line: Text) -> Unit pub note(line: Text) -> Unit - uses @journal: Log[write] + uses @log: Log[write] = @log.write(line) ``` ## Failing example ```una module demo capability Log op write(line: Text) -> Unit pub note(line: Text) -> Unit uses @journal: Log[write] = @log.write(line) ``` ## Fixed example ```una module demo capability Log op write(line: Text) -> Unit pub note(line: Text) -> Unit uses @log: Log[write] = @log.write(line) ``` --- # U3002: Operation not permitted by capability type The code uses an operation that the capability type of the binding in scope does not permit. ## Why Una rejects it A binding `@x: C[ops]` permits only the operations listed in brackets; without brackets it permits all of them (`spec/05 §3`). U3002 reports: - an operation that the binding in scope does not permit; - a call whose callee needs more operations of `@x` than the caller holds, since passing a capability attenuates it but never widens it (`spec/05 §4`). ## How to fix it - When another binding in scope permits the operation, use it, or rebind the callee's reference to it with `with`. The code keeps its authority. - Adding the operation to the `uses` clause, or dropping the brackets to permit every operation, widens the header: every caller must then permit it too. That repair is marked as a widening in `--json` and ranks after the ones that keep authority (ADR 0097). ## The repair at a glance ```diff module demo capability Log op write(line: Text) -> Unit op flush() -> Unit pub finish() -> Unit - uses @log: Log[write] + uses @log: Log[write, flush] = @log.flush() ``` ## Failing example ```una module demo capability Log op write(line: Text) -> Unit op flush() -> Unit pub finish() -> Unit uses @log: Log[write] = @log.flush() ``` ## Fixed example ```una module demo capability Log op write(line: Text) -> Unit op flush() -> Unit pub finish() -> Unit uses @log: Log[write, flush] = @log.flush() ``` --- # U3003: Effects exceed declared `uses` The effects of a body exceed the `uses` that its header declares. ## Why Una rejects it The `uses` clauses of a header bound every effect of the body, including the effects of the functions it calls (`spec/04 §2`, `spec/10 §8`). A public function declares every `uses` explicitly (`spec/04 §5`), so a public function without `uses` is pure. - U3003 reports a call in it of a function, or an installation of a handler, that uses capabilities. - It also reports a function passed as an argument whose `uses` the expected function type does not allow (`spec/10 §2`). ## How to fix it - Call a pure function, which keeps the function pure. - Or declare the `uses` that the callee needs, which widens the header. That repair is marked as a widening (ADR 0097). ## The repair at a glance ```diff module demo capability Log op write(line: Text) -> Unit pub note(line: Text) -> Unit uses @log: Log[write] = @log.write(line) - pub report() -> Unit = note("done") + pub report() -> Unit + uses @log: Log[write] + = + note("done") ``` ## Failing example ```una module demo capability Log op write(line: Text) -> Unit pub note(line: Text) -> Unit uses @log: Log[write] = @log.write(line) pub report() -> Unit = note("done") ``` ## Fixed example ```una module demo capability Log op write(line: Text) -> Unit pub note(line: Text) -> Unit uses @log: Log[write] = @log.write(line) pub report() -> Unit uses @log: Log[write] = note("done") ``` --- # U3004: Capability used in a pure function A pure function uses a capability. ## Why Una rejects it A function without `uses` is pure: it cannot contain any `@` (`spec/04 §2` rule 4). This holds for: - a public function, which declares every `uses` explicitly; - a lambda whose expected function type has no `uses` (`spec/04 §6`), such as the argument of `map`. A private function without `uses` is not pure: its `uses` are inferred (`spec/04 §5`). ## How to fix it Declare the capability in the header, or in the function type the lambda is written for. The repair is marked as a widening of authority (ADR 0097). ## The repair at a glance ```diff module demo capability Log op write(line: Text) -> Unit - pub report() -> Unit = @log.write("done") + pub report() -> Unit + uses @log: Log[write] + = + @log.write("done") ``` ## Failing example ```una module demo capability Log op write(line: Text) -> Unit pub report() -> Unit = @log.write("done") ``` ## Fixed example ```una module demo capability Log op write(line: Text) -> Unit pub report() -> Unit uses @log: Log[write] = @log.write("done") ``` --- # U3005: Capability reference used as a value Capability references are not values (`spec/05 §6`). A bare `@c`, not followed by `.op(...)`, appears only on either side of a `with` binding and after `given @x =` (`spec/02 §8`); it cannot be bound with `let`, passed as an argument, returned, stored in a kind, compared or interpolated. Authority moves only downward along calls, by name: the callee declares the capability with `uses`, and the caller passes it under that name or rebinds it with `with`. ## The repair at a glance ```diff module demo capability Log op write(line: Text) -> Unit - pub run() -> Unit + pub note(line: Text) -> Unit uses @log: Log[write] = - let sink = @log - unit + @log.write(line) + + pub run() -> Unit + uses @sink: Log[write] + = + note("done") with @log = @sink ``` ## Failing example ```una module demo capability Log op write(line: Text) -> Unit pub run() -> Unit uses @log: Log[write] = let sink = @log unit ``` ## Fixed example ```una module demo capability Log op write(line: Text) -> Unit pub note(line: Text) -> Unit uses @log: Log[write] = @log.write(line) pub run() -> Unit uses @sink: Log[write] = note("done") with @log = @sink ``` --- # U3006: Effectful or failing lambda escapes A lambda or a function with `uses` or `fails` is bound with `let`, returned or stored. ## Why Una rejects it A lambda whose function type has `uses` or `fails` is second-class: it may be passed directly as a call argument, and nothing else (`spec/05 §6`, `spec/10 §9`). It cannot be bound with `let`, returned or stored, so that the authority it carries never outlives the call. The same holds for a function with `uses` or `fails` used as a value. A kind cannot have a field of such a function type. ## How to fix it Pass the lambda or the function directly where it is called. ## The repair at a glance ```diff module demo capability Log op write(line: Text) -> Unit pub each(lines: List[Text], write: fn(Text) -> Unit uses @log: Log[write]) -> Unit uses @log: Log[write] = unit pub run(lines: List[Text]) -> Unit uses @log: Log[write] = - let write: fn(Text) -> Unit uses @log: Log[write] = fn(line) -> @log.write(line) - each(lines, write) + each(lines, write: fn(line) -> @log.write(line)) ``` ## Failing example ```una module demo capability Log op write(line: Text) -> Unit pub each(lines: List[Text], write: fn(Text) -> Unit uses @log: Log[write]) -> Unit uses @log: Log[write] = unit pub run(lines: List[Text]) -> Unit uses @log: Log[write] = let write: fn(Text) -> Unit uses @log: Log[write] = fn(line) -> @log.write(line) each(lines, write) ``` ## Fixed example ```una module demo capability Log op write(line: Text) -> Unit pub each(lines: List[Text], write: fn(Text) -> Unit uses @log: Log[write]) -> Unit uses @log: Log[write] = unit pub run(lines: List[Text]) -> Unit uses @log: Log[write] = each(lines, write: fn(line) -> @log.write(line)) ``` --- # U3007: Fallible expression without handling Failures never propagate implicitly: a statement, `let` or final expression that can fail is followed by an `if error` clause, or its call is wrapped in `attempt` (`spec/06 §3, §5`). `if error fail V` turns the failure into a variant of the function's error kind, `if error pass` propagates it unchanged when the kinds are equal, and `if error use e` recovers with a value. The message names the call and the error kind it can fail with. ## The repair at a glance ```diff module demo kind StoreError = Timeout | Corrupted capability Store op find(key: Int) -> Option[Int] fails StoreError pub has(key: Int) -> Bool uses @store: Store[find] = let found = @store.find(key) + if error use None found.is_some() ``` ## Failing example ```una module demo kind StoreError = Timeout | Corrupted capability Store op find(key: Int) -> Option[Int] fails StoreError pub has(key: Int) -> Bool uses @store: Store[find] = let found = @store.find(key) found.is_some() ``` ## Fixed example ```una module demo kind StoreError = Timeout | Corrupted capability Store op find(key: Int) -> Option[Int] fails StoreError pub has(key: Int) -> Bool uses @store: Store[find] = let found = @store.find(key) if error use None found.is_some() ``` --- # U3008: `if error pass` with a different error kind An `if error pass` passes a failure whose error kind is not the error kind of the current function. ## Why Una rejects it `if error pass` propagates a failure unchanged, so the error kind of the expression must equal the error kind of the current function (`spec/06 §3`): a function has at most one error kind (`spec/06 §1`). A function without `fails` cannot pass a failure at all, except a private one, whose error kind is inferred from its first failure in source order (`spec/04 §5` rule 3, ADR 0099): a pass of another kind is reported here. ## How to fix it - Convert the failure instead with `if error fail V`, where `V` is a variant of the function's error kind. - Or declare the kind with `fails`. ## The repair at a glance ```diff module demo kind StoreError = Timeout | Corrupted kind LookupError = Missing | Unavailable capability Store op find(key: Int) -> Option[Int] fails StoreError pub lookup(key: Int) -> Option[Int] uses @store: Store[find] fails LookupError = @store.find(key) - if error pass + if error fail Unavailable ``` ## Failing example ```una module demo kind StoreError = Timeout | Corrupted kind LookupError = Missing | Unavailable capability Store op find(key: Int) -> Option[Int] fails StoreError pub lookup(key: Int) -> Option[Int] uses @store: Store[find] fails LookupError = @store.find(key) if error pass ``` ## Fixed example ```una module demo kind StoreError = Timeout | Corrupted kind LookupError = Missing | Unavailable capability Store op find(key: Int) -> Option[Int] fails StoreError pub lookup(key: Int) -> Option[Int] uses @store: Store[find] fails LookupError = @store.find(key) if error fail Unavailable ``` --- # U3009: Failure variant not in the declared error kind A failure names a variant that is not a variant of the function's error kind. ## Why Una rejects it `fail V` ends the function with a failure, and `V` must be a variant of the function's error kind (`spec/06 §2`). A function without `fails` cannot fail (`spec/04 §2` rule 4). The same holds for: - `fail` after `if error` and `if none`; - `checked`; - handler operations, which fail only with their operation's error kind (`spec/05 §5`); - a function passed as an argument, which fails only as its expected function type allows (`spec/10 §2`). A private function without `fails` has the error kind of its first failure in source order inferred, a raised variant or a passed failure (`spec/04 §5` rule 3, ADR 0099), so a variant of another kind is reported where it is raised. ## The repair at a glance ```diff module demo kind StoreError = Timeout | Corrupted kind LookupError = Missing | Unavailable pub check(key: Int) -> Int fails LookupError = - if key < 0 then fail Timeout else key + if key < 0 then fail Missing else key ``` ## Failing example ```una module demo kind StoreError = Timeout | Corrupted kind LookupError = Missing | Unavailable pub check(key: Int) -> Int fails LookupError = if key < 0 then fail Timeout else key ``` ## Fixed example ```una module demo kind StoreError = Timeout | Corrupted kind LookupError = Missing | Unavailable pub check(key: Int) -> Int fails LookupError = if key < 0 then fail Missing else key ``` --- # U3010: Handler does not match its capability A handler implements the capability it names after `for`, with one implementation per operation, named as the capability names it and with the same number of parameters (`spec/05 §5`). A handler installed with `with @x = h(args)` or `given @x = h(args)` implements the capability that the statement or the `do` line needs at `@x`, and the name installed is a handler (`spec/05 §4`, `spec/02 §8`). U3010 reports a `for` that names something other than a capability, an operation that the capability lacks or with another parameter count, and an installation of something other than a matching handler. ## The repair at a glance ```diff module demo capability Log op write(line: Text) -> Unit - capability Audit - op record(line: Text) -> Unit - - handler silent() for Audit - op record(line) = unit + handler silent() for Log + op write(line) = unit pub note(line: Text) -> Unit uses @log: Log[write] = @log.write(line) pub report() -> Unit = note("done") with @log = silent() ``` ## Failing example ```una module demo capability Log op write(line: Text) -> Unit capability Audit op record(line: Text) -> Unit handler silent() for Audit op record(line) = unit pub note(line: Text) -> Unit uses @log: Log[write] = @log.write(line) pub report() -> Unit = note("done") with @log = silent() ``` ## Fixed example ```una module demo capability Log op write(line: Text) -> Unit handler silent() for Log op write(line) = unit pub note(line: Text) -> Unit uses @log: Log[write] = @log.write(line) pub report() -> Unit = note("done") with @log = silent() ``` --- # U3011: Handler missing an operation A handler implements every operation of its capability (`spec/05 §5` rule 1): an installed handler stands for the whole capability, whatever operations a caller needs. The message lists the operations that are missing. Add an `op` line for each of them. ## The repair at a glance ```diff module demo capability Log op write(line: Text) -> Unit op flush() -> Unit handler silent() for Log op write(line) = unit + op flush() = unit ``` ## Failing example ```una module demo capability Log op write(line: Text) -> Unit op flush() -> Unit handler silent() for Log op write(line) = unit ``` ## Fixed example ```una module demo capability Log op write(line: Text) -> Unit op flush() -> Unit handler silent() for Log op write(line) = unit op flush() = unit ``` --- # U3012: Host capability in `main` not granted by `una run` A `uses` clause of `main` names a host operation that no grant allows. ## Why Una rejects it Host capabilities enter a program only through the `uses` of `main`, and `una run` grants only the capabilities listed in `--grant` flags or in the package's grants: `[run] grants` in `una.toml`, or from edition `0.4` the `grants` line of the `run` section of `ita.una` (`spec/04 §8`, `spec/05 §7`). - When the package lists grants, `una check` compares them with the host operations in the `uses` of `main` in the entry module, and reports each `uses` clause with an operation that no grant allows. - `una run` reports it too, before anything runs, with the package's grants and those of its `--grant` flags together (`spec/13 §5`). ## How to fix it - Remove the `uses` clause when `main` does not need the operation. - Otherwise add a grant spec for the capability, such as `"clock"`, to `[run] grants` in `una.toml`, or from edition `0.4` to the `grants` of the `run` section of `ita.una`, or pass it to `una run` as `--grant clock`. The program then gets this host authority when it runs, and the repair is marked as a `grant` widening (ADR 0097). - For a capability that is not a host capability, no grant provides it: install a handler for it with `with` inside `main`. ## The repair at a glance `una.toml` ```diff [package] name = "demo" version = "0.1.0" edition = "0.1" [run] entry = "demo" - grants = ["console"] + grants = ["console", "clock"] ``` ## Failing example `una.toml` ```toml [package] name = "demo" version = "0.1.0" edition = "0.1" [run] entry = "demo" grants = ["console"] ``` `src/demo.una` ```una module demo pub main() -> Unit uses @console: Console[print] uses @clock: Clock[now] = let now = @clock.now() @console.print("now: {now}") ``` ## Fixed example `una.toml` ```toml [package] name = "demo" version = "0.1.0" edition = "0.1" [run] entry = "demo" grants = ["console", "clock"] ``` `src/demo.una` ```una module demo pub main() -> Unit uses @console: Console[print] uses @clock: Clock[now] = let now = @clock.now() @console.print("now: {now}") ``` --- # U3013: Effectful or fallible call nested inside an expression A capability operation, or a call of a function that uses capabilities or can fail, is nested inside another expression or an argument. ## Why Una rejects it One effect per line: a capability operation, or a call of a function that uses capabilities or can fail, is the whole expression of a statement, a `let` right-hand side or a final expression, optionally wrapped in `attempt` (`spec/04 §4`). It cannot be nested inside another expression or an argument. This fixes the order of evaluation, gives every failure a handling site and makes every effect visible on its own line. Example `do` lines are exempt (`spec/08 §2` rule 5). ## How to fix it Bind the result with `let` first. ## The repair at a glance ```diff module demo capability Clock op now() -> Int pub later() -> Int uses @clock: Clock[now] = - 1 + @clock.now() + let now = @clock.now() + 1 + now ``` ## Failing example ```una module demo capability Clock op now() -> Int pub later() -> Int uses @clock: Clock[now] = 1 + @clock.now() ``` ## Fixed example ```una module demo capability Clock op now() -> Int pub later() -> Int uses @clock: Clock[now] = let now = @clock.now() 1 + now ``` --- # U3014: Host capability used in an example Examples, the tests written `test` from edition 0.3 and `example` in editions 0.1 and 0.2 (ADR 0105), are deterministic, so they never reach the host: every capability that the `do` line needs comes from a `given` line (`spec/08 §2` rule 1). U3014 reports a `do` line that needs a host capability (`Console`, `Clock`, `Env`, `Files` or `Keys`, from edition 0.2 also `Http`, and from edition 0.4 `HttpServer`, `spec/14 §3`) that no `given` line binds. User code may write a handler for a host capability and install it with `given`. ## The repair at a glance ```diff module demo + handler quiet() for Console + op print(line) = unit + pub greet(name: Text) -> Unit uses @console: Console[print] = @console.print("hello {name}") example "a greeting" + given @console = quiet() do greet("Ana") - expect true + expect performed @console.print ``` ## Failing example ```una module demo pub greet(name: Text) -> Unit uses @console: Console[print] = @console.print("hello {name}") example "a greeting" do greet("Ana") expect true ``` ## Fixed example ```una module demo handler quiet() for Console op print(line) = unit pub greet(name: Text) -> Unit uses @console: Console[print] = @console.print("hello {name}") example "a greeting" given @console = quiet() do greet("Ana") expect performed @console.print ``` --- # U3015: `std.testing` used outside a handler or example A function of `std.testing` is used outside handler operation bodies and the lines of a test. ## Why Una rejects it The functions of `std.testing`, such as `fake_hash`, produce fake values for tests. They are usable only inside handler operation bodies and the lines of a test, an `example` in editions 0.1 and 0.2 and a `test` in edition 0.3 (`spec/14 §4`, ADR 0105), so production code never depends on them. - Importing `std.testing` is allowed. U3015 reports a call of, or a reference to, one of its functions elsewhere. - A handler that uses `std.testing` is installed only by `given` lines of examples: installing it with a `with` binding is U3015 at the binding. - A function of `std.testing` used as a value, not called, is U3015 everywhere (ADR 0043). ## How to fix it Move the fake into a handler, and install the handler in the example. ## The repair at a glance ```diff module demo import std.testing (fake_hash) - pub digest(seed: Int) -> internal Hashed = fake_hash(seed) + capability Hasher + op hash(seed: Int) -> internal Hashed + + handler fake() for Hasher + op hash(seed) = fake_hash(seed) + + pub digest(seed: Int) -> internal Hashed + uses @hasher: Hasher[hash] + = + @hasher.hash(seed) + + example "a digest" + given @hasher = fake() + do digest(1) + expect result == fake_hash(1) ``` ## Failing example ```una module demo import std.testing (fake_hash) pub digest(seed: Int) -> internal Hashed = fake_hash(seed) ``` ## Fixed example ```una module demo import std.testing (fake_hash) capability Hasher op hash(seed: Int) -> internal Hashed handler fake() for Hasher op hash(seed) = fake_hash(seed) pub digest(seed: Int) -> internal Hashed uses @hasher: Hasher[hash] = @hasher.hash(seed) example "a digest" given @hasher = fake() do digest(1) expect result == fake_hash(1) ``` --- # U3016: Second-class type used as a type argument A function type with `uses` or `fails` instantiates a type parameter. U3016 points at the written type argument, or at the value whose type instantiates the type parameter. ## Why Una rejects it A function type with `uses` or `fails` is second-class (`spec/05 §6`, ADR 0038 D2). It may be the type of a parameter, so an effectful or failing function can be passed directly as a call argument and called there. But it can never instantiate a type parameter: - not as a written type argument, such as `List[fn() -> Unit uses @log: Log[write]]` or `Option[fn(Int) -> Int fails Boom]`; - not by inference, such as `id(note)` for a generic `id[T](x: T) -> T` and a function `note` with `uses`. A value of type `T` can be bound, stored or returned, so a second-class type in its place would carry authority out of the `with` scope where it was created. ## How to fix it Pass the function directly to the function that calls it, with a parameter of function type. ## The repair at a glance ```diff module demo capability Log op write(line: Text) -> Unit - id[T](x: T) -> T = x - note(line: Text) -> Unit uses @log: Log[write] = @log.write(line) run(write: fn(Text) -> Unit uses @log: Log[write]) -> Unit uses @log: Log[write] = write("hello") pub main() -> Unit uses @log: Log[write] = - run(id(note)) + run(note) ``` ## Failing example ```una module demo capability Log op write(line: Text) -> Unit id[T](x: T) -> T = x note(line: Text) -> Unit uses @log: Log[write] = @log.write(line) run(write: fn(Text) -> Unit uses @log: Log[write]) -> Unit uses @log: Log[write] = write("hello") pub main() -> Unit uses @log: Log[write] = run(id(note)) ``` ## Fixed example ```una module demo capability Log op write(line: Text) -> Unit note(line: Text) -> Unit uses @log: Log[write] = @log.write(line) run(write: fn(Text) -> Unit uses @log: Log[write]) -> Unit uses @log: Log[write] = write("hello") pub main() -> Unit uses @log: Log[write] = run(note) ``` --- # U3017: `of` clause that names no parameter In edition 0.2, a function header can write `uses of p` and `fails of p`: the function performs the effects, and passes the failures, of whatever function its parameter `p` receives (ADR 0062, `spec/05 §9` rule 9). `p` MUST be one of the function's own parameters. A name that is no parameter, often a typo or a parameter renamed later, is U3017 at the name in the clause. ## The repair at a glance `src/demo.una` ```diff module demo pub apply_all(xs: List[Int], each: fn(Int) -> Unit) -> Unit - uses of action + uses of each = for x in xs each(x) ``` ## Failing example `una.toml` ```toml [package] name = "demo" version = "0.1.0" edition = "0.2" ``` `src/demo.una` ```una module demo pub apply_all(xs: List[Int], each: fn(Int) -> Unit) -> Unit uses of action = for x in xs each(x) ``` ## Fixed example `una.toml` ```toml [package] name = "demo" version = "0.1.0" edition = "0.2" ``` `src/demo.una` ```una module demo pub apply_all(xs: List[Int], each: fn(Int) -> Unit) -> Unit uses of each = for x in xs each(x) ``` --- # U3018: `of` clause that names a parameter not of function type `uses of p` and `fails of p` give a function the effects and failures of the function that parameter `p` receives, so `p` MUST have a function type (ADR 0062). Naming a parameter of another type, such as a list or a number, is U3018. Name the parameter of function type instead. ## The repair at a glance `src/demo.una` ```diff module demo pub apply_all(xs: List[Int], each: fn(Int) -> Unit) -> Unit - uses of xs + uses of each = for x in xs each(x) ``` ## Failing example `una.toml` ```toml [package] name = "demo" version = "0.1.0" edition = "0.2" ``` `src/demo.una` ```una module demo pub apply_all(xs: List[Int], each: fn(Int) -> Unit) -> Unit uses of xs = for x in xs each(x) ``` ## Fixed example `una.toml` ```toml [package] name = "demo" version = "0.1.0" edition = "0.2" ``` `src/demo.una` ```una module demo pub apply_all(xs: List[Int], each: fn(Int) -> Unit) -> Unit uses of each = for x in xs each(x) ``` --- # U3019: `of` clause that names a function type with its own `uses` or `fails` An `of` clause leaves the effects and failures of a parameter open: each call gives them by its argument (ADR 0062). A parameter whose type writes its own `uses` or `fails`, as in `fn(Int) -> Unit uses @log: Log[write]`, fixes them already, so `uses of` or `fails of` on it is U3019. Remove the clauses from the parameter's type to make it open, or remove the `of` clause to keep the fixed effects. ## The repair at a glance `src/demo.una` ```diff module demo pub capability Log op write(line: Text) -> Unit - pub apply_all(xs: List[Int], each: fn(Int) -> Unit uses @log: Log[write]) -> Unit - uses @log: Log[write] + pub apply_all(xs: List[Int], each: fn(Int) -> Unit) -> Unit uses of each = for x in xs each(x) ``` ## Failing example `una.toml` ```toml [package] name = "demo" version = "0.1.0" edition = "0.2" ``` `src/demo.una` ```una module demo pub capability Log op write(line: Text) -> Unit pub apply_all(xs: List[Int], each: fn(Int) -> Unit uses @log: Log[write]) -> Unit uses @log: Log[write] uses of each = for x in xs each(x) ``` ## Fixed example `una.toml` ```toml [package] name = "demo" version = "0.1.0" edition = "0.2" ``` `src/demo.una` ```una module demo pub capability Log op write(line: Text) -> Unit pub apply_all(xs: List[Int], each: fn(Int) -> Unit) -> Unit uses of each = for x in xs each(x) ``` --- # U3020: Call into a boundary module whose capability is not granted with `with` A call into a boundary module needs a capability that the call does not grant with `with`. ## Why Una rejects it From edition `0.3`, `una.toml` can declare modules of the package as boundaries under `[boundaries]`, and from edition `0.4` the `boundaries` section of `ita.una` does (ADR 0093): code the package's author does not control, such as a vendored library or a plug-in. No authority crosses a boundary by name. A call into a boundary module, from any module outside its extent, does not meet the callee's `uses` from the caller's bindings by name. Every capability the callee needs is granted at the call with `with`, as a rebinding, a narrowed rebinding (`@y[ops]`) or a handler. The same holds for: - a function of a boundary used as a value outside it, at the reference; - a handler of a boundary installed outside it, whose `uses` are granted by another binding of the same `with`. An example's `do` line takes no `with`, so an example outside a boundary can call only boundary functions that need no capability. ## How to fix it The repair is a grant at the call, within the boundary's ceiling (U3021), narrowed to what the callee declares. - When the ceiling allows every operation the callee needs and the caller holds a binding that permits them, the first repair is `with @x = @y[ops]`. `una fix` applies it at a call that is its statement's whole expression, when `@y` is `@x` itself or the only binding that qualifies. - When several bindings qualify, the repair lists them and carries no edit: which resource the boundary receives is the consumer's decision. - When the ceiling withholds an operation, no grant is offered. The repair is a handler whose own `uses` lie within the ceiling, and it names what the ceiling withholds. Widening the caller's header or the ceiling is never the repair: the grant is what the consumer reviews, and the ceiling is the consumer's decision. ## The repair at a glance `src/demo/app.una` ```diff module demo.app import demo.store (Files) import demo.vendor (load) pub open(path: Text) -> Text uses @files: Files[read, write] = - load(path) + load(path) with @files = @files[read] ``` ## Failing example `una.toml` ```toml [package] name = "demo" version = "0.1.0" edition = "0.3" [boundaries] "demo.vendor" = ["Files[read]"] ``` `src/demo/store.una` ```una module demo.store pub capability Files op read(path: Text) -> Text op write(path: Text, data: Text) -> Unit ``` `src/demo/vendor.una` ```una module demo.vendor import demo.store (Files) pub load(path: Text) -> Text uses @files: Files[read] = @files.read(path) ``` `src/demo/app.una` ```una module demo.app import demo.store (Files) import demo.vendor (load) pub open(path: Text) -> Text uses @files: Files[read, write] = load(path) ``` ## Fixed example `una.toml` ```toml [package] name = "demo" version = "0.1.0" edition = "0.3" [boundaries] "demo.vendor" = ["Files[read]"] ``` `src/demo/store.una` ```una module demo.store pub capability Files op read(path: Text) -> Text op write(path: Text, data: Text) -> Unit ``` `src/demo/vendor.una` ```una module demo.vendor import demo.store (Files) pub load(path: Text) -> Text uses @files: Files[read] = @files.read(path) ``` `src/demo/app.una` ```una module demo.app import demo.store (Files) import demo.vendor (load) pub open(path: Text) -> Text uses @files: Files[read, write] = load(path) with @files = @files[read] ``` --- # U3021: Call that grants a boundary module more than its ceiling A call into a boundary module grants it more than its ceiling. ## Why Una rejects it From edition `0.3`, each entry of `[boundaries]` in `una.toml`, or from edition `0.4` of the `boundaries` section of `ita.una`, gives a boundary module its ceiling: the most authority it may ever receive, as `C[ops]` strings (ADR 0093). At every call into the boundary, what the call grants must lie within the ceiling: - each `with` binding that the callee's `uses` name counts at every operation the binding permits, not only those the callee declares, so rebinding a read-write binding as it is grants both; - a handler counts with its own `uses`, the authority it runs with on the boundary's behalf; - the `uses` of a function value or lambda given as an argument count too, since the boundary can run it. The examples of a boundary module grant it their `given` handlers, each with its own `uses`, and are checked the same way, at the `given` line. ## How to fix it - The repair narrows the grant to the ceiling, with `with @x = @y[ops]` or a handler whose `uses` lie within it. - When the callee needs more than the ceiling, no grant keeps both, and the repair says so: the consumer decides between the library and the ceiling. Raising the ceiling is a decision about trust, never a repair, and `una fix` never applies an edit of U3021 nor writes `una.toml` or `ita.una`. ## The repair at a glance `src/demo/app.una` ```diff module demo.app import demo.store (Files) import demo.vendor (load) pub open(path: Text) -> Text uses @files: Files[read, write] = - load(path) with @files = @files + load(path) with @files = @files[read] ``` ## Failing example `una.toml` ```toml [package] name = "demo" version = "0.1.0" edition = "0.3" [boundaries] "demo.vendor" = ["Files[read]"] ``` `src/demo/store.una` ```una module demo.store pub capability Files op read(path: Text) -> Text op write(path: Text, data: Text) -> Unit ``` `src/demo/vendor.una` ```una module demo.vendor import demo.store (Files) pub load(path: Text) -> Text uses @files: Files[read] = @files.read(path) ``` `src/demo/app.una` ```una module demo.app import demo.store (Files) import demo.vendor (load) pub open(path: Text) -> Text uses @files: Files[read, write] = load(path) with @files = @files ``` ## Fixed example `una.toml` ```toml [package] name = "demo" version = "0.1.0" edition = "0.3" [boundaries] "demo.vendor" = ["Files[read]"] ``` `src/demo/store.una` ```una module demo.store pub capability Files op read(path: Text) -> Text op write(path: Text, data: Text) -> Unit ``` `src/demo/vendor.una` ```una module demo.vendor import demo.store (Files) pub load(path: Text) -> Text uses @files: Files[read] = @files.read(path) ``` `src/demo/app.una` ```una module demo.app import demo.store (Files) import demo.vendor (load) pub open(path: Text) -> Text uses @files: Files[read, write] = load(path) with @files = @files[read] ``` --- # U3022: Labeled operation passed to code that reads it lower A call passes a binding whose operation gives more than the label at which the callee reads its answers. ## Why Una rejects it In edition `0.3`, an operation listed in a header's `uses` brackets can carry `gives` and a label: `uses @service_files: Files[owner gives internal[Service]]` says that what `owner` answers through this binding, the value and whether it failed, belongs to the principal `Service` (ADR 0094, `spec/05 §3`). The answer then carries the label, and the flow rules of `spec/07` keep it from reaching anyone below it. A binding flows to a callee by name or with `with`, and its labels go with it. The callee reads the operation's answers at the label its own header writes, `public` when it writes none. A private function without `uses` clauses infers its labels instead, the join of what its callers pass, so the labeled binding reaches it and its body reads the answers at that label. A binding whose operation gives more than that is refused at the call with U3022: the callee would read the answer below its label. ## How to fix it The repairs never lower a label: - Pass another binding whose operation gives at most what the callee reads, when the caller holds one. - Or raise the `gives` in the callee's header, which then changes what its callers see. ## The repair at a glance `src/demo.una` ```diff module demo pub capability Files op owner(file: Text) -> Text - owner_seen(file: Text) -> Text - uses @files: Files[owner] + owner_seen(file: Text) -> internal[Service] Text + uses @files: Files[owner gives internal[Service]] = @files.owner(file) pub refusal(file: Text) -> internal[Service] Text uses @service_files: Files[owner gives internal[Service]] = let seen = owner_seen(file) with @files = @service_files seen ``` ## Failing example `una.toml` ```toml [package] name = "demo" version = "0.1.0" edition = "0.3" [labels] categories = ["Service"] ``` `src/demo.una` ```una module demo pub capability Files op owner(file: Text) -> Text owner_seen(file: Text) -> Text uses @files: Files[owner] = @files.owner(file) pub refusal(file: Text) -> internal[Service] Text uses @service_files: Files[owner gives internal[Service]] = let seen = owner_seen(file) with @files = @service_files seen ``` ## Fixed example `una.toml` ```toml [package] name = "demo" version = "0.1.0" edition = "0.3" [labels] categories = ["Service"] ``` `src/demo.una` ```una module demo pub capability Files op owner(file: Text) -> Text owner_seen(file: Text) -> internal[Service] Text uses @files: Files[owner gives internal[Service]] = @files.owner(file) pub refusal(file: Text) -> internal[Service] Text uses @service_files: Files[owner gives internal[Service]] = let seen = owner_seen(file) with @files = @service_files seen ``` --- # U3023: Header that grants more than its lock in `una.toml` The header of a public function grants more than its lock in `una.toml`, or from edition `0.4` in `ita.una`. ## Why Una rejects it From edition `0.3`, `una.toml` can lock the `uses` of a public function under `[contracts]`, and from edition `0.4` the `contracts` section of `ita.una` does (ADR 0092 rule 8). The lock is the consumer's file, so an edit to the function's header cannot widen what the function may do. The header must be at least as strong as its lock: - every binding of the header is one that the lock names, with the same capability; - every operation of a binding is one that the lock lists; - the header's condition on a locked operation implies the lock's condition. This is a `contract_lock` obligation, and when it is refuted the diagnostic is U3023 too; - the header reads a locked operation at least at the label the lock writes after `gives` (ADR 0094): a lock `"@service_files: Files[owner gives internal[Service]]"` refuses a header that reads `owner` at `public` or at a label that leaves out `Service`. `una fix` writes the label back, joined with the header's. A header may drop a binding or an operation, strengthen a condition, or read an operation at a higher label: that grants less. ## How to fix it The repair is to bring the header back to its lock. Changing the lock is never the repair. ## The repair at a glance `src/demo.una` ```diff module demo pub capability Catalog op price(sku: Int) -> Int op set_price(sku: Int, cents: Int) -> Unit pub update(sku: Int, cents: Int, dry_run: Bool) -> Unit - uses @shop: Catalog[price, set_price] + uses @catalog: Catalog[price, set_price where not dry_run] = - @shop.set_price(sku, cents) + if not dry_run + @catalog.set_price(sku, cents) + unit ``` ## Failing example `una.toml` ```toml [package] name = "demo" version = "0.1.0" edition = "0.3" [contracts] "demo.update" = ["@catalog: Catalog[price, set_price where not dry_run]"] ``` `src/demo.una` ```una module demo pub capability Catalog op price(sku: Int) -> Int op set_price(sku: Int, cents: Int) -> Unit pub update(sku: Int, cents: Int, dry_run: Bool) -> Unit uses @shop: Catalog[price, set_price] = @shop.set_price(sku, cents) ``` ## Fixed example `una.toml` ```toml [package] name = "demo" version = "0.1.0" edition = "0.3" [contracts] "demo.update" = ["@catalog: Catalog[price, set_price where not dry_run]"] ``` `src/demo.una` ```una module demo pub capability Catalog op price(sku: Int) -> Int op set_price(sku: Int, cents: Int) -> Unit pub update(sku: Int, cents: Int, dry_run: Bool) -> Unit uses @catalog: Catalog[price, set_price where not dry_run] = if not dry_run @catalog.set_price(sku, cents) unit ``` --- # U3024: Call into a boundary module from which a release is reachable A call goes into a boundary module, and a release is reachable from it. ## Why Una rejects it In edition `0.3`, a boundary module (ADR 0093) never declassifies. A call into a boundary, from which a release is reachable, is an error: a call of a policy (`spec/07 §5`), through the callee's body, the functions it calls, the handlers it may run, and the functional arguments granted at the call. The primary span is the call, and the related span is the release. Releases stay in the trusted modules (`spec/07 §6`), and a boundary module is never one of them. A vendored library or a plug-in that lowers a label would release information with the consumer's authority, outside the code the consumer trusts. ## How to fix it The repair is to move the release into a trusted module of the consumer, before or after the call into the boundary. `una fix` never applies one. ## The repair at a glance `src/demo/vendor.una` ```diff module demo.vendor - import demo.release (reveal) - - pub count(n: secret Int) -> Int = reveal(n) + 1 + pub count(n: Int) -> Int = n + 1 ``` `src/demo/app.una` ```diff module demo.app + import demo.release (reveal) import demo.vendor (count) - pub total(n: secret Int) -> Int = count(n) + pub total(n: secret Int) -> Int = count(reveal(n)) ``` ## Failing example `una.toml` ```toml [package] name = "demo" version = "0.1.0" edition = "0.3" [boundaries] "demo.vendor" = [] [trusted] modules = ["demo.release"] ``` `src/demo/release.una` ```una trusted module demo.release pub policy reveal from secret Int to public Int via open purpose "count" owner ops open(n: secret Int) -> public Int = n ``` `src/demo/vendor.una` ```una module demo.vendor import demo.release (reveal) pub count(n: secret Int) -> Int = reveal(n) + 1 ``` `src/demo/app.una` ```una module demo.app import demo.vendor (count) pub total(n: secret Int) -> Int = count(n) ``` ## Fixed example `una.toml` ```toml [package] name = "demo" version = "0.1.0" edition = "0.3" [boundaries] "demo.vendor" = [] [trusted] modules = ["demo.release"] ``` `src/demo/release.una` ```una trusted module demo.release pub policy reveal from secret Int to public Int via open purpose "count" owner ops open(n: secret Int) -> public Int = n ``` `src/demo/vendor.una` ```una module demo.vendor pub count(n: Int) -> Int = n + 1 ``` `src/demo/app.una` ```una module demo.app import demo.release (reveal) import demo.vendor (count) pub total(n: secret Int) -> Int = count(reveal(n)) ``` --- # U3025: `if error` clause on an expression that cannot fail An `if error` clause is on an expression that cannot fail. ## Why Una rejects it In edition 0.3, an `if error` clause belongs only where the expression can fail (`spec/06 §3`, ADR 0100). A clause on an expression that cannot fail never runs: - arithmetic; - a call of a function without `fails`; - an operation without `fails`; - or anything wrapped in `attempt`, which already turns the failure into a value. It also misleads the reader, and a dead `if error fail V` in a private function gives that function an error kind of its own, which every caller then has to handle. The rule waits while the package has an error that can hide a failure: an error outside U3007, U3008 and U3009, or one inside the function that is called. Editions 0.1 and 0.2 accept the clause. ## How to fix it Remove the clause. `una fix` applies this repair. ## The repair at a glance `src/demo.una` ```diff module demo kind LookupError = Missing | Unavailable pub next(n: Int) -> Int fails LookupError = let x = n + 1 - if error fail Unavailable x ``` ## Failing example `una.toml` ```toml [package] name = "demo" version = "0.1.0" edition = "0.3" ``` `src/demo.una` ```una module demo kind LookupError = Missing | Unavailable pub next(n: Int) -> Int fails LookupError = let x = n + 1 if error fail Unavailable x ``` ## Fixed example `una.toml` ```toml [package] name = "demo" version = "0.1.0" edition = "0.3" ``` `src/demo.una` ```una module demo kind LookupError = Missing | Unavailable pub next(n: Int) -> Int fails LookupError = let x = n + 1 x ``` --- # U3026: `attempt` of a call that cannot fail The operand of an `attempt` is a call that cannot fail. ## Why Una rejects it In edition 0.3, the operand of `attempt` must be a call that can fail (`spec/06 §5`, ADR 0100). `attempt` of a call that cannot fail gives a `Result` whose `Err` arm is never taken, with an error type that the program never produces. The rule waits while the package has an error that can hide a failure, as U3025 does. Editions 0.1 and 0.2 accept the `attempt`. ## How to fix it Remove `attempt` and use the value of the call directly. Then unwrap each use of the `Result`: - a `when ... is Ok(v)` becomes the value `v`; - its `is Err` arm goes; - a declared `Result[T, E]` becomes `T`. The repair describes this change and carries no edit, since the uses must change with it. ## The repair at a glance `src/demo.una` ```diff module demo double(n: Int) -> Int = n * 2 - pub tried(n: Int) -> Result[Int, Text] = attempt double(n) + pub tried(n: Int) -> Int = double(n) ``` ## Failing example `una.toml` ```toml [package] name = "demo" version = "0.1.0" edition = "0.3" ``` `src/demo.una` ```una module demo double(n: Int) -> Int = n * 2 pub tried(n: Int) -> Result[Int, Text] = attempt double(n) ``` ## Fixed example `una.toml` ```toml [package] name = "demo" version = "0.1.0" edition = "0.3" ``` `src/demo.una` ```una module demo double(n: Int) -> Int = n * 2 pub tried(n: Int) -> Int = double(n) ``` --- # U3027: Code that may run forever where it is not allowed to A `for ever`, or a call of a function that says `diverges`, is where it is not legal, or a function the host calls in a loop of its own says `diverges`. ## Why Una rejects it In edition 0.4, a function that may run forever says so in its header with `diverges` (`spec/26 §5`, ADR 0116 rule 8). `for ever`, and a call of a function that says `diverges`, are legal only in the body of such a function, and not: - in a lambda, which is an ordinary value that code without `diverges` can call later; - in a `together` task, since the tasks of a block run one after another in the interpreter; - in an `on stop` block, which runs once its loop has ended and must end itself; - in the body of a `for ever` loop, whose every iteration must end (rule 9); - in a test, except in its `do` line when the test ends with a `stop after N` line, which stops every `for ever` once `N` of their iterations have started (`spec/26 §8`, rule 19). `diverges` is never inferred, so every header that may run forever says it. The error is at the `for ever` or the call. The functions the host calls in a loop of its own may not say `diverges` themselves: `init`, `step` and `on_stop` of a driven module (ADR 0116 rule 8), and `handle` and `on_stop` of the module of a `serve` section, so that every request and the stop end after finitely many steps (`spec/31 §7`, ADR 0123 rule 16). The error is then at the `diverges` clause. ## The repair at a glance `src/demo.una` ```diff module demo pub count() -> Int + diverges = let edit n = 0 for ever stop when n > 9 n = n + 1 n ``` ## Failing example `ita.una` ```una ita demo version 0.1.0 edition 0.4 ``` `ita.lock` ```una lock 1 solver encoding "una-smt-1" name "z3" version "5.1.0" logic "QF_UFLIA" steps 5000000 seed 0 ``` `src/demo.una` ```una module demo pub count() -> Int = let edit n = 0 for ever stop when n > 9 n = n + 1 n ``` ## Fixed example `ita.una` ```una ita demo version 0.1.0 edition 0.4 ``` `ita.lock` ```una lock 1 solver encoding "una-smt-1" name "z3" version "5.1.0" logic "QF_UFLIA" steps 5000000 seed 0 ``` `src/demo.una` ```una module demo pub count() -> Int diverges = let edit n = 0 for ever stop when n > 9 n = n + 1 n ``` --- # U3028: A function that says `diverges`, used as a value A function that says `diverges` may run forever (`spec/26 §5`, ADR 0116 rule 8). Bound as a value, it could be called later through a function type that carries no `diverges`, from code that does not say it may run forever, so it is not a value anywhere: name it only as a callee, in a function that says `diverges`. The error is at the name. ## The repair at a glance `src/demo.una` ```diff module demo spin() -> Int diverges = let edit n = 0 for ever stop when n > 9 n = n + 1 n pub held() -> Int + diverges = - let f = spin - 1 + spin() ``` ## Failing example `ita.una` ```una ita demo version 0.1.0 edition 0.4 ``` `ita.lock` ```una lock 1 solver encoding "una-smt-1" name "z3" version "5.1.0" logic "QF_UFLIA" steps 5000000 seed 0 ``` `src/demo.una` ```una module demo spin() -> Int diverges = let edit n = 0 for ever stop when n > 9 n = n + 1 n pub held() -> Int = let f = spin 1 ``` ## Fixed example `ita.una` ```una ita demo version 0.1.0 edition 0.4 ``` `ita.lock` ```una lock 1 solver encoding "una-smt-1" name "z3" version "5.1.0" logic "QF_UFLIA" steps 5000000 seed 0 ``` `src/demo.una` ```una module demo spin() -> Int diverges = let edit n = 0 for ever stop when n > 9 n = n + 1 n pub held() -> Int diverges = spin() ``` --- # U3029: A failure that must be handled where it is not A failure is not handled inside code that runs where no caller can receive it. ## Why Una rejects it Some code runs where no caller can receive a failure, so each failure it meets is handled inside it, with `if error use` or `attempt` (`spec/26`, ADR 0116): - an `on stop` block, which runs once its loop has ended, after a failure of the body too, so that a failure of its own would hide the first (rule 10); - `step` and `on_stop` of a driven module, which declare no `fails`, since the host has no caller to give a failure to (rule 2); - `on_stop` of the module of a `serve` section, which declares no `fails` for the same reason (`spec/31 §7`, ADR 0123 rule 16); its `handle` may, and the host answers a failed request with `500`; - the expression of a `start`, whose task no code waits on for a value or a failure (`spec/27 §7`, ADR 0117 rule 7). The error is at the statement, or at the `fails` clause. ## The repair at a glance `src/demo.una` ```diff module demo pub kind Lost = | Gone close(name: Text) -> Unit fails Lost = if name == "" then fail Gone else unit pub run() -> Unit - fails Lost diverges = for ever stop on stop close("log") + if error use unit unit ``` ## Failing example `ita.una` ```una ita demo version 0.1.0 edition 0.4 ``` `ita.lock` ```una lock 1 solver encoding "una-smt-1" name "z3" version "5.1.0" logic "QF_UFLIA" steps 5000000 seed 0 ``` `src/demo.una` ```una module demo pub kind Lost = | Gone close(name: Text) -> Unit fails Lost = if name == "" then fail Gone else unit pub run() -> Unit fails Lost diverges = for ever stop on stop close("log") unit ``` ## Fixed example `ita.una` ```una ita demo version 0.1.0 edition 0.4 ``` `ita.lock` ```una lock 1 solver encoding "una-smt-1" name "z3" version "5.1.0" logic "QF_UFLIA" steps 5000000 seed 0 ``` `src/demo.una` ```una module demo pub kind Lost = | Gone close(name: Text) -> Unit fails Lost = if name == "" then fail Gone else unit pub run() -> Unit diverges = for ever stop on stop close("log") if error use unit unit ``` --- # U3032: A `simd required` clause outside a `systems` package of edition `0.5` Not reported by 0.4.0: reserved for the `simd required` clause, which this release does not read. ## Why Una rejects it The `simd required` clause of ADR 0120 rule 58, `simd required target neon, avx2` after a function's `ensures` clauses, requires that the function's loops use the processor's vector instructions. It is legal only in a package of edition `0.5` (preview) whose profile is `systems` (ADR 0109 rules 1 and 5): a construct that only `systems` may use. Anywhere else, in an `app` package, in a single file or in an earlier edition, it is U3032. The clause lands with its slice of ADR 0120. Until then the release reads no `simd required` clause, so no program reports U3032, and this text has no example of its own. ## How to fix it - The repair is to declare the profile in the package's `ita.una`, with the head line `profile systems`, and the run's memory budget with the `run` line `max_memory`, which a `systems` package with an entry declares. - Or remove the clause: without it the same loops keep their meaning, and the runtime may still vectorize them. --- # U3033: An operation of `HttpServer` in the effect set of a `together` branch, a `together for` body, a `first of` branch, or `handle` or `on_stop` of a `serve` module An operation of `HttpServer` is in the effect set of a branch of `together`, a body of `together for` or a branch of `first of`, or `handle` or `on_stop` of a `serve` module names `HttpServer` in its `uses`. ## Why Una rejects it The branches of `together`, the bodies of `together for` and the branches of `first of` run at once and act for the one task that runs the construct (`spec/19 §1`, `spec/27 §6`). A reply right of `HttpServer` is held by one task at a time (ADR 0123 rule 4), so two branches that could both answer it would answer in an order that timing decides. The effect set of a branch therefore MUST NOT contain an operation of `HttpServer`: `next`, `reply` or `close` (`spec/31 §1`, ADR 0123 rule 5). This holds for an operation performed: - in the branch; - by a function it calls or names; - by a function value whose type's requirements hold `HttpServer`; - by a handler it installs; - by an operation whose handler can perform one; - or, in a program that imports a name of the server, by a `uses of` parameter that it calls or passes on, whose code its callers choose. The error is at the operation, the call, the function value or the installation. The same holds for `handle` and `on_stop` of the module that the `serve` section of `ita.una` names (`spec/31 §7`, ADR 0123 rule 16). In that form the host owns every exchange and answers each request with the reply `handle` returns, so neither function may name `HttpServer`, or a capability whose handlers can perform one of its operations, in its `uses`. The error is at the binding. ## How to fix it - In a branch, the repair is to compute in the branches and to answer after the construct. - In `handle` and `on_stop`, the repair is to return the reply from `handle`, or to write the server in the language form, with `next` in a `for ever` loop and no `serve` section. ## The repair at a glance `src/demo.una` ```diff module demo import std.host (Exchange, HttpServer, Reply) price(n: internal Int) -> internal Int = n * 3 answer(exchange: internal Exchange, n: internal Int) -> Unit uses @server: HttpServer[reply] = together let total = price(n) - let sent = @server.reply(to: exchange.right, reply: Reply(status: 204, headers: [], body: "")) - if error use unit - unit + let tax = price(n + 1) + @server.reply(to: exchange.right, reply: Reply(status: 200, headers: [], body: "{total + tax}")) + if error use unit ``` ## Failing example `ita.una` ```una ita demo version 0.1.0 edition 0.4 ``` `ita.lock` ```una lock 1 solver encoding "una-smt-1" name "z3" version "5.1.0" logic "QF_UFLIA" steps 5000000 seed 0 ``` `src/demo.una` ```una module demo import std.host (Exchange, HttpServer, Reply) price(n: internal Int) -> internal Int = n * 3 answer(exchange: internal Exchange, n: internal Int) -> Unit uses @server: HttpServer[reply] = together let total = price(n) let sent = @server.reply(to: exchange.right, reply: Reply(status: 204, headers: [], body: "")) if error use unit unit ``` ## Fixed example `ita.una` ```una ita demo version 0.1.0 edition 0.4 ``` `ita.lock` ```una lock 1 solver encoding "una-smt-1" name "z3" version "5.1.0" logic "QF_UFLIA" steps 5000000 seed 0 ``` `src/demo.una` ```una module demo import std.host (Exchange, HttpServer, Reply) price(n: internal Int) -> internal Int = n * 3 answer(exchange: internal Exchange, n: internal Int) -> Unit uses @server: HttpServer[reply] = together let total = price(n) let tax = price(n + 1) @server.reply(to: exchange.right, reply: Reply(status: 200, headers: [], body: "{total + tax}")) if error use unit ``` --- # U4001: Flow to a lower label Data flows to a lower label. The message names the declared type and the value's type with their labels. ## Why Una rejects it A label says who may observe a value, and data never flows to a lower label (`spec/07 §3`): a value flows into a parameter, a field, an annotated `let`, a policy's `from` type or a function's result only when each position of its type is labeled below the declared label there. Labels follow data: - an operator, an interpolation or an equality takes the labels of its operands; - a generic call the labels of its arguments; - the value of an `if` or `when` the label of its condition, which also makes the condition of a branch in a return position an implicit flow into the result. In a generic body, a value decided by comparing values of a type parameter `T` carries `label(T*)`, every label of `T`'s type argument, which is not below `label(T)`: it cannot flow into an annotation, a field or a function value's parameter of type `T`, as in `[if a == b then p else q].map(each: k)`. In edition `0.4`, an `http` grant of `run grants` with limits needs every `Http` request timed by `internal` data at most, since `HttpError.RateLimited` reveals when each request was made (ADR 0117 IF4, `spec/27 §9`): a request in a function that also works on a `secret` parameter is U4001 at the request. A `limiter` of `std.limit` the same (ADR 0117 IF5, `spec/27 §10`): whether `acquire` finds a token depends on the timing of the statement its `with` scopes over, so that statement must be timed by `internal` data at most; U4001 at the binding otherwise. In edition `0.4`, the host hands the state of a `drive` module from `init` to `step`, from `init` and `step` to `on_stop`, and that hand-off is a flow too (`spec/26 §2` rule 2): a state parameter of `step` or `on_stop` labeled below the type it receives, as `step(edit count: Int, ...)` after `init() -> secret Int`, is U4001 at the parameter's type. In edition `0.4`, no label is checked in a policy's `via` function, but a deadline or race outcome may reach its result only if what runs beside it cannot time it (`spec/07 §5` rule 7, ADR 0098): a `within`, `first of`, `for ever within` or `limiter` in a `via` body, or in code it calls, is U4001 at the site when the policy can be called beside other tasks, as in a branch of `together`, since whether the deadline passes or which branch wins would then release their timing at the label of the policy's `to`. A `via` that calls a function value, or applies one whose code is not known at the call, reaches the code of every lambda and every function named as a value, so their timing sites count wherever the policy is called. (Edition `0.3`, ADR 0094 rule 7.) When the label comes from the answer of an operation that its binding labels with `gives`, the message and the first repair name that binding and operation, as "the answer of `@service_files.owner`, labeled `internal[Service]`", and the call is a related location. ## How to fix it - Raise the declared label, or lower the value's label through a policy (`spec/07 §5`). - A declared label of the standard library, a field of a kind such as `Header` or `Json` or a parameter of a host operation, cannot be raised: lower the value through a policy. - For an HTTP request, a token the API takes as a bearer token goes by the name of its key, `key_name`, which sends `Authorization: Bearer ` without the program seeing it. A token the API takes in another header, as `X-Api-Token`, is a header value, so a `secret` one goes through a policy to `internal` first (`spec/24 §1`). - In a generic body, pass values of `T` through unchanged, or return the decision to the caller (`spec/07 §7` rule 8; the guide's section on labels). - For a request under an `http` grant with limits, move that work out of the function that makes the request, or remove the limits. - For a `limiter`, move the work on data above `internal` out of the statement, or install the `limiter` around a statement that does not compute on it. - For a state parameter of `step` or `on_stop`, label the parameter at least as high, position by position. - For a `within`, `first of`, `for ever within` or `limiter` in a `via` body, or in code it calls, call the policy outside every part of a task construct, or move the deadline or the race out of the `via` function and the code it reaches. - For a `via` that calls a function value, pass only lambdas written at the call to functions such as `map` in the `via` and the code it calls. - When the label comes from the answer of an operation that its binding labels with `gives`: read the operation through a binding that answers within the declared label, send the value where its label may go, or, last, release the answer through a policy of a trusted module. ## The repair at a glance ```diff module demo - pub leak(pin: secret Int) -> Int = pin + pub keep(pin: secret Int) -> secret Int = pin ``` ## Failing example ```una module demo pub leak(pin: secret Int) -> Int = pin ``` ## Fixed example ```una module demo pub keep(pin: secret Int) -> secret Int = pin ``` --- # U4002: Implicit flow through control, failure or call under raised pc A failure, a call or a policy call appears inside a branch on a labeled value, where the program counter does not allow it. The message names the construct and the label; its related location is the condition. In a program that starts tasks, U4002 also reports a check point that data above `internal` decide. ## Why Una rejects it Inside the branches of an `if`, `when` or `if none` on a labeled value, the program counter carries that label (`spec/07 §3`). A failure there would reveal which branch ran, so: - `fail`, `if error fail`, `if error pass`, `if none fail` and `checked` on a labeled value are allowed only under a `public` program counter. - A call is allowed only when the program counter is below the callee's `bound`, which is `public` for a function that can fail and the lowest `accepts` of its effects otherwise. - A policy call is allowed only when the program counter is below its `to` label. (Edition `0.3`, ADR 0094 rule 7.) When the label comes from the answer of an operation that its binding labels with `gives`, the message and the first repair name that binding and operation, as "the answer of `@service_files.owner`, labeled `internal[Service]`", and the call is a related location. In a program that starts tasks (edition `0.4`, `spec/27 §8` rule 5), the schedule moves from one task to the next after a count of check points: calls of Una code, operations, loop iterations and the elements that `map`, `filter`, `first_where` and `fold` visit. A check point that data above `internal` decide would let that data order the tasks' later prints and trace events. Such a check point is, for example, a call inside a branch on a `secret` value, a loop whose bound is `secret`, a `map` over a `secret` list or a call of a function value chosen by a `secret` value. So it is U4002 in a package: - whose code holds a `tasks` statement, - that has a `serve` section (its driver runs each request as a started task), or - that calls a dependency not checked with it. So is a call of a generic function or of `first_where`, or of code the label rules do not check, whose function argument returns such data, and a `tasks at most n at once` whose `n` is such data. The rule is coarse: a branch whose two sides pass as many check points is refused too. Data at `internal`, as the requests of `HttpServer`, are not refused, so they can still order the effects of started tasks, a known residual (#1708). `una report` lists each such check point in `information.timing` as a `task switch` at `internal`. ## How to fix it Code that must branch on labeled data returns a labeled value instead of failing. When the label comes from the answer of an operation that its binding labels with `gives`: - Read the operation through a binding that answers within the label it would reveal. - Move the code out of the branch on the answer. - Last, release the answer through a policy of a trusted module. In a program that starts tasks: - Compute on data above `internal` without the calls, operations and loops it decides: a loop over a `public` range whose body only assigns, or a branch that only picks a value. - Or do the work in a program without `tasks`. ## The repair at a glance ```diff module demo - kind PinError = | Rejected - - pub check(pin: secret Int) -> secret Int - fails PinError - = - if pin == 1234 - 1 - else - fail Rejected + pub check(pin: secret Int) -> secret Bool = pin == 1234 ``` ## Failing example ```una module demo kind PinError = | Rejected pub check(pin: secret Int) -> secret Int fails PinError = if pin == 1234 1 else fail Rejected ``` ## Fixed example ```una module demo pub check(pin: secret Int) -> secret Bool = pin == 1234 ``` --- # U4003: Sink label exceeded A capability operation is given data, or runs under a program counter, that is not below the operation's `accepts` label. ## Why Una rejects it Every argument of a capability operation is a sink with the operation's `accepts` label, `public` when the operation declares none (`spec/05 §2`, `spec/07 §4`). The data an operation sends outside the program, every label of its type, and the program counter under which it runs, must be below that label. Interpolation keeps the labels of what it interpolates, so printing `"id {phone}"` of a `secret` phone to `Console`, which accepts `public`, is U4003. (Edition `0.3`, ADR 0094 rule 7.) When the label comes from the answer of an operation that its binding labels with `gives`, the message and the first repair name that binding and operation, as "the answer of `@service_files.owner`, labeled `internal[Service]`", and the call is a related location. In a program that serves (edition `0.4`, `spec/31 §1` rule 5 item 6), a `start` that moves a reply right to its task is a sink of `internal` too. When the task ends without replying, the host answers for it, and a task that runs past `--task-depth` ends alone and is answered `500`. So a peer that varies its request could read from the status how deep the task went. A `start` is therefore U4003 at the `start` when both hold: - Its task can recurse, call a function value, or reach code the checker does not see (a standard module other than the prelude, a dependency not checked with the package). - Its task can hold data above `internal` anywhere in what it runs. The rule is coarse: it does not ask whether that data decides the recursion. What `Env.get` and `Files.read` return is `internal`, so printing it, or anything computed from it, is U4003 too, and no label of the program can be lowered to fix it. ## How to fix it The repairs that keep the label come first: - Send only the data, or the fields, that the operation accepts. - Or send the value to an operation that accepts its label. Declassifying through a policy is the last repair, marked as an escape (ADR 0095): the guarantee then rests on the policy's trusted code, whose labels are not checked. When the label comes from the answer of an operation that its binding labels with `gives`: - Read the operation through a binding that answers within the label the operation accepts. - Send the value to an operation that accepts its label. - Last, release the answer through a policy of a trusted module. In a program that serves, the repair keeps the task's data at most `internal`, by moving the `secret` work out of a task that recurses, or keeps a task that holds `secret` data free of recursion and of function values. Prelude functions such as `trim` and `sort` are fine. When what `Env.get` and `Files.read` return must be printed, the escape is the only route: declassify it through a `policy` in a module that both its header and `una.toml` mark trusted, and call the policy where the data is printed, as the second fixed example does. The build report lists every call of a policy with its purpose and owner. ## The repair at a glance ```diff module demo - pub greet(name: secret Text) -> Unit + pub greet(name: Text) -> Unit uses @console: Console[print] = @console.print("hello {name}") ``` ## Failing example ```una module demo pub greet(name: secret Text) -> Unit uses @console: Console[print] = @console.print("hello {name}") ``` ## Fixed example ```una module demo pub greet(name: Text) -> Unit uses @console: Console[print] = @console.print("hello {name}") ``` ## Fixed example: data from the environment, through a policy `una.toml` ```toml [package] name = "demo" version = "0.1.0" edition = "0.2" [trusted] modules = ["release"] ``` `src/release.una` ```una trusted module release pub policy shown_name from internal Text to public Text via as_shown purpose "greet the user by the name the environment gives" owner demo_owner as_shown(name: internal Text) -> public Text = name ``` `src/demo.una` ```una module demo import release (shown_name) pub main() -> Unit uses @console: Console[print] uses @env: Env[get] = let name = @env.get("USER") if none use "nobody" @console.print("hello {shown_name(name)}") ``` --- # U4004: `policy` outside a trusted module A module whose header does not say `trusted` declares a policy. ## Why Una rejects it A policy lowers labels, so it is part of the trusted computing base. It is allowed only in a module whose header says `trusted module` and that `una.toml` lists under `[trusted] modules`, or from edition `0.4` the `trusted` section of `ita.una` (`spec/07 §5, §6`). U4004 reports a policy in a module whose header does not say `trusted`. A header that says `trusted` without the listing is U7005. ## How to fix it - The repair that keeps the trusted base comes first: move the policy and its `via` function into a module that is already trusted, as the fixed example does. - Declaring this module trusted in both places is the last repair, marked as an escape (ADR 0095): every line of a trusted module joins the trusted base and is listed in the build report. ## The repair at a glance `src/keys.una` ```diff trusted module keys pub pepper() -> Int = 7 + + pub policy reveal + from secret Text + to Text + via shown + purpose "show a digest" + owner privacy + + shown(t: secret Text) -> Text = t ``` `src/demo.una` ```diff module demo - pub policy reveal - from secret Text - to Text - via shown - purpose "show a digest" - owner privacy - - shown(t: secret Text) -> Text = t + pub one() -> Int = 1 ``` ## Failing example `una.toml` ```toml [package] name = "demo" version = "0.1.0" edition = "0.1" [trusted] modules = ["keys"] ``` `src/keys.una` ```una trusted module keys pub pepper() -> Int = 7 ``` `src/demo.una` ```una module demo pub policy reveal from secret Text to Text via shown purpose "show a digest" owner privacy shown(t: secret Text) -> Text = t ``` ## Fixed example `una.toml` ```toml [package] name = "demo" version = "0.1.0" edition = "0.1" [trusted] modules = ["keys"] ``` `src/keys.una` ```una trusted module keys pub pepper() -> Int = 7 pub policy reveal from secret Text to Text via shown purpose "show a digest" owner privacy shown(t: secret Text) -> Text = t ``` `src/demo.una` ```una module demo pub one() -> Int = 1 ``` --- # U4005: Invalid policy (public `via`, or type mismatch) A policy's `via` function does not meet one of the conditions below. The message says which of these fails. ## Why Una rejects it A policy's `via` function computes the declassified value, and the policy is its only entry point (`spec/07 §5`): - The `via` function is a private function of the policy's trusted module. - Its one parameter has the type of `from` and its result the type of `to`, refinements included, since only labels differ. - It has no `requires` clause, since a policy call checks its argument against `from` only. - No other code uses it. Inside it no label is checked. ## The repair at a glance `src/keys.una` ```diff trusted module keys pub policy mask from secret[PII] Text to internal Text via masked purpose "show the last digits" owner privacy - pub masked(t: secret[PII] Text) -> internal Text = t + masked(t: secret[PII] Text) -> internal Text = t ``` ## Failing example `una.toml` ```toml [package] name = "demo" version = "0.1.0" edition = "0.1" [labels] categories = ["PII"] [trusted] modules = ["keys"] ``` `src/keys.una` ```una trusted module keys pub policy mask from secret[PII] Text to internal Text via masked purpose "show the last digits" owner privacy pub masked(t: secret[PII] Text) -> internal Text = t ``` ## Fixed example `una.toml` ```toml [package] name = "demo" version = "0.1.0" edition = "0.1" [labels] categories = ["PII"] [trusted] modules = ["keys"] ``` `src/keys.una` ```una trusted module keys pub policy mask from secret[PII] Text to internal Text via masked purpose "show the last digits" owner privacy masked(t: secret[PII] Text) -> internal Text = t ``` --- # U4007: Unknown label category A label's categories, as in `secret[PII]`, name the kinds of data it protects, and each package declares its categories in `una.toml` under `[labels] categories`, or from edition `0.4` in the `labels` section of `ita.una` (`spec/07 §2`). U4007 reports a category that the package does not declare, in a type's label or an `accepts` clause; a file checked on its own declares none. Declare the category, or correct its name. ## Failing example `src/demo.una` ```una module demo pub keep(t: secret[PII] Text) -> secret[PII] Text = t ``` ## Fixed example `una.toml` ```toml [package] name = "demo" version = "0.1.0" edition = "0.1" [labels] categories = ["PII"] ``` `src/demo.una` ```una module demo pub keep(t: secret[PII] Text) -> secret[PII] Text = t ``` --- # U4008: A text literal with interpolation in a pattern A pattern holds a text literal with interpolation. U4008 reports it in every edition. ## Why Una rejects it A pattern's literal is a constant: a `when` arm `is "…"` and the expression `x is "…"` compare a value with it (`spec/10 §4`). A text literal with interpolation, such as `"{s}"`, is not a constant: its text is computed from the values it interpolates, and those can be labeled. Testing a value against it would decide a branch, or a `Bool`, by those values without their labels (`spec/07 §7` rule 3), so U4008 reports it, in every edition. ## How to fix it - Compare with `==` instead, whose result carries the labels of both sides. - Or match a constant. ## The repair at a glance `src/demo.una` ```diff module demo - pub matches(name: Text, other: secret Text) -> Bool = name is "{other}" + pub matches(name: Text, other: secret Text) -> secret Bool = name == other ``` ## Failing example `src/demo.una` ```una module demo pub matches(name: Text, other: secret Text) -> Bool = name is "{other}" ``` ## Fixed example `src/demo.una` ```una module demo pub matches(name: Text, other: secret Text) -> secret Bool = name == other ``` --- # U5001: Obligation refuted The solver found values for which a proof obligation fails: a refinement at a value, a `requires` clause at a call, an `ensures` clause, a nonzero divisor, or the arms of a `when` over ranges (`spec/12 §3, §6`). The diagnostic points at the value, the call, the failing return, the division or the `when` keyword, and names the obligation with its goal. When the goal names any value, it gives a counterexample: values of the names involved for which the goal is false. ## How to fix it - Make the goal hold on every path, with a guard or a stronger type or contract that the solver may assume. - Or correct the goal. The repairs list these first. `checked(value, goal) else fail ` is the last repair, marked as an escape (ADR 0095): a runtime test replaces the proof, counts against the module's escape budget and is listed in the build report. ## The repair at a glance ```diff module demo pub kind Seats = Int in 0..5000 - pub cap_seats(raw: Int) -> Seats = if raw > 5000 then 5000 else raw + pub cap_seats(raw: Int) -> Seats = if raw < 0 then 0 else if raw > 5000 then 5000 else raw ``` ## Failing example ```una module demo pub kind Seats = Int in 0..5000 pub cap_seats(raw: Int) -> Seats = if raw > 5000 then 5000 else raw ``` ## Fixed example ```una module demo pub kind Seats = Int in 0..5000 pub cap_seats(raw: Int) -> Seats = if raw < 0 then 0 else if raw > 5000 then 5000 else raw ``` --- # U5002: Obligation unknown The solver could not decide a proof obligation within the `step_budget` of `verification.lock` or the wall-clock guard of `--solver-wallclock`. The message gives the solver's reason. ## Why Una rejects it In v0.1 an unknown obligation is an error, as a refuted one is (ADR 0008): nothing the solver could not prove is accepted. A loop has a reason of its own: "the loop forgets every fact about ...". A loop keeps only the refinements of the bindings it updates, so a postcondition about what it built, as `result.len <= votes.len` or `counts.has(key: v)` after the loop, stays unknown however the solver is given time. Floating point has reasons of its own (edition `0.3`, `spec/29 §8`): - A query with an `F64` term runs with the fixed step budget 5,000,000 whatever the lock sets, so raising `step_budget` does not decide it. - A query whose float arithmetic weighs more than 4 is not sent at all. A multiplication, a division, a square root or a conversion weighs 4, an addition or a subtraction 1. - A refutation that holds unless floating-point facts make its path unreachable is unknown too. - So is a fact that needs `n.to_f64()` of an `Int` outside -2^63..2^63, which the verifier does not interpret. ## How to fix it - Simplify the goal. - Give the proof the hypotheses it needs through stronger types or `requires` clauses. - Or raise the step budget. The proof is still required, so a raised budget keeps the guarantee. The repairs are those of U5001, and `checked` is the last one, marked as an escape (ADR 0095). For a loop, put the fact on a helper that does one iteration's update to an `edit` parameter, whose `ensures` names the parameter's value on entry as `old(p)`, as `counts.has(key: vote)` or `counts.len <= old(counts).len + 1`. The solver proves it once, and each call gives it to the caller right after the call. The loop's own postcondition about everything it built still cannot be proven; state what the callers need on the helper (`spec/17 §5`, the guide for agents, §11). For a floating-point query that runs with the fixed step budget or is not sent: - Move the fact to a checked boundary (`checked(value, p(it))`, an escape). - Split the contract so that each helper's `ensures` states a fact about one operation. - Or state a weaker property, such as finiteness, a sign or a bound by a constant. For a fact that needs `n.to_f64()` of an `Int` outside -2^63..2^63, give `n` a range refinement or a fixed-width type. ## The repair at a glance `verification.lock` ```diff encoding_version = "una-smt-1" solver = "z3" solver_version = "5.1.0" logic = "QF_UFLIA" - step_budget = 1 + step_budget = 5000000 random_seed = 0 ``` ## Failing example `verification.lock` ```toml encoding_version = "una-smt-1" solver = "z3" solver_version = "5.1.0" logic = "QF_UFLIA" step_budget = 1 random_seed = 0 ``` `src/demo.una` ```una module demo pub kind Seats = Int in 0..5000 pub shift(seats: Seats, by: Int) -> Int ensures result >= by = seats + by ``` ## Fixed example `verification.lock` ```toml encoding_version = "una-smt-1" solver = "z3" solver_version = "5.1.0" logic = "QF_UFLIA" step_budget = 5000000 random_seed = 0 ``` `src/demo.una` ```una module demo pub kind Seats = Int in 0..5000 pub shift(seats: Seats, by: Int) -> Int ensures result >= by = seats + by ``` --- # U5003: Solver missing or version mismatch U5003 says that the solver could not run, and its message says why. ## Why Una rejects it Tier 1 runs the Z3 solver built into `una`, at the exact version that `verification.lock` pins, so that every proof can be reproduced (`spec/12 §5`, ADR 0003, ADR 0124). `una` never looks for a `z3` program on the path: each query runs in a confined child process of `una` itself. When the solver could not run, `una check` stops before discharging any obligation that the proof cache does not hold, and points at the `solver_version` of the lock. `una check --tier 0` checks everything else without a solver. ## How to fix it The repair depends on the reason the message gives: - **Another version.** "verification.lock pins z3 4.8.12, and this una (0.4.0) has z3 5.1.0 built in": set `solver_version` to the version this `una` has, which `una --version` prints, or use a `una` whose built-in Z3 is the pinned one. - **No solver built in.** "this development build has no solver built in": the `una` was built from source without the Z3 library. Run `eval "$(scripts/z3-library.sh --export)"` in the checkout, which sets `UNA_Z3_LIB`, then build `una` again (`compiler/testing.md §3`). - **Not confined.** "the solver could not be confined", followed by the reason, such as "the solver must not run as root": run `una` as an ordinary user, in a container too (`docker run --user 1000:1000 ...`). - **No handshake.** The child could not be started, broke its confinement, or did not answer as this `una`. ## The repair at a glance `verification.lock` ```diff encoding_version = "una-smt-1" solver = "z3" - solver_version = "4.8.12" + solver_version = "5.1.0" logic = "QF_UFLIA" step_budget = 5000000 random_seed = 0 ``` ## Failing example `verification.lock` ```toml encoding_version = "una-smt-1" solver = "z3" solver_version = "4.8.12" logic = "QF_UFLIA" step_budget = 5000000 random_seed = 0 ``` `src/demo.una` ```una module demo pub kind Seats = Int in 0..5000 pub book(seats: Seats) -> Int = seats pub first() -> Int = book(1) ``` ## Fixed example `verification.lock` ```toml encoding_version = "una-smt-1" solver = "z3" solver_version = "5.1.0" logic = "QF_UFLIA" step_budget = 5000000 random_seed = 0 ``` `src/demo.una` ```una module demo pub kind Seats = Int in 0..5000 pub book(seats: Seats) -> Int = seats pub first() -> Int = book(1) ``` --- # U6001: `main` failed When `main` fails, `una run` stops and reports the variant of the failure as U6001 at the name of `main`, with exit code 1 (`spec/04 §8`). The payload fields of the failure are shown only when their labels are `public`, so the report never reveals labeled data; lines the program printed before the failure stay printed. Handle the failure inside `main`, with an `if error` clause or `attempt`, or make sure the path that fails is never taken. ## The repair at a glance ```diff module demo pub kind StartError = | MissingConfig check_config(ready: Bool) -> Unit fails StartError = if ready then unit else fail MissingConfig pub main() -> Unit fails StartError = - check_config(false) + check_config(true) if error pass ``` ## Failing example ```una module demo pub kind StartError = | MissingConfig check_config(ready: Bool) -> Unit fails StartError = if ready then unit else fail MissingConfig pub main() -> Unit fails StartError = check_config(false) if error pass ``` ## Fixed example ```una module demo pub kind StartError = | MissingConfig check_config(ready: Bool) -> Unit fails StartError = if ready then unit else fail MissingConfig pub main() -> Unit fails StartError = check_config(true) if error pass ``` --- # U6003: Call depth or memory limit exceeded `una run`, `una test` and native executables abort when the calls in progress exceed the maximum call depth: 10,000 by default, or the value of `--max-depth` (`spec/11 §7`). The diagnostic points at the call that goes one level too deep. Calls of functions, predicates, lambdas, policies and handler operations all count. Most often a recursion never reaches its base case; a recursion that is only deep can run with a higher `--max-depth`, up to what a stack of 1 GiB holds. They also abort when a call finds the run holding more memory than its budget: 4096 MiB by default, or the value of `--max-memory` in MiB (ADR 0061). The message then reads `this call exceeds the memory limit of N MiB`. A program that holds every intermediate value, such as a recursion that keeps each step's text, can hold less, or run with a higher `--max-memory`. They also abort when a run writes an `Int` of more than 4300 digits as text, the bound of parsing (`spec/11 §7`, #923): by interpolation, `to_text` or `to_json`, or in the Una form of a trace, an output or a failure. The message reads `an integer of more than 4300 digits is written as text here, past the limit of a run`, at the interpolation, the call or the operation; the final value of `main` has no position. Converting d digits takes quadratic time, and a few multiplications build an integer of millions of digits, so no run converts one. Keep such an integer unwritten, or write a part of it, such as its remainder by a power of ten. A native executable whose program has a task construct or a `for ever` also stops with U6003 before `main`, with no position and the message `the threads and stacks of this run's tasks could not be made`, when the system refuses its threads or the 64 task stacks it reserves before `main` (`spec/27 §1`). Each stack holds 16 MiB plus `--max-depth` times the program's frame bound, the largest frame its compiled code takes per call, and never more than the about 328 MiB that `--max-depth` alone gives at the default 10,000 (`spec/27 §4`). With a frame bound of 128 bytes the run reserves about 1.1 GiB of address space, of which it uses only what its tasks touch. A Linux system with strict overcommit (`vm.overcommit_memory=2`) can refuse that reservation; a lower `--max-depth` shrinks it. A run granted `Http` also starts, before `main`, the threads of its requests: `--io-threads` helpers, as many connect threads, and `max(2, --io-threads / 4)` lookup threads (`spec/24 §4`), besides `--workers` and `--file-threads`. A large `--io-threads` can pass the system's limit on a process's threads: at 4096, about 9,200 threads with the defaults, beyond macOS's usual limit (`kern.num_taskthreads`, often 8192) and many containers' limit on processes and threads. The run then stops with U6003 before `main`, with no position and the message `the lookup and connect threads of this run's requests could not be made`, or `the threads and stacks of this run's tasks could not be made` when the helpers are refused. A smaller `--io-threads` runs. Running out of depth or memory, or into the bound of written integers, is outside the noninterference model (`spec/07 §1`). ## The repair at a glance ```diff module demo - countdown(n: Int) -> Int = if n == 0 then 0 else countdown(n - 1) + countdown(n: Int) -> Int = if n <= 0 then 0 else countdown(n - 1) pub main() -> Unit = let steps = countdown(-1) unit ``` ## Failing example ```una module demo countdown(n: Int) -> Int = if n == 0 then 0 else countdown(n - 1) pub main() -> Unit = let steps = countdown(-1) unit ``` ## Fixed example ```una module demo countdown(n: Int) -> Int = if n <= 0 then 0 else countdown(n - 1) pub main() -> Unit = let steps = countdown(-1) unit ``` --- # U6004: A header value contains a control character `una run` and native executables abort when an operation of `Http` is given a header whose value contains a control character other than a tab: a byte below `0x20`, or `0x7f` (`spec/24 §1`). The diagnostic points at the operation. Nothing is sent. ## Why Una rejects it It is an abort, not an `HttpError`, because a header's value is `internal` (`spec/24 §5`). A failure the program could handle would tell it whether an `internal` value holds a control character, one bit per request. An abort ends the run, which is outside the noninterference model, as running out of depth or memory is (`spec/07 §1`). ## How to fix it A program that builds a header value from data removes the control characters first, for example with `replace`. ## The repair at a glance `src/demo.una` ```diff module demo pub main() -> Unit uses @http: Http[get] = - let token = "abc\ndef" + let token = "abc\ndef".replace(pattern: "\n", by: "") let r = attempt @http.get("http://127.0.0.1:9/", headers: [Header(name: "X-Token", value: token)], key_name: None) unit ``` ## Failing example `una.toml` ```toml [package] name = "demo" version = "0.1.0" edition = "0.2" [run] entry = "demo" grants = ["http:http://127.0.0.1:9"] ``` `src/demo.una` ```una module demo pub main() -> Unit uses @http: Http[get] = let token = "abc\ndef" let r = attempt @http.get("http://127.0.0.1:9/", headers: [Header(name: "X-Token", value: token)], key_name: None) unit ``` ## Fixed example `una.toml` ```toml [package] name = "demo" version = "0.1.0" edition = "0.2" [run] entry = "demo" grants = ["http:http://127.0.0.1:9"] ``` `src/demo.una` ```una module demo pub main() -> Unit uses @http: Http[get] = let token = "abc\ndef".replace(pattern: "\n", by: "") let r = attempt @http.get("http://127.0.0.1:9/", headers: [Header(name: "X-Token", value: token)], key_name: None) unit ``` --- # U6005: A host value is not valid UTF-8 `una run` and native executables abort when a host operation would make a `Text` from bytes that are not valid UTF-8: the content `Files.read` reads, or the value `Env.get` reads (`spec/14 §3`, ADR 0086). The diagnostic points at the operation, and its message says which of the two it was. ## Why Una rejects it It is an abort, not a `FileError` or a `None`, because those bytes are `internal`. A failure or an `Option` tag that the program could branch on would tell a `public` branch whether an `internal` file or variable is valid UTF-8, one bit per operation (S-16). An abort ends the run, which is outside the noninterference model, as running out of depth or memory is (`spec/07 §1`). ## How to fix it The cause is the host's data, not the program, so there is no failing example to show here: no program text causes it, and no change to the program removes it. Store the file, or set the variable, as UTF-8, for example by converting a file in a legacy encoding with `iconv -f latin1 -t utf-8`. --- # U6006: The floating-point environment of the platform is not the default one A self-test finds that the floating-point environment of the platform is not the default one. When a probe gives other bits, the run stops before the program starts, with U6006 and the name of the probe, exit code 1 and no source location. ## Why Una rejects it Every `F64` result is the same, bit for bit, in both engines and on every machine (`spec/29`, ADR 0114). That holds only under the default floating-point environment: rounding to nearest, ties to even, with subnormal numbers neither flushed to zero nor read as zero. - A native executable of edition `0.3` or later writes that environment when it starts and on each of its threads, and then runs a self-test whose probes tell each other rounding mode and each flush mode apart. - `una run`, `una test`, `una check`, `una build` and `una core` run the same self-test on a package of edition `0.3` or later before they read its sources, since they convert float literals. - The language server runs it when it opens such a package. - Packages of editions `0.1` and `0.2` never run the self-test. ## How to fix it The cause is the platform, not the program, so there is no failing example to show here: an emulator setting, a preloaded library or other foreign code left a mode the language cannot run under as specified. Run on a supported platform, and remove what changes the environment. --- # U6007: The host stopped the run before it finished `una run` and native executables end a run with this error when the hard stop of a host stop cancels it (`spec/26 §6`, ADR 0116 rule 16). The output so far stays printed, the trace is written, and the exit code is 1. ## Why Una rejects it A host stop request is one of: - SIGINT or SIGTERM, - the end of `--deadline `, - a driver's shutdown, or - the run's own stop after `--stop-after-iterations `. After the first request, every `for ever` ends at its next iteration start and runs its `on stop`, and the rest of the program runs on. The hard stop comes at the end of the grace period, `--stop-grace ` (10 by default), or at a second request. It cancels the run at its next call or loop iteration, `on stop` blocks included. A run that ends within the grace period ends normally, with exit code 0. ## How to fix it - Keep the work after a stop short: an `on stop` that releases what the loop holds, and no long computation or wait there. - A run that must not be cut gets a longer grace period. ## The repair at a glance `src/demo.una` ```diff module demo pub main() -> Unit diverges = let edit n = 0 for ever n = n + 1 on stop - for i in 0..<1000000000 + for i in 0..<10 n = n + 1 unit ``` ## Failing example Run it with `una run --deadline 1 --stop-grace 1`: the `on stop` block counts far past the grace period. `ita.una` ```una ita demo version 0.1.0 edition 0.4 run entry demo ``` `ita.lock` ```una lock 1 solver encoding "una-smt-1" name "z3" version "5.1.0" logic "QF_UFLIA" steps 5000000 seed 0 ``` `src/demo.una` ```una module demo pub main() -> Unit diverges = let edit n = 0 for ever n = n + 1 on stop for i in 0..<1000000000 n = n + 1 unit ``` ## Fixed example Run it with `una run --deadline 1 --stop-grace 1`: the `on stop` block ends well within the grace period. `ita.una` ```una ita demo version 0.1.0 edition 0.4 run entry demo ``` `ita.lock` ```una lock 1 solver encoding "una-smt-1" name "z3" version "5.1.0" logic "QF_UFLIA" steps 5000000 seed 0 ``` `src/demo.una` ```una module demo pub main() -> Unit diverges = let edit n = 0 for ever n = n + 1 on stop for i in 0..<10 n = n + 1 unit ``` --- # U6009: The host gave no random bytes for keyed hashing The host gives no random bytes for the secret key of hash tables. `una run`, `una test` and native executables read the key before `main` and before any effect, and abort with U6009, exit code 1, when the host gives no random bytes. ## Why Una rejects it A program that can make a hash table, a `HashMap` or a `HashSet` of `std.collections` (edition `0.5`, a preview), needs a secret key for the hash of its keys: 128 bits from the operating system's cryptographic random source, read once when the run starts (`spec/28 §1`, ADR 0119 rule 9). No fixed or guessable key ever replaces the random one. A key that an attacker could know would let them choose keys that all land in one place, which turns each operation of a table from constant expected time into time linear in its size: a denial of service. Only a run whose code can reach a hash table reads the key. A package of edition `0.1` to `0.4`, or one that makes no hash table, never reads it and never reports U6009. ## How to fix it The cause is the host, not the program, so there is no failing example to show here: no program text causes it, and no change to the program removes it. - On Linux, the kernel's random pool must be seeded, and a sandbox must allow the `getrandom` system call or reading `/dev/random` and `/dev/urandom`. - On macOS, `getentropy`. --- # U7001: Non-canonical formatting A region of a file differs from the file's canonical form. `una check` compares each file with its canonical form and reports U7001 for every region that differs. ## Why Una rejects it Every Una program has one canonical form (ADR 0011, ADR 0020): - two spaces per indentation level, - one line per statement or clause, - one space around binary operators, - the short form for a function without clauses whose body is one line, - constructor arguments in the order their fields are declared, - sorted imports, and - exactly one blank line between declarations. A file with syntax errors is checked for U7001 once they are fixed. ## How to fix it `una check` reports each region with a mechanical edit that replaces the region. `una fmt` rewrites whole files, and `una fmt --check` reports without writing. The formatter keeps every comment on its line. ## The repair at a glance ```diff module demo - pub double(x: Int) -> Int - = - x * 2 + pub double(x: Int) -> Int = x * 2 ``` ## Failing example ```una module demo pub double(x: Int) -> Int = x * 2 ``` ## Fixed example ```una module demo pub double(x: Int) -> Int = x * 2 ``` --- # U7002: Invalid `una.toml` `una.toml` describes the package (`spec/13 §7`, ADR 0021): a required `[package]` table with `name`, `version` and `edition`, one of `"0.1"`, `"0.2"` and `"0.3"`, and the optional tables `[labels]`, `[trusted]`, `[escape_budget]` and `[run]`; edition `0.3` adds the tables `[contracts]` and `[boundaries]`, `profile` in `[package]` and `max_memory` in `[run]`. From edition `0.4` the package is described by `ita.una`, and an edition of `0.4` or later in `una.toml` is U7002. U7002 reports a TOML syntax error, an unknown table or key, a missing required key, and a value of the wrong type or out of range, such as a `[run] entry` that is not a module of the package. ## The repair at a glance `una.toml` ```diff [package] name = "demo" version = "0.1.0" edition = "0.1" - license = "MIT" ``` ## Failing example `una.toml` ```toml [package] name = "demo" version = "0.1.0" edition = "0.1" license = "MIT" ``` `src/demo.una` ```una module demo pub one() -> Int = 1 ``` ## Fixed example `una.toml` ```toml [package] name = "demo" version = "0.1.0" edition = "0.1" ``` `src/demo.una` ```una module demo pub one() -> Int = 1 ``` --- # U7003: Escape budget exceeded A module uses `checked` more times than its budget allows. U7003 reports the first use beyond the budget, with the later uses as related locations. ## Why Una rejects it `checked` replaces a static proof with a runtime test, so each module may use it only as many times as `[escape_budget] checked_per_module` in `una.toml`, or from edition `0.4` `checked per module` in the `escapes` section of `ita.una`, allows. The default is 0, and a file checked on its own has the default (`spec/06 §6`). ## How to fix it Its repairs keep the proof first: - State the fact in a refined type or a `requires` clause, so that the solver proves it, or handle the values where it does not hold with a guard, and remove the `checked`. - Raising the budget is the last repair, marked as an escape (ADR 0095): it allows more runtime tests in place of proofs, and each one is listed in the build report and needs review. ## The repair at a glance ```diff module demo kind ParseError = | Empty pub nonempty(raw: Text) -> Text fails ParseError = - checked(raw, raw.len > 0) else fail Empty + if raw.len > 0 then raw else fail Empty ``` ## Failing example ```una module demo kind ParseError = | Empty pub nonempty(raw: Text) -> Text fails ParseError = checked(raw, raw.len > 0) else fail Empty ``` ## Fixed example ```una module demo kind ParseError = | Empty pub nonempty(raw: Text) -> Text fails ParseError = if raw.len > 0 then raw else fail Empty ``` --- # U7004: Missing or invalid `verification.lock` Every package commits a `verification.lock` next to its `una.toml` (`spec/12 §9`), up to edition `0.3`; from edition `0.4`, `ita.lock` next to `ita.una` pins the solver instead (U7009): it pins the SMT encoding, the solver and its exact version, the logic, the step budget and the seed, so that verification gives the same answer on every machine. U7004 reports a missing lock, at the start of `una.toml` (ADR 0022), and a lock with a syntax error, a missing or unknown key, or a value v0.1 does not support. Whether the installed solver matches the lock is U5003. ## The repair at a glance `verification.lock` ```diff - encoding_version = "una-smt-0" + encoding_version = "una-smt-1" solver = "z3" solver_version = "5.1.0" logic = "QF_UFLIA" step_budget = 5000000 random_seed = 0 ``` ## Failing example `verification.lock` ```toml encoding_version = "una-smt-0" solver = "z3" solver_version = "5.1.0" logic = "QF_UFLIA" step_budget = 5000000 random_seed = 0 ``` `src/demo.una` ```una module demo pub one() -> Int = 1 ``` ## Fixed example `verification.lock` ```toml encoding_version = "una-smt-1" solver = "z3" solver_version = "5.1.0" logic = "QF_UFLIA" step_budget = 5000000 random_seed = 0 ``` `src/demo.una` ```una module demo pub one() -> Int = 1 ``` --- # U7005: Trusted module not declared in both header and `una.toml` A module is declared trusted in its header or in its package's settings, `una.toml` or from edition `0.4` `ita.una`, but not in both. U7005 also reports a listed module that the package does not have. ## Why Una rejects it A trusted module may declare information-flow policies (`spec/07 §6`), so trust is declared twice: the module's header says `trusted module`, and `una.toml` lists the module under `[trusted] modules`, or from edition `0.4` the `trusted` section of `ita.una` does. U7005 reports a module declared in only one of the two places, and a listed module that the package does not have. A file checked on its own has no `una.toml` and no `ita.una`, so a `trusted module` header there is always U7005. ## How to fix it - The repair that keeps the trusted base comes first: remove `trusted` from the header, or remove the entry from `[trusted] modules`, as the fixed example does. A policy outside a trusted module is U4004, so narrowing trust never lets a policy through silently. - Completing the declaration in the other place is the last repair, marked as an escape (ADR 0095): the module joins the trusted base. ## The repair at a glance `src/keys.una` ```diff - trusted module keys + module keys pub pepper() -> Int = 7 ``` ## Failing example `src/keys.una` ```una trusted module keys pub pepper() -> Int = 7 ``` ## Fixed example `src/keys.una` ```una module keys pub pepper() -> Int = 7 ``` --- # U7008: Invalid `ita.una` or `itaty.una` `ita.una` or `itaty.una` holds an error. U7008 reports it at its line. ## Why Una rejects it From edition `0.4`, a package describes itself in `ita.una`, and a workspace in `itaty.una` (ADR 0122, `spec/30`). Both are written in Una's own lexical syntax, by a closed grammar: a head `ita ` with its `version` and `edition` lines, then sections in a fixed order (`sources`, `needs`, `replace`, `trust`, `labels`, `trusted`, `escapes`, `boundaries`, `contracts`, `run`, `drive`, `serve`). Nothing in them is evaluated: there are no expressions, no interpolation and no includes. U7008 reports, at its line: - a syntax error, - an unknown, repeated or misplaced line or section, - a value of the wrong form or out of range, - an edition before `0.4`, - a directory that holds both `ita.una` and `una.toml`, - a reserved local name, - a `from git` origin, - a `foreign` section or grant, - an invalid limit line under a grant (a form other than `at most per second`, `minute` or `hour`, `at most at once` and `waiting at most `, a count below 1 or above 2147483647, a limit under a grant other than `http`, or a kind of limit given twice; ADR 0117 rule 8, `spec/27 §9`), - every error that `una.toml` reports as U7002 for the setting it corresponds to, and - a `requires`, or a refined parameter or result type, on `handle` or `on_stop` of the module a `serve` section names, or on `init`, `step` or `on_stop` of the module a `drive` section names, a precondition that no call of the host establishes (`spec/31 §7`, `spec/26 §2`). For a `drive` module, a refinement inside a type argument counts too, as in `step(edit state: Option[Pos], input: Tick)` with `kind Pos = Int where it > 0`: the host hands the state on by its type without its refinements. ## The repair at a glance `ita.una` ```diff ita demo - version 0.1 + version 0.1.0 edition 0.4 ``` ## Failing example `ita.una` ```una ita demo version 0.1 edition 0.4 ``` `ita.lock` ```una lock 1 solver encoding "una-smt-1" name "z3" version "5.1.0" logic "QF_UFLIA" steps 5000000 seed 0 ``` `src/demo.una` ```una module demo pub one() -> Int = 1 ``` ## Fixed example `ita.una` ```una ita demo version 0.1.0 edition 0.4 ``` `ita.lock` ```una lock 1 solver encoding "una-smt-1" name "z3" version "5.1.0" logic "QF_UFLIA" steps 5000000 seed 0 ``` `src/demo.una` ```una module demo pub one() -> Int = 1 ``` --- # U7009: Missing, invalid or inconsistent `ita.lock` The `ita.lock` of a package is missing, invalid or does not meet `ita.una`. ## Why Una rejects it A package of edition `0.4` commits `ita.lock` next to its `ita.una` (ADR 0122, `spec/30`). Only `una ita` and `una migrate` write it. It pins the solver, as `verification.lock` does for earlier editions, and, for every package of the program, its version, origin and content digest. Every command that loads the package reads it offline. U7009 reports: - a missing lock, at the start of `ita.una`; - a lock with a syntax error, an unknown or misplaced line, or a value it does not support; and - a lock that does not meet `ita.una`, such as a need with no locked package. ## How to fix it The repair is `una ita lock`, which writes the lock again. ## Failing example `ita.una` ```una ita demo version 0.1.0 edition 0.4 ``` `src/demo.una` ```una module demo pub one() -> Int = 1 ``` ## Fixed example `ita.una` ```una ita demo version 0.1.0 edition 0.4 ``` `ita.lock` ```una -- Written by `una ita`; do not edit. lock 1 solver encoding "una-smt-1" name "z3" version "5.1.0" logic "QF_UFLIA" steps 5000000 seed 0 ``` `src/demo.una` ```una module demo pub one() -> Int = 1 ``` --- # U7010: A package, archive, statement, root, checkpoint or log proof that fails verification A package, an archive or a registry document fails verification. U7010 reports what failed and where it came from. ## Why Una rejects it A package of edition `0.4` is pinned by `ita.lock` to the content digest of each package it uses (ADR 0122, `spec/30`). Every command that loads the package verifies, offline, each locked registry package it reads from the vendor directory or from Itaoca: - Its files are read with no symbolic link followed, only regular files and directories, and only the paths a package may hold. - The digest of the bytes read must be the lock's. - The provenance stored beside it must verify against the lock: the source's root metadata from the pin in `ita.una`, the checkpoint of the lock's resolution point with its log signature and its witnesses' cosignatures, and the release statement, its digest, its signature by the key the lock names, and its inclusion in that checkpoint. `una ita lock`, `update`, `add` and `fetch` verify what they read from a registry the same way, from a mirror as from the source itself. A mirror that serves a copy that does not verify is skipped and named. This release has no https transport, so a registry is read only from a mirror directory that Itaoca's `mirrors.una` lists as a `file://` URL. They verify: - the root chain and its expiry, - the checkpoint's witnesses, its freshness and its consistency with the one stored, - every inclusion proof, - each name's whole chain against the name map, - the owner's keys at each statement's position, - the archive against its statement, and - that no release needs more authority or trust than the highest earlier one of its major line (rule 26). U7010 reports what failed and where it came from: - a vendored or stored package that was changed after it was fetched, - a file a package may not hold, - an archive that does not read, - a provenance that does not verify, - a registry or mirror whose files do not verify, or - a mirror skipped for such a copy. A vendored package that fails is not replaced by the copy in Itaoca. `una ita audit` also reports evidence against a registry, at the source's `registry` section of `ita.lock`: - An entry of an owner's chain that a registry following the rules never logs (`spec/30 §14` rule 5, "What a registry logs"), naming the owner, its log index and the rule it was judged by. This also refuses the owner's packages. - A release or a yank that its owner's keys as logged do not sign, which is skipped. An owner's chain that is contested, where a claim of compromise that counts is void under the chain's compromises (`spec/30 §14` rule 5, "Which claims count"), also refuses the owner's packages, while it stays contested. It is not evidence against the registry, and a later claim of compromise by the owner can resolve it. ## How to fix it There is no mechanical repair: a failure is evidence that the files were changed, or of an attack. Find out why, then remove the copy and vendor or fetch it again. When `una ita audit` reports evidence against a registry, keep the registry's checkpoint and that chain's entries, and publish them. After such an entry the owner registers under a new owner name, with new keys, since a key that another owner's chain named is refused. In the failing example, a file of the vendored release was edited after it was vendored. The fixed example shows the package once the dependency is no longer needed, since a self-contained example cannot carry a registry's signed files. ## Failing example `ita.una` ```una ita demo version 0.1.0 edition 0.4 sources acme "https://ita.acme.example" root "sha256:5e0d1b7a5e0d1b7a5e0d1b7a5e0d1b7a5e0d1b7a5e0d1b7a5e0d1b7a5e0d1b7a" needs ledger 0.3 from acme ``` `ita.lock` ```una -- Written by `una ita`; do not edit. lock 1 solver encoding "una-smt-1" name "z3" version "5.1.0" logic "QF_UFLIA" steps 5000000 seed 0 registry acme root "sha256:5e0d1b7a5e0d1b7a5e0d1b7a5e0d1b7a5e0d1b7a5e0d1b7a5e0d1b7a5e0d1b7a" checkpoint 2 "sha256:0b7e3c110b7e3c110b7e3c110b7e3c110b7e3c110b7e3c110b7e3c110b7e3c11" last root 1 "sha256:5e0d1b7a5e0d1b7a5e0d1b7a5e0d1b7a5e0d1b7a5e0d1b7a5e0d1b7a5e0d1b7a" package ledger 0.3.1 from acme digest "sha256:3b1f8e0c3b1f8e0c3b1f8e0c3b1f8e0c3b1f8e0c3b1f8e0c3b1f8e0c3b1f8e0c" signed "ed25519:itauna:7c0a91d27c0a91d27c0a91d27c0a91d27c0a91d27c0a91d27c0a91d27c0a91d2" logged 1 ``` `vendor/ita/acme/ledger-0.3.1/ita.una` ```una ita ledger version 0.3.1 edition 0.4 ``` `vendor/ita/acme/ledger-0.3.1/src/ledger.una` ```una module ledger pub total() -> Int = 4 ``` `src/demo.una` ```una module demo pub one() -> Int = 1 ``` ## Fixed example `ita.una` ```una ita demo version 0.1.0 edition 0.4 ``` `ita.lock` ```una -- Written by `una ita`; do not edit. lock 1 solver encoding "una-smt-1" name "z3" version "5.1.0" logic "QF_UFLIA" steps 5000000 seed 0 ``` `src/demo.una` ```una module demo pub one() -> Int = 1 ``` --- # U7011: A locked package that is neither in the vendor directory nor in Itaoca U7011 reports a locked package that is neither in the vendor directory nor in Itaoca, or whose provenance at the lock's resolution point Itaoca does not hold. The need is not mounted, so the package's modules cannot import it. ## Why Una rejects it A package of edition `0.4` builds from what its lock pins, with no network (ADR 0122, `spec/30`). Every command that loads the package looks for each locked registry package in the vendor directory of the root, `vendor/ita//`, and then in Itaoca, the store of fetched packages under `~/.una/itaoca` or the directory `UNA_ITAOCA` names. No command but `una ita` ever reads a registry. ## How to fix it - The repair is `una ita fetch`, which reads the release from the first of the source's places whose copy verifies, the mirrors Itaoca's `mirrors.una` lists then its own URL, verifies it and stores it in Itaoca. This release has no https transport, so only a mirror directory listed as a `file://` URL is read. - Then, to build anywhere with `una` alone, `una ita vendor`, which copies it with its provenance into the vendor directory to commit with the lock. A self-contained example cannot carry a registry's signed files, so the fixed example shows the package once the dependency is no longer needed. ## The repair at a glance `ita.una` ```diff ita demo version 0.1.0 edition 0.4 - - sources - acme "https://ita.acme.example" - root "sha256:5e0d1b7a5e0d1b7a5e0d1b7a5e0d1b7a5e0d1b7a5e0d1b7a5e0d1b7a5e0d1b7a" - owners acme - - needs - acme/ledger 0.3 from acme ``` `ita.lock` ```diff -- Written by `una ita`; do not edit. lock 1 solver encoding "una-smt-1" name "z3" version "5.1.0" logic "QF_UFLIA" steps 5000000 seed 0 - - registry acme - root "sha256:5e0d1b7a5e0d1b7a5e0d1b7a5e0d1b7a5e0d1b7a5e0d1b7a5e0d1b7a5e0d1b7a" - checkpoint 2 "sha256:0b7e3c110b7e3c110b7e3c110b7e3c110b7e3c110b7e3c110b7e3c110b7e3c11" - last root 1 "sha256:5e0d1b7a5e0d1b7a5e0d1b7a5e0d1b7a5e0d1b7a5e0d1b7a5e0d1b7a5e0d1b7a" - - package acme/ledger 0.3.1 - from acme - digest "sha256:3b1f8e0c3b1f8e0c3b1f8e0c3b1f8e0c3b1f8e0c3b1f8e0c3b1f8e0c3b1f8e0c" - signed "ed25519:acme:7c0a91d27c0a91d27c0a91d27c0a91d27c0a91d27c0a91d27c0a91d27c0a91d2" - logged 1 ``` ## Failing example `ita.una` ```una ita demo version 0.1.0 edition 0.4 sources acme "https://ita.acme.example" root "sha256:5e0d1b7a5e0d1b7a5e0d1b7a5e0d1b7a5e0d1b7a5e0d1b7a5e0d1b7a5e0d1b7a" owners acme needs acme/ledger 0.3 from acme ``` `ita.lock` ```una -- Written by `una ita`; do not edit. lock 1 solver encoding "una-smt-1" name "z3" version "5.1.0" logic "QF_UFLIA" steps 5000000 seed 0 registry acme root "sha256:5e0d1b7a5e0d1b7a5e0d1b7a5e0d1b7a5e0d1b7a5e0d1b7a5e0d1b7a5e0d1b7a" checkpoint 2 "sha256:0b7e3c110b7e3c110b7e3c110b7e3c110b7e3c110b7e3c110b7e3c110b7e3c11" last root 1 "sha256:5e0d1b7a5e0d1b7a5e0d1b7a5e0d1b7a5e0d1b7a5e0d1b7a5e0d1b7a5e0d1b7a" package acme/ledger 0.3.1 from acme digest "sha256:3b1f8e0c3b1f8e0c3b1f8e0c3b1f8e0c3b1f8e0c3b1f8e0c3b1f8e0c3b1f8e0c" signed "ed25519:acme:7c0a91d27c0a91d27c0a91d27c0a91d27c0a91d27c0a91d27c0a91d27c0a91d2" logged 1 ``` `src/demo.una` ```una module demo pub one() -> Int = 1 ``` ## Fixed example `ita.una` ```una ita demo version 0.1.0 edition 0.4 ``` `ita.lock` ```una -- Written by `una ita`; do not edit. lock 1 solver encoding "una-smt-1" name "z3" version "5.1.0" logic "QF_UFLIA" steps 5000000 seed 0 ``` `src/demo.una` ```una module demo pub one() -> Int = 1 ``` --- # U7012: A dependency the root may not use as written A package of edition `0.4` uses a dependency only on terms its root states (ADR 0122, `spec/30`). U7012 reports, at the root's need, a dependency the root may not use as written: a package from a local path whose name a registry may hold, without `accept name` under the need, so a local package never silently takes the place of a published one; and a dependency of a later edition than the package. The repair is to accept the name, after checking that the path is the package meant, or to use an earlier version. ## The repair at a glance `ita.una` ```diff ita demo version 0.1.0 edition 0.4 needs util from path "deps/util" + accept name ``` `src/demo.una` ```diff module demo - pub one() -> Int = 1 + import util.text (shout) + + pub greet() -> Text = shout("hello") ``` ## Failing example `ita.una` ```una ita demo version 0.1.0 edition 0.4 needs util from path "deps/util" ``` `ita.lock` ```una lock 1 solver encoding "una-smt-1" name "z3" version "5.1.0" logic "QF_UFLIA" steps 5000000 seed 0 package util 0.1.0 from path "deps/util" digest "sha256:0000000000000000000000000000000000000000000000000000000000000000" ``` `deps/util/ita.una` ```una ita util version 0.1.0 edition 0.4 ``` `deps/util/src/text.una` ```una module text pub shout(word: Text) -> Text = word ``` `src/demo.una` ```una module demo pub one() -> Int = 1 ``` ## Fixed example `ita.una` ```una ita demo version 0.1.0 edition 0.4 needs util from path "deps/util" accept name ``` `ita.lock` ```una lock 1 solver encoding "una-smt-1" name "z3" version "5.1.0" logic "QF_UFLIA" steps 5000000 seed 0 package util 0.1.0 from path "deps/util" digest "sha256:0000000000000000000000000000000000000000000000000000000000000000" ``` `deps/util/ita.una` ```una ita util version 0.1.0 edition 0.4 ``` `deps/util/src/text.una` ```una module text pub shout(word: Text) -> Text = word ``` `src/demo.una` ```una module demo import util.text (shout) pub greet() -> Text = shout("hello") ``` --- # U7013: No resolution: no release meets a need, or a bound of resolution is exceeded U7013 reports that there is no resolution, and nothing is written. `una ita verify`, and every command that loads a package, report U7013 too for a registry package they cannot verify. ## Why Una rejects it `una ita lock`, `una ita update` and `una ita add` resolve a package of edition `0.4` by minimal version selection (ADR 0122 rules 23 to 25, `spec/30 §10`): for each identity, a source, a name and a major line, the highest of the least versions that the needs reached ask for. U7013 reports that there is no resolution, and nothing is written: - No release of an identity is at or above a need. - A selection must be raised past a yanked, advised or avoided release and no later release qualifies, or the one that would is held back by the cooldown, in which case `una ita audit` shows why the release is left. - A pre-release would be selected that no need reached names. - A release needs its own identity. - A bound of resolution is exceeded, such as 1,000 needs of one release or 10,000 packages in the build list. - A source of `sources` with no place this release can read, since it has no https transport, so a source is read from a mirror directory that Itaoca's `mirrors.una` lists as a `file://` URL. - A package whose owner's chain holds an entry of a kind this release does not replay, a recovery, a dispute, a co-signer change, a cancellation, an overruling or a registration with recovery cosigners (`spec/30 §14` rule 5, "This release"), which a later release may judge. So no release of that owner is resolved until then, or until the owner registers under a new owner name, with new keys. - A need of `itaty`, whose root metadata is not built into this release, so nothing it serves can be verified, and no registry is ever resolved from a partial or unverified view of it. `una ita verify` reports U7013 too for a registry package whose copies match the lock but which it does not verify, since it does not hold the owner's key chain. Every command that loads a package, `una check`, `una run`, `una build`, `una test` and the others of `spec/30 §9` rule 9, also reports U7013, at the locked package's line of `ita.lock`, for a registry package it cannot verify offline (ADR 0122, amendment of 2026-11-03): - Its provenance's checkpoint, signed under an older root version, carries the cosignature of a witness that the last root version retired, and the provenance carries no consistency proof that it is a prefix of a checkpoint signed under that last version, as a provenance of the earlier format `ita-provenance/1` never does. - Or the root version this machine has accepted for the registry, which Itaoca keeps as a floor, exists and cannot be read. The load is never decided on fewer cosignatures, nor without the floor. The command ends with exit code 1. A program cannot cause U7013 on its own: the provenance is a registry's signed documents, which an example of this text cannot carry, so it has no example of its own, and the conformance cases `ita_registry_retired_unproven` and `ita_registry_retired_no_proof` hold them. ## How to fix it When there is no resolution: - When the release that would qualify is held back by the cooldown, the repair is to wait out the cooldown rather than to skip it, since a recent yank or advisory is when a hurried release is most dangerous. - Name a release that exists. - Need a version past one that must be raised. - Remove the `avoid` line that excludes the only one. - Need fewer packages. - Or list a mirror directory for the source in Itaoca's `mirrors.una`. When a command that loads a package cannot verify a registry package offline: - The repair is `una ita fetch`, which stores the registry's provenance of the newer format beside the earlier one, then `una ita vendor` for a vendored copy, or `una ita lock` at a fresh resolution point. - For a floor, make `registry//root-version` in Itaoca readable again. --- # U7014: A locked release yanked, under an advisory or signed after a stated compromise, or a pending recovery, a key change or a transfer of its owner `una ita audit` finds a locked release that is yanked, named by an advisory or signed by a key later revoked as compromised, or a pending recovery or a key change of its owner. `una ita lock` and `una ita update` report a key change of an owner too. ## Why Una rejects it `una ita audit` checks the registry packages of `ita.lock` against each name's state at a fresh checkpoint of its registry, verified as every registry document is (ADR 0122 rule 41, `spec/30 §15`). This release has no https transport, so a registry is read only from a mirror directory that Itaoca's `mirrors.una` lists as a `file://` URL. U7014 reports, once per package with every finding: - a locked release that its owner has yanked; - one that an advisory names; - one signed by a key that was later revoked as compromised since a log entry before it; and, - since the lock's resolution point, a recovery pending for its owner or a change of its owner's keys. A lock keeps a yanked release, and `una build` stays offline and never calls the audit, so a project's release gate runs `una ita audit` and fails on U7014. `una check` does not report U7014. The examples below are audited against a registry `acme` whose state has `acme/ledger 0.3.1` yanked and `0.3.2` released, neither advised. A package of edition `0.4` locks each registry release with the key that signed it (ADR 0122 rules 25 and 38, `spec/30 §14`). The keys of a package's owner are the ones its chain in the registry's log gives at each log position: keys added and revoked, a threshold, and recoveries and changes of recovery co-signers, which take effect only seven days of witness time after they were logged, unless a current key cancels them. `una ita lock` and `una ita update` compare the owner's keys with the ones the lock was written under. Another signing key, or a key event of the owner logged after the lock's resolution point, a recovery or a co-signer change that took effect included, is a key change, and one still pending is reported too. U7014 reports it at the need, and nothing is written, so a stolen or recovered owner account never changes what a program runs without the programmer's consent. A release signed after its key's stated compromise is skipped by new resolutions as a yanked one is. ## How to fix it - For a finding of `una ita audit`, the repair is to raise the package with `una ita update `, which takes the next release that is neither yanked nor advised, or to find out why the owner's keys changed before taking anything new. - For a key change that `una ita lock` or `una ita update` reports, the repair is to review the owner's key events in the registry's log, then to record the change with `una ita lock --accept-key ` or `una ita update --accept-key `. ## The repair at a glance `ita.lock` ```diff lock 1 solver encoding "una-smt-1" name "z3" version "5.1.0" logic "QF_UFLIA" steps 5000000 seed 0 registry acme root "sha256:5e5e5e5e5e5e5e5e5e5e5e5e5e5e5e5e5e5e5e5e5e5e5e5e5e5e5e5e5e5e5e5e" checkpoint 10 "sha256:d4d4d4d4d4d4d4d4d4d4d4d4d4d4d4d4d4d4d4d4d4d4d4d4d4d4d4d4d4d4d4d4" last root 1 "sha256:5e5e5e5e5e5e5e5e5e5e5e5e5e5e5e5e5e5e5e5e5e5e5e5e5e5e5e5e5e5e5e5e" - package acme/ledger 0.3.1 + package acme/ledger 0.3.2 from acme digest "sha256:3b3b3b3b3b3b3b3b3b3b3b3b3b3b3b3b3b3b3b3b3b3b3b3b3b3b3b3b3b3b3b3b" ``` ## Failing example `ita.una` ```una ita demo version 0.1.0 edition 0.4 sources acme "https://ita.acme.example" root "sha256:5e5e5e5e5e5e5e5e5e5e5e5e5e5e5e5e5e5e5e5e5e5e5e5e5e5e5e5e5e5e5e5e" owners acme needs acme/ledger 0.3 from acme ``` `ita.lock` ```una lock 1 solver encoding "una-smt-1" name "z3" version "5.1.0" logic "QF_UFLIA" steps 5000000 seed 0 registry acme root "sha256:5e5e5e5e5e5e5e5e5e5e5e5e5e5e5e5e5e5e5e5e5e5e5e5e5e5e5e5e5e5e5e5e" checkpoint 10 "sha256:d4d4d4d4d4d4d4d4d4d4d4d4d4d4d4d4d4d4d4d4d4d4d4d4d4d4d4d4d4d4d4d4" last root 1 "sha256:5e5e5e5e5e5e5e5e5e5e5e5e5e5e5e5e5e5e5e5e5e5e5e5e5e5e5e5e5e5e5e5e" package acme/ledger 0.3.1 from acme digest "sha256:3b3b3b3b3b3b3b3b3b3b3b3b3b3b3b3b3b3b3b3b3b3b3b3b3b3b3b3b3b3b3b3b" ``` `src/demo.una` ```una module demo pub one() -> Int = 1 ``` ## Fixed example `ita.una` ```una ita demo version 0.1.0 edition 0.4 sources acme "https://ita.acme.example" root "sha256:5e5e5e5e5e5e5e5e5e5e5e5e5e5e5e5e5e5e5e5e5e5e5e5e5e5e5e5e5e5e5e5e" owners acme needs acme/ledger 0.3 from acme ``` `ita.lock` ```una lock 1 solver encoding "una-smt-1" name "z3" version "5.1.0" logic "QF_UFLIA" steps 5000000 seed 0 registry acme root "sha256:5e5e5e5e5e5e5e5e5e5e5e5e5e5e5e5e5e5e5e5e5e5e5e5e5e5e5e5e5e5e5e5e" checkpoint 10 "sha256:d4d4d4d4d4d4d4d4d4d4d4d4d4d4d4d4d4d4d4d4d4d4d4d4d4d4d4d4d4d4d4d4" last root 1 "sha256:5e5e5e5e5e5e5e5e5e5e5e5e5e5e5e5e5e5e5e5e5e5e5e5e5e5e5e5e5e5e5e5e" package acme/ledger 0.3.2 from acme digest "sha256:3b3b3b3b3b3b3b3b3b3b3b3b3b3b3b3b3b3b3b3b3b3b3b3b3b3b3b3b3b3b3b3b" ``` `src/demo.una` ```una module demo pub one() -> Int = 1 ``` --- # U7015: The executable cannot be laid out: a branch beyond its target's range, or a section larger than its format allows U7015 reports that the program's code and the runtime cannot be placed within the limits of the target's format. No file is written. ## Why Una rejects it On macOS arm64, `una build` links the executable with its own linker (ADR 0124 rules 22 to 25, `spec/16`, "Linking"). On Linux arm64 it links through the system `cc`, whose failure is a usage error, so U7015 is not reported there. The limits of the target's format on macOS arm64 are: - On arm64, a branch reaches at most 128 MiB in either direction and a page address 4 GiB, and the linker adds no range-extension thunks. - The image must stay below 4 GiB. - The `__eh_frame` that compact unwind encodings point into must stay below 16 MiB. `una check` never reports U7015, since it is a property of the built executable, not of the program's text, so this text has no example. ## How to fix it No program of the repository comes within a factor of 50 of these limits, so the cause is a program whose generated code is that large. The repair is to split the work into smaller functions and data, or to keep large tables out of the program's text. --- # U8001: Internal compiler error (always a bug) The compiler reached a state it considers impossible: a Core IR that the interpreter cannot evaluate, a query that the solver rejects, or output that cannot be rendered. The program may be right or wrong; the diagnostic says nothing about it, only that `una` failed, with exit code 3. The message names what failed. One case is not a bug of the compiler but a damaged `una`: `una build` checks the native runtime built into `una` against the digest recorded when `una` was built, before every link, and a runtime that is missing or differs is U8001, with nothing linked (ADR 0124). ## How to fix it - For a damaged `una`, reinstall `una`. - Otherwise, report it with the smallest program that reproduces it and the command that was run. There is no failing example to show here: an input that causes this error is a bug of the compiler, which the fix of that bug removes.