<!-- SPDX-License-Identifier: CC-BY-4.0 -->
<!-- seo-title: Borrow Checking Explained with HoldFast Examples -->
<!-- description: Learn how a borrow checker enforces ownership, aliasing, and lifetimes. Try HoldFast examples of shared and exclusive loans, disjoint indices, and initialization. -->

# Borrow checking and ownership

Borrow checking tracks who can access a value, how, and for how long. At compile
time, it can catch a reference that outlives its data or a write that invalidates
a live reference.

[See a borrow checker accept and reject a call](#disjoint-loans) ·
[See argument modes in the Playground](../#argument-modes)

<a id="ownership"></a>

## What does a borrow checker track?

| Concept | What the checker tracks |
| --- | --- |
| Ownership | Moving transfers control of a resource and makes the original binding unavailable. |
| Aliasing | Paths alias when they refer to overlapping storage. Shared reads can coexist. A live exclusive loan suspends competing access. |
| Lifetime | A loan must end while the borrowed storage is still valid. Its last use can differ between branches. |

HoldFast exposes shared and exclusive access, familiar from Rust's `&T` and
`&mut T`, as explicit modes on call arguments.
[The Rust Book on references and borrowing](https://doc.rust-lang.org/book/ch04-02-references-and-borrowing.html)

<a id="loan-modes"></a>

## Loan modes and ownership transfer

| Mode | Access rules |
| --- | --- |
| `in` | Share read access. The checker rejects overlapping writes while the loans are live. |
| `ref` | Read and write an initialized place exclusively. Overlapping parent access is suspended. Proven disjoint places remain available. |
| `out` | Lend storage for initialization on every normal return. Reads require prior initialization. |
| `move` | Transfer ownership to an `owned` parameter, consuming the caller's binding. |

[Loan modes for calls and receivers](../language/reference/#loans-and-parameter-modes)

<a id="disjoint-loans"></a>

## Example of borrowing two elements of the same vector

`ReadAfterClear` lends one row to `ClearPeer` for reading and another for
writing. If both arguments referred to the same row, clearing the target would
also empty the source before the read.

```hf
module NestedIndexedInvalidation;

private Result<byte, bool> ClearPeer(in Seq<byte> source, ref Seq<byte> target) {
    target = Seq.Empty<byte>();
    if (0 < source.Count) {
        return Ok(source[0]);
    }
    return Err(false);
}

public Result<byte, bool> ReadAfterClear(ref Vec<Seq<byte>, 3> rows, Nat i, Nat j) {
    if (i < 2 && j < 2 && i != j) {
        return ClearPeer(in rows[i], ref rows[j]);
    }
    return Err(false);
}
```

The range checks limit both indices to rows 0 and 1. The `i != j` guard proves
disjointness. With `i = 0` and `j = 1`, the helper clears row 1, reads the first
byte of row 0 if present, and leaves row 2 untouched.

Remove `&& i != j` and both indices can name the same row. The native checker
rejects `ref rows[j]` because disjointness is unproved. The regression test checks
that refusal and independently replays the accepted read and writeback in Rocq.
[Complete HoldFast source](https://github.com/symbiogenesis/HoldFast/blob/main/tools/tests/fixtures/nested-indexed-invalidation.hf) ·
[Nested-row replay and comparison](../language/loan-analysis/#nested-row-invalidation)

<a id="initialization"></a>

## Example of an initialization loan

`InitBounds` bounds its input with `requires` and specifies both initialized
outputs with `ensures`.

```hf
module LoanExample;

public Unit InitBounds(u32 base, out u32 low, out u32 high)
    requires base <= 100
    ensures low == base + 1
    ensures high == base + 2
{
    low = base + 1;
    high = low + 1;
    return;
}

public u32 SumInitializedBounds()
    ensures result == 23
{
    InitBounds(10, out var low, out var high);
    return low + high;
}
```

`out var low` and `out var high` declare fresh locals. On a normal return
from `InitBounds(10, …)`, both are initialized. Its two postconditions give
`low == 11` and `high == 12`, so their sum is 23. Remove `high = low + 1;`
and the native checker refuses the return with `high` uninitialized.
[Initialization example in the source module](https://github.com/symbiogenesis/HoldFast/blob/main/examples/dependent.hf)

<a id="loan-ends"></a>

## When does a borrow end?

In `ObserveAndWrite`, `selected` is a read-only view of `values[i]`. With
`readFirst` true, the function saves the byte, ends the loan, then overwrites
`values[i]`. With `readFirst` false, the view stays live, so writing `values[0]`
requires `i != 0`.

Move the first read of `selected[0usize]` after the overwrite, or change the
second path to write `values[i]`. Both edits conflict with the live view.
[Complete branch example](https://github.com/symbiogenesis/HoldFast/blob/main/tools/tests/fixtures/branch-view-last-use.hf) ·
[Branch-local borrowing checks](../language/loan-analysis/#branch-local-view-use)

Returning a borrowed view carries the loan into the caller. On success, the
packet validator returns a read-only destination slice.
[Run the packet validator and try a write through its read-only view](../tooling/packet-walkthrough/#success-returns-a-read-only-view-of-the-destination)

<a id="borrow-local"></a>

## Check loans with the native tools

From the repository root, launch the local Playground with `python` on Windows
or `python3` on Linux. Open the printed URL and replace the editor contents
with one of the complete modules above. For `ObserveAndWrite`, copy its linked
source file. Select **Compile**, make the suggested edit, then compile again.
**Problems** shows where the access or initialization check failed.
[Playground launch guide](../tooling/playground/#scope-and-launch)

```shell
python tools/run.py holdfast-playground
```

The browser Playground can evaluate supported mathematical examples. Use the
local compiler for these loan exercises and Rocq to replay model properties
from the emitted Gallina.
[Replaying proofs with Rocq](../formal-verification/#kernel-replay)
