Access validation and lifetime topology prove the legal program. The compiler-owned memory planner then chooses a physical representation for those validated facts, and backend lowering only encodes the resulting plan.

Static memory topology and backend representations

Moth separates two questions that often get bundled together:

Borrow validation answers access questions. Lifetime-region and escape validation proves one legal lifetime topology. A memory-strategy planner then chooses a representation for each validated allocation family.

A garbage-collected representation can carry an already-proven topology, but garbage collection never supplies the proof. A capable full-control release backend must lower without a tracing or reachability collector.

The sentence to keep

Moth is reference-semantic by default, copy-explicit and move-inferred. It omits explicit reference types and lifetime syntax, not references themselves.

Moth keeps shared aliases and exclusive mutation in the language model without asking authors to write &T, &mut T or lifetime parameters. The compiler tracks those relationships and keeps source APIs small.

Two layers of memory safety

Access validation and lifetime validation work together, but they own different facts.

Borrow validation checks shared and exclusive access, alias activity, last potential use and optional affine transfer. It reads validated HIR and writes side tables.

Lifetime and retained-edge analysis checks one semantic lifetime owner, retained-edge outlives relationships, escapes, cycles, non-lexical intervals, cleanup frontiers, builder lifecycle roots and exported summaries.

Those two sentences carry five terms worth unpacking before the rest of the page leans on them.

Affine describes a cleanup responsibility exactly one owner holds at a time. It can pass to a new owner, but it never splits and never duplicates, so cleanup happens once at a proven final use. Borrowing a value doesn't take that responsibility. Transferring it does.

A retained edge is one value holding onto another so the second must outlive the first. A list keeping its items alive has retained edges. A local reading a value briefly does not.

A non-lexical interval is the stretch of control flow where something is genuinely still needed, which is usually shorter than the block it was declared in. The compiler picks the narrowest owner that works and widens only to the nearest enclosing owner on the same chain. It never slides sideways to an unrelated sibling scope or invents a broad owner to make the sums easier.

A cleanup frontier is a point where cleanup is provably safe. Reaching one takes a full proof: every relevant retained edge is gone, no live alias remains, nothing can recreate an edge and no external holder or surviving aggregate still retains it. Partial confidence does not count.

An epoch is one round of a fill-and-empty cycle. A collection repeatedly populated and cleared has many value epochs while the collection itself, and the memory backing it, outlives every one of them.

Neither analysis depends on a collector. A GC backend must receive the same validated topology as a collector-free backend.

The proof pipeline

The first two steps decide whether the program is allowed at all. Only the last two decide how it gets stored. Swapping that order is the mistake this whole design exists to prevent.

The accepted memory pipeline reads from one owner at each stage:

access and copy rules
    -> borrow and last-use facts
    -> lifetime topology and retained-edge summaries
    -> complete intervals, frontiers and epochs
    -> backend-neutral memory requirements
    -> target-affinity analysis and partition
    -> target-contract validation
    -> per-physical-variant family/layout refinement
    -> target/profile-aware compiler-owned memory planning
    -> ValidatedMemoryPlan
    -> backend lowering

The seam worth memorising: backend-neutral memory requirements is the last shared artefact. Build-owned target partition and target-contract validation come next and establish the candidate physical variants. Only after that does work become per variant.

The selection changes memory quality, not source legality or observable behaviour. Two variants of one source function may end up with different physical representations and identical semantics.

check runs through creation and validation of the ValidatedMemoryPlan and stops before lowering.

When transfer proof is missing

Moth infers cleanup-responsibility transfer only at a proven final use. If analysis cannot prove transfer on every relevant path, the operation remains a borrow and the statically proven region retains responsibility.

unproven transfer
    -> borrow remains
    -> statically proven region retains responsibility

This fallback keeps the source program under the same legal topology. It does not ask a capable release backend to switch to tracing garbage collection.

One fact, several consumers

One set of last-use and retained-edge facts feeds several decisions while each stage keeps its own responsibility:

Fact

Consumer

a shared or exclusive access may still be used

borrow conflict validation

no later source use exists on every relevant path

optional affine transfer

no capable source alias survives

cleanup-frontier proof

a final-use persistent store commits

affine root to persistent edge reclassification

a stored value is detached into an owned result

persistent edge to affine root reclassification

a final loop iteration is statically known

final-iteration responsibility transfer

no observer or recreating source survives an epoch

inferred-region epoch completion

edge sets are mutually exclusive across paths or epochs

avoid a false cycle coexistence result

Borrow validation supplies the facts. Lifetime analysis and memory planning own the decisions.

Explicit copies and declared regions

Existing values use shared access by default. copy place deep-copies the complete copyable graph, preserves its internal alias topology and shares no mutable allocation with the source. A non-copyable member, such as an external handle or resource, is a diagnostic rather than a silently surviving alias.

A copied acyclic graph may enter an inferred or declared destination region. A copied cyclic graph must enter one declared region as a whole, because declared regions are Moth's only source mechanism for direct cycles.

A declared region gives its own allocations one hard, count-free bulk lifetime. Last-use analysis still checks access within it, but it never releases a declared-region-owned allocation early, and region exit reclaims the domain together.

Count-free stops at the region boundary. An edge running from declared-region storage into an externally owned REC family stays a counted obligation, released at region exit before the bulk reclaim.

Backend representations

Backends realise the validated memory plan through different physical mechanisms:

Retained Edge Counting

Each step down the ladder costs more than the one above it, so the planner takes the first rung that answers precisely enough. A counter is the last option.

REC is a last resort, and the planner works down that ladder before reaching it. Selection needs all three conditions:

  1. runtime-many persistent retained edges that disappear independently
  2. no earlier mechanism answers precisely enough, meaning static cleanup, inferred regions, frontiers, declared regions, field splitting and cheap bounded retention have all been ruled out
  3. falling back to a region would hold substantial storage materially longer than the values are useful

A selected counter carries the live counted persistent-edge obligations plus at most one affine-root obligation.

REC counts only direct persistent edges in the post-refinement family graph. Transitive reachability never counts, which is exactly what keeps it away from tracing.

Contributing nothing at all:

One storage operation may still contribute several direct edges, so counting is per edge rather than per statement.

REC is not general ARC, it is not source-visible retain/release behaviour and it never establishes legality.

Reclassification runs both ways and costs nothing at the counter. A final-use store turns the affine root into one persistent edge. A detached result turns one persistent edge back into an affine root. Either way that single reclassified edge produces zero net counter traffic.

An operation touching several direct edges at once still moves the count by whatever remains after those cancel out. And the planner fuses a same-family replacement, so the backend never emits a decrement to zero followed immediately by an increment for the same slot.

Backends consume a validated memory plan. They do not infer source meaning, reconstruct lifetime topology or choose a new strategy when lowering.

Builder-owned lifetimes

Page, mount, request, frame and arena roots are accepted future inputs to lifetime topology. When a builder-owned consumer retains Moth values, those roots enter the same proof as source regions. A collector-free backend can use validated lifecycle regions directly. A GC backend may represent the already-proven topology with reachability, but reachability does not define which topology the compiler accepts. Future observation and event lifecycles need their own accepted contract before they become memory-planning inputs.

What can fail

Source failures use structured diagnostics. Missing compiler-owned metadata or a missing physical strategy uses InfrastructureFailure.

Roadmap and current status

Read this page as the accepted destination. The memory rows in docs/docs/progress/@entry.moth are the authority on what runs today.

Exit state

You leave with one model: static proof defines legality, the validated memory plan defines physical cleanup and a collector remains an optional representation for a topology already proven legal.

Next: how borrow validation computes access and last-use facts over HIR.

Compiler design / Previous / Next