Skip to content

D120 stage 3: a struct of values is a value (no impl Copy written); std identity types declared resource - #2442

Merged
ehartford merged 11 commits into
mainfrom
d120-cow3
Oct 17, 2026
Merged

ehartford merged 11 commits into
mainfrom
d120-cow3

Conversation

@ehartford

Copy link
Copy Markdown
Contributor

Stage 3 of docs/proposals/d120-implementation-plan.md (ruling D120, §2.3, §4.3).

A struct whose fields are all values is a value: it copies with no impl Copy written, unless it implements Drop or is declared resource type. The same for an instance of a generic struct of values, so BTreeMap/BTreeSet of values are values through their List. An enum stays opt-in; a generator's state struct is consumed once (§13.4). A struct of integers copies by its bits; one holding a str, a List or a map retains each field, and the first write through a copy makes that field's buffer unique.

  • Sema: is_copy falls back to a field walk after the explicit impl, memoized per type (struct_copy_cache; uncached, check of hello world took 23 s). SlotMap and Atomic stay resources by the compiler's knowledge (Atomic because the pinned seed cannot parse resource type in std.collections).
  • std: Task, ScopedTask, JoinHandle, ScopedJoinHandle, MutexGuard, MutexGuardMut, RwReadGuard, RwWriteGuard declared resource type.
  • Codegen: field-by-field copy glue covers generic struct instances.
  • Fixtures: 25 compile-error fixtures that used a plain struct of values as "the non-Copy type" declare it resource type (the ruling's spelling), with a comment each.
  • Tests: behav_d120_struct_value_copy, da_d120_struct_shared_drop (three holders, one written: freed once, no leak), err_d120_resource_struct_still_moves.

Known on main too: behav_1944_comptime_snapshot_memory fails under main's own stage1 (verified in reseed-main at 16fbd06).

Corpora, gate, battery, A/B: pending.

Eric Hartford added 3 commits October 16, 2026 15:16
…td identity types declared resource

A struct whose fields are all values is a value (§2.3, §4.3): it copies
with no `impl Copy` written (one stays legal and redundant), unless it
implements Drop or is declared `resource type`. The same for an instance of
a generic struct whose instantiated fields are values, so a BTreeMap or
BTreeSet of values is a value through its List field. An enum stays opt-in;
a generator's state struct is a running producer, consumed once (§13.4),
never a value of its fields. A struct of integers copies by its bits; one
holding a str, a List or a map copies by retaining each field (the
field-by-field copy glue, now also for generic struct instances), and the
first write through a copy makes that field's buffer unique.

Sema: is_copy's TY_STRUCT branch falls back to fields_all_copy after the
explicit impl; the TY_GENERIC_INST branch does the same for a struct base
with no Drop impl, not a resource, not a SlotMap (its handles are its
identity and the runtime keeps no count), not an Atomic (a cell other
threads address; compiler-modeled by name like the channel ends, because
the pinned seed cannot parse `resource type` in std.collections). The walk
is memoized per resolved type once exact (struct_copy_cache: no unresolved
field, no cycle met): uncached it walked every field of every struct at
every query — type_needs_drop stops at the first droppable field, this
walk must see them all — and `check` of hello world took 23 s against 1.

std: the identity types without a Drop impl are declared `resource type`:
Task, ScopedTask (std.task), JoinHandle, ScopedJoinHandle (std.thread),
MutexGuard, MutexGuardMut, RwReadGuard, RwWriteGuard (std.sync).

Fixtures: the two D87 fixtures whose non-Copy `Ctx` was a struct of a str
declare it `resource type` (the ruling's spelling for a non-Copy struct of
values). Tests: behav_d120_struct_value_copy (ints, str + List fields, a
generic struct, a BTreeMap, passing by value), da_d120_struct_shared_drop
(three holders, one written: freed once, no leak),
err_d120_resource_struct_still_moves.
…ce type (D120 stage 3)

23 fixtures used a plain struct of value fields as the canonical non-Copy
type (`Thing { vals: List[i32] }`, `Counter { value: i32 }`, `Buffer {
text: str }`, …): a use-after-move, a `copy` refused, a `&T` argument to a
plain `T` parameter, a mut-receiver escape, a Copy/Clone derive refused
for a non-Copy field or payload, an effect pin too narrow for an escape.
Under D120 such a struct is a value and the pinned error no longer
occurs; each struct is declared `resource type` (the ruling's spelling
for a struct whose meaning forbids duplication) so the pin stands on a
type with identity. Mechanical: the first `type` line of each file, with
a comment saying why (scratchpad d120_struct_sweep.w).
…rce type (D120 stage 3)

Its `Resource { id: i32 }` carried an inherent `fn drop(move self)`, which
was never a destructor (verified under main: it does not run at scope
end); the type was non-Copy only by the old default. Under D120 it is a
value, `take(r) -> Resource: return r` no longer escapes it, and the
pinned `escape_value` contract no longer matches. Declared `resource type`,
like its sibling err_pin_ceiling in the sweep.
Eric Hartford added 8 commits October 16, 2026 18:33
…tage 3 surfaced it)

compile_bundle_interface_root declared `var taken_zcu` twice in one
scope. The old compiler let it through because the first binding had been
moved into self.zcu; under D120 stage 3 Zcu is a struct of values, that
assignment copies, the binding stays live, and the shadowing rule refuses
the second declaration. The second is a reassignment of the first.
… is a move; a held copy of a large aggregate goes through memory (D120 stage 3)

Three defects the self-build surfaced once Sema, Zcu and their kin became
values (stage 2's build was clean; stage 3's peaked at 8.6 GB against the
2 GB tripwire, LLVM's unit emit 61 s against 15 s, one unit's `llc` 41 s
against 2 s on same-sized IR). Found by WITH_KEEP_BITCODE + llvm-dis +
opt/llc standalone, and the per-function IR size tables.

1. Codegen: the copy glue of a struct (or a generic struct instance) is a
   cached per-type `__copy_struct_<ty>(ptr)` (ensure_structural_copy_fn,
   the twin of ensure_structural_drop_fn, #691): inlined at every consumed
   copy, Sema's hundreds of collection fields put 5,000 retains into one
   function.

2. MirLower: `move x` of a local binding whose type has drop glue lowers as
   OK_MOVE of the place (the rule the field arm already had), never as a
   retained copy: read as a copy, a moved Sema stayed live across every
   exit path and the drop plan dropped it field by field at each one
   (4,400 drop statements in run_mir_lower). Sema already refuses a later
   use of an explicitly moved binding (#691).

3. Codegen: a held copy (retain or take) of an aggregate of 64 bytes or
   more is memcpy'd into a slot, the glue or the blank runs on the source,
   and the consumer loads the slot — so its load and store stay the
   adjacent pair wl_lower_aggregate_copies turns into a memmove. Read as a
   first-class value with the glue call between load and store, the pass
   could not match, SROA scalarized the 2,378 leaves of a Zcu into a load
   and an insertvalue each, and SelectionDAG's store merging went
   quadratic (the #1129 class).

Also: WITH_TRACE_COW_COPIES=<bytes> (rt_core.w) reports every
copy-on-write copy of a List buffer or map table at or above that size
with a backtrace, and the `taken_zcu` double declaration in
Compilation.compile_bundle_interface_root is a reassignment (the old
compiler accepted it because the first binding had been moved out).

Self-build after: peak RSS 2.3 GB (main 2.2 GB), llvm.units_total 16.1 s
(main 14.9 s).
…ites swept; the census counts rt/ and the pattern

`dbg_puts("…" as *const u8, 11)` spelled, 124 times, what a literal already
is: a str, {ptr, len}, immortal, no count traffic. The signature predated
str-as-value and every caller counted its literal's length by hand (Eric,
2026-10-16: "why are we casting absolutely everything to *const u8"). No
language feature is needed: dbg_puts takes `&str` (as with_eprint twenty
lines away always did), dbg_put_bytes keeps the pointer-and-length form
for the seven sites that only have bytes (an origin tag, a payload), and
make_str("…" as *const u8, N) is the literal. Swept with a `with -p`
regex; cow_trace_copy follows.

The ceremony census gains the pattern (lit-ptr-len: a string literal, `as
*const u8`, a comma, an integer) and counts rt/ — the runtime is written
With, not a migrated corpus. The counts that stand today (the byte-level
seams left: rt_write, rt_buf_write_ascii, dbg_cstr_eq_lit, the platform
files; 36 c_strncmp/bridge sites in src/compiler; rt's existing
let-underscore, len-cast and move-arg) are granted against the bar of 0
until the reseed records them.
…ject's drop (D120 stage 3)

`var Bag { items, name, n } = make_bag()` with Bag a struct of values:
the parts are copied out with their own holds (carrier_read_kind, D111's
rule for a Copy carrier with drop glue), so the subject still holds its
own and must keep its drop — retire_decomposed_carrier's rule. The
irrefutable-destructure path cancelled it unconditionally, assuming
moved-out parts, and the subject's holds leaked
(da_var_destructure_owned_moves_once: LEAK size=32 origin=List). A
subject that moves its parts out (a resource, a struct with Drop) is
retired as before.
…ge 3 reaches (phase, spec, bundle interface, §11.8's example comments)

A derived Clone copied every Copy field and called `clone` on the rest.
Under D120 a struct of values is Copy without a declaration, and one that
also writes its own `clone` means it (Leaf's adds one in
spec_ss11_8_derive): a Copy field copies only when its type declares no
clone of its own (type_declares_clone: an impl Clone or an inherent
method; same for enum payloads).

Fixtures the ruling reaches, updated under it: the prelude-free Task of
test/phase/dump_abi_async_owned_capture.w is a `resource type` as
std.task's is; spec_ss11_8_derive asserts Pixel (a struct of u8s) IS Copy;
test/bundle_interface/wi_demo.wi carries the `impl Copy for Packet` and
`impl Copy for Pair` lines the emitter now writes for its value structs.
docs/spec/011_traits.md's two example comments "NOT Copy — aggregate
types require explicit Copy opt-in" are the projection §2.3/§4.3 (D120)
superseded; repaired to "Copy is not derived: a struct of values is
already a value".
…the demo bundle's Pair is one

The .wi emitter spelled every struct `pub type …`, and wrote `impl Copy`
for a Copy one. Under D120 a struct of values is a value with no
declaration, so a `resource type` struct of values crossing a bundle as a
plain struct would be a value to the consumer's compiler: the emitter now
writes `pub resource type …` (the parser reads it).

test/bundle_interface: the demo bundle's `take(p: Pair)` is the case
"consumed by declaration, though the source body only reads p" — with
Pair a struct of two i32 that is now a value to both sides and consumed by
neither, so Pair is declared a resource (the property the case tests), and
wi_demo.wi carries the emitted spelling.
…(D120)

`*p = v` and `p[i] = v` through a raw pointer (`TY_PTR`) skip drop-before-
overwrite (`assign_target_is_raw_pointer_store`), so `let v = *p` is how
`Box.drop`, `Box.into_inner`, and `comptime_try_eval_expr_result` (`var sema =
*sema_ptr` ... `*sema_ptr = synced_sema`) take a value out of raw memory.
When D120 stage 3 made a struct of values Copy with drop glue,
`retain_consumed_copy` set `MIR_HOLD_RETAIN` on `*p`: every boxed value
collection/struct leaked its payload on drop/into_inner, and the first
comptime evaluation during `sema.bodies` retained `Sema`'s ~130 tables without
a matching drop on write-back, forcing CoW copies across the rest of the
self-check (a 19.8% regression on `check src/main.w`).

`place_is_raw_pointer_pointee` leaves a direct `PK_DEREF` / `PK_INDEX` on a
`TY_PTR` local unretained while keeping retains on `&T` derefs and field
projections through pointers. `check src/main.w` returns to 51.60 s vs
50.80 s on main (ratio 1.0158, within the 5% gate).
@ehartford

Copy link
Copy Markdown
Contributor Author

Battery & Self-Host A/B Gate (813f412)

  • Battery: GREEN (battery rc=0 wall=749s on 813f412d2, all 83 targets green including fixpoint, debug-alloc-tests, behavior-tests, d-acceptance-tests, ceremony-census).
  • Self-build stage times: stage1 70.4 s, stage2 68.4 s, selfcheck 75.9 s.
  • Self-host A/B benchmark (tools/ab_bench.w, 3 interleaved rounds of check src/main.w vs main 16fbd064f):
    • Round 1: 46.72 s vs 50.54 s (ratio 1.0818)
    • Round 2: 48.28 s vs 49.93 s (ratio 1.0342)
    • Round 3: 49.26 s vs 49.30 s (ratio 1.0009)
    • Median: 48.28 s baseline vs 49.93 s candidate (ratio 1.0342, within the 5% gate).

@ehartford
ehartford marked this pull request as ready for review October 17, 2026 06:40
@ehartford
ehartford merged commit e38e86f into main Oct 17, 2026
@ehartford
ehartford deleted the d120-cow3 branch October 17, 2026 06:40
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant