Repository navigation
Modeled C stage 4c: toolchain libc facade replaces Mechanism A; owns:/borrows: deprecated - #1361
Merged
Merged
Conversation
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.
Contributor
Author
ehartford
force-pushed
the
modeled-c-stage4c
branch
from
September 23, 2026 00:41
04b6da6 to
d29ef4f
Compare
ehartford
marked this pull request as ready for review
September 23, 2026 00:41
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
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/:testbattery has run.The toolchain libc facade
src/compiler/LibcFacade.wholds the facade as ordinaryc facadetext. It is parsed, verified (§61) and rendered by the existing 4a/4b renderer. It is not the oldCOwned_*generator.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.void *, per D55 ruling 1), and a lend takes it.Users see:
CHeapStr.strdup(s),CFile.fopen(p, m),CDir.opendir(p), each returningOption[R]d.readdir()andd.rewinddir()unsafeDeprecation 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:
owns: ["f -> d"]becomesresource F wraps <f's return>/from f/drop dborrows: ["g(i) -> f"]becomesfn g/lend<c_import annotations>.#owns/#borrowslines and moves tocimport-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
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".unsafe {}.&selfmethod.c_facade_lend_call_needs_no_unsafe.wno longer callsdb_close(null)ordb_count(db*)raw.free,fcloseandclosedirsafe on any pointer in every program that imports the headers.from.Option[R](§16.2b.8). Without this, a failed fopen or opendir would armfclose(NULL)orclosedir(NULL). The 4a tests now.unwrap().fclose(*mut c_void).owns:/borrows:deprecated.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 givesNone.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'sfn telldirlend, rendered asd.telldir()on the toolchain facade'sCDir.behav_c_import_borrow_param_readdirand itsd_acceptancecopy:d.readdir()andd.rewinddir(); thedirfdis closed after drop; a missing path givesNone.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
*c_facade*,*c_import*and*retain*test on stage2: 142 pass, 1 fail.d_acceptance/behav_retained_cstring_owned_ok, aprint_i32import error. It fails the same way on main's stage2 at ae609cd.Drop exactly once
run --debug-alloc: leak count 0.freeis witnessed by Darwin'smalloc_sizeinbehav_c_facade_libc_free_once. I checked this witness against a negative control.fcloseandclosedirare witnessed by the file descriptor closing once.leaks --atExitfinds 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.Real headers (commit 7)
Root cause:
src/compiler/ClangBridge.wtranslate_type_recursive_mode, pointer branch, therecord_is_reserved_system(can_pointee)arm. It spelled every pointer to a reserved-spelled system record (Darwinstruct __sFILEbehind FILE, glibcstruct _IO_FILE) as*mut c_void, andwith_ci_type_is_reserved_system_recordmadeCImport.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 twoCiMigrateparse sites. A c_import keeps*mut __sFILEwithtype FILE = __sFILE(glibc:*mut _IO_FILE,type FILE = _IO_FILE;DIRis*mut __dirstream,type DIR = __dirstream). The facade's alias-aware comparison matches those.Results on this Mac, new stage2:
behav_c_facade_libc_system_headers: real<string.h> <stdlib.h> <stdio.h> <dirent.h> <unistd.h>d.readdir()/d.rewinddir()) all work--debug-alloc*migrate*)d_acceptance/behav_retained_cstring_owned_ok, which fails the same way on mainexamples/**.wcheckoutput byte-identical before and after (raylib failscheckboth before and after, as on main):move-audit:drop-auditglibc was reasoned from its headers, not run:
typedef struct _IO_FILE FILE;andtypedef struct __dirstream DIR;produce the same shape as the inline-prototype tests, which use those exact glibc spellings and pass.Unresolved (for Eric)
CHeapStr/CFile/CDirawait confirmation.CHeapStr wraps *mut i8: any facade fn item with achar *parameter now leaves that parameter uncovered when CHeapStr is present.