Contents

Memory management model (mere)

A summary of Mere's memory-management strategies, implemented behavior and design goals. For the current thread-sharing rules and their limits, start with Concurrency and sharing. Historical implementation milestones below are labeled separately.


1. Comparison of memory-management strategies

StrategyWhen is memory freed?ExamplesStrengthsWeaknesses
Manual (malloc/free)The programmer calls free each timeCMaximum controlFrequent use-after-free / leaks
GCA runtime garbage collector decidesOCaml, Java, Go, PythonSafe, easyPause times, memory overhead, poor for real-time
Ownership (move + borrow)Automatically at scope exitRustCompile-time guarantees, zero costCyclic / self-references are painful; learning curve
Region (bulk per-region)The whole region scope is freed at onceCone, Vale, Cyclone, ML/Talpin researchFast alloc / bulk free; cyclic refs OKRequires designing region lifetimes
Stack-onlyAt stack-frame exitC autos, Rust letZero costStrict size/lifetime constraints

Mere lets the programmer choose region and ownership boundaries explicitly. Static checks and runtime checks enforce different parts of that contract; the concurrency section below states their coverage and limits.


2. Mere's memory strategies (5)

This section introduces the design vocabulary. The owned T, &borrowed T and stack { ... } sketches are design notation, not current Mere syntax. Use the implemented forms and limits in section 4 when writing a program.

① owned T — sole ownership (design sketch)

A value has one owner; freed when the owner leaves scope. Equivalent to Rust's T.


let x: owned String = String.from("hello")
let y: owned String = x    // move; x is no longer usable

② &borrowed T — borrow (design vocabulary)

Pass a reference without transferring ownership. Equivalent to Rust's &T / &mut T, with implemented borrow modes &R T, &shared write R T, &exclusive R T and &mut R T. Their overlap rules are described below; they do not grant permission to share a region reference between threads.

③b region R loop x { ... } — the region-carrying loop (v0.1.296)

Long-lived state that is periodically compacted — an interpreter's heap, a server's session table — does not fit region R { }: its lifetimes nest (LIFO), and a compaction needs the NEW generation to outlive the OLD one. The loop is the hand-over-hand version: each iteration runs in a fresh arena named R; the body sees x : option C (None on entry, Some carry after) and answers region_flow[C, D] (prelude): Continue carry deep-copies the carry into the next arena — containers included, via the __mdeep family — and releases the current one; Done d copies d out and exits.

The escape rule splits where the block's could not: C may mention R (a Map[R, ...] carried from arena to arena is the construct's point), D may not — same check as a block's result. No fresh rigid variable per iteration is needed: nothing of arena N reaches arena N+1 except through the Continue copy, so one name R honestly denotes "the loop's current arena" throughout. Not carryable (refused at emit time, by type): functions (their captures hide behind a void* the deep copier cannot see into), Channel, ThreadHandle, OwnedVec, StrBuf, ByteBuf.

Measured on the C backend: 2.4 GB of dead map-entry overwrites churned through 2000 cycles, live set 51 entries — peak footprint 1.6 MiB, 0.32 s. Backends: interp + C; llvm / wasm / rv32 refuse cleanly (their reclamation is a LIFO bump rollback, which cannot express the swap).

③ region R { ... } — bulk per-region

Values placed in region R are freed all together when R is destroyed. Bump-allocator backed. Only Trivial types (no Drop) can live in a region. Unified with `arena` under Q-008.

④ view V[R] of T — self-referential views (Q-009)

A "bundle type" built inside a region: immutable, non-moving. Lets you express self-references without unsafe.


view DocumentView[R] of Document {
  own:    &R Document,
  tokens: &R [&R str],    // points into own.text
}

⑤ stack { ... } — stack-only (design goal)

The proposed construct would restrict allocation to the stack. It is not a current source-language construct; stack-size requests in mere.toml are a separate feature.


3. Why region (in detail)

Problems it solves

Areas where Rust's ownership struggles:

Region resolves these via bulk-free per region.

How it works


region R {
  // R is a bump allocator (just a pointer + size)
  let a = R.alloc(Node {...})    // one pointer bump
  let b = R.alloc(Node {...})    // ditto
  a.next = b                      // references freely valid inside the region
  b.next = a                      // cycle is fine
  // ... computation ...
}  // The whole region's memory is freed at once — no individual destructors

Typical uses

The Trivial constraint

Only "types without Drop" (Trivial) can be placed in a region. Why: bulk free without invoking individual destructors. Types that have Drop (DB connections, file handles, etc.) are managed separately via with (Q-011 resolved):


with db = Database.connect(...) in
  region R {
    let nodes = ...   // many allocations into R
    process(db, nodes)
  }
  // R is destroyed (Trivial only; no destructors)
// db.drop() runs (it has Drop, so it's released individually)

3.5 Region blocks reclaim values (v0.1.30–31, implemented)

The "one request = one region" use case above is no longer aspirational — as of v0.1.31 it is the implemented semantics on the C backend:

and variant nodes allocate in a thread-local current region. A region R { ... } block makes itself current for its body, so everything the body allocates is reclaimed when the block exits. Container structs (Vec / Map / StrBuf) stay in their own binding region — they carry identity and must not die with a scratch block.

(v0.1.464, C backend). A container's region lives in its type, and a function's body used to allocate through the region variable in its own scheme, which the call site never bound: the type said the caller's block, the value went to the default region. The region is now passed IN, as leading `__lang_region*` arguments on the uncurried `__direct` twin, and a call site hands over what it bound — a block it is inside, one of its own region parameters (which is how a chain reaches a body three calls down), or the default region where nothing decided.

What this is NOT is the callee asking what region is current at run time. That was tried in v0.1.453 and is unsound for a chain of calls, because the body and the call site hold different copies of the variable; m3d could not render a second frame, and v0.1.456 withdrew it. Passing it in makes the type and the value say the same thing, so carrying the result out of the block stays the type error it already was.

Through an inner function (v0.1.562). An inner function — an inner let rec, a let-bound lambda, a lift inside a lift — takes region parameters of its own, the way a top-level function's __direct twin does: they lead its lifted definition, a direct call passes what it bound, and a use as a value (a closure) passes the default region. Before, it handed its callees the default region whatever region its caller was in. v0.1.559 tried the other route — not letting the inner function quantify, so the enclosing function's parameter reached it — and that took region polymorphism away from every inner function; v0.1.560 withdrew it (test/parity/region_inner_poly.mere). The last shape — an inner function of one member of a let rec ... and group calling another member — is reached since v0.1.564: an inner binding keeps the mark of a region variable it does not quantify when the variable belongs to a group still being inferred (the group quantifies it), and unmarks every other one, which belongs to a value that outlives it. And a let holding a ByteBuf is not generalised (v0.1.564): ByteBuf was missing from the value restriction's mutable containers, so the region of a buffer bound by let was decided by nobody. The two together are what mgit's reads needed: 34.7 GB of the default region became 11.5 GB.

Per backend: C (v0.1.464) and LLVM (v0.1.466) pass it. Wasm needs nothing: it has one bump for every region, and what keeps a callee's allocation alive there is the high-water mark (Q-132), not a region argument. RISC-V needs nothing either, for the same reason: since v0.1.613 it reclaims with Wasm's scheme (before that it did not reclaim at all). Those two are not "unimplemented" — there is no argument for them to pass.

used to be allocated in the default (program-lifetime) region for one reason: a closure's env is a type-erased void*, so nothing could copy it out of a dying block, and a permanent allocation was the only safe answer. A closure now carries a third member beside env and fn — a copy function generated per env type, which region-allocates a fresh env and deep-copies each captured field through that field's own __mcopy_<tag>. __mcopy for an arrow calls it, so a closure leaves a region block the way every other value does. A closure with no captures (env == NULL) and an FFI adapter holding a borrowed pointer leave copy zero and are copied shallowly, exactly as before.

env struct starts with {__lang_region* __r; void* (*__copy)(region*, void*);}, and __mcopy for an arrow reads that header through the void* it already has. So the closure struct stays {env, fn} — two pointers, for every program. That matters because a closure is passed by value through every frame of an interpreter's dispatch: a third pointer per frame took a 512 MB-stack interpreter over the edge on a deeply recursive program, and ld caps -stack_size at 512 MB on arm64, so there is nothing to buy it back with. The __r field also makes copying idempotent: copying an env into the region it is already in returns it unchanged, so a chain of envs capturing closures does not copy without bound, and a shared env keeps its identity instead of becoming two mutable states. An FFI adapter's env is a real struct too — a header plus the borrowed pointer, in the default region, with __copy = NULL meaning "do not copy me". One field answers both questions, and every closure with a non-NULL env can be asked.

An arrow type names no region, so a closure that captured a container made in region R { } can be stored somewhere older and outlive R without any type saying so. Every such store goes through a copier, and a container's copier marks R "kept": when R is released, its memory is handed to the region the value was stored into (or to one that is never freed) instead of being freed. The container keeps naming R's struct as its region, so that struct is never reused either — it stays behind as a forwarder to the region that took its memory, and every later push, set or grow through it follows the forward. v0.1.557 recycled the struct, which was right for reading the escaped value and wrong for writing it: the writes went into the next block and died with it (Q-190). Three more stores now copy what they store, for the same reason: owned_vec_push (an OwnedVec is malloc'd and outlives every block), spawn's env (the thread may run after the block), and on LLVM a channel message. A Map or a Vec whose storage moved to an arena of its own (map_recycle, map_compact, vec_compact) still has its struct where it was made, so retention keeps both (v0.1.567, Q-195). The other direction holds too (v0.1.688): when the block is released and NOT kept, the private arenas of the containers whose structs live in it are retired with it. Before, the struct went with the block and its arena with nothing -- 8,000 maps compacted inside region R { } left 480 MB behind R. Guarded by scripts/region_deps_check.sh. RISC-V had the same hole until v0.1.694: a block's exit rolls the containers' cells back, and now frees the arenas made since the block was entered whose container lies in the range it rolled back. Each arena names its container and carries a serial, so the walk stops at the first arena older than the block. On a coroutine's chain of heap blocks this is done only when that range is inside one block; a rollback that crossed blocks keeps the arenas, as it keeps everything else. Without coroutines an arena block was cut from gp and raised the block's high-water mark, which kept the containers' cells as well, so there the arenas stayed. Since v0.1.696 a program that compacts or recycles a container gets the coroutine layout whether or not it makes a coroutine: arena blocks come from the top of the heap down, and the main stack is bounded (an eighth of RAM when no coroutine can run, with no coroutine region; past it, "stack overflow (recursion too deep)"). Guarded by scripts/rv_arena_sweep_check.sh. scripts/region_uaf_check.sh runs each of these after forcing the block's memory to be reused.

(per-type deep copy, specialized like the show/== derive family), so returning a value from a block is always safe. A container cannot be a block result — the typer's region-escape check rejects it.

deep-copies the key and value into the map's own region; vec_push / vec_set copy the element. A stored value therefore outlives whoever stored it, no matter where it was allocated. Strings are immutable, so the copies are unobservable. The LLVM backend does the same as of v0.1.613, but only while a region block is open (with none open, every value is in the default region or the container's, and neither goes away). Until then it stored the pointer: a string put into an older Map inside region R { } was read after R was released, as whatever the next block wrote there.

the container's region is bump-allocated, vec_set/map_set copying a new string into a slot that already held one cannot reclaim the old copy — so a hot loop that overwrites the same slot with fresh strings grows O(writes), not O(1) (measured: 4M vec_set of a fresh string into index 0 ≈ 550 MB). Scalar (int/bool) elements are unaffected (their "copy" is a no-op). Eliding the copy for a value already resident in the container's region needs type-level region tracking on str (deferred); until then, prefer scalar slots for hot-overwrite loops, or a fresh per-batch region. (map_set on an existing key copies only the value, v0.1.77, so a counter keyed by repeated strings stays O(distinct keys).)

deep-copies into a malloc-backed message region; channel_recv copies out into the receiver's current region and frees the message. A sender's scratch region can die while the message is in flight.

region runs at constant ~1.5 MB RSS over 8M lines (previously 246 MB); a Redis-wire KV server with per-command regions holds flat RSS under sustained load.

per-line region loop so a tool does not have to hand-roll it: import "contrib/stream/stream.mere"; Stream.each_line path cb (side effect per line) and Stream.count_lines path pred keep peak memory at O(longest line) — measured 1.4 MB vs 61.7 MB for the naive loop on a 57 MB file. The callback must not let the line escape (storing it into an outer container deep-copies it out and reintroduces O(file) growth); this is the ergonomic path a streaming line tool wants.

Backend note: the interpreter is GC-backed (same value semantics, memory behaviour trivially fine).

The LLVM backend gained the same semantics in v0.1.443. It had none of it before: every value allocation named @__lang_default_region whatever region blocks were around it, region R { } was a stack alloca that only explicitly region-typed things went into, and there was no per-type copy-out because nothing it held needed copying out. On test/regionreclaim/pertree.mere -- a tree built inside a region block, only a scalar leaving it -- 100 iterations at depth 16 cost 2.5 MB on C and 316 MB on LLVM; it is 5.8 MB now, and flat in the iteration count like C's.

Both printed the same answer throughout, which is why the parity suite never saw it: parity compares what a program prints, and this was a difference in what it held. scripts/region_reclaim_check.sh is the gate that does see it, and it was written to fail either way -- it pinned the gap while the gap existed, went red when v0.1.443 closed it, and now pins the reclamation.

Two things the LLVM backend refuses as region-block results, both by the same rule the C backend uses: a container (identity -- a copy would be a different object) and a function (its captured environment lives in the block, and this backend has no environment copier). A result whose type never resolved is not copied at all, because the only values that reach a region boundary without a concrete type are the shared nullary nodes of a boxed variant, which live outside every arena.

The Wasm backend reclaims region blocks as of v0.1.37 (mark on the value stack + result copy-out via $__mcopy_<tag>; boxed results -- lists, tuples, records, variants, floats, bytes -- copy out correctly since v0.1.418, before which only scalar results assembled), with one honest difference from C: there is no per-container storage, and therefore no copy-on-store. Until v0.1.458 the answer to that was to make escaping stores compile errors. It was the wrong answer twice over — the same store performed by a callee went through and corrupted memory, and the exemption for unboxed elements let the container's reallocated buffer dangle instead of the element (Q-132) — because a guard that has to be right about every store in the program cannot be syntactic.

The answer now is a high-water mark. A store into a container that predates the innermost open block — or lies below the high-water mark (v0.1.613) — raises $__lang_hwm to the current bump, and the block's exit restores max(its mark, hwm) instead of its mark. The second half closes a hole: a container a callee builds inside the block and stores into an older one is reachable from outside but sits above the block's mark, so a later push that grew it put the new buffer above the high-water mark, and the rollback took it. Once the container has been stored outward it is below the high-water mark, and every store into it after that is protected. Sound because the value stored, and any buffer the store reallocated, were allocated before that point and lie below the bump; conservative because the block keeps its other garbage too — which is what the C backend does with a __heap value anyway, namely never free it. It costs one global compare when no block is open, and nothing at all for a block that touches only its own containers.

The RISC-V backend (RV32IM and RV64IM) uses the same scheme as of v0.1.613: a block mark, a depth and a high-water mark in three runtime words, a protect after every vec_push, vec_set and strbuf_push (a Map, being Vecs since v0.1.611, goes through them), and the result copied out twice by a per-type __rcopy_<tag>. Every store protects, an int's too: after monomorphization a type variable reads as int here, and one instance of the prelude's Map insert serves every Map whose values are words or pointers. The mark is only ever raised, and a block never rolls back past its own gp, which on one heap changes nothing and on bare metal is what keeps another task's stores harmless (docs/bare-metal.md). A failure leaving the block skips the rollback; try_or puts the depth and the block mark back. A block whose result cannot be copied by value — a closure, a container — runs without rolling back, which is what every block did here before. Measured on test/regionreclaim/pertree.mere: 100 trees of depth 14 run in a 16 MB machine, and ran out of it before.

As of v0.1.614 RISC-V containers also live the way C's do. An arena is a chain of power-of-two blocks (4 KB up) carved from the bump heap a megabyte at a time, freed onto size-class free lists and taken again, never merged. A container whose type says __heap is made in the shared default arena -- its cell, its buffer, and every value stored into it, which a store COPIES there (C's copy-on-store; containers and closures in the value are kept as handles) -- so a store into it needs no protect, and the region block it was made in gives everything else back. vec_compact / map_compact move a container into an arena of its own (the live elements copied, by their types) and free the one it had; map_recycle empties a Map and resets its arena to the first block; vec_bytes / map_bytes answer an owned arena's capacity, 0 for the shared one, as C answers. The copies are made at the call site, where the types are known: the prelude's own Map code stores words, and map_set is lowered to find / copy / update-or-insert around it. A block- or parameter-region container stays on the bump heap, protected as above.

The contract is C's: a value read out of a container before it is compacted (or recycled) does not survive the compaction. RISC-V had never freed anything, so code that broke the contract ran there by accident; the first mere-ruby run on arenas found two such reads (fixed in mere-ruby, and confirmed as use-after-free on C with AddressSanitizer). Measured on mere-ruby (RV64, --ram 256): corpus 165 and 285, which ran out of 256 MB, finish in 165 MB and 139 MB; test/regionreclaim/arena_churn.mere -- 60,000 stores into compacted and recycled containers inside blocks -- runs in an 8 MB machine.

What is still refused inside a region block is what a mark cannot help with: channel_send, spawn, and closure-registering externs. Those hand the value to another thread or to the host, on no schedule ordered with the block's exit.

Measured: the playground 2048 with a per-move region holds its bump pointer constant across 30,000 moves.

The default (program-lifetime) arena grows by chaining blocks rather than aborting when it fills: when an allocation would overrun the current block, a geometrically larger block is malloc'd and chained on, and blocks never move so existing pointers stay valid. The C backend gained this in v0.1.25 (a long-running server exhausted the old fixed-cap arena); the LLVM backend gained the same bounds-check-and-grow in v0.1.82 — before it, its __lang_region_alloc was a pure bump with no bounds check, so an allocation-heavy program (e.g. a per-pixel renderer) silently overran the 4 MB arena and crashed while interp/C/Wasm agreed. Guarded by test/parity/region_growth.mere (a checksum over ~6 MB of live region allocations, matching across all four backends).

On macOS a block of 16 KB or more is mapped, not malloc'd (v0.1.686). The C runtime maps it with mmap and unmaps it when the block is freed, so what a released region held goes back to the system at once. On macOS 26, by default, malloc keeps freed memory in both the resident size and the footprint, and a program that compacts or recycles arenas over and over grew without bound under it. Linux keeps malloc for the blocks (a mapping per block would count toward vm.max_map_count), but glibc's mmap threshold is dynamic: the first mapped block that is freed raises it, and from then on blocks that size come from the heap, where a freed one stays resident -- the same growth (v0.1.688). A program fixes the threshold at 64 KiB when it starts (mallopt(M_MMAP_THRESHOLD), unless MALLOC_MMAP_THRESHOLD_ is set; a library does not). Guarded by scripts/block_return_check.sh: on macOS a 400 MB region left, then the resident size read from outside (1 MB, against 841 MB under malloc); on Linux a region of 1,000 compacted maps (5 MB, against 405 MB with the threshold left dynamic).

Containers grow in place when they can (v0.1.414). vec_push, strbuf_push and bytebuf_push double their buffer when it fills. In a bump arena the old buffer cannot be handed back, so before v0.1.414 a container built by pushing cost twice its final size in cumulative allocation -- the matmul benchmark allocated 12.6 MB for three 2 MiB matrices, to within 248 bytes of exactly 3 x (2 + 2) MiB. Now, when the buffer being grown is the most recent allocation in its region and the current block has room, the bump pointer simply moves and the buffer keeps its address; when a large buffer lives in a dedicated block of its own (the v0.1.307 policy for allocations bigger than a quarter of the bump block), that block is realloc'd and the chain re-linked; otherwise the growth is a fresh allocation plus a copy, as before. The program cannot observe which path ran -- only alloc_total and the footprint change (matmul 12.6 -> 6.3 MB; a 200,000-int Vec 4 -> 2 MiB, which scripts/region_slack_check.sh now holds). The C backend does all three; the LLVM backend does the in-place path for Vec; the Wasm backend does it for Vec only while no region block is open, because its blocks are a rollback of the one bump pointer and extending an outer container's buffer into a block would be undone with it. A Map still copies its arrays on growth.

Lists can be built in order (v0.1.416). ListBuf[R, T] (lb_new / lb_push / lb_to_list, stdlib reference) appends by splicing the previous cell's tail, so a list produced first-to-last costs one cell per element instead of two -- the reversed accumulator an immutable list otherwise needs was 23 MB of the JSON benchmark's 105 MB. Its cells reference the pushed values without copying, which is sound because a push is refused while a different region is current (and after lb_to_list has handed the cells out); the builder itself is a container and obeys the escape rules above.


4. Implemented memory behavior (v0.1.700)

Concurrency and sharing

Mere has five backends, with different execution models:

BackendExecution of spawn
InterpreterOCaml 5 domains
CNative POSIX threads
LLVM IRNative POSIX threads
Wasm with scripts/run_wasm.jsNode.js workers over shared Wasm memory; other hosts must supply the required imports
RISC-V (RV32IM / RV64IM)The prelude's coroutine-based green threads

The interpreter uses OCaml-managed allocation. Compiled region storage and reclamation are described in section 3.5; availability of spawn does not imply identical allocation, scheduling or runtime guards on every backend.

Static checks

The interpreter and emission paths share type inference, borrow checking and spawn-capture analysis. These checks run before evaluation or emission.

BoundaryImplemented rule
channel_send ch valueThe element must be Send. Obligations are tracked through inference, including polymorphic wrappers. par_map also requires Send input and output elements.
A captured binding whose resolved type is SyncIt may be shared with the spawned thread.
A captured binding that is Send and not SyncIt is moved into the thread. Subsequent use of that binding in the parent is rejected. Branches must agree on moves; repeated moves from a reusable closure are rejected.
A captured binding that is neither Send nor Sync, or whose classification is unresolvedThe capture is rejected.
local typeNeither Send nor Sync; wrapping it in an ordinary record or variant preserves that restriction.
Region references (&R T, &shared write R T, &exclusive R T, &mut R T)Neither Send nor Sync, regardless of the borrow mode. Direct captures and channel sends of these references are rejected.
Region-bound mutable containers (Map, Vec, StrBuf, ByteBuf, ListBuf) and CoroNeither Send nor Sync. Direct captures are rejected.

Ordinary records and variants derive Send/Sync from their contents. A Channel is shareable. Types such as File, ThreadHandle and OwnedVec[int] are movable but not shareable. sync type is the type author's assertion that a capability is safe to share: it adds no lock. The compiler refuses a sync declaration that holds a builtin value such as a Map, Vec, OwnedVec, File, ThreadHandle or Coro, including through an ordinary record or variant. See the standard-library ownership rules.

Borrow modes govern overlapping borrows within a region. For a tracked variable or field place in the same region, two shared-read borrows may coexist, as may two shared-write borrows. Other mode pairs conflict while both borrows are active. A shared-write annotation adds no synchronization and does not override the thread-boundary rules above.

Runtime guards and coverage limits

Spawn analysis follows functions whose bodies are visible in the program. It rejects a reachable mutable container, with an exception for a table whose uses pass the whole-program read-only check. A handler received as a function parameter, a channel message or a call result has no visible body to follow. Such callbacks can be accepted even when they reach a mutable container. Type acceptance alone therefore does not establish that the callback's accesses are safe.

In standalone interpreter, C and LLVM programs, mutable containers track their owner thread. A foreign write fails. A foreign read makes the container permanently shared and read-only: a later write by its owner fails too, even after readers have been joined. OwnedVec has a separate ownership handoff when moved into a spawned closure. These behaviors are exercised by `owner_check.sh`.

LLVM also guards vec_recycle, map_clear and map_recycle as of v0.1.683. Rejected calls leave the contents intact. Map clearing and recycling empty the existing storage while preserving its owner, shared bit, region and capacity; they do not replace the header with a fresh Map. LLVM does not give these containers private arenas, so recycling does not reclaim their backing storage.

Threaded Wasm modules also guard `Vec` (v0.1.680) and `Map` (v0.1.681). A foreign write fails before mutation, and a foreign storage read permanently prevents later writes, including after join. Vec checks cover ordinary, range-versioned and SIMD accesses, plus vec_recycle. Map checks cover map_set, map_delete, map_clear and map_recycle; reads through map_get, map_has, map_len and map_iter freeze the Map. Hashed scalar keys and linear compound keys follow the same rule. Wasm's map_bytes and map_compact remain constant/no-op operations without a storage access. Read-only sharing and each worker's own mutable containers remain valid. The cases and negative controls in `owner_check.sh` and the Wasm Map matrix cover these rules, worker identity separation and allocation alignment.

Threaded Wasm modules also guard `StrBuf` and `ByteBuf` (v0.1.684). strbuf_push, bytebuf_set and bytebuf_push reject foreign writes and writes after a foreign read, before modifying storage. Reads through strbuf_len (including len), strbuf_to_str, bytebuf_len, bytebuf_get and bytes_of_bytebuf permanently freeze the source buffer, including empty buffers. Conversions produce independent immutable snapshots; reading a snapshot in another worker does not freeze its source. bytebuf_of_bytes creates a buffer owned by the calling worker. The `wasm_buffer_owner_check.sh` matrix covers these operations, caught and uncaught failures, worker-local growth, region reuse, allocation alignment and distinct worker identities, with negative controls for guards, alignment and identity assignment.

Threaded Wasm modules guard `ListBuf` as of v0.1.685. Both lb_push and lb_to_list require the builder's owner: converting it to a list also writes its frozen flag. A rejected call does not append an element or freeze the builder. The owner may continue building after a rejected foreign call. Completed immutable lists can still be shared or sent when their elements satisfy the frontend's Send/Sync rules. Existing frozen-builder and region checks remain in force. The `wasm_listbuf_owner_check.sh` matrix checks empty/nonempty builders, caught failures, immutable messages, worker-local use, region reuse and distinct identities, with negative controls for each operation's guard, alignment and identity assignment.

Threaded Wasm modules guard `OwnedVec` access and handoff (v0.1.687). owned_vec_new and vec_to_owned create storage owned by the current worker. owned_vec_push, owned_vec_get, owned_vec_len (including len) and owned_vec_to_vec require ownership before accessing storage, including empty-vector reads and conversions. Foreign reads fail rather than freezing the vector as a shared Vec. Caught failures leave its contents intact.

As on the native backends, direct OwnedVec bindings captured by an inline spawn (fn ... -> ...) are released, then claimed atomically by the next thread to use them. Once claimed, other threads fail, including a retained function alias in the parent. Frontend move checks reject direct parent use; runtime claiming does not predetermine which alias reaches released storage first. An opaque function value passed to spawn does not release the OwnedVecs hidden in its environment. The `wasm_ownedvec_owner_check.sh` matrix checks both constructors, every access API, transfer and retained aliases, worker-local growth and conversions, and distinct identities. Negative controls remove access guards, release and claiming, and duplicate worker identities. Unthreaded modules use the storage helpers directly and omit the ownership machinery; threaded modules without OwnedVec omit its ownership helpers.

An embedding host must set the exported mutable __lang_thread_id global before executing Mere code: use a distinct integer in 1..1073741823 for each instance sharing memory. scripts/run_wasm.js uses 1 for the main instance and tid + 1 for each worker. A zero or out-of-range identity causes execution to fail when a guarded container is used. The existing __lang_in_thread global remains a boolean for failure propagation. Modules that use neither thread nor channel builtins omit container owner checks and atomic metadata accesses.

RISC-V guards `Vec` in programs with green threads (v0.1.689). Owners are logical scheduler threads, including par_map callbacks. Foreign reads permanently freeze a Vec; a foreign write or a later write by its owner fails before mutation. Checks cover ordinary and range-versioned get/set, push, length (including len), sorting, recycling, compaction, conversions, show/to_json and SIMD loads/stores. vec_bytes only measures the arena and does not mark element storage shared. Vec-producing conversions and file read results belong to their caller; arena promotion and compaction preserve ownership metadata. Programs without green threads omit the checks and keep the four-word header. RISC-V and C mark reads through show, JSON and byte conversion, and through empty iteration, folding and Vec-to-OwnedVec conversion. C covers these paths as of v0.1.690; the ownership gate requires all its fixtures to match C.

Vec read boundaries, including conversions, empty traversals, partial application and file output, are inventoried in Vec read boundaries. The v0.1.703 audit closes additional interpreter, C and LLVM gaps and checks supported RISC-V paths against explicit expected results.

RISC-V Map guards (v0.1.691). User Maps follow the same logical-thread rule: foreign reads through lookups (including a missing key), membership, length or iteration make them read-only. Set, delete (including a missing key), clear, recycle and compact check ownership before modifying storage, even for an empty Map. The check preserves contents on rejection. Growth, clear, recycle, compact and default-arena promotion retain the owner. Only programs with green threads append ownership to the Map's metadata Vec; runtime-private Maps remain untracked. map_bytes measures arena capacity without sharing element storage.

RISC-V ByteBuf and ListBuf guards (v0.1.692). User builders use the Vec header's ownership word in programs with green threads. ByteBuf reads freeze foreign storage, including empty byte conversion and failed lookups; set and push reject foreign or shared writes before mutation. ListBuf push and conversion require the owner. Rejected foreign operations leave an unfrozen builder writable by its owner. Conversion freezes the builder even when empty, and repeated owner conversions are valid. Already-frozen push reports the frozen state before ownership, as C does. Growth and default-arena promotion preserve ownership. Immutable byte/list snapshots can be shared.

As of v0.1.706, RISC-V ListBufs also remember their creation region depth. Push rejects a different current depth before appending; returning to the creation depth permits further pushes. Conversion may run at another depth and still freezes the builder. LLVM now reports an already-frozen push before checking ownership, matching the other backends. The buffer boundary inventory records these contracts and the common tests with explicit expected results on all six execution targets.

Map read boundaries are inventoried in Map read boundaries. As of v0.1.704, LLVM marks map_iter before either layout's raw storage loads, C marks Map/Vec region-loop carry copies, and Wasm's linear missing-key lookup is catchable. The common read gate checks explicit expected results on all supported backends, including empty and fully deleted Maps and delayed calls.

RISC-V StrBuf guards (v0.1.693). User StrBufs use a fourth ownership word in programs with green threads. Foreign length queries (including len) and string conversion freeze the buffer, including empty storage. Push rejects foreign and shared writes before mutation, even for an empty append. Growth retains ownership. An independent immutable string snapshot can be read by another thread without freezing its source. Prelude and formatting buffers stay untracked; thread-free programs keep the original three-word header and omit ownership helpers.

RISC-V OwnedVec guards (v0.1.695). Constructors record the current logical thread. Push, get, length (including len) and Vec conversion require exclusive ownership, including empty access and failed lookups. Foreign reads fail rather than making the source shared. Inline spawn closures release directly captured OwnedVec bindings, and the first user claims released storage. There is no scheduler switch within a claim. Opaque callback values do not release hidden OwnedVecs. Once another thread claims the value, retained aliases fail even after that thread is joined. Growth and default-arena promotion preserve ownership; converted Vecs are independent and belong to their caller. Thread-free programs omit the checks and retain the existing storage layout.

As of v0.1.695, C, LLVM and the interpreter check ownership before owned_vec_to_vec, including empty conversion, and claim released storage before copying. C and LLVM defer automatic scope cleanup when a captured OwnedVec may outlive the scope through a ThreadHandle; the program registry retains its buffer until shutdown.

As of v0.1.697, the interpreter uses the same handoff boundary as the compiled backends: only a closure literal passed directly to the unshadowed builtin spawn releases its direct OwnedVec bindings. Function parameters, call results, channel messages, annotated callbacks and aliased or rebound spawn builtins do not release hidden captures. The interpreter previously inspected runtime callback bodies and released their captures even at these opaque call sites. A callback whose body is visible can instead be rejected by the frontend before execution; runtime checks cover callbacks that remain opaque to that analysis.

The interpreter also distinguishes OwnedVec storage for generic len: it requires exclusive ownership and claims released storage, just as owned_vec_len does. An ordinary Vec, including the result of owned_vec_to_vec, keeps the freeze-on-foreign-read behavior.

As of v0.1.700, the interpreter publishes OwnedVec release atomically and claims released storage with compare-and-set. Exactly one of two competing domains can become its owner. Vec and OwnedVec share an atomic owner cell; ordinary Vec reads mark the shared bit with a compare-and-set retry loop. The interpreter previously checked release and assigned the new owner as separate operations, allowing both contenders to succeed. `ownedvec_claim_check.sh` exercises the actual runtime helpers from two domains, including empty access, bounds failure after claiming, mutation, conversion and formatting. An unsafe reference control verifies detection of double acquisition.

As of v0.1.698, the interpreter treats show and to_json as storage reads. Vec, Map, StrBuf and ByteBuf mark a foreign read before inspecting their contents, including empty storage. ListBuf requires its owner for formatting and retains its frozen state; formatting in the owner leaves an unfinished builder writable. OwnedVec requires exclusive ownership and claims released storage before formatting. C also guards its OwnedVec show helper at entry.

Recursive formatting checks each container it visits, including containers inside tuples, records, variants, lists, options and other containers. An immutable string snapshot can be read by another thread without marking its source shared. A saved interpreter strbuf_push v partial application checks the current sharing state when the string argument is supplied.

`container_format_owner_check.py` covers all six container families on the interpreter, Vec formatting and OwnedVec show on C, and Vec formatting on RV32/RV64. Formatting representations and availability differ by backend; the gate compares paths that traverse container storage.

The container checks enforce access rules at operation boundaries; they do not lock an entire operation against concurrent access or synchronize FFI code.

FFI code and the implementation behind a sync type require the capability author to provide the promised synchronization. The --lib host boundary has separate lifecycle and overlapping-call rules, documented in the standard-library ownership section.

Small examples

A channel carrying an integer is accepted. With the interpreter, C, LLVM or the Node Wasm host, this program prints 42:


let ch = channel_new ();
let h = spawn (fn () -> channel_send ch 42);
let n = channel_recv ch;
let _ = join h;
print_int n

A thread-local value cannot be sent, including when wrapped in an ordinary record or variant. This program is rejected with is not Send:


local type Conn = MkConn of int;
let ch = channel_new ();
channel_send ch (MkConn 0)

A shared-write borrow also cannot be captured by a spawned closure. This program is rejected with neither Send nor Sync; the same applies to the other three borrow modes:


region R {
  let v = 5 in
  let b = &shared write R v in
  let h = spawn (fn () -> let _ = b in ()) in
  join h
}

The rules above are backed by the Send, move and borrow cases in `test/test_basic.ml`, container ownership cases in `test/owner/`, and the native allocation and failure checks in `threads_alloc_check.sh` and `thread_fail_check.sh`.

Earlier implementation milestones

The "Phase 2" section below is a record of the first implementation slices (the region/view syntax layer). Phase 11 → 31 implemented the 4 borrow modes (`&R T` / `&mut R T` / `&shared write R T` / `&exclusive R T`) + borrow checker + `with` Drop integration + the 4 Q-010 collections (`Vec` / `OwnedVec` / `StrBuf` / `Map`) + parity across the interpreter, C, LLVM and Wasm. Details: language-reference.md §3 region/view/with / codegen.md §4.

Added in Phase 36 (2026-06-22): a narrow value restriction in the typer. let v = map_get m k in ...-style let-binds through mutable containers are no longer generalized (so 'a doesn't leak). Details:

This is a narrowed variant of ML's standard value restriction (limited to types involving mutable containers) — ordinary fn lets like let inc = fn x -> x + 1 remain polymorphic.

Fixed in v0.1.508: the restriction, and the --lib boundary escape check below, now reach every spelling of a top-level binding. Until then both were applied by the let arm of each declaration loop and inlined by hand in the let rec arm, so let rec store = vec_new (); was generalised where let store = vec_new (); was not, and one Vec could hold an int and a str. scripts/binding_form_check.sh now runs each property in all five spellings — let, let rec, a member of a let rec ... and ..., and both inside a module — and fails when they disagree, whichever one is right.

Added in Phase 38.G-1 (2026-06-22): automatic scope-bound Drop for let v = owned_vec_new () in body (Level 1). This is lexical scope cleanup:

This is a compromise from Mere's "explicitness > brevity" philosophy: explicit with is still supported and recommended (for custom Drop types), and the typical OwnedVec pattern (build → query → return scalar) gets auto-Drop.

What works (Phase 2: syntax + value expressions + escape check + view declarations + region-enforced construction + field-access region propagation)


> region R { 42 }
- : int = 42

> fn (x: &R int) -> x
- : (&R int -> &R int)

> region R { let x = &R 5 in 42 }
- : int = 42                              // &R used inside, but result is int → OK

> region R { &R 5 }
ERROR: region escape: `&R int` cannot leave region `R`

> region R { region S { 100 } }            // nesting OK
- : int = 100

> view Node[R] of int { value: int, next: int };
  region R { let n = Node { value = 1, next = 0 } in n.value }
- : int = 1                                // view construction is only inside a region

> view Slot[R] { item: &R int };
  region S { let s = Slot { item = &S 42 } in 100 }
- : int = 100                              // R is substituted to S

> view Node[R] of int { value: int };
  let n = Node { value = 1 } in n.value    // outside any region
ERROR: view Node must be constructed inside a region block

Remaining region design work

with and scope cleanup are implemented. General last-use cleanup and full linear analysis have the limits described above.

The original syntax layer and compiled region storage

mere is a tree-walking interpreter written in OCaml, and in interpreter mode the actual memory management is done by OCaml's GC.

In Phase 4 codegen (C output), region becomes a real bump allocator (achieved 2026-06-18, Phase 4.17). region R { body } initializes the C runtime's __lang_region; &R v (sugar for R.alloc(v)) bump-allocates inside the region and returns T; leaving the scope releases it all at once. Combined with the typer's escape check, leaving a region scope frees memory while the type signature guarantees no `&R T` value has leaked. Details in [codegen.md](codegen.md)'s Phase 4.17.


5. View types — self-referential / cyclic structures inside a region

A region is "a box that shares the same lifetime"; we also need a way to safely express structures that point at each other inside (graphs, linked lists, ASTs, JSON trees, etc.). That's what view types are for.

Motivation: weak spots of ownership


// In Rust this is nearly unwritable: two mutually-referencing nodes
let a = Node { value = 1, next = ??? }  // want ??? to be b
let b = Node { value = 2, next = a }    // but a should also point to b

In ownership-based languages, cyclic references are fundamentally hard (Rc<RefCell<T>>, unsafe, custom arenas, etc.). Inside a region, everyone shares the same lifetime, so cycles are fine. View types capture this "in-region relational structure" as a type.

View design goals

The table describes the design goals. The implemented view-typing rules and the remaining tightening work are listed separately below.

GoalMeaning
immutableView values cannot be modified after construction; cannot be reassigned.
region-scopedAlways tied to some region R; cannot leave R (the type bakes in [R]).
structural identity by regionSame-typed views inside the same region are identified — this is the basis on which cyclic references work safely.

Difference from records


type Point = { x: int, y: int };       // ordinary record: lifetime via GC; region-independent
view Node[R] of int { value: int };    // view: bundle type tied to region R

Why "view"?

The physical layout (the inner type of T) and what the programmer manipulates (the Node type) are viewed as different things. Enables expressions like "internally a sequential int, but viewed as a Node struct" (a planned future feature).

Implemented view typing

View construction is restricted to inside a region block; the region parameter R at the declaration site is substituted with the innermost active region's name at construction time; and the view value's type itself carries the region tag as `Name[R]`. Field accesses / record updates propagate the region, and the view value is subject to escape checking.


view Node[R] of int { value: int, next: int };
region R { let n = Node { value = 1, next = 0 } in n.value }    // 1

view Slot[R] { item: &R int };
region S { 
  let s = Slot { item = &S 7 } in
  s.item                                                         // : &S int (R → S propagation)
}                                                                // ERROR: &S int would escape

region S { 
  let s = Slot { item = &S 7 } in
  let take_s = fn (x: &S int) -> 99 in
  take_s s.item                                                  // 99 (s.item is &S int)
}

region S { Cell { v = 1 } }    // ERROR: Cell[S] cannot leave region S
let n = Node { ... }            // ERROR: must be inside a region block

Tightening planned for later phases

The detailed design lives in the internal design notes (Q-009 resolved).


6. Implementation milestones and remaining design work

Phase 2: completed syntax and view milestones

Phase 3 (larger; some design needs to be revisited)

Borrow modes and concurrency

The current contract is described in Concurrency and sharing. Borrow-mode compatibility and thread-sharing checks are separate checks; a shared-write borrow does not make its referent thread-safe.

Phase 4 (codegen)

The milestones below record the original C implementation. Current compiled targets are C, LLVM IR, Wasm and RISC-V; their support differs. See codegen.md and bare-metal.md.


Experimental C library instance lifetime

mere -c --lib-instance source.mere uses one default allocation region for the loaded library, released by mere_lib_shutdown. Generate its matching header with mere --lib-instance --header source.mere. This experimental mode is for long-lived state such as an interpreter's reusable queues. Ordinary --lib keeps its per-call regions and escape checks.

In instance mode, a function can allocate a Vec or Map and retain it in module state for subsequent calls. Explicit region R { ... } blocks still release their storage at block exit and still reject escaping references. Temporary-region arguments remain polymorphic; instance lifetime does not force every function argument into the default region.

Immutable str inputs are copied into a temporary region for each exported call. Retaining an input in instance-owned state copies it into that state before the temporary region is released, including when the call fails. Mutable bytes inputs keep instance lifetime so their existing aliasing semantics are preserved. Nested calls on the same thread use separate input regions.

All exported calls are serialized by rejection of overlapping calls from another thread, even when the entry file has no mutable top-level binding. Calls on the same thread can reenter. The host must not race init/shutdown against an active call. There is one state per loaded library, not a public multi-instance context API. Failure returns status and unwinds temporary regions, but does not roll back mutations to instance state. Output buffers remain owned by the host and are released with mere_lib_free.

A shutdown request leaves the library initialized while any of its non-root coroutines remain unfinished, including coroutines on another host thread. Finish them on their owning threads and retry shutdown; requests do not cancel or unwind suspended coroutine bodies. Finish all coroutines before their host thread exits. A successful shutdown can be repeated and a later exported call initializes fresh module state.

Both ordinary and instance libraries release a host thread's cached temporary regions when that thread exits. Successful shutdown also releases the calling thread's idle caches, coroutine bookkeeping and retired arena generations. Compacted module-owned Map/Vec arenas follow the module lifetime. Serialized calls may move module state between host threads; the block registry, scan bounds and allocation epochs preserve coroutine pins across that handoff. On macOS, the pthread cleanup value keeps a snapshot of idle resources because image TLS can be discarded before ordinary pthread key destructors run. Other host threads release their own caches when they exit or successfully call shutdown. Before unloading a shared library, finish all calls and coroutines, release each participating thread's caches by shutdown or thread exit, and perform final shutdown. Module unload unregisters the runtime's TLS callbacks so no callback can subsequently enter unmapped module code.

Unreferenced default-region allocations also remain until shutdown. Use explicit temporary regions and the application's own reclamation policy; this mode does not add tracing GC or make unbounded allocation bounded. It does not provide a Ruby embedding API or change process-exit behavior in application code. C is the only supported output for this experiment.

python3 scripts/lib_instance_check.py --output /tmp/lib-instance-check checks queue reuse, retained strings, discarded-input allocation stability, failure recovery, overlap rejection, unfinished-coroutine shutdown requests, module-state handoff between host threads, arena reclamation and repeated module unloading with ASan/UBSan C hosts. scripts/lib_check.sh continues to check the ordinary library boundary.

7. Public implementation references

and region escape routes.


8. Academic roots

ReferenceContent
Tofte & Talpin (1997)"Region-Based Memory Management" — the foundational region calculus
Cyclone (2002)A research language that extends C with lifetimes and regions
Cone (2018-)A modern language with region as a primitive
Vale (2020-)Region + generational references
Mike Acton et al."Data-Oriented Design" — practical examples of frame-arena patterns

Bottom line: Mere is designed to map memory lifetime onto program structure — looser than ownership but stricter than GC; permits cycles; predictable. Currently mere is at Phase 1 (syntax-only); the real power emerges in Phase 2+'s static checks + codegen.