Una for agents
A compact reference for writing Una in packages of edition 0.2, written for the v0.2 toolchain; later toolchains serve edition 0.2 unchanged. Editions 0.3 and 0.4 are previews: this guide notes where they differ and §22 moves a package to edition 0.4, but it does not teach their new constructs (for edition 0.4, see Tasks and time, Serving HTTP and Driven programs). The specification in docs/spec/ is normative; this guide summarizes it for an agent that writes, checks and repairs code.
How to read the blocks: every una block is a whole module that una check accepts in canonical form, as the only module of a package of edition 0.2, unless its first line is -- fails with U####, in which case checking it yields that code and no other. A block whose first line is -- edition 0.1 is checked in a package of edition 0.1. A block preceded by a file path belongs to a package with the other files named around it. Every json block is a document the CLI prints, and every sh block runs from the repository root, or in a fresh copy of the directory its # copy comment names. crates/una-cli/tests/guide.rs checks all of them.
1. The loop
This section has its own page: The loop.
2. Files and packages
- A package is a directory with
una.toml,verification.lockand sources undersrc/. Moduleshop.cartlives insrc/shop/cart.una, and a file holds exactly one module. - Imports name a module of the same package by its path and list what they take from it:
import shop.prices (Item, total). Onlypubdeclarations can be imported (U1004, with an edit that addspub). Importing a sum kind brings its variants too. The only other modules are the standard ones,std.hostandstd.testing(§8). The prelude is always in scope and is never imported, and no package imports another. (Edition0.4also has the standard modulesstd.time,std.driveandstd.limit, and dependencies on other packages throughita.una.) - A single
.unafile is also a package, with default settings and the default lock. una.tomlhas[package](name,version,edition = "0.2"), and optionally[labels] categories,[trusted] modules,[escape_budget] checked_per_module(default 0) and[run](entrymodule,grants). Unknown keys are U7002.- Editions.
edition = "0.2"enables the constructs of v0.2: editable values andforloops (§11), fixed-width integers (§12), recursive kinds (§4),uses ofandfails of(§8), constraints on generics (§13), maps (§14), JSON (§15), text functions (§16), HTTP (§17) andtogether(§18). A package of edition0.1keeps the language of v0.1 in every later compiler, and a single.unafile outside a package is edition0.1. §21 lists what changes between them. verification.lockpins the solver: tier 1 runs the Z3 built intouna, which must be the exact version the lock names, or it reports U5003.unanever looks for az3on the path, and installs no separate Z3;una --versionprints the version it has. U5003 also reports a development build with no solver built in and a solver that could not be confined, such as one run as root (una explain U5003).
3. Syntax in brief
- Indentation is significant: two spaces per level, no tabs. A line break inside brackets continues the line, but the canonical form joins such lines, so
una checkreports the split as U7001 (anduna fmtjoins it) unless a comment sits inside the brackets. Write each call on one line. --starts a comment,---a doc comment attached to the next declaration.- Names:
lower_snakefor values, functions, fields, modules, handlers and operations;UpperCamelfor kinds, variants, capabilities and label categories;@namefor capability references;UPPER_SNAKE_1for requirements. - Literals: integers without leading zeros (
1_000is fine),true,false,unit, and single-line text with{expression}interpolation. Text escapes are\",\\,\n,\t,\{,\}and\u{H}: a literal brace is\{or\}, so JSON written in text reads"\{\"id\": 7\}". A bare brace that cannot start or end an interpolation is U0007, with the edit that escapes it. There is no\r: a carriage return is\u{D}. - Operators, tightest first: calls and
.field; unary-;*/mod;+-; comparisons==!=<<=>>=,is Variantandin 0..5, which do not chain;not;and;or;implies. - Edition
0.2adds the keywordsedit,take,oldandtogether;foralso starts a loop. - Words that are keywords in other languages are errors with a hint (U0103):
match(usewhen),return(the last expression is the result),var(uselet edit),whileandloop(useforor recursion),type(usekind),asyncandawait(usetogether). Reserved for later versions:shared,iso,weak,all,table,queryand others. - A reserved word cannot name a binding:
let result = ...is U0101, sinceresultnames a function's result inensures. Pick another name, such asoutcome. - A handling clause (
if error ...,if none ...) stands on its own line, indented under the expression it handles, never on the same line.
-- fails with U0103
module demo
pub size(type: Text) -> Int = type.len4. Kinds
module demo
--- An alias: a Label is a Text.
pub kind Label = Text
--- A refinement with range sugar; an Int flows into it only with a proof.
pub kind Percent = Int in 0..100
--- A record.
pub kind Tool
name: Text
deposit: Nat
--- Sums, with and without payloads. A sum of one variant starts with `|`.
pub kind CheckoutError = NotOnShelf(tool: Text) | ShelfDown
pub kind Oops = | TooLarge
--- Generic kinds; parameters are unconstrained.
pub kind Bin[T]
label: Label
entries: List[T]
pub kind NonEmpty[T] = List[T] where it.len > 0A sum of one variant keeps its leading |: write kind Oops = | TooLarge. Without it, kind Oops = TooLarge is an alias of a type named TooLarge. That is U1001 when no such type exists, or U2002 when TooLarge is a variant of some other kind. A sum of two or more variants has no leading |.
Built-in types: Int (unbounded), Nat (Int at least 0), Bool, Text, Unit, List[T] ([a, b], xs.len), Option[T] (Some(value), None), Result[T, E] (Ok(value), Err(failure)), Hashed (from Keys only) and function types fn(A) -> B. Records and sums are nominal; aliases and refinements are their base type. Recursive kinds go only through List or Option in edition 0.1; edition 0.2 allows any recursion with a base variant, as kind Expr = Lit(value: Int) | Add(left: Expr, right: Expr) (ADR 0060).
Recursive kinds contain themselves through any field, as long as the kind has a finite value: some variant must end the recursion, or the field must be an Option or a List. A kind without a finite value is U2002.
module demo
--- A kind may contain itself when it has a finite value: `Lit` ends the recursion.
pub kind Expr = Lit(value: Int) | Add(left: Expr, right: Expr) | Neg(inner: Expr)
pub eval(e: Expr) -> Int
=
when e
is Lit(value) -> value
is Add(left, right) -> eval(left) + eval(right)
is Neg(inner) -> 0 - eval(inner)-- fails with U2002
module demo
pub kind Stream = | Next(head: Int, tail: Stream)Interpolation writes any value that holds no function in its Una form, the one una test shows: Point(x: 1, y: -2), [1, 2], Some(3), Err(NotFound). Text inside a structure is quoted. A record or variant with one field prints it without its name, as Some(3) or Offline("south"); with two or more fields, each is named. A field that holds a function is U2001. A value of a type parameter T needs [T: Eq]. The text keeps the labels of every field, so a record with a secret field cannot be printed (U4003) (ADR 0068).
module demo
pub kind Point
x: Int
y: Int
--- Interpolation writes the record itself: `at Point(x: 1, y: -2)`.
pub describe(p: Point) -> Text = "at {p}"5. Functions
A function is header = body. Clauses come in this order: requires, ensures, uses, fails, derived from. With no clause and a one-line body, the short form is canonical.
module demo
pub kind Item
name: Text
amount: Nat
--- Short form.
pub double(x: Int) -> Int = x * 2
--- Long form: the header is the contract, the body follows `=`.
pub restock(item: Item, added: Nat) -> Item
ensures result.amount == item.amount + added
=
Item(name: item.name, amount: item.amount + added)
--- Method calls and lambdas: `items.filter(keep: ...)` is `filter(items, keep: ...)`.
pub missing(items: List[Item]) -> List[Text]
ensures result.len <= items.len
=
items.filter(keep: fn(i) -> i.amount == 0).map(each: fn(i) -> i.name)
--- Generic functions take function parameters for what they cannot do themselves.
pub count_where[T](xs: List[T], keep: fn(T) -> Bool) -> Nat
ensures result <= xs.len
=
xs.filter(keep).len
example "restocking adds to the amount"
do restock(Item(name: "rice", amount: 2), added: 3)
expect result.amount == 5- Arguments after the first are labeled,
f(a, b: 2); from the second argument on, a bare name equal to the parameter's name counts as labeled (f(a, b)when the parameter isb). The first argument always binds the first parameter, sominus(b, a)with parameters(a, b)is U2006, not a swap. Constructors with two or more fields label every field. - Blocks bind with
let; values are immutable, and alet editbinding can be rebound (§11). A name is bound once in its scope: alet, a pattern or a lambda parameter named like a binding already in scope, a parameter or an outerlet, is U1002 ("itemsis already bound in this scope"). Rename the inner one; there is no shadowing. Two sibling blocks, as the arms of onewhen, may each bind the same name.if c then a else bfits on a line;ifandwhenalso take indented blocks. whenbranches on variants (is Some(x),is Err), literals (is 0) and ranges (in 1..<20); anelsearm comes last. Arms over variants must cover every variant (U2007).- The prelude has
abs,min,max,is_digits,starts_with,trim,to_int,is_empty,first,at,append,contains,map,filter,first_where,fold,sum,is_some,or_elseandis_ok, and in edition0.2alsosort,set,empty_map(§14), the JSON functions (§15) and the text functions (§16); their contracts are hypotheses for the solver (spec/14, spec/20 §6). Loop withfor(§11), recursion,map,filterorfold. - The result of
filterandfirst_wherecarries the labels of the predicate's result at its top, since which elements remain depends on it: oversecretelements, a predicate that reads them gives a list whose top issecret(spec/14, result labels, ADR 0067). A predicate with effects whose result is labeled is U4002 infirst_where. - A call of a generic function raises each position of its result only by the type arguments that position depends on;
una contractshows them as-- result labels: .... A list whose top depends on comparisons ofTvalues carriesT's labels, and a parameter of a user function still takes only what its type allows, so build such lists with the prelude (fold,append), not by passing them to your own generic functions.
-- fails with U2004
module demo
pub add(a: Int, b: Int) -> Int = a + b
pub three() -> Int = add(1, 2)-- fails with U1002
module demo
pub total(items: List[Int]) -> Int
=
let items = items.filter(keep: fn(n) -> n > 0)
items.sum()6. Contracts and proofs
This section has its own page: Contracts and proofs.
7. Failures
This section has its own page: Failures.
8. Capabilities
This section has its own page: Capabilities.
9. Labels and information flow
This section has its own page: Labels and information flow.
10. Requirements and examples
This section has its own page: Requirements and examples.
11. Editable values and loops
This section has its own page: Editable values and loops.
12. Fixed-width integers
This section has its own page: Fixed-width integers.
13. Constraints on generics
This section has its own page: Constraints on generics.
14. Maps
This section has its own page: Maps.
15. JSON
This section has its own page: JSON.
16. Text
This section has its own page: Text.
17. HTTP
This section has its own page: HTTP.
18. Concurrent tasks: together
This section has its own page: Concurrent tasks: together.
19. Native executables and the language server
This section has its own page: Native executables and the language server.
20. The Agent ABI
This section has its own page: The Agent ABI.
21. Migrating from edition 0.1
This section has its own page: Migrating from edition 0.1.
22. Migrating to edition 0.4
From edition 0.4, a package is described by ita.una and pinned by ita.lock, in Una's own syntax, in place of una.toml and verification.lock (spec/30). Edition 0.4 is a preview. Collections and the numeric types after F64 are in edition 0.5, also a preview and also named in ita.una, as edition 0.5 (ADR 0139); una migrate writes edition 0.4, or keeps 0.5 when una.toml names it. The steps, in the package's directory:
una migrate --dry-runprints the two files it would write and every diagnostic the new edition causes, and writes nothing.una migratewritesita.unaandita.lock, rewrites each module in the canonical form of edition0.4, removesuna.tomlandverification.lock, and prints the same diagnostics, such as a function namedwithin, a word edition0.4reserves (U0103). It exits with code 0: the diagnostics are the next steps. A[package] namethat is not a package name, such asevents-example, becomesevents_example;--namegives another.una fixapplies the mechanical repairs, such as renamingwithin, anduna checkchecks the result.- Commit
ita.una,ita.lockand the rewritten modules together.
What changes:
- The manifest.
ita <name>and itsversionandeditionlines head the file; the tables ofuna.tomlbecome sections with one entry per line, and a grant is a line such asfiles "data/" read.edition = "0.4"inuna.tomlis U7002, withuna migrateas its repair. - Dependencies. A package may need another one from a directory,
util from path "../util"withaccept name, or from a registry itssourcessection declares and pins,acme/ledger 0.3 from acme, which this release reads only from a mirror directory that Itaoca'smirrors.unalists as afile://URL, since it has no https transport, and import its modules asutil.textorledger.ledger.una ita lockresolves and writes the lock;una ita addanduna ita updatechange the needs and lock. A need ofitaty, the default registry, has no resolution in this release (U7013). - Authority. A dependency receives a capability only at a call, with
with, within themaylines its need writes, anduna ita lock --accept-authority <package>records each wider ceiling. A dependency's trusted modules count only with atrustline and--accept-trust <package>@<digest>. - Offline.
una check,una run,una buildanduna testnever read a registry:una ita fetchfills Itaoca, in this release from afile://mirror directory only,una ita vendorwritesvendor/ita/to commit, anduna ita bundleanduna ita unbundlecarry the packages to a machine with no network. A locked package that is not there is U7011; one whose files changed is U7010. - Never by hand.
ita.lockis written byuna ita lock;una fixnever editsita.unaorita.lock. CI runsuna ita lock --check --freshanduna ita audit.
A package of edition 0.4, with its manifest, its lock and one module:
ita demo
version 0.1.0
edition 0.4lock 1
solver
encoding "una-smt-1"
name "z3"
version "5.1.0"
logic "QF_UFLIA"
steps 5000000
seed 0module demo
pub total(xs: List[Int]) -> Int
=
let edit sum = 0
for x in xs
sum = sum + x
sum