Skip to content

First-class allocators: real Arena/FrameArena/Pool, Vec.new_in, ephemeral virality (§8.3) #437

Closed

Description

@ehartford

First-class allocators: real Arena/FrameArena/Pool, Vec.new_in, ephemeral virality (§8.3)

Summary

§8.3 promises first-class allocators: a real region Arena, a per-frame FrameArena, a fixed-block PoolAllocator, containers that accept an optional allocator (Vec.new_in), and the ephemeral-virality rule (container built over a borrowed allocator becomes ephemeral). Today's lib/std/alloc.w Arena/Pool are malloc passthroughs (arena_reset literally frees a freshly-made allocation and nothing else), FrameArena doesn't exist, and no container takes an allocator — so allocator-ephemeral-virality has nothing to attach to. TempArena is the only real type. Implement the §8.3 model.

Spec

§8.3 (docs/with-specification.md:2897-2926), §8.3a (:2928-2960).

  • "First-class. Standard library provides: Arena — region-based; all allocations freed at once; FrameArena — resets each frame; PoolAllocator — fixed-size blocks. Standard containers accept an optional allocator parameter." (8.3.1.1-.5)
  • Ephemeral virality (8.3.1.6-.8, docs/with-specification.md:2905-2921):
fn example(arena: &FrameArena):
    var candidates = Vec.new_in(arena)   // borrows arena → ephemeral
    candidates.push(1)                    // OK as local; cannot escape
    var stored = Vec.new_in(Rc.clone(&shared_arena))
    // stored owns its allocator handle → NOT ephemeral
  • §8.3a table (8.3.2.6-.8): Arena = user-controlled reset/drop, long-lived regions; FrameArena = external reset per frame/tick; TempArena = lexical scratch.

Current state

  • lib/std/alloc.w (66 lines, verified): Arena { block_size } — arena_alloc is alloc(size) (plain malloc via std.mem); arena_free frees individual pointers; arena_reset is free_mem(alloc(block_size)) — a no-op stub that allocates and frees a dummy block. Pool { item_size, capacity } — pool_alloc is malloc passthrough; no block reuse. TempArena is real (records allocations in Vec[i64], frees on reset(), drop calls reset).
  • No FrameArena anywhere (grep -rn FrameArena lib/ src/ → no hits).
  • No new_in / allocator parameter on any container. Vec is compiler-built-in: its {ptr,len,cap,elem_size} layout and allocation flow through with_vec_* runtime calls (rt/rt_core.w:1586+, e.g. with_vec_new, with_vec_push) which call the global allocator unconditionally.
  • No allocator abstraction (no Allocator trait/handle type).
  • Requirements campaign verdicts: 8.3.1.1/.2/.3/.5 partial ("stubs", "malloc passthrough; reset no-op", "no block reuse"); 8.3.1.6/.7 absent ("no new_in/allocator params"); 8.3.1.4/.8/.10 absent (tests with impl); 8.3.2.6/.7/.8 partial/absent (FrameArena missing, Arena reset stub).
  • Related: ArenaScope guard (Add ArenaScope guard type with @[no_await_guard] (§7.9, §8.3a) #411) currently specifies TempArena-style internals pending this issue's real region semantics; Context.temp (lib/std/context.w) carries a TempArena.

Implementation plan

Genuinely large; three phases, each independently green.

Phase 1 — real allocator types (pure lib/std, no compiler changes)

  1. Arena: region allocator in lib/std/alloc.w. Data: Vec[i64] of block pointers, current block ptr/offset/capacity, block_size. Arena.alloc(size) bumps the offset (align to 16); on overflow, pushes a new block (doubling up to a cap, min block_size). Arena.reset() frees all blocks except the first and rewinds the offset — "all allocations freed at once" for real. Arena.drop frees everything. Add Arena.mark() -> i64 / Arena.reset_to(mark) watermarks (consumed by Add ArenaScope guard type with @[no_await_guard] (§7.9, §8.3a) #411's ArenaScope).
  2. FrameArena: same bump core, API framed for per-frame use: frame_arena_new(capacity), FrameArena.alloc(size), FrameArena.reset() (external authority calls it each frame/tick), FrameArena.high_water() -> i64 for tuning. Implement by composition over the same block core (private helper functions, not @[c_export], per AGENTS.md).
  3. Pool → real fixed-block pool: preallocated slab of item_size * capacity (item_size rounded to ≥ pointer size), intrusive free list threaded through free slots; pool_alloc pops the free list (grows by slab when exhausted), pool_free pushes. Keep the existing pool_new/pool_alloc/pool_free names; the spec name PoolAllocator can be an alias if the inventory gate (Add the spec inventory gate (keywords/attributes/CLI/modules vs spec tables) #410) wants the spec spelling.
  4. Keep arena_alloc_zeroed/arena_free surface compatible: arena_free on a region allocator becomes a documented no-op (region memory is reclaimed by reset/drop) — audit in-repo callers first (grep -rn arena_free); freeing individual region pointers with libc free would be UB once allocations are interior, so any caller relying on it must move to TempArena or reset.

Phase 2 — allocator handles for containers

  1. Define the allocator interface the containers will use. Minimal honest shape: a trait Allocator = fn alloc_raw(mut self, size: i64) -> *mut u8 / fn dealloc_all(mut self)-style trait in lib/std/alloc.w with impls for Arena, FrameArena, Pool (trait-based; depends on trait-object or generic dispatch quality — see Fix sema generic type instantiation (TY_GENERIC_INST erasure) — prerequisite for stdlib-as-generics #391/Bug: trait default method bodies never resolve (§11.6) #538 caveats). Decide borrowed (&Arena) vs owned (Rc[Arena], needs Implement Rc[T] and Arc[T] (+ Shared[T] alias) (§8.2, §8.4, §14.16) #470) handle representations.
  2. Vec.new_in(allocator): because Vec is a compiler-builtin lowered to with_vec_* runtime calls, this needs either (a) an extra allocator slot in the Vec header consulted by the with_vec_* growth paths (ABI change to the 4-field {ptr,len,cap,elem_size} layout — touches src/Codegen.w, rt/rt_core.w, and every embedded-runtime consumer; bootstrap hazard: rt changes must land in a separate commit from Link.w changes per AGENTS.md, and stage convergence must be re-verified), or (b) a stdlib-level ArenaVec[T] generic that owns its element storage in the arena and reuses none of the builtin Vec runtime. Option (b) is the smaller, honest first step and unblocks virality; option (a) is the spec's end state ("standard containers accept an optional allocator parameter"). Plan: ship (b) in this issue; file the ABI work for (a) as a follow-up if (b) proves the model.

Phase 3 — ephemeral virality

  1. Mark the borrowed-allocator constructor results ephemeral: a container built from &Arena/&FrameArena stores the borrow → its type (e.g. ArenaVec[T] holding the arena pointer) is declared ephemeral, so the existing type-level machinery (storage rejection in structs/containers) applies. The "owned handle → storable" half needs Rc (Implement Rc[T] and Arc[T] (+ Shared[T] alias) (§8.2, §8.4, §14.16) #470) and value-level provenance (Make ephemerality provenance-tracked and modular #362) to distinguish new_in(&arena) from new_in(Rc.clone(&arena)) when the handle type is one spelling — until then, borrowed-handle containers are unconditionally ephemeral (conservative, spec-compatible).
  2. Wire 8.3.2.10 (arena raw pointers untracked) into Make ephemerality provenance-tracked and modular #362's provenance work: pointers returned by Arena.alloc outliving reset are unsound; at minimum document the unsafe contract on the raw alloc surface, and route safe use through containers/ArenaScope.

Test plan

  • test/behavior/behav_arena_region.w — //! expect-stdout: ok: allocate many blocks > block_size (forces growth), write/read through pointers, reset(), allocate again and verify reuse (same first-block pointer via mark()), drop frees (run under leaks --atExit locally; assert no crash in CI).
  • test/behavior/behav_frame_arena.w — simulate 3 "frames": alloc, reset, alloc; assert high_water stable and values correct per frame.
  • test/behavior/behav_pool_alloc.w — alloc capacity items, free half, re-alloc and verify recycled addresses (free-list reuse observable via pointer equality), exhaustion growth path.
  • test/behavior/behav_vec_new_in.w (or behav_arena_vec.w per Phase 2 choice) — container over &FrameArena: push/get/len inside the scope works.
  • test/compile_errors/err_arena_vec_escapes.w — //! expect-check-fail: ephemeral — returning/storing the borrowed-allocator container (8.3.1.7: "candidates cannot escape this scope").
  • test/compile_errors/err_arena_vec_struct_field.w — borrowed-allocator container as a non-ephemeral struct field → rejected.
  • Keep behav_temp_arena.w green (TempArena semantics unchanged).
  • Coordinate with Tests: allocators coverage (§8) #481 (Tests: allocators coverage §8) — 8.3.2.5's "drop-calls-reset unasserted" belongs there but can be folded in here.

Acceptance criteria

  • Arena.reset() actually reclaims all region allocations; no malloc-passthrough stubs remain in lib/std/alloc.w.
  • FrameArena exists with external-reset semantics; Pool reuses freed blocks (observable in tests).
  • A container can be created over a borrowed arena and used locally; its escape is a compile error (virality).
  • Arena.mark()/reset_to() available for Add ArenaScope guard type with @[no_await_guard] (§7.9, §8.3a) #411's ArenaScope.
  • No silent behavior change for existing TempArena/scratch_arena users (Context, tests).
  • If any rt/*.w or Vec ABI is touched: rt changes and Link/consumer changes land in separate, individually-fixpoint-green commits (AGENTS.md bootstrap rules).
  • with build && with build :fixpoint && with build :test pass (and with build :test-green recorded).

Dependencies

Traceability

From the requirements campaign (docs/requirements.md, spec v7.1). Affected requirement IDs: 8.3.1.1, 8.3.1.10, 8.3.1.2, 8.3.1.3, 8.3.1.4, 8.3.1.5, 8.3.1.6, 8.3.1.7, 8.3.1.8, 8.3.2.6, 8.3.2.7, 8.3.2.8.

Activity

  1. ehartford commented on Jun 12, 2026

    @ehartford
    ContributorAuthor

    Implemented in 24c07ff. Added real std.alloc Arena, FrameArena, Pool/PoolAllocator, Arena mark/reset watermarks, ArenaScope over real arena marks, ephemeral ArenaVec[T] local-use coverage, and a generic pointer binding codegen fix needed for ArenaVec helpers. Added positive tests for arena region reuse, frame reset/high-water, pool reuse, ArenaVec local use, generic pointer binding, and a negative ArenaVec storage test. Builtin Vec.new_in ABI/runtime work is tracked separately in #570 per this issue’s own Phase 2 option-B split. Verification passed before push: build, fixpoint, full test, test-green; after the final remote rebase, focused allocator/generic tests passed again.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions