Skip to content

Modeled C stage 4a: facade resources rendered with Drop, destroys as move fn, safe direct-return constructor - #1274

Merged
ehartford merged 4 commits into
mainfrom
modeled-c-stage4
Sep 22, 2026
Merged

ehartford merged 4 commits into
mainfrom
modeled-c-stage4

Conversation

@ehartford

Copy link
Copy Markdown
Contributor

Stage 4a of docs/modeled-c-implementation-plan.md (ruling §9, §11–§13.2, spec §16.2b.3–4), per docs/handoff-modeled-c-stage4.md. Depends on nothing unmerged; based on main 478b264.

What 4a renders

Pointer and by-value resources of every c facade block, as a second synthetic file <facade NAME> spliced by the Frontend after all source and <c_import …> files are parsed and before Sema (src/compiler/FacadeRender.w, hook in Frontend.w render_c_facades_frontend). Sema sees ordinary With; collect_c_facades still verifies §61 against the same declarations.

For the phase test's

c facade dbl:
    resource Database wraps *mut db
        from db_new
        drop db_close
        destroys db_close_v2

the emitted <facade dbl> is exactly:

type Database { repr: *mut db, live: bool }
impl Drop for Database:
    move fn drop():
        if self.live: db_close(self.repr)
impl Database:
    move fn db_close_v2(how: c_int) -> c_int:
        self.live = false
        db_close_v2(self.repr, how)
fn Database.db_new(flags: c_int) -> Database:
    Database { repr: db_new(flags), live: true }

Design points, each verified by running, not reasoning:

  • live arming bit. A move fn destroyer consumes self; With has no spelling that forgets a consumed value's Drop, and the naive rendering (read self.repr, let self drop) destroyed twice under a counting destroyer. The destroyer clears live, Drop checks it (std.regex's Regex arms its pcre2 free the same way); 4b's in-place resources arm the same bit from init. The handoff's type R { repr } is therefore type R { repr, live: bool }. (Pattern destructuring does silently skip Drop — that is a leak bug, filed as Destructuring a Drop-typed value by pattern (let { .. } / match) never runs its Drop — a silent leak #1272, not relied on.)
  • No unsafe in the rendering. Stage 3 coverage makes the covered extern call safe, and an unsafe {} with no unsafe operation is an error; the one callee still wrapped is a translated static inline body c_import marked unsafe fn (read off the AST). A call that would still be raw is a facade-level error instead (below), never wrapped on the user's behalf.
  • Rendered decls are user decls, not c_import-origin (decl_is_c_import = 0, unlike the handoff's "exactly like a c_import file"): a c_import symbol is hidden from modules without their own c_import, and a resource type must be usable wherever its module is imported.
  • Constructor is R.<C name>, destroyer methods keep the C name; presentation (prefix stripping, of/rename) is a later stage. *const i8 parameters are presented as str (D47) and passed through to the extern.
  • Out-parameter producers (stage 5) render Drop and destroyers but no constructor; the existing facade tests (db_open(out param 1)) keep passing through that path.

Facade-level errors (Sema, verify_facade_resources)

  • producer with no drop and no destroys;
  • destroyer callable as a lend (an fn item without destroys, incl. lend-by-default under of/rename);
  • drop with parameters beyond the representation (Drop has nothing else to pass);
  • destroyer/direct-return producer still raw after coverage (variadic, raw return, undescribed raw pointer parameter);
  • in-place resource (init/preinit, or a destroyer taking a pointer to the representation): verified, not rendered until 4b, reported loudly rather than emitting a type without Drop.

Tests

  • test/behavior/behav_c_facade_resource_drop_once.w — Drop exactly once on scope exit, early return, moved into a fn, moved out and returned, in a Vec; pointer and by-value resources (C objects count their own destructions).
  • test/behavior/behav_c_facade_resource_destroys_once.w — destroys never double-destroys; drop and destroys may name the same fn.
  • test/behavior/behav_c_facade_resource_libc_dup_close.w — real libc dup/close, by-value form, no unsafe.
  • test/phase/c_facade_resource_renders.w — prototype-only, expect-check-stdout: ok.
  • test/compile_errors/err_c_facade_{producer_without_destroyer,destroyer_callable_as_lend,destroyer_lend_by_default,drop_with_arguments,destroyer_still_raw,in_place_not_rendered}.w.

All existing behav_c_facade_*, c_facade_*, err_c_facade_* tests and the three guards keep their expectations under the fresh stage1 — except err_c_import_raw_call_requires_unsafe.w, which fails identically on main's own stage1 (stage1 mistranslates stdlib.h's div_t; stage2 passes): #1273, pre-existing.

Not in scope (per handoff): in-place/init/preinit/zeroed() (4b), out-parameter constructors and status (5), retiring mechanism A and flipping the five tests (4c). CImport.w untouched.

Audits

:move-audit / :drop-audit: running from the pinned seed; verdicts to follow in a comment.

Open points for the maintainer

  1. Ruling §61 "destroyer accepts the representation" is checked as exact type equality: free(void*) does not accept a char* representation, so strdup→free cannot be facaded as-is. 4c's libc facade will hit this; needs a ruling (C's implicit void* conversion as an evidence-free accept?).
  2. A resource with destroys but no drop renders no impl Drop: dropping it live is a silent leak. Handoff error Type resolution corruption when single source file exceeds ~14K lines #1 allows this shape; suggest ruling that such a resource's Drop panics or that drop is required.
  3. repr and live are ordinary fields: in-module code can spell Database { repr: null, live: true } or read .repr (the tests do, to observe). Field privacy for rendered resources is not addressed by 4a.

Eric Hartford added 3 commits September 22, 2026 07:25
A `c facade` block's pointer and by-value resources are rendered by the
Frontend as a second synthetic file, `<facade NAME>`, after every source
file and `<c_import …>` translation is parsed and before Sema:

    type R { repr: Repr, live: bool }
    impl Drop for R:
        move fn drop():
            if self.live: <drop>(self.repr)
    impl R:
        move fn <destroys>(<args after the representation>) -> <ret>:
            self.live = false
            <destroys>(self.repr, <args>)
    fn R.<producer>(<args>) -> R:          // direct-return producer
        R { repr: <producer>(<args>), live: true }

`live` is the Drop arming bit (ruling §13.2): a `move fn` destroyer
consumes `self` and With has no spelling that forgets a consumed value's
Drop — a destroyer that read `self.repr` and let `self` drop destroyed
twice (counting test) — so the destroyer clears the bit and Drop checks
it, as std.regex's Regex arms its pcre2 free. Stage 4b's in-place
resources arm the same bit from `init`.

Raw calls are spelled bare: the facade covers the destroyer's first
parameter and the producer's return (stage 3), so the extern is not raw
there, and an `unsafe` block with no unsafe operation is itself an
error; a translated `static inline` body c_import marked `unsafe fn` is
the one callee still wrapped, read off its AST. A `*const i8` parameter
is presented as `str` (§16.3c, D47) and passed straight through.

The rendered decls are ordinary user declarations of the facade's module
(not c_import-origin: a c_import symbol is hidden from modules without a
c_import of their own, and a resource type must be usable wherever its
module is imported). A resource the renderer cannot express — in-place
(init/preinit or a pointer-taking destroyer), a name that is not a
declaration, a producer with nothing to destroy it — renders nothing;
Sema reports it at the resource, never a placeholder.
…safely)

After every facade's facts are collected, each resource is checked
(ruling §9, spec §16.2b.3), reported at the resource:

- a producer with no `drop` and no `destroys` (a safe constructor for a
  value nothing can release);
- a destroyer that an fn item makes callable as a lend (no `destroys`,
  not `consumes` of the representation — an fn item lends by default);
- a `drop` operation with parameters beyond the representation (Drop has
  nothing else to pass; such an operation is a `destroys`);
- a destroyer or direct-return producer still raw after the facade's
  coverage (variadic, raw return, an undescribed raw pointer parameter):
  the facade must describe it rather than the compiler wrapping the call
  in `unsafe` on the user's behalf;
- an in-place resource (`init`/`preinit`, or a destroyer taking a pointer
  to the representation): verified but not rendered until stage 4b, said
  loudly instead of emitting a type without a Drop.
Behavior (real C bodies, each object counting its own destructions):
- behav_c_facade_resource_drop_once: Drop runs the facade's `drop`
  exactly once on every path — scope exit, early return, moved into a
  function, moved out and returned, held in a Vec — for a pointer
  resource and a by-value one.
- behav_c_facade_resource_destroys_once: a `destroys` method consumes the
  resource and Drop does not destroy again; `drop` and `destroys` may
  name the same function.
- behav_c_facade_resource_libc_dup_close: real libc, by-value form —
  `dup` produces a descriptor resource `close` drops; `dup` on the raw fd
  afterwards fails, proving Drop closed it. No `unsafe` in the program.

Phase (prototype-only C): c_facade_resource_renders — constructor,
`destroys` method, by-value resource in a Vec, no `unsafe`.

Compile errors: producer without a destroyer; destroyer callable as a
lend (explicit `lend`, and lend-by-default under `of`/`rename`); `drop`
with parameters beyond the representation; destroyer still raw after
coverage; in-place resource not rendered yet (4b).

The counting tests spell libc prototypes rather than `#include`: the
bootstrap stage1 mistranslates system headers (#1273), which also fails
err_c_import_raw_call_requires_unsafe under stage1 alone (stage2 passes).
@ehartford

Copy link
Copy Markdown
Contributor Author

Audits from the pinned seed (WITH=$PWD/src/main), on acd038b: :move-audit green (rc=0, wall 173s), :drop-audit green (rc=0, wall 93s; survey: all targets green).

@ehartford

Copy link
Copy Markdown
Contributor Author

Isolation battery on f9ca50c8 (seed-driven, alone in its batch): build, :fixpoint, :move-audit, :drop-audit, :test, :test-green, :last-green — all rc=0.

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