Skip to content

Implement Box[T] (§3.7, §3.9, §8, §18.7) #475

Closed

Description

@ehartford

Summary

Implement Box[T] as With's explicit heap-owned single-owner pointer. This unlocks §3.7 auto-deref through Box, §3.9 Box[T] -> Box[dyn Trait] coercion, consuming trait-object receivers, and alloc-tier heap types promised by §18.7.

Spec

§3.7 examples use Box[User] = Box.new(...) and field access through the box (docs/with-specification.md:641). §3.9 says the same implicit trait-object coercion that works for &T -> &dyn Trait also applies to Box[T] -> Box[dyn Trait] (docs/with-specification.md:742). §18.7 lists Box[T] as a heap-allocated type that requires std/alloc support (docs/with-specification.md:10028) and says alloc = true brings back Vec[T], Box[T], str, String, HashMap, and HashSet without full OS std (docs/with-specification.md:10071, docs/with-specification.md:10090).

Required surface:

let user: Box[User] = Box.new(User { name: "Ada" })
assert(user.name == "Ada")

let logger: Box[dyn Logger] = Box.new(ConsoleLog {})
logger.log("ready")

Box[T] is an owning pointer, not Copy, and drops its payload and allocation when it goes out of scope.

Current state

The original body says Box does not exist; as a user-facing type, that remains correct. lib/std/collections.w defines Vec, HashMap, HashSet, and related collection helper types but no Box (lib/std/collections.w:8). lib/std/alloc.w exposes raw allocation helpers and lightweight arena/pool wrappers but no owning boxed allocation (lib/std/alloc.w:20). The prelude imports collections and traits, not a Box module (lib/std/prelude.w:3).

There is a compiler symbol slot for Box (src/Sema.w:145, src/Sema.w:1475), and the spec mentions Box in examples, but sema cannot resolve a real Box[T] type from stdlib today. Current auto-deref strips only pointer/reference types (src/SemaCheck.w:5448), so even after adding the type, field and method access should be routed through #407's Deref trait rather than a new hardcoded Box branch.

Trait-object support exists for references in the spec tests, but Box[dyn] consuming receiver shims are separately tracked by #432. The original note's "Sequence after generics fix (#391)" is still important because Box[T] must be a real generic type with distinct instantiations.

Implementation plan

  1. Implement or depend on Fix sema generic type instantiation (TY_GENERIC_INST erasure) — prerequisite for stdlib-as-generics #391 first so Box[i32], Box[str], and Box[dyn Trait] are distinct sema types.
  2. Add a stdlib alloc module surface for Box[T]: type Box[T], Box.new(value: T) -> Box[T], Box.into_inner(self) -> T, Box.as_ref(self: &Self) -> &T, and a safe scoped mutable-access API consistent with the current no-&mut language direction.
  3. Define impl Drop for Box[T] so payload drop glue runs before freeing the allocation. This must use existing allocator/runtime primitives, not new C helper code.
  4. Define impl Deref[T] for Box[T] after Implement user Deref trait for auto-deref (§3.7) #407 so field/method access follows the ordinary user trait path. Until Implement user Deref trait for auto-deref (§3.7) #407 lands, tests for .field through Box should remain expected failures rather than adding a special case.
  5. Add sema/coercion support for Box[T] -> Box[dyn Trait]. This must preserve ownership, install the correct vtable, and reject coercions when T does not implement the target trait. Use the existing trait-object coercion path as the model rather than creating a parallel representation.
  6. Coordinate with Object safety: vtable exclusion and Box[dyn] consuming-receiver shim (§11.3) #432 for consuming receiver calls through Box[dyn Trait]. A boxed trait object should be the allowed way to call fn consume(self) through a trait object because the box owns the erased payload.
  7. Ensure tier rules match §18.7: Box is available with full std and with alloc = true, unavailable in core no_std without alloc, and does not require OS/fiber runtime.

Test plan

Add behavior/spec tests:

  • test/spec/spec_ss03_7_box_auto_deref.w: Box.new(User {}), .field, .method(), nested reference-to-box deref;
  • test/spec/spec_ss03_9_box_dyn_coercion.w: Box[Concrete] coerces to Box[dyn Trait] and dispatches methods;
  • test/behavior/behav_box_drop.w: boxed payload Drop runs exactly once;
  • test/spec/spec_ss18_7_alloc_box_tier.w: alloc = true no_std project can use Box.

Add compile-error tests:

Run with build && with build :fixpoint && with build :test.

Acceptance criteria

  • Box[T] is a real stdlib heap owner in alloc/full std tiers.
  • Box.new allocates, stores T, and Drop frees exactly once.
  • Box[T] is not Copy; moves and explicit APIs preserve ownership.
  • Box auto-deref works through the user Deref trait path.
  • Box[T] -> Box[dyn Trait] coercion works and rejects missing trait implementations.
  • with build && with build :fixpoint && with build :test pass.

Dependencies

#391 is prerequisite for generic identity. #407 should provide the auto-deref mechanism. #432 overlaps for boxed trait-object consuming receiver shims.

Traceability

From the requirements campaign (docs/requirements.md, spec v7.1). Affected requirement IDs: 1.7.1.8, 18.7.1.26, 18.7.1.40, 3.7.1.1, 3.9.1.4.

Activity

  1. ehartford commented on Jun 14, 2026

    @ehartford
    ContributorAuthor

    Implemented in 85d99c5. Added std.box with Box[T] as a non-Copy owning heap pointer, Box.new/into_inner/as_ref/as_ptr, Drop/Deref integration, MIR/codegen lowering for allocation/free/drop, Box[T] -> Box[dyn Trait] coercion, and prelude shadowing so user-defined Box types remain valid. Added positive and negative tests for drop/into_inner, auto-deref, boxed dyn dispatch, missing trait impl rejection, move-after-move rejection, and alloc-tier availability. Verification passed: WITH=$PWD/out/bin/with ./out/release/bin/with build; build :fixpoint; build :test; 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