Skip to content

Modeled C stage 4c: toolchain libc facade replaces Mechanism A; owns:/borrows: deprecated - #1361

Merged
ehartford merged 7 commits into
mainfrom
modeled-c-stage4c
Sep 23, 2026
Merged

ehartford merged 7 commits into
mainfrom
modeled-c-stage4c

Conversation

@ehartford

@ehartford ehartford commented Sep 22, 2026 •

Copy link
Copy Markdown
Contributor

Modeled C stage 4c (docs/modeled-c-implementation-plan.md stage 4; ruling §5, §9, §60, §65; spec §16.2b). Draft: iterate-tier evidence only; no :fixpoint/:test battery has run.

The toolchain libc facade

src/compiler/LibcFacade.w holds the facade as ordinary c facade text. It is parsed, verified (§61) and rendered by the existing 4a/4b renderer. It is not the old COwned_* generator.

c facade libc:
    resource CHeapStr wraps *mut i8
        from strdup
        from strndup
        drop free
    resource CFile wraps *mut FILE
        from fopen
        from fdopen
        from tmpfile
        drop fclose
    resource CDir wraps *mut DIR
        from opendir
        drop closedir
    fn readdir
        lend
        of CDir
    fn rewinddir
        lend
        of CDir

Where it lives. After every c_import translation, the Frontend (inject_toolchain_facades_frontend) splices in only the part of this text the program's imported declarations support. The spliced text becomes the synthetic file <toolchain facade libc>, which is its provenance in every diagnostic, and it belongs to the importing module.

  • It describes a declaration only when that declaration has libc's shape: a producer returns the representation, the drop takes it (or void *, per D55 ruling 1), and a lend takes it.
  • If the program's own facade already names a resource, producer or fn item, that name is left to the program.

Users see:

  • CHeapStr.strdup(s), CFile.fopen(p, m), CDir.opendir(p), each returning Option[R]
  • d.readdir() and d.rewinddir()
  • Drop runs the destroyer exactly once
  • no unsafe

Deprecation of owns: / borrows: (Canon)

The plan's stage 4 says owns:/borrows: "become deprecated spellings with a diagnostic naming the facade clause". The spec already has a precedent for how a deprecated spelling behaves: retains: (§16.3c) is "a compatibility spelling … accepted during migration and deprecated in favour of the facade vocabulary".

So both keys keep working, with a warning:

  • Each entry is converted into the facade it spells:
    • owns: ["f -> d"] becomes resource F wraps <f's return> / from f / drop d
    • borrows: ["g(i) -> f"] becomes fn g / lend
  • The result is spliced in as <c_import annotations>.
  • The warning names the clauses to write instead.
  • A malformed entry is an error.
  • The c_import cache key drops its #owns/#borrows lines and moves to cimport-v18.

Please confirm this reading. Canon says "deprecated" but does not literally say "warning". If you meant an error, the change is one line per diagnostic.

Commits

  1. A resource is the safe surface of its representation (§16.2b.5).
    • Before: resource clauses lifted the raw C names out of the raw classification. db_close(d.repr) compiled in safe code, and then Drop closed the handle again. The spec says "destroy through C, then Drop destroys again is not expressible in safe code".
    • Now: the rendering calls C inside an inner unsafe {}.
    • A lend of a pointer representation is now a &self method.
    • A parameter that takes a resource representation is no longer covered on the raw name. This reverses part of stage 3's "a facaded call compiles with no unsafe" for representation parameters: c_facade_lend_call_needs_no_unsafe.w no longer calls db_close(null) or db_count(db*) raw.
    • Without this change, the libc facade would make free, fclose and closedir safe on any pointer in every program that imports the headers.
  2. Several producers per resource: one constructor per from.
  3. A pointer producer's constructor yields Option[R] (§16.2b.8). Without this, a failed fopen or opendir would arm fclose(NULL) or closedir(NULL). The 4a tests now .unwrap().
  4. Facade types compare through pointee aliases. The renderer now picks the c_import declaration over std.libc's same-named one: before this, it had picked std.libc's fclose(*mut c_void).
  5. The libc facade replaces Mechanism A; owns:/borrows: deprecated.
  6. Test adjustment: the system-header test is Darwin-only (see Unresolved).

Flipped tests (ordinary tests, rewritten to the facade surface as the plan says)

  • behav_c_import_owning_wrapper_fopen: CFile from fopen, tmpfile and fdopen. Each file descriptor is closed exactly once after drop. A missing path gives None.
  • behav_c_import_owning_wrapper_strdup: CHeapStr from strdup and strndup.
  • behav_c_import_owns_annotation: the program's own facade resource over a getcwd shim.
  • behav_c_import_borrows_annotation: the program's fn telldir lend, rendered as d.telldir() on the toolchain facade's CDir.
  • behav_c_import_borrow_param_readdir and its d_acceptance copy: d.readdir() and d.rewinddir(); the dirfd is closed after drop; a missing path gives None.

The §60 guards still fail as pinned: err_c_import_destroy_heuristic_no_owning_wrapper, err_c_import_uncurated_ptr_return_raw, err_c_import_raw_call_requires_unsafe (checked on stage2).

Evidence (iterate tier)

Test runs

  • Every *c_facade*, *c_import* and *retain* test on stage2: 142 pass, 1 fail.
  • The one failure is d_acceptance/behav_retained_cstring_owned_ok, a print_i32 import error. It fails the same way on main's stage2 at ae609cd.

Drop exactly once

  • The flipped tests run under run --debug-alloc: leak count 0.
  • libc memory is outside the debug allocator, so free is witnessed by Darwin's malloc_size in behav_c_facade_libc_free_once. I checked this witness against a negative control.
  • fclose and closedir are witnessed by the file descriptor closing once.
  • leaks --atExit finds nothing. It is not a valid witness here, though: the negative control did not flag an unfreed strdup either.

Audits and fixtures

  • with analyze … audit:all: 0 violations on the libc programs.
  • :move-audit: 15 cells, 0 vs-expected FAIL, 0 candidate-vs-baseline DIFF.
  • :drop-audit: 136 cells, 0 non-PASS, 0 regressions.
  • The UAT fixtures and the c_import examples check identically on the new and baseline stage2.

Real headers (commit 7)

Root cause: src/compiler/ClangBridge.w translate_type_recursive_mode, pointer branch, the record_is_reserved_system(can_pointee) arm. It spelled every pointer to a reserved-spelled system record (Darwin struct __sFILE behind FILE, glibc struct _IO_FILE) as *mut c_void, and with_ci_type_is_reserved_system_record made CImport.w's structural builder agree. The rule belongs to the migrator (#1151, #1219): migrated code calls std.libc, whose stdio takes *mut c_void. The bridge is shared, though, so c_import erased FILE's identity too.

Fix: the erasure is now CImportSession.migration, set only at the two CiMigrate parse sites. A c_import keeps *mut __sFILE with type FILE = __sFILE (glibc: *mut _IO_FILE, type FILE = _IO_FILE; DIR is *mut __dirstream, type DIR = __dirstream). The facade's alias-aware comparison matches those.

Results on this Mac, new stage2:

Check Result
behav_c_facade_libc_system_headers: real <string.h> <stdlib.h> <stdio.h> <dirent.h> <unistd.h> CHeapStr, CFile (tmpfile, fputs/rewind/fgets round-trip) and CDir (d.readdir()/d.rewinddir()) all work
fclose and closedir run exactly once fd witness passes; leak count 0 under --debug-alloc
migrate tests (all 26 *migrate*) pass, unchanged; migration keeps the erasure
facade, c_import and retains tests (with the migrate tests: 167 pass, 1 fail) the 1 failure is d_acceptance/behav_retained_cstring_owned_ok, which fails the same way on main
UAT fixtures (bzip2 includes stdio) and every examples/**.w check output byte-identical before and after (raylib fails check both before and after, as on main)
:move-audit 15 cells, 0 FAIL, 0 DIFF
:drop-audit 136 cells, 0 non-PASS, 0 regressions

glibc was reasoned from its headers, not run: typedef struct _IO_FILE FILE; and typedef struct __dirstream DIR; produce the same shape as the inline-prototype tests, which use those exact glibc spellings and pass.

Unresolved (for Eric)

  • Resource names CHeapStr/CFile/CDir await confirmation.
  • Commit 1 reverses stage 3's raw-name coverage for representation parameters (spec §16.2b.5).
  • A side effect of CHeapStr wraps *mut i8: any facade fn item with a char * parameter now leaves that parameter uncovered when CHeapStr is present.

Eric Hartford added 7 commits September 22, 2026 20:02
… C name stays raw (§16.2b.5)

A resource clause (producer, drop, destroys, init, preinit) no longer lifts
the C function it names out of the raw classification, and an fn item no
longer covers a parameter that takes a resource's representation or the
one a `destroys` item destroys. Before, `db_close(d.repr)` compiled in safe
code and Drop closed the handle again — "destroy through C, then Drop
destroys again" is not expressible in safe code (§16.2b.5) — and a bare
producer call handed back a pointer nothing destroys.

The rendering calls each C operation inside an inner `unsafe {}` when the
callee is raw (FacadeRender.w facade_render_is_raw, the AST reading of
ci_function_requires_raw_abi), and a lend of a pointer representation is
rendered as a `&self` method of the resource (`d.db_count()`): With proves
the receiver live, unmoved and undestroyed, which it cannot prove of a raw
pointer. The §61 "still a raw call" checks now ask whether the operation is
raw apart from the representation it is handed (facade_op_raw_beyond).

Tests: err_c_facade_raw_destroyer_stays_raw, err_c_facade_raw_producer_stays_raw,
err_c_facade_raw_lend_on_resource_stays_raw; c_facade_lend_call_needs_no_unsafe
keeps its covered lend over a non-resource parameter; c_facade_resource_renders
calls the lend as a method.
…rom`

libc's fopen, fdopen and tmpfile each produce the FILE that fclose destroys;
strdup and strndup each produce the string free releases. FacadeResource
keeps a producer per `from` clause (with its out parameter), every §61
check runs over each, `borrows` names a parameter of the `from` it follows,
and the renderer emits one safe constructor per direct-return producer.

Test: behav_c_facade_resource_several_producers (Drop once per producer).
Unknown nullability is nullable and never silently becomes non-null
(§16.2b.8). The rendered direct-return constructor of a pointer resource
returned `R` over whatever C handed back, so a failed producer armed Drop
over NULL — for libc, fclose(NULL) and closedir(NULL) are undefined. It now
returns `Option[R]`: NULL produced nothing (§16.2b.4) and no Drop is armed.
A by-value representation's constructor still returns `R`.

Test: behav_c_facade_resource_null_producer_none (None arms no destroyer);
the stage-4a tests unwrap their constructors.
…orted declaration

Two §61 verification defects that libc's own headers expose:

- A header's `typedef struct __dirstream DIR` translates opendir as
  returning `*mut __dirstream` while a facade names `*mut DIR`. The
  producer-return, destroyer, out-parameter, init and lend comparisons
  resolved the outer alias only, so the same representation was refused.
  SemaFacade.w facade_same_type chases aliases through pointees; the
  renderer's facade_render_unalias does the same on the text (and stops at an
  `opaque` declaration, which is a distinct type, not an alias of void).
- The renderer found an operation by name among every declaration of the
  compilation, so std.libc's hand-written `fclose(*mut c_void)` could stand
  in for the `fclose(FILE *)` the program imported. A facade describes
  imported declarations (§16.2b.13): the Frontend hands the renderer the
  c_import flags and a c_import declaration wins.

Also exposes facade_render_import_shape for the toolchain libc facade.

Test: behav_c_facade_resource_pointee_alias.
…wns:/borrows: are deprecated facade spellings

The #357 owning-wrapper tables (strdup/strndup -> free, fopen/fdopen/tmpfile
-> fclose, opendir -> closedir, readdir/rewinddir borrowing the directory)
and their COwned_* generators are deleted from CImport.w. The same eight
rows are now a `c facade` shipped with the toolchain (ruling §5 "bounded
knowledge"; spec §16.3c "the curated libc facade, which is a standard
deliverable"), compiler/LibcFacade.w:

    c facade libc:
        resource CHeapStr wraps *mut i8     from strdup, strndup; drop free
        resource CFile wraps *mut FILE      from fopen, fdopen, tmpfile; drop fclose
        resource CDir wraps *mut DIR        from opendir; drop closedir
        fn readdir / fn rewinddir           lend, of CDir

After every c_import translation the Frontend splices the part of it the
program's imported declarations support — each described declaration must
have libc's shape (a producer returns the representation, the drop takes it
or void *, a lend takes it) — as the synthetic file `<toolchain facade
libc>`, owned by the importing module; names the program's own facades
state are left to them. It renders and verifies like any facade: safe
constructors yielding Option[R], Drop calling the destroyer once, lends as
methods (`d.readdir()`), the raw C names raw. Darwin's <stdio.h> hands
FILE * through as `*mut c_void`, not libc's shape, so CFile does not apply
there and fopen stays raw.

owns:/borrows: are deprecated spellings (plan stage 4: "become deprecated
spellings with a diagnostic naming the facade clause"; the compatibility
precedent is retains:, spec §16.3c): each entry is projected into the
facade it spells — `owns: ["f -> d"]` is `resource F wraps <f's return>`,
`from f`, `drop d`; `borrows: ["g(i) -> f"]` is `fn g`, `lend` — spliced as
`<c_import annotations>`, with a warning naming the clauses to write. A
malformed entry is an error. The c_import cache key drops its #owns/#borrows
lines (translation no longer depends on them) and moves to cimport-v18.
Both land together: retiring the generator alone would have turned the keys
into silent no-ops.

Flipped to the facade surface: behav_c_import_owning_wrapper_fopen,
_strdup, behav_c_import_owns_annotation, _borrows_annotation,
behav_c_import_borrow_param_readdir (+ d_acceptance copy). New:
behav_c_facade_libc_free_once (Darwin malloc_size witness),
behav_c_facade_libc_system_headers, behav_c_facade_libc_stdio_stays_raw,
behav_c_import_owns_borrows_deprecated, behav_c_import_owns_deprecated_warns,
err_c_import_owns_malformed. The §60 guards
(err_c_import_destroy_heuristic_no_owning_wrapper,
err_c_import_uncurated_ptr_return_raw, err_c_import_raw_call_requires_unsafe)
still fail as pinned.
…idge rule that erases FILE *

The bridge types a pointer to a reserved system record as `*mut c_void`
(CImport.w type_from_libclang): Darwin's `struct __sFILE` FILE and glibc's
`struct __dirstream` DIR. Neither is libc's shape for the toolchain facade,
so behav_c_facade_libc_system_headers (CDir over <dirent.h>) runs on Darwin
only, and behav_c_facade_libc_stdio_stays_raw names the rule.
…igration spells them void *

Root cause: ClangBridge.w translate_type_recursive_mode's pointer branch
(the `record_is_reserved_system` arm) spelled every pointer to a
reserved-spelled record from a system header — Darwin's `struct __sFILE`
behind FILE, glibc's `struct _IO_FILE` — as `*mut c_void`, and
with_ci_type_is_reserved_system_record made CImport.w's structural builder
agree. The rule is the migrator's (#1151, #1219): migrated code calls
std.libc, whose stdio takes `*mut c_void`, and the migrator never emits
system records. But the bridge is shared, so every c_import of <stdio.h>
lost FILE's identity too, and the toolchain libc facade's `CFile wraps
*mut FILE` could never match a real header.

The erasure is now a property of a migration session
(CImportSession.migration, set by with_cimport_session_set_migration at
both CiMigrate parse sites). A c_import keeps the pointee's identity:
fopen returns `*mut __sFILE` with `type FILE = __sFILE` on Darwin
(`*mut _IO_FILE` / `type FILE = _IO_FILE` on glibc), which the facade's
alias-aware comparison matches. The record's fields are translated as
before; nothing gains a safe operation.

Test: behav_c_facade_libc_system_headers imports the real <string.h>,
<stdlib.h>, <stdio.h>, <dirent.h>, <unistd.h>: CHeapStr from strdup,
CFile from tmpfile (fputs/rewind/fgets round-trip, fd closed once after
drop), CDir from opendir with d.readdir()/d.rewinddir() (dirfd closed once
after drop), leak count 0 under --debug-alloc. behav_c_facade_libc_stdio_stays_raw
pinned the defect and is removed. All migrate tests pass unchanged; UAT
fixtures and examples check byte-identically before and after.
@ehartford

Copy link
Copy Markdown
Contributor Author

Battery (seed-driven, alone per the isolation rule, rebased on main dd786a4 → d29ef4f, force-pushed so the PR is the tested tree): build ok, :fixpoint ok, :drop-audit ok, :move-audit ok, :test ok (no reds), :test-green ok, :last-green ok. Resource names CHeapStr / CFile / CDir confirmed by Eric.

@ehartford
ehartford marked this pull request as ready for review September 23, 2026 00:41
@ehartford
ehartford merged commit 00408eb into main Sep 23, 2026
@ehartford
ehartford deleted the modeled-c-stage4c branch September 24, 2026 16:57
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