Skip to content

Idiomatic Pia

Pia can often say one fact in several ways. A bound on an argument can be a requires clause or the argument's type. A family of functions can be written out by hand, made generic, or generated by a metaprogram. A hard proof can be one big goal or several small ones. Each version is correct, but they differ in where the fact lives, who has to prove it again, and how much work the solver does. This page gives the house opinions on which to choose, and why. They are opinions, not rules: the compiler warns when code goes against one, and every warning can be turned off (ADR 0037).

The hierarchy

Prefer the earliest rung that can say what you mean:

  1. Make illegal states unrepresentable. Put facts in types: range types such as int{0..99}, ranges on the elements of a slice, variants instead of integer tags, slices instead of a buffer and a separate length, and buffers of records instead of parallel arrays. A fact in a type travels with the value, through calls, fields and returns, and costs nothing where it is used: interval analysis decides it before the solver is asked.
  2. Contracts for facts that relate several values. requires i < len xs, requires lo <= hi, ensures result >= a: no single type can say these. A contract is a cut point. The callee is proved once against it, and each caller proves it at the call.
  3. Spec functions and lemmas to name ideas and prove hard steps once. A let spec names a property that several contracts share. A let lemma proves a fact once, and each use only assumes it.
  4. Generics, concepts and metaprograms for families. When the same body appears at several types, write one generic function constrained by a concept. When it differs in constants or in structure, take the constants as parameters or generate the family with a metaprogram, such as @derive(eq).
  5. Assertions as stepping stones. assert inside a body splits one hard goal into smaller ones the solver can take in turn.
  6. Escape hatches, last. assume, @overflow(wrap) where you do not mean modular arithmetic, --allow-unproved and, when it lands, unsafe. Each one moves a fact out of the proof and onto the reader.

The order is also the order of proof cost. A type is checked where a value is made and then never again. A contract is proved once in the callee and again at every call. A lemma is proved once and assumed where it is used. An assertion is a goal of its own. An escape hatch costs nothing to prove, because nothing is proved.

Measured

Each pair below says the same thing two ways. The costs are Z3's resource counts from piac --verify --solver-cost on the iMac (they vary by about 1% from run to run), summed over the file:

Fact As a contract As a type
a parameter below 100, with x + 1 in the body and a caller passing y / 3 2 goals to the solver 1 goal to the solver, x + 1 by intervals
inc and twice above, with x < 255 and x < 200 5 goals, all to the solver, cost 1,261 4 goals, 3 to the solver, cost 711
every element of xs below 16, then t.[nibble_at xs i] into a 16-entry table cost 10,022, and the table index still fails: nibble_at's u8 result does not keep the bound cost 96, and the table index is proved by intervals
w * h fits, for w and h up to 1000 requires w * h <= 1000000: cost 1,075,117, 87 ms int{0..1000} each: cost 0, proved by intervals

The third row is the point of this page in one line: a fact in a contract stops at the function, and a fact in a type does not.

Facts in types

A constant bound on one value is a range type

A precondition that only bounds one parameter by constants says what a range type says:

let scale (p : u8) : u16
  requires p <= 100
= p * 3

The fact holds only inside scale. A caller proves it at every call, and the value it passed does not keep it. As a type it goes wherever the value goes:

let scale (p : int{0..100}) : u16 = p * 3

piac says so, and pia-lsp offers the same text as a quick fix:

$ piac --check percent.pia
percent.pia:2:3: warning: this precondition only bounds 'p' by constants; say it in the type instead, (p : int{0..100}), so the fact travels with the value and intervals can use it [range_requires]
    requires p <= 100
    ^
  fix: Move the bound into the type: (p : int{0..100})

What it costs: a caller that passes y / 3 for an x < 100 precondition proves it with one solver query, the precondition of 'f' holds [smt], and so does a caller whose argument is already int{0..50}, because a precondition is always sent to the solver. With the range type, a caller whose value already has a narrower range passes it with no goal at all: widening between range types is free. A caller with a wider value proves the value fits in int{0..99}, one goal, as before. Inside the function, arithmetic on the parameter is decided by intervals instead of the solver: x + 1 with x < 100 is [smt], and with x : int{0..99} it is [intervals].

Two things change with the type, and the warning says when either applies:

  • Storage. A range type is stored in the smallest machine integer that holds it, so (x : u32) bounded by x <= 1000 becomes a u16, which changes the C signature of an exported function.
  • Arithmetic with nothing wider expected. Arithmetic happens at the join of its operand types and the type its context expects. x - 1 returned as a u8 is computed in u8, but let d = x - 1 in with x : int{1..64} is computed in int{1..64}, and fails when x is 1. Give the let a type, let d : u8 = x - 1 in, or compare in a wider type.

A one-sided bound on a wide type, such as w >= 3 on a usize, stays a contract for now: as a type it would read int{3..18446744073709551615}. Ranges with an open side are a planned follow-up (#153).

A constant bound on the result is a range return type

let low_nibble (x : u8) : int{0..15} = x & 15

let lookup (t : [u8; 16]) (x : u8) : u8 = t.[low_nibble x]

With ensures result < 16 instead, the index into t needs the solver. With the return type it is proved by intervals, since the index's type alone keeps it in the table. The lint is range_ensures.

Ranges on the elements of a slice

A quantified precondition that bounds every element by constants is an element type:

let nibble_at (xs : [int{0..15}]) (i : usize) : int{0..15}
  requires i < len xs
= xs.[i]

instead of requires forall (k in 0..len xs). xs.[k] < 16. Quantifiers are the most expensive thing a query can hold: every goal in the function assumes the forall, and the solver has to find the right instance of it. The element type needs no quantifier at all. The lint is range_requires, on the quantified part.

Bounds the type already says

requires x >= 0 on a u8 restates the type. It costs a little in every query of the function, and it suggests to a reader that the type could be negative. The lint is redundant_bound, and its fix removes the clause.

Other facts that belong in types

These have no lint yet, but the same opinion applies:

  • An integer that stands for a choice is a variant. requires mode < 3 on a u8 is a three-constructor variant, type | Read | Write | Append. match must cover every constructor, and the verifier knows which one built a value.
  • A buffer and a separate length is a slice. (buf : [u8]) (n : usize) requires n <= len buf is buf.[0 .. n]: a slice carries its length, and its bounds are one goal where it is made.
  • Parallel arrays of the same length are a buffer of records. requires len fill = len dem on every function that takes both is a slice of { fill : u16; dem : u16 }, stored as one buffer per field anyway, so the layout does not change and the lengths are equal by construction.
  • Facts about several fields will be record invariants. let range = type { lo : i32; hi : i32 } where lo <= hi states once what every function on ranges would otherwise require. Record where invariants and refinement types such as { y : i32 | lo <= y } are designed but not implemented yet (status).

Facts between values: contracts

A contract is for what no single type can say:

let plus (a : u8) (b : u8) : u8
  requires a + b <= 255
  ensures result = a + b
= a + b

let plus3 (a : u8) (b : u8) (c : u8) : u8
  requires a + b + c <= 255
= plus (plus a b) c

plus3 is proved against plus's contract, not its body. Its two calls are two goals, and the outer one is proved from the inner call's postcondition. This is the right shape for a relation, and the cost is one goal per call.

Where a contract and a type can both say it, the type wins. Range types work with contracts too:

let inc (x : int{0..254}) : u8
  ensures result = x + 1
= x + 1

let twice (x : int{0..199}) : u8
  ensures result = x + 2
= inc (inc x)

The inner call passes an int{0..199} where an int{0..254} is expected, a widening with nothing to prove. Only the outer call has a goal, that inc's result fits, which the postcondition proves.

Naming ideas and proving them once

A spec function names a property that several contracts use, so it is written once and read once. A lemma proves a fact once, and a call to it adds the fact where it is needed, instead of each function proving it again (the verifier). Keep @fuel low: @fuel(n) unfolds a recursive spec function n times in every query that mentions it, and a lemma proved by induction does the same work once. The lint deep_fuel warns above @fuel(4).

Families: generics, concepts and metaprograms

The same body at several types is one generic function:

let max_u8 (a : u8) (b : u8) : u8 = if a > b then a else b
let max_u16 (a : u16) (b : u16) : u16 = if a > b then a else b
$ piac --check maxes.pia
maxes.pia:2:5: warning: 'max_u16' has the same body as 'max_u8' (line 1) at other types; write it once as a generic function, '(t : type where C t)', where the concept C names what the body uses, and its laws are proved once per type instead of once per copy [generic_candidate]
  let max_u16 (a : u16) (b : u16) : u16 = if a > b then a else b
      ^

Written once, with a concept that names what the body needs, the body is checked once at its definition (the tour), and each type proves the concept's laws once, however many functions use them.

Bodies that differ only in their constants want the constants as parameters, range-typed so callers keep the facts, or a metaprogram that generates the family (metaprogram_candidate). A function that compares every field of a record is what @derive(eq) makes, with a postcondition that stays in step when a field is added (derivable_eq). An exact copy is a call (duplicate_function).

Decomposed reasoning

Every goal is its own solver query (ADR 0032), with the function's preconditions and the code before it as assumptions. So the cost of a function grows with how much each query has to carry, and these keep queries small:

  • Functions are proof boundaries. A loop body moved into a function with its own contract is proved once, and the loop sees only the contract. A caller never sees a callee's body.
  • Keep preconditions linear. A precondition is assumed in every goal of the function. A product of two variables, or a division by one, in an inequality makes every query nonlinear, which the solver has no decision procedure for. Bound the factors with range types so intervals decide the product, compute it in a helper with @overflow(saturate) and a linear contract, or prove the fact once as a lemma. The lint is nonlinear_contract.
  • Split a hard goal. An assert before a hard postcondition is a stepping stone: it is proved on its own, then assumed by the goals after it.
  • Prove one goal at a time while you work. --verify-only=file:line proves just that goal, with everything before it still assumed, and --proof-cache skips goals proved before.
  • Watch the cost. After --verify, a goal that costs 10% or more of the solver's resource limit gets a costly_goal warning that names it and says how to split it. --costly-goal=<n> sets the threshold, and --verify-stats reports how many goals the types raised and how many the contracts stated, and what each group cost:
verify-stats: goals=4 unselected=0 intervals=1 ... type=2 type_smt=1 type_cost=529 contract=2 contract_smt=2 contract_cost=182

A program that moves facts into types shows more type goals proved by intervals and fewer contract goals sent to the solver.

Escape hatches

assume p tells the verifier that p holds without proving it, so it is allowed only in a file marked @trusted, and --trust-report lists each one. If callers can promise it, it is a requires; if it follows from what is known, it is an assert or a lemma. The lint is assume. @overflow(wrap) and @overflow(saturate) are for arithmetic that is meant to wrap or clamp, such as hashes and pixels, not a way to make overflow goals go away. --allow-unproved is for a goal the verifier cannot prove yet, named one at a time.

The lints

Lint Warns about Better Fix
range_requires a requires that bounds one parameter, or every element of a slice parameter, by constants a range type, or a slice of a range type yes
range_ensures an ensures that bounds the result by constants a range return type yes
redundant_bound a bound the type already says nothing yes
generic_candidate a function with the same body as another at other types a generic function with a concept no
metaprogram_candidate a function that differs from another only in constants parameters, or a metaprogram no
duplicate_function a function with the same signature and body as another a call no
derivable_eq a hand-written field-by-field equality @derive(eq) no
nonlinear_contract a product of variables in a precondition's inequality, or a division by a variable in a contract range types, a saturating helper, or a lemma no
deep_fuel @fuel(n) above 4 a lemma proved by induction no
assume assume requires, assert or a lemma no
costly_goal a goal that costs 10% or more of the solver's limit a smaller query: range types, a lemma, a helper function no
needless_rec a let rec type that refers to no type of its cycle let without rec (ADR 0047) no

Lints run on the program as written, before metaprograms expand it, in piac --check, --verify and every --emit mode. They are warnings and never stop a build. @allow(range_requires) on a function's return annotation turns one off for that function, piac --no-lint=<name> turns one off for a run, and piac --no-lint turns them all off. In VS Code they appear as warnings from pia-lint, with the fixes above as quick fixes.

let narrow (x : u32) : u8 @allow(range_requires)
  requires x < 256   \ kept as a contract: it mirrors the C API
= x

Where Pia's own code does this

The lints were run over the documentation, the examples and the case studies when they were added. The tour now uses range types where it used constant preconditions. What remains is listed here, as material for later changes:

  • The stream delineation demo (streams.pia.md) passes fill and dem as parallel slices, and nearly every function requires len fill = len dem: a buffer of records would make that true by construction. Its walk requires bound < 4294967295, which range_requires suggests as int{0..4294967294}. Its relational forall (k in 0..len fill). fill.[k] >= dem.[k] wants a record invariant on that buffer's element, once record where invariants land.
  • The VecDeque case study (rust-vecdeque.pia.md) requires 0 < old_cap on a usize in four functions, a one-sided bound that an open range type would carry.
  • The tests keep constant preconditions on purpose, since they test contracts; they are not idioms to copy.