Length generics

Signatures that relate the lengths of their arguments and results, proven by the compiler.

A signature can say how the sizes of its arguments and its result relate. The compiler proves it twice: once where the function is written, and again at every call. Nothing is checked at run time, and nothing is assumed.

In Verus or TLA+ this would be a separate proof. In Extra it is the type.

An index that cannot be out of bounds

L is Length names the length of something you have not seen yet.

  • L is a type: the set of valid indexes, 0..<n. So index: L reads "a valid index".
  • An empty array has no valid indexes, so a function that needs one cannot be called with it. That is a consequence, not a special rule.
  • L is a subtype of Int(>=0): a valid index can go anywhere an Int can.
  • L must be bound by an argument, as length: L on an Array, String, Dict or Set, or as Int(=L) on a number. A Length that nothing binds is a compile error.
fn get<T, L is Length>(
  items: Array(T, length: L)
  index: L
): T =>
  items[index]            -- T, not T?

The call is where the proof happens, from what the caller knows:

fn first-name(names: Array(String), i: Int) =>
  if i >= 0 and i < names.length then
    get(items: names, index: i)     -- ✓ String
  else
    ""

-- without the guard:
--   Could not prove that 'i' is >= 0 in argument 'index' of 'get' (L = names.length)
-- with `i <= names.length`:
--   Could not prove that 'i' is <= names.length - 1 in argument 'index' of 'get' (L = names.length)

Two things with length: L have the same length

That is all zip needs to say. Inside the body, map hands its callback an index of type L, so b[index] is a B, not a B?. The declared result, length: L, is proven from the body.

fn zip<L is Length, A, B>(
  a: Array(A, length: L)
  b: Array(B, length: L)
): Array({A, B}, length: L) =>
  a.map(|a-item, index| {a-item, b[index]})

-- zip(a: [1, 2, 3], b: ["a", "b"])
--   Could not prove that the length of '["a", "b"]' is == 3 in argument 'b' of 'zip'
--   (L = [1, 2, 3].length)

At a call, the two lengths must be provably equal: fixed and equal, compared by a guard (if names.length == ages.length then …), or one derived from the other (zip(a: names, b: names.map(|name| name.length))).

Arithmetic on lengths

A length expression can go wherever a number can in a refinement: exact, a bound, or a range.

WrittenMeans
L1 + L2the lengths added (concatenation)
L + 1, L - 1one more, one fewer. length: L + 1 on an argument says "at least one item"
L1 | L2the longer of the two: the union of their index sets
L1 & L2the shorter of the two: their intersection
Int(=N)a number argument used as a length
length: >=(L1 | L2)a bound, when the exact size is not known
fn concat<T, L1 is Length, L2 is Length>(
  a: Array(T, length: L1)
  b: Array(T, length: L2)
): Array(T, length: L1 + L2) =>
  a ++ b

fn pop<T, L is Length>(
  items: Array(T, length: L + 1)
): {T, Array(T, length: L)} =>
  {items[items.length - 1], items.slice(0, items.length - 1)}

fn take<T, L is Length, N is Length>(
  items: Array(T, length: L)
  count: Int(=N)
): Array(T, length: L & N) =>
  items.slice(0, count)

fn repeat<T, N is Length>(
  item: T
  times: Int(=N)
): Array(T, length: N) =>
  times.times(|index| item)

-- the size of a union is not known exactly, so the type says only what is true
fn union<T, L1 is Length, L2 is Length>(
  a: Set(T, length: L1)
  b: Set(T, length: L2)
): Set(T, length: (L1 | L2)...L1 + L2) =>
  a + b

What the caller gets back:

CallType
concat(a: [1, 2], b: [3, 4, 5])[1 | 2 | 3 | 4 | 5, length: =5]
concat(a: u, b: v)[Int, length: =u.length + v.length]
pop(items: [1, 2, 3]){1 | 2 | 3, [1 | 2 | 3, length: =2]}
pop(items: u)✗ Could not prove that u.length is >= 1, which 'L + 1' requires
take(items: u, count: 2)[Int, length: =(u.length & 2)]
union(a: set2, b: set3)Set(Int, length: 3...5)

Facts flow out of a call

The result type mentions the caller's own values, so an expression type-checks on its own, wherever it appears. same(a: u) has the type [Int, length: =u.length], and what you know about u.length applies to it with no name in between. Built-in methods follow the same rule: u.map(…) has length: =u.length.

fn same<T, L is Length>(
  a: Array(T, length: L)
): Array(T, length: L) =>
  a

fn doubled(u: Array(Int), i: Int) =>
  if i >= 0 and i < u.length then
    same(a: u)[i] + u.map(|x| x * 2)[i]    -- ✓ Int
  else
    0

When a let ends, a type may only mention names that still exist. Each term is rewritten to an equal name that survives, or to a bound in surviving names that is still provable, or, failing both, to the constant range that is still provable:

fn kept(u: Array(Int), i: Int) =>
  let
    z =
      let
        t = u.filter(|x| x > 0)
      in
        same(a: t)       -- inside: [Int, length: =t.length]
  in
    -- outside, z is [Int, length: <=u.length]
    if i >= 0 and i < z.length then
      u[i]               -- ✓ Int
    else
      0

Anywhere the types line up

A length generic can appear in callback parameters, optional arguments and objects. A callback type promises the callback only valid indexes; the check runs the other way round, so the function you pass must accept every index it may be given.

fn with-index<L is Length>(
  a: Array(Int, length: L)
  g: fn(# i: L): Int
): Array(Int, length: L) =>
  a.map(|x, i| g(i))

fn indexes(u: Array(Int)) =>
  with-index(a: u, g: |i| u[i])    -- u[i] is an Int here

fn or-first<L is Length>(
  a: Array(Int, length: L)
  b: Array(Int, length: L)?
): Array(Int, length: L) =>
  b ?? a

Limits

Everything here is a valid program that is rejected today, or a relation the compiler does not infer. None of it is unsound: the failure is always "not proven".

  • The prover combines facts that are a difference of two quantities: a <= b and c <= d do not prove a + c <= b + d.
  • An equation determines L only with a coefficient of ±1: not L + L, and not L inside | or &. L1 + L2 needs one of the two bound by another argument.
  • A function without a declared result does not infer a length relation: fn f(u) => same(a: u) returns [Int]. Declare L to keep it.
  • length: =u.length is inferred and printed, but cannot be written in an annotation yet.
  • Only lengths. A value relation such as clamp(x, lo, hi) requiring lo <= hi is the natural next step.