Home / Docs / Language guide
Functions and contracts
4.1 Two forms
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
withclause belongs to a statement, not an expression, so a body withwithneeds 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 everyensures, then everyusesanduses of(one capability or parameter per clause), then at most onefailsand onefails of, then at most onederived from. Anything else is U0102. requiresandensuresmust be in RL (U2014).resultexists only inensuresclauses and exampleexpectlines (U2012).old(x)exists only inensures, on aneditparameter (§5.6).ensurescovers normal returns only; failures carry no postcondition.- Partial correctness:
ensuresholds if the function returns. Termination is not checked. - Pure means no
uses. A function withoutusescannot contain any@(U3004). - No
failsmeans it cannot fail.
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 - countThe 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.
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))
unit4.3 Visibility and inference
pubfunctions must declare everyuses, theirfailsand the constraints of their type parameters explicitly. They are the reviewed boundary.- Private functions may omit
uses,fails,uses of,fails ofand constraints; the compiler infers them.una contract <name>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 ("
Phas 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 checkreports another order as U7001, anduna fmtrewrites 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 == Foundis U2009, with the repaire is Found.
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)
found4.5 Method-call syntax
e.f(args)callsf(e, args). The receiver becomes the first, unlabeled argument.- If
ehas a fieldfof function type,e.f(args)calls that field instead. e.fwithout arguments is field access, orf(e)whenehas no fieldfandfis a function with one parameter..lenis built in forTextandList, and the conversions and arithmetic methods of §3.1 for integers.edit xs.set(index: 0, item: v)passes the receiver as aneditargument (§5.6).
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.len4.6 Lambdas and function types
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'seach; without one, annotate them (fn(x: Int) -> x + 1), or it is U2010. - Function types are written
fn(A, B) -> C, optionally withusesandfails:fn(Text) -> Unit uses @log: Log[write]. - A lambda is pure unless its expected type declares
usesorfails, or is a parameter named by auses oforfails ofclause. - 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), whererecorddeclaresfails, is U3007. A lambda may still fail directly, as infn(k) -> if k > 0 then k else fail Bad, when its expected type declaresfails. Put fallible work in a named function with handling clauses, and pass the function by name, asapply_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) declareuses ofandfails oftheir function parameter in edition0.2, sonames.map(each: fn(n) -> @console.print(n))works (§4.2). In edition0.1they accept only pure, non-failing lambdas (U3004 otherwise). Prefer aforloop 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
editortakeparameter 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() -> Unitin the module set asentryinuna.toml. It can declareusesover host capabilities (§7.7) and afailsclause. - If
mainfails, the runtime prints the variant name and exits with code 1. Payload fields are printed only if they arepublic.