Skip to content

Add allocation attribution and no-allocation checking substrate #361

Closed

Description

@ehartford

Add allocation attribution and no-allocation checking substrate

Summary

The spec now says allocation does not need to be syntactically spelled, but every allocation must be attributable, documented, diagnosable, and must never create an invisible ownership/lifetime/cleanup obligation.

This requires a compiler-visible allocation classification/checking substrate. The current language has many intentional allocation-producing constructs (Vec.new, .to_owned, comprehensions, f-strings, owned literals, async fibers, modeled FFI temporaries), but there is no coherent allocation-attribution model, no no-allocation checking context, and string-literal elision is not yet specified/implemented as a deterministic rule visible to such checking.

Spec

  • docs/with-specification.md §15.3 String Literals (:7541): &str context is static zero-cost storage; owned str context allocates/copies unless a deterministic elision rule applies.
  • docs/with-specification.md §20 Performance Guarantees (:10298): allocation attributability, no hidden ownership/cleanup obligations.
  • docs/requirements.md 15.3.1.3 through 15.3.1.11, 20.1.1.1 through 20.1.1.23.

Five whys / root cause (preserved from original)

  1. Why is the old allocation visibility rule wrong?
    The language intentionally allocates behind ergonomic constructs: f-strings, comprehensions, owned literals, async fibers, and modeled FFI adapters.
  2. Why not make all allocation explicit?
    That would force users to spell mechanical allocation machinery the compiler already understands, violating With's ergonomics mission.
  3. What property actually matters?
    Allocation must be attributable for performance and must never create hidden ownership, cleanup, lifetime, or caller-must-free obligations.
  4. Why is an implementation substrate needed?
    No-allocation contexts, diagnostics, tier/freestanding enforcement, and deterministic string-literal elision all need compiler-visible allocation facts.
  5. Root cause:
    Allocation is currently a behavior of many lowering/codegen/runtime paths, not a first-class effect/cost fact tracked through sema/MIR/build diagnostics.

Current state

No allocation classification, attribution metadata, or no-allocation checking context exists anywhere in sema/MIR/codegen. Grounding in current code:

  • Single runtime funnel. All compiler-emitted heap allocation reaches with_alloc(size) / with_alloc_zeroed(count, size) in rt/rt_core.w:613-616. This is the chokepoint an attribution model can anchor on, but nothing upstream records which construct requested the allocation.
  • Allocating constructs are scattered across MIR surfaces with no common marker: RvalueKind.RK_STR_CONCAT_N (src/Mir.w:58, f-string/concat lowering, see :1101, :1557), MirIntrinsic.VEC_NEW (src/Mir.w:90) and the Vec/Map growth intrinsics, .to_owned-style calls, fiber/task creation intrinsics (FIBER_*, src/Mir.w:177ff), and modeled FFI temporaries from c_import lowering. There is no AllocClass/effect field on MIR rvalues, intrinsics, or call sites.
  • The tier substrate this must coordinate with already exists and is the precedent pattern: require_alloc_tier_for_symbol / require_std_tier_for_symbol (src/SemaCheck.w:277-305) and validate_no_std_requirements (:511), with working fixtures test/compile_errors/err_no_std_vec_requires_alloc.w, err_no_std_owned_str_requires_alloc.w, test/behavior/behav_no_std_alloc_prelude.w. The freestanding/alloc/std tiers prove the "reject symbol-by-symbol in a restricted context" enforcement shape — no_alloc is the same shape keyed on allocation facts instead of tier membership.
  • String literals: &str-context literals are already static (no with_alloc involvement); owned-str contexts copy. The elision rule (owned value provably equivalent to a static immutable string) is neither specified in implementation terms nor visible to any checker.
  • Related already-filed issues: CoreFoundation's reference-counted type family: model it as a D51 convention profile #357 covers C ownership cleanup wrappers and forbids heuristic hidden cleanup; Make c_import string/buffer/void* coercions contract-driven #358 covers contract-driven C string/buffer/void* coercions and hidden caller-free FFI allocations.

Implementation plan

Phased; each phase independently lands green (no rt/Link changes until phase 4's optional runtime hook, which follows the export-first commit discipline).

  1. Phase 1 — Allocation classification metadata (MIR). Add an allocation-class side table to MirBody (ordered Vec, not a map): entries (site_id, construct_kind, ast_node, result_local, alloc_source) where construct_kind ∈ {explicit-API, vec-new/growth, to-owned, owned-literal, fstring/concat, comprehension, async-fiber, ffi-temporary}. Populate it at the lowering sites named above in src/MirLower.w (e.g. wherever RK_STR_CONCAT_N rvalues or VEC_NEW/FIBER_* intrinsic calls are built). Attach enough metadata for diagnostics: construct/source location, owning result type, allocator/policy, failure behavior, lifetime/owner, and whether elision is possible/proven.
  2. Phase 2 — Deterministic string-literal storage rule. Specify and implement: &str context → static storage (assert no alloc-class entry emitted); owned str context → owned allocation unless the documented elision rule applies (owned value equivalent to a static immutable string for all observable purposes — never mutated, never freed through a user-visible owner, identity not observable). Elision verdicts must be deterministic (AST-order analysis only) and recorded in the phase-1 table as elided.
  3. Phase 3 — no_alloc checking context. Surface: @[no_alloc] on functions (and a build-level mode for freestanding), co-designed with the tier and allocator model (First-class allocators: real Arena/FrameArena/Pool, Vec.new_in, ephemeral virality (§8.3) #437 allocator capabilities; freestanding tier). Enforcement: for a no_alloc context, walk the function's alloc-class entries plus callee summaries (a per-signature "may-allocate" bit propagated like the existing effect summaries in src/Sema.w sig tables); reject any entry not proven elided or routed through an explicit arena/allocator capability. Diagnostic names the construct: f-string allocates here; no_alloc context forbids it — help: format into a caller-provided buffer, or lift the allocation out of the no_alloc region. Conservative direction is rejection; false rejection is a compiler precision bug to fix by improving the analysis, never by user ceremony.
  4. Phase 4 — Obligation legibility. Audit that every compiler-generated allocation is either compiler-owned/non-escaping or represented by a visible owning type with Drop; emit directional diagnostics when an FFI/modeled temporary would create a hidden caller obligation (boundary shared with CoreFoundation's reference-counted type family: model it as a D51 convention profile #357/Make c_import string/buffer/void* coercions contract-driven #358 — keep their contracts authoritative for c_import surfaces).

Required behavior (preserved from original)

  • Classify allocation-producing constructs in the compiler: explicit allocation APIs, Vec.new, .to_owned, owned buffer constructors, comprehensions, f-strings, owned string literals when not elided, async fiber/task creation, and modeled FFI temporaries.
  • Attach enough metadata for diagnostics: construct/source location, owning result type, allocator/policy, failure behavior, lifetime/owner, and whether elision is possible/proven.
  • Make string-literal storage deterministic:
    • &str context is static zero-cost storage.
    • owned str context produces owned str, allocating/copying unless a documented deterministic elision rule applies.
    • elision is allowed only when the owned value is equivalent to a static immutable string for all observable purposes.
  • Add no-allocation checking contexts, co-designed with the tier and allocator model.
  • In no-allocation contexts, reject allocating constructs unless allocation is proven elided or routed through an explicit arena, allocator, or capability.
  • Make false rejection a compiler precision bug: improve analysis instead of forcing user ceremony.
  • Keep obligation legibility enforced: compiler-generated allocations are compiler-owned/non-escaping or represented by visible owning types with Drop; no hidden caller obligations.

Test plan

test/compile_errors/ (negative no-allocation contexts):

  • err_no_alloc_fstring.w — f-string inside @[no_alloc] fn; //! expect-check-fail naming the f-string construct.
  • err_no_alloc_comprehension.w — comprehension allocating a Vec.
  • err_no_alloc_owned_literal.w — owned str literal where elision is not provable.
  • err_no_alloc_async.w — async fn call / fiber creation in no_alloc context.
  • err_no_alloc_vec_new.w — Vec.new() without an approved allocator.

test/behavior/ / test/spec/ (positive):

Acceptance criteria

  • Add an allocation-effect/cost classification pass or equivalent sema/MIR metadata.
  • Add diagnostics that identify the construct responsible for a possible allocation.
  • Add a no_alloc/no-allocation checking design and initial enforcement point, coordinated with freestanding/alloc/std tiers.
  • Add tests for positive and negative no-allocation contexts covering: f-strings; comprehensions; owned string literals with and without deterministic elision; async fn calls / async: fiber allocation; explicit allocator/arena-approved allocation.
  • Add tests proving &str literal context is zero allocation and owned str literal elision is deterministic.
  • Ensure modeled FFI temporary allocation behavior remains covered by CoreFoundation's reference-counted type family: model it as a D51 convention profile #357/Make c_import string/buffer/void* coercions contract-driven #358 and emits directional diagnostics when obligations would be hidden.
  • with build && with build :fixpoint && with build :test pass; with build :test-green recorded.

Dependencies

Traceability

Original spec references (preserved): docs/with-specification.md §15.3 String Literals, §20 Performance Guarantees; docs/requirements.md 15.3.1.3-15.3.1.11, 20.1.1.1-20.1.1.23. Related already-filed issues noted in the original body: #357, #358.

Activity

  1. ehartford commented on Jun 12, 2026

    @ehartford
    ContributorAuthor

    Implemented in 7dbad14. Added the @[no_alloc] function attribute, deterministic allocation-site metadata in Sema, per-function may-allocate summaries, and construct-specific diagnostics for hidden/ambient allocation. Covered f-strings, comprehensions, owned literals with deterministic direct-return elision, async task/fiber creation, Vec.new()/with_capacity, direct allocator APIs, allocating callees, and explicit ArenaScope/TempArena capability methods. Focused positive/negative tests added. Verification passed: with build, with build :fixpoint, with build :test, and with build :test-green.

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