Skip to content

Modeled C stage 4b: in-place resources (preinit/init, Drop arming) - #1275

Merged
ehartford merged 3 commits into
mainfrom
modeled-c-stage4b
Sep 22, 2026
Merged

ehartford merged 3 commits into
mainfrom
modeled-c-stage4b

Conversation

@ehartford

@ehartford ehartford commented Sep 22, 2026 •

Copy link
Copy Markdown
Contributor

Rebased on main (83b3f1f+, after #1274 stage 4a and #1279 facade void*/drop rulings); no longer stacked.

Stage 4b of docs/modeled-c-implementation-plan.md (ruling §13–§13.2, §67; spec §16.2b.3–4; D54 / spec §16.2b.3 pinning, PR #1276), per docs/handoff-modeled-c-stage4.md. Keeps #1279 behaviors: facade_void_ptr_accepts (a void * destroyer gets self.repr as *mut c_void), the destroys-without-drop error (a resource renders only with drop).

What 4b renders

An in-place resource — a by-value C struct representation with init (and optionally preinit, ok, movable). Pinned by default (D54): the representation lives in a Box cell the value owns; the value stays an ordinary movable With value; every pointer handed to C points into the cell; R's own Drop runs the destroyer and the Box field's Drop frees the cell after. For the phase test's

c facade zlib:
    resource InflateStream wraps z_stream
        init inflateInit(self)
        ok Z_OK
        drop inflateEnd
        destroys inflateReset
    fn inflateReset
        destroys

over int inflateInit(z_streamp s); int inflateEnd(z_streamp s); int inflateReset(z_stream* s, int windowBits); the emitted <facade zlib> is

type InflateStream { repr: Box[z_stream], live: bool }
impl Drop for InflateStream:
    move fn drop():
        if self.live: inflateEnd(self.repr.as_mut_ptr())
impl InflateStream:
    move fn inflateReset(windowBits: c_int) -> c_int:
        self.live = false
        inflateReset(self.repr.as_mut_ptr(), windowBits)
fn InflateStream.inflateInit() -> (c_int, InflateStream):
    var repr = Box.new(z_stream {})
    let status = inflateInit(repr.as_mut_ptr())
    (status, InflateStream { repr, live: status == Z_OK })

A movable resource — the facade's claim that no operation keeps the address, never inferred — renders over a by-value field. For the same test's

    resource Ctx wraps z_stream
        movable
        init ctx_init(self)
        drop ctx_end

the emitted text is

type Ctx { repr: z_stream, live: bool }
impl Drop for Ctx:
    move fn drop():
        if self.live: ctx_end(&raw mut self.repr)
fn Ctx.ctx_init() -> Ctx:
    var repr = z_stream {}
    ctx_init(&raw mut repr)
    Ctx { repr, live: true }

With preinit deflate_storage the storage expression is deflate_storage(<preinit args>) (inside Box.new(...) when pinned) and the constructor takes preinit's parameters before init's.

Design points, each verified by compiling and running:

  • Storage is Repr {} — the ordinary zeroed construction of an imported struct: c_import gives every field its zero default (ci_default_for_type; probed scalar, pointer, nested-struct, array and function-pointer fields), while a user struct without defaults rejects T {}. T.zeroed() of the storage-types campaign is not implemented anywhere and is not needed; ruling §67 is consumed, nothing defined. preinit returns the representation and stands in that position.
  • Pinned cell (D54). Box[T] is the existing owned-heap-cell idiom (lib/std/box.w); Box.as_mut_ptr is added beside as_ptr. The cell exists, at its one address, from Box.new — before init, so "allocated, not live" already has its stable address. Drop order: R's move fn drop() body runs the destroyer, then the repr field's Box Drop frees the cell (da_c_facade_pinned_cell_destroy_then_free.w reads the state through the kept address inside z_end, under the debug allocator: leak count=0, no read of freed memory). A raw pointer from s.repr.as_ptr() taken before let b = move a reads correctly after the move. No immovable type category.
  • Resolve edge. The rendering is spliced after resolution, so a use line in rendered text is not an import edge and the D29 gate refused Box in <facade …>. A facade block declaring a pinned resource is now that module's import of std.box (Resolve.w facade_declares_pinned_resource), the way the prelude's own use std.box is text.
  • Failure status (ruling §13.2, spec §16.2b.4). With ok CONST, live is status == CONST: a failed init leaves Drop unarmed; the cell (or by-value storage) cleans up as ordinary With. Without ok the status is uninterpreted — "there is no rule that 0 means success" — so the resource is live and the status is handed back unread. A status-returning init yields (status, R), the low-level model every Result-shaped projection sits over (stage 5). ok on a void init is an error.
  • Pointer-taking operations. Any drop/destroyer whose first parameter is a pointer to the representation is handed the cell's address (pinned) or &raw mut self.repr (movable, or a by-value token whose destroyer takes its address — previously a 4a "in-place not rendered" error). z_streamp typedefs are chased through their type alias so the renderer agrees with Sema's resolve_alias. A pinned resource's op taking the representation by value is an error (it would act on a copy).
  • Silence is caught. verify_facade_resources ends with a net: a resource with a drop or destroyer that passed every check and has no struct under its name is reported as a renderer defect.

Sema

init must take a pointer to the storage; preinit returns the representation; from/init exclude each other; preinit needs init; ok needs a status; init/preinit safe once covered (an int* argument needs fn <init> lend, as the tests do); preinit/init parameter-name clash refused at the resource; movable without init refused; pinned by-value op refused. 4a's two "not rendered yet" errors are gone; facade_covers_return covers preinit's return.

Tests

  • behav_c_facade_resource_in_place_pinned.w — address kept by z_init (s->strm = s), checked after the constructor, rebinding, Vec.push, a function argument; raw pointer across a move; ends=4 misplaced=0.
  • behav_c_facade_resource_in_place_drop_once.w — Drop exactly once on scope exit, early return, moved-in, moved-out, in a Vec (pinned).
  • behav_c_facade_resource_in_place_arming.w — Stream is movable with preinit/ok/destroys (tag survives, failed init never runs the destroyer, destroys disarms); Blind is pinned and ok-less (status handed back, live).
  • test/debug_alloc/da_c_facade_pinned_cell_destroy_then_free.w — destroy-then-free ordering, cells freed once per path, failed init frees its cell.
  • test/phase/c_facade_in_place_renders.w — prototype-only; pinned + pinned-with-preinit + movable over one z_stream, z_streamp alias.
  • err_c_facade_{init_by_value,preinit_wrong_return,ok_without_status,from_and_init,preinit_without_init,preinit_init_param_clash,movable_not_in_place,pinned_by_value_op}.w; err_c_facade_in_place_not_rendered.w removed.

All behav_c_facade_*/c_facade_*/err_c_facade_* tests, the three guards, and the five mechanism-A tests pass under the fresh stage1 (#1273 still applies to err_c_import_raw_call_requires_unsafe.w on stage1).

Audits

:move-audit / :drop-audit / :debug-alloc-tests: verdicts in a comment below.

Open points for the maintainer

  1. (status, R) as the constructor's surface without ok, and with ok a dead-but-owned R on failure (methods callable, Drop unarmed): the low-level model; stage 5 owns the projection.
  2. A tail-position Stream.z_init(0).1 is refused ("a vacate needs a var base") while the same expression as a call argument is accepted — found writing the fixture, worked around with a let (_, s); not a facade defect.
  3. Not in scope: out-parameter constructors and status beyond ok (5), mechanism A retirement (4c).

@ehartford

Copy link
Copy Markdown
Contributor Author

Audits, driven by the pinned seed (WITH=$PWD/src/main src/main build …) on e2856a3/d9c79502:

  • :move-audit: rc=0, survey: all targets green (wall 189.1s)
  • :drop-audit: rc=0, survey: all targets green (wall 92.2s)

Not run here by design: :fixpoint, :test, the battery.

@ehartford

Copy link
Copy Markdown
Contributor Author

Audits after the D54 rework (94fe7b7), driven by the pinned seed (WITH=$PWD/src/main src/main build …):

  • :move-audit: rc=0, survey: all targets green (wall 257.1s)
  • :drop-audit: rc=0, survey: all targets green (wall 114.3s)
  • :debug-alloc-tests (includes da_c_facade_pinned_cell_destroy_then_free.w): rc=0, survey: all targets green (wall 42.1s)

Not run here by design: :fixpoint, :test, the battery.

@ehartford

Copy link
Copy Markdown
Contributor Author

Rebased onto main's tip 02e618e (after #1274, #1279, #1291, #1301); base is now main. Head: 2335fe0.

Will rebase once more onto main after #1306 merges so the battery tree builds.

@ehartford

Copy link
Copy Markdown
Contributor Author

Isolation battery on 774d4a36 (rebased on main with #1306; seed-driven, alone in its batch): build, :fixpoint, :move-audit, :drop-audit rc=0; :test rc=1 only from main's pre-existing behav_migrate_* failures (the §18.1-vs-migrate defect, fix #1309) — nothing from this change. Re-battery on a rebase once #1309 lands; ready then.

Eric Hartford added 3 commits September 22, 2026 11:47
…stage 4b)

A resource whose representation is a by-value C struct and whose facade
names `init` renders as `type R { repr: Repr, live: bool }` with a
constructor `R.<init>`: storage is the representation's ordinary zeroed
construction `Repr {}` (every field of an imported struct carries its zero
default; ruling §67 consumes that rule) or the `preinit` operation's result,
then the C initializer over `&raw mut repr`, then the arming bit. With
`ok CONST` a status other than the constant leaves Drop unarmed and the
storage cleans up as ordinary With (ruling §13.2); without `ok` the status
is uninterpreted (§16.2b.4), so the resource is live and the status is
handed back unread. A status-returning init yields `(status, R)`, the
low-level model a projection sits over; a void init yields `R`.

An operation taking a pointer to the representation — Drop, a destroyer, a
by-value token's address-taking destroyer — is handed `&raw mut self.repr`
(`&raw const` for a const pointer); a typedef'd pointer (`z_streamp`) is
chased through its alias so the renderer agrees with Sema's resolve_alias.

Sema: 4a's "in-place not rendered yet" errors go; `init` must take a
pointer to the storage (by value would initialize a copy), `preinit`
returns the representation, `ok` needs a status to read, `from` and `init`
exclude each other, `preinit` needs an `init`, init/preinit must be safe
once covered, and a C parameter name both preinit and init spell is
refused at the resource (it surfaced as a shadowing error at
`<facade NAME>:1:1`). A resource that passed every check without becoming
a struct is reported as a renderer defect rather than left silent.

Tests: Drop exactly once on every path for an in-place resource; preinit
used when named, a failed init under `ok` never runs the destroyer, a
`destroys` op disarms, an `ok`-less status is handed back live; the
prototype-only phase render (three resources over one z_stream, alias
pointer); six resource-shape errors.
… facade's claim (D54)

Spec §16.2b.3 / D54: an in-place resource's representation has one address
from the creation of the resource value until foreign destruction
completes. The renderer keeps the value ordinary and movable and puts the
representation in a `Box[Repr]` cell the value owns: `Box.new(Repr {})`
(or of the preinit result) exists — at its one address — before `init`
runs, every pointer handed to C is `self.repr.as_mut_ptr()` (`.as_ptr()`
for a const parameter), and R's own Drop runs the destruction operation
before the field's Drop frees the cell, so the cell outlives the C state.
A raw pointer taken from a borrow of the representation stays valid across
moves of the value. No immovable type category is introduced.

`movable` is a new resource clause (Ast/Parser/FacadeResource): the
facade's claim, with `ok`'s evidence weight, that no operation keeps the
address; it keeps the by-value rendering. It is an error on a resource
with no `init`, and a pinned resource's drop/destroyer taking the
representation by value is an error (it would act on a copy).

The rendering is spliced after resolution, so Resolve makes a facade
block that declares a pinned resource its module's import of std.box —
the D29 gate refused `Box` in the rendered file otherwise, and a `use`
line in rendered text is not an import edge. `Box.as_mut_ptr` joins
`as_ptr` in std.box.

Tests: address stability across rebinding, a Vec and a function argument
with a header whose init keeps the address (misplaced=0, ends=4); raw
pointer across a move; destroy-then-free under the debug allocator
(`da_c_facade_pinned_cell_destroy_then_free.w`, leak count=0); the arming
test's `Stream` is `movable` (by-value path, preinit) and `Blind` pinned;
the phase render covers both; two new clause errors.
@ehartford

Copy link
Copy Markdown
Contributor Author

Isolation battery on a562abe6 (rebased on main with #1309; seed-driven, alone in its batch): build, :fixpoint, :move-audit, :drop-audit rc=0; :test red only in main's own currently-red targets — examples fizzbuzz (print PR), rt-decl-audit and deep-debug rebind (#1318) — none in this change's paths (all 60+ facade tests, guards, debug-alloc fixtures green). Marking ready; a rebased confirmation battery follows once those merge.

@ehartford
ehartford marked this pull request as ready for review September 22, 2026 16:17
@ehartford
ehartford merged commit 0bf34d4 into main Sep 22, 2026
@ehartford
ehartford deleted the modeled-c-stage4b branch September 22, 2026 16:24
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