Contents

A refinement type is a distinct type with the same representation as a base type plus one or more invariants. The invariant is a boolean predicate over self, and a value of the refinement type is guaranteed to satisfy it. Refinements are the smallest and most precise tool for making invalid values unrepresentable.

Declaring a Refinement#

A refinement declaration uses = to name the base type and one or more : invariant clauses to state the predicate. The keyword self refers to the candidate value.

type Positive = i32 : invariant self > 0

type Percent = i32
    : invariant self >= 0
    : invariant self <= 100

The base type must be a scalar or pointer type. Records, sums, enums, Option, Result, functions, generic references, and type parameters cannot be refinement bases. This restriction keeps the representation of a refinement identical to its base and avoids hiding a heap object behind a scalar type name.

A refinement of a refinement composes the invariants. The new type inherits every invariant of its base and appends its own.

type Positive = i32 : invariant self > 0
type Percent = Positive : invariant self <= 100

A Percent must be positive and at most one hundred. The base invariant is copied into the new type at declaration, so construction checks the whole chain.

Invariant Expressions#

An invariant must be a boolean expression. It may use arithmetic, comparisons, bitwise operators, and calls to pure functions. It may also refer to module constants. It may not call an impure function.

pure fn even(n i32) bool => n % 2 == 0

type Even = i32 : invariant even(self)

const LIMIT i32 = 100
type Small = i32 : invariant self > 0 && self < LIMIT

The purity restriction applies to type invariants specifically. A precondition or postcondition may call an impure helper, but the compiler then cannot fold it and the clause becomes a runtime check. A type invariant cannot make that trade because it may be evaluated during construction in contexts where an effect would be unsound.

Construction#

Normal construction has the refinement type and must never fail. It is allowed only when the input is a compile-time constant that satisfies the invariants, or when the value already has the refinement type. A constant that violates an invariant is a compile error.

const good = Positive { 5 }        // accepted and checked at compile time
const bad = Positive { 0 }         // compile-time error

A refinement literal uses a single positional value, not named fields. The braces are part of the construction syntax even though the base type is scalar.

const raw = 42
const value = Positive { raw }     // error: raw is not a compile-time constant

When the input is a runtime value, use checked construction with the postfix ?. The enclosing function must return Result[_, str] when a runtime check is needed. On failure, the construction returns Error("invariant failed for 'Positive'").

fn make_positive(n i32) Result[Positive, str] => Success(Positive { n }?)

If the compiler can prove the construction, the ? is redundant and produces a warning. If it can prove the construction invalid, it is a compile error even with ?. The Checked Construction chapter gives the complete rules for records, refinements, and nested invariants.

Assignment#

A refinement value can be assigned to its base type without a check, because the refinement is stronger. The reverse direction requires construction.

fn as_i32(value Positive) i32 => value

fn from_i32(n i32) Result[Positive, str] => Success(Positive { n }?)

Arithmetic on a refinement value produces the base type. The compiler does not attempt range or relational reasoning, so value + 1 is an i32, not a Positive. A cast or truncation cannot target a refinement type, because a raw numeric conversion would bypass the invariant; use checked construction instead.

fn increment(value Positive) Result[Positive, str] {
    const next = value + 1
    return Success(Positive { next }?)
}

This rule is deliberate. Making arithmetic produce a refinement would require the compiler to prove that the operation preserves the invariant, which it does not do. The explicit construction makes the obligation visible.

Refinements as Patterns#

The is operator tests a value against a refinement and binds the refined value when the invariant holds. This is the way to recover a refinement from a raw value without a Result.

const raw = 42
if raw is Positive(p) {
    print(p)
} else {
    print("not positive")
}

The bound name has the refinement type, so it can be passed to functions that require it. The test evaluates the invariant at runtime. A refinement pattern takes at most one binding.

match does not accept a refinement pattern because a refinement is not a sum, enum, Option, or Result. Use is for refinements and match for the sum-shaped types.

Refinements in Records#

A record field may have a refinement type. Construction checks the field invariant, and a record with a cross-field invariant cannot have that field assigned in isolation.

type Positive = i32 : invariant self > 0

type Counter {
    n Positive
}

type Window : invariant lo <= hi {
    lo Positive
    hi Positive
}

fn bump(counter Counter) Result[Counter, str] {
    counter.n = Positive { counter.n + 1 }?
    return Success(counter)
}

Counter has no cross-field invariant, so counter.n may be assigned when the new value is a Positive. Window has its own invariant, so it must be replaced as a whole.

fn shift(window Window, by i32) Result[Window, str] {
    const lo = Positive { window.lo + by }?
    const hi = Positive { window.hi + by }?
    return Success(Window { lo = lo, hi = hi }?)
}

The whole-value replacement is atomic: either the new Window is valid and the assignment happens, or the construction returns an error and the original value is unchanged.

Invariants Are Established at Construction#

A refinement invariant is checked when a value is constructed. It is not re-checked on every read, and the language does not maintain the invariant automatically after mutation. This is why compound assignment on a refinement is rejected and why arithmetic produces the base type.

The practical rule is that a refinement should be treated as immutable. If a value must change, construct a new one with checked construction. This keeps the guarantee meaningful and avoids a situation where a stored value no longer satisfies its declared type.

Composing Invariants#

Refinements compose through the base type. A refinement of a refinement inherits all base invariants, and a record may combine several refined fields with a cross-field invariant.

pure fn positive(n i32) bool => n > 0
pure fn ordered(lo i32, hi i32) bool => lo <= hi

type Positive = i32 : invariant positive(self)
type Percent = Positive : invariant self <= 100

type Window : invariant ordered(lo, hi) {
    lo Positive
    hi Percent
}

The construction of a Window checks each field's refinement and then the cross-field relation. If any check fails, the checked construction returns an error.

Refinements and Traits#

A refinement type is a distinct target for traits. An implementation for the refinement does not apply to the base, and an implementation for the base does not apply to the refinement.

trait Ord {
    fn lt(x, y Self) bool
}

type Positive = i64 : invariant self > 0

impl Positive of Ord {
    fn lt(x, y Self) bool => x < y
}

This allows a refinement to have operations that are only meaningful under its invariant, while the base type keeps its own implementation.

Design Guidance#

Use a refinement when the constraint is a simple predicate over one value: a positive count, a percentage, a non-empty string, an aligned pointer. Use a record invariant when the constraint relates several fields: a range whose lower bound is at most its upper bound, an account whose balance is within a limit, a span whose length is bounded. Use a sum type when the value is one of several alternatives rather than a constrained scalar.

Prefer a small, pure invariant that is cheap to evaluate. A complex invariant makes construction expensive and makes compile-time evaluation less likely to succeed. If the predicate needs several helper functions, keep those helpers pure and give them names that explain the domain rule they encode.