# Chapter 13: Refinement Types

A **refinement type** is a type with an attached predicate: `{x: T | predicate(x)}`. Only values satisfying the predicate inhabit the type. First checks these predicates at **compile time** where possible, and injects runtime checks at system boundaries (function calls, return values) where compile-time verification isn't feasible.

Refinement types give you guarantees like "this function only accepts positive integers" or "this index is always in bounds" without needing `Option<T>` wrappers or defensive runtime checks scattered through your code.

---

## Basic syntax

```first
// A natural number: Int with the constraint n >= 0
type Nat = {n: Int | n >= 0};

// A positive real: Float > 0
type PositiveFloat = {x: Float | x > 0.0};

// A probability: Float in [0, 1]
type Probability = {p: Float | p >= 0.0 && p <= 1.0};
```

---

## Refinements on function arguments

```first
// safeDivide only accepts non-zero divisors
function safeDivide(a: Float, b: {x: Float | x != 0.0}) -> Float {
    return a / b;
}

safeDivide(10.0, 2.0);    // OK: 2.0 != 0 — checked at compile time
safeDivide(10.0, 0.0);    // ERROR: refinement violated: 0.0 is not != 0.0
```

The error appears at the **call site**, not inside the function. The function body can assume `b != 0` without any runtime check.

---

## Refinements on return types

```first
function abs(x: Int) -> {n: Int | n >= 0} {
    return if (x >= 0) { x } else { -x };
}

let n: {n: Int | n >= 0} = abs(-5);   // n = 5, guaranteed non-negative
```

The compiler verifies the return value satisfies the refinement. Callers receive a type that carries the guarantee.

---

## Nat — the most common refinement

`Nat` (natural numbers) is a built-in type alias for `{n: Int | n >= 0}`:

```first
import "Nat";

function factorial(n: Nat) -> Nat {
    return if (n == 0) { 1 } else { n * factorial(n - 1) };
}

factorial(5);    // 120
factorial(-1);   // ERROR: refinement violated at call site
```

---

## Refinements and dependent types

Refinements and dependent types work together. `Fin<n>` from Chapter 12 is essentially:

```first
// Fin<n> is structurally: {i: Int | i >= 0 && i < n}
```

Using `Fin<n>` as an index into `Vec<T, n>` gives you:
- **Dependent types** guarantee the Vec has exactly n elements
- **Refinement types** guarantee the index is in `[0, n)`
- Together: compile-time proof that array access is always safe

---

## Subtyping with refinements

Refinement types form a natural subtype hierarchy:

```first
// {n: Int | n > 0}  is a subtype of  {n: Int | n >= 0}
// Because every n > 0 is also n >= 0

function takesNat(n: {n: Int | n >= 0}) -> Int { return n; }

let pos: {n: Int | n > 0} = 5;
takesNat(pos);   // OK: Int > 0 is a subtype of Int >= 0
```

The compiler inserts a subtype coercion automatically; you don't need explicit casts.

---

## Float refinements

```first
function sqrt(x: {n: Float | n >= 0.0}) -> {n: Float | n >= 0.0} {
    // body can assume x >= 0 — no NaN from negative sqrt
    return __builtin_sqrt(x);
}

sqrt(4.0);    // OK: 4.0 >= 0
sqrt(-1.0);   // ERROR at call site
```

---

## Runtime checks at boundaries

For values that come from outside the program (user input, file reads, network), the compiler can't verify refinements statically. It inserts a runtime check:

```first
interaction main() {
    let userInput: Int = readInt();
    // userInput has type Int (unrestricted)
    
    // Explicit coercion to Nat — compiler inserts a runtime check here
    let n: Nat = userInput;   // runtime: panics if userInput < 0
    
    factorial(n);   // safe: n is definitely a Nat
}
```

You can also check explicitly:

```first
interaction main() {
    let x: Int = readInt();
    if (x >= 0) {
        // Inside this branch, x is known to satisfy x >= 0
        let n: Nat = x;    // no runtime check needed: compiler proved it
        factorial(n);
    }
}
```

---

## Defining your own refinement types

```first
// Even integers
type Even = {n: Int | n % 2 == 0};

// Sorted arrays (checked structurally — may require proof)
type SortedList = {xs: Array<Int> | isSorted(xs)};

// Email — only checked at runtime (non-computable statically)
type Email = {s: String | isValidEmail(s)};
```

For complex predicates (like `isSorted`), First falls back to runtime checks unless you provide a proof.

---

## Refinements vs. dependent types — when to use which

| Feature | Dependent types (Ch 12) | Refinement types (Ch 13) |
|---------|------------------------|--------------------------|
| Constraint on | A type parameter | The value itself |
| Typical use | Array length, index | Ranges, non-zero, sign |
| Checked at | Compile time (always) | Compile time or runtime |
| Syntax | `Vec<T, n>`, `Fin<n>` | `{x: T \| predicate}` |

For **structural invariants** (lengths, shapes), use dependent types. For **value constraints** (ranges, non-zero, ordering), use refinement types.

---

## Summary

- `{x: T | p(x)}` — refine any type with a boolean predicate
- Violations are reported at the **call site** (not inside the function)
- `Nat` is the most common refinement: `{n: Int | n >= 0}`
- Refinements compose with dependent types (`Fin<n>`)
- Compile-time for literal values; runtime for external input

Chapter 14 covers **higher-kinded types** — polymorphism over type constructors like `Option`, `Array`, and user-defined containers.
