Repository navigation
Modeled C stage 7: strings, buffers, domains (ruling §31-§43) - #1597
Merged
Merged
Conversation
added 3 commits
September 23, 2026 22:08
…(ruling §41, spec §16.2b.8)
Modeled C stage 7, first mechanism (docs/modeled-c-implementation-plan.md).
A `CStr` is a view of NUL-terminated bytes something else owns — a C string
literal's static storage, a `CString`, a modeled resource, a foreign-state
domain — never the owner, so the builtin type is ephemeral (§5): a value
takes the origins of what produced it, cannot be stored past them
(`type Holder { text: CStr }` is refused, as `&CStr` already was), and a
borrowed `CStr` a facade returns is kept inside its origin's life by the
ordinary view analysis. Nothing in the tree stored one by value.
Conversion to With text is explicit (ruling §41: "`to_str()` validates and
does not silently repair invalid UTF-8. `to_str_lossy()` makes repair
explicit. `to_owned()` makes ownership/allocation explicit."):
pub fn to_str() -> Result[&str, Utf8Error] // a view over the same bytes, no copy
pub fn to_str_lossy() -> str // U+FFFD for each ill-formed sequence
`to_str` is zero-copy: `str` and `CStr` share a `{ptr, len}` layout, so a
validated `CStr` is reinterpreted the way `CString.as_cstr` reinterprets.
`Utf8Error.InvalidAt(offset)` names the first ill-formed byte. The
validator is RFC 3629 (no overlongs, no surrogates, nothing past
U+10FFFF), written in With in lib/std/string.w; the runtime had none.
Tests: err_cstr_stored_in_struct; the to_str cases join
behav_cstr_from_ptr_to_owned with the libc facade flip later in the stage.
…ign-state domains, presented calls (ruling §31-§43) Second mechanism of stage 7 (docs/modeled-c-implementation-plan.md), on top of `CStr` as a view. `returns borrow CStr from param N` and `returns static CStr` (ruling §32, §40, §41): on an operation whose first parameter receives a resource the renderer makes a lend method `R.op(...) -> Option[CStr]` (on `Borrowed<R>` too) — the `CStr` value is the borrowed modeled text, the way stage 6's `Borrowed<R>` is the borrowed modeled resource; NULL is None (§43); a declared summary keeps it inside the origin parameter's life. A resource over a C string (`strdup` → `free`) exposes `as_cstr() -> CStr` (§42), the same way. `returns static` is `CStr` only (§40); a non-string return or an origin parameter that is neither a resource nor a C string is an error naming §16.2b.7-8. Invalidation (§38, "unknown effect means invalidate"): every call to a facade operation — the rendered method, a constructor, or the raw C function — poisons the live views borrowed from each resource it receives and each foreign-state domain of its library unless its fn item states `preserves param N` / `preserves domain D`; the next use names the call, what the view borrowed from, and the clause to add (§57). Dependent children (§27) are lifetime, not views, and are not invalidated. The stage 6 fixture behav_c_facade_borrowed_return states `preserves param 0` on `db_id`, which it needs under §38 (spec over test stability). Domains (§33-§37): `domain X kind` records an origin symbol views depend on; `returns borrow CStr from domain D` is the spelling for a domain-borrowed return (composed from the ruling's `returns borrow … from` and `preserves domain D`); a domain's coarse library (§34) is the set of `<c_import …>` translations of the functions its facade describes. `strerror` over `domain errno` is the example (behav_c_facade_domain_errno). Presented calls (§31, spec §16.2b.8): a text-view return on a function that is no resource's method — `getenv`, `strchr`, `note_version()` — is presented at the call: the declaration keeps C's signature and the call's result is `Option[CStr]` in every module that c_imported it (check_call), the pointer made into the view through the prelude's `cstr_option_from_ptr` (lower_call). A first version rendered a wrapper `fn strchr(&str, c_int) -> Option[CStr]` over a renamed import; this compiler keys signatures by text, so it collided with std.re's own `extern fn strchr` — the class that already makes the #379 `memchr` buf_in wrapper fail behav_c_facade_libc_system_headers under a `:dev` stage1 on the stage 6 baseline — hence the call-site form, gated by `current_module_uses_c_import`. Rendered C-string parameters are `&str` (§3.8: a function that observes takes `&T`; D47: the extern lends): a `str` consumed the caller's string, and a text borrowed from the parameter needs the borrow. Tests: behav_c_facade_text_view, behav_c_facade_view_invalidation, behav_c_facade_domain_errno; err_c_facade_text_view_outlives_origin, _origin_dropped, _outlives_str_param, err_c_facade_owned_text_view_outlives, err_c_facade_returns_borrow_cstr_not_string, _no_origin, err_c_facade_returns_static_not_cstr, err_c_facade_view_invalidated_by_lend, _by_domain, _by_raw_call; test/behavior/c_facade_text.h (no inline body takes a `const char *`: #1589).
…resented text views; the #379 borrowed-pointer overlay is gone (ruling §33, §37, §41) The last of stage 7 (docs/modeled-c-implementation-plan.md, "Flip"). The overlay table `ci_overlay_return_is_borrowed_ptr` vouched five libc functions' pointer returns as safe raw nullable pointers, by name. They are items of the toolchain libc facade now: `getenv` returns text borrowed from the domain `environ`, `strerror` from its own buffer (`strerror_text`), and the four string functions from the string they are lent (`returns borrow CStr from param 0`); each is presented under its C name as `Option[CStr]`. The string functions and `getenv` state `preserves` on both domains — they read their arguments and nothing else — so a view from `getenv` survives a `strchr` over it (§35); every other libc operation keeps the conservative default (§38). libc_facade_select keeps a domain line when a kept item names the domain and the program's facades do not declare it (a program's `domain` is its own, §35). behav_c_import_overlay_getenv_none, behav_c_import_overlay_strchr_borrowed and behav_cstr_from_ptr_to_owned are what an app developer writes: no `unsafe`, `Option[CStr]`, `to_str` / `to_str_lossy` / `to_owned`.
Contributor
Author
|
Battery green — head 8976cbf (0f6f1ab rebased onto main 52d60d0, identical diff), driven by the pinned seed with a cold c_import cache, audits included (stage 7 adds Drop of owned foreign text): Ready to merge. |
ehartford
force-pushed
the
modeled-c-stage7
branch
from
September 24, 2026 02:38
0f6f1ab to
8976cbf
Compare
ehartford
marked this pull request as ready for review
September 24, 2026 02:38
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.
Stage 6 (#1519) is merged; this is a single PR on main, rebased with
--onto. Draft until the seed-driven battery is green and posted (D56): stage 7 is its own batch with:move-auditand:drop-audit(Drop of owned foreign text).Commits:
CStras a view withto_str/to_str_lossy; the stage 7 mechanisms (text views, owned text, invalidation, domains, presented calls — these share the same SemaFacade/Sema/SemaCheck functions and were not separable into independently:dev-green states without re-deriving intermediate code, so they are one commit); the libc facade flip. Each is:dev-green. Main's stage2 switch-table fix (#1596) is not carried::devbuilds without it.Implements the plan's stage 7 paragraph (docs/modeled-c-implementation-plan.md) under the ruling docs/Ruling-modeled-C-ownership-effects-conventions-and-foreign-lifetimes.md §31-§43, with §65/§66 respected: nothing here grants ownership, destruction or success from a name; the SQLite facade is untouched.
Ruling sections implemented
CStris the borrowed modeled text and is now a view (ephemeral, §5): it takes the origins of what produced it and cannot be stored past them.CStr.to_str() -> Result[&str, Utf8Error]validates (zero-copy:strandCStrshare{ptr, len}),to_str_lossy()repairs with U+FFFD,to_owned()copies (lib/std/string.w; the validator is RFC 3629, in With).returns borrow CStr from param Non an operation whose first parameter receives a resource renders a lend methodR.op(...) -> Option[CStr](and onBorrowed<R>), theCStrkept inside the resource's life by a declared summary — the stage 6Borrowed<R>machinery, reused.Noneis NULL (§43: unknown nullability is nullable).resource NoteText wraps *mut i8 / from strdup / drop free; libc'sCHeapStr) exposesas_cstr() -> CStr, a view kept inside the resource's life. The foreign allocator pairing is untouched.returns static CStr→Option[CStr]with no origin. OnlyCStris ruled forreturns static; another type is an error naming §16.2b.7.domain X process|thread|resource|staticrecords aFacadeDomainwith an origin symbol views depend on.returns borrow CStr from domain D(new spelling, composed from the ruling'sreturns borrow … fromandpreserves domain D). The coarse library of a domain (§34) is the set of<c_import …>translations of the functions its facade describes.errnois the documented example (behav_c_facade_domain_errno, the twoerr_c_facade_view_invalidated_by_*fixtures).preserves param N/preserves domain D. The next use of an invalidated view is an error naming the call, what the view borrowed from, and the clause to add (§57). Dependent children (§27) are lifetime, not views, and are not invalidated.getenv,strchr,strerror,note_version()— is presented at the call: the declaration keeps C's signature and the call's result isOption[CStr]in every module that c_imported it (Semacheck_call; MirLowerlower_call→ preludecstr_option_from_ptr). A borrowed-from-parameter result (strchr) depends on thestrit was lent.ci_overlay_return_is_borrowed_ptr(getenv, strchr, strrchr, strpbrk, strstr) is deleted; the toolchain libc facade (compiler/LibcFacade.w) carries them as fn items withreturns borrow CStr from param 0/from domain environ, plusstrerrorfrom its own domain, and statespreserveson both domains for the pure string functions andgetenv.behav_c_import_overlay_getenv_none,_strchr_borrowedandbehav_cstr_from_ptr_to_ownedare what an app developer writes: nounsafe,Option[CStr],to_str/to_owned.Fixtures
Added: behav_c_facade_text_view, behav_c_facade_view_invalidation, behav_c_facade_domain_errno; err_cstr_stored_in_struct, err_c_facade_text_view_outlives_origin, err_c_facade_text_view_origin_dropped, err_c_facade_owned_text_view_outlives, err_c_facade_text_view_outlives_str_param, err_c_facade_returns_borrow_cstr_not_string, err_c_facade_returns_borrow_cstr_no_origin, err_c_facade_returns_static_not_cstr, err_c_facade_view_invalidated_by_lend, err_c_facade_view_invalidated_by_domain, err_c_facade_view_invalidated_by_raw_call; test/behavior/c_facade_text.h.
Flipped: behav_c_import_overlay_getenv_none, behav_c_import_overlay_strchr_borrowed, behav_cstr_from_ptr_to_owned.
Touched: behav_c_facade_borrowed_return states
preserves param 0ondb_id— it reads a borrowed database after a lend on the database it views, which §38 now invalidates without the clause (spec over test stability; the comment says so).Derived decisions
Option[CStr], notOption[&CStr], is the rendered surface. Ruling §32: "Option[&CStr]is the conceptual shape". A&CStris a thin pointer to a{ptr, len}record (codegendeclare_builtin_cstr_type,gen_c_string_literal_ref), and C hands back only the bytes' pointer; a&CStrwould need storage With invents, which §31 forbids ("With does not invent lifetimes … does not silently allocate a copy"). So the borrowed modeled value is theCStrview itself — exactly stage 6's reading of §26 for resources, where the borrowed modeled value is the by-valueBorrowed<R>. Every capability of&CStr(to_str,to_owned,len) is on the value through auto-ref, and the value is ephemeral, so it cannot escape its origin; a typedlet m: Option[&CStr]would be refused, which at worst rejects a program.CStris ephemeral. Not stated by the ruling; required for (1) to be safe — a by-value view that could be stored in a struct would outlive its origin. Nothing in the tree stored aCStrby value.returns borrow CStr from domain Dis the spelling for a domain-borrowed return; the ruling givesreturns borrow R from param N(§26),domain D kindandpreserves domain D(§33, §38) and says borrowed memory tied to no resource "borrows from a foreign-state domain" (§33) without spelling the clause. A resource cannot be borrowed from a domain (error).link:") is the set of<c_import …>translations of the functions the declaring facade describes. Merging separate c_imports by identicallink:lists is not done yet: a domain declared in a facade that describes functions of both imports already covers both, and §34 says a facade must name the domain when no stable link identity exists. Left as a gap in the report.prepare; exec; step, which nopreserveson a child could restore.preserves param 0ondb_id. That is §38 applied to a fixture written before §38 was implemented.returns staticisCStronly (§40 statesreturns static CStr); another type is an error rather than a silently raw return.&str, notstr(§3.8: a function that observes takes&T; D47: the extern lends). The origin of afrom param Ntext view needs the borrow. A plainstrconsumed the caller's string (probe:CFile.fopen(path, "r")thenprint(path)printed empty — the associated-call check hole is Sema: a consumingstrparameter of an associated call (T.make(p)) escapes the use-after-move check; a free call is diagnosed #1588).fn strchr(&str, c_int) -> Option[CStr]over a renamed import; signatures are keyed by text in this compiler, so it collided with std.re's ownextern fn strchr(the class that already makes the Curated libc contract overlay for c_import modeled surfaces #379memchrbuf_in wrapper failbehav_c_facade_libc_system_headersunder a:devstage1 on the stage 6 baseline). The presentation is at the call site instead, gated to modules that c_imported the function (current_module_uses_c_import).renameon a presented item is refused.CStris ephemeral and ephemeral values cannot be handed to a spawned task, so the restriction is inherited by construction; no separate check was added.Left unimplemented / found
sqlite3_mprintfas a producer: variadic producers render no constructor (a variadic call is raw, §16.2b.5); the owned-text resource is exercised withstrdup. The SQLite facade (§66, stage 12) will need a ruling on variadic producers.link:identity (decision 4)._Nonnull) is not read; every text view isOption[CStr](§43: unknown never becomes non-null).strparameter of an associated call (T.make(p)) escapes the use-after-move check; a free call is diagnosed #1588 (associated-call consumingstrparameter escapes use-after-move), c_import: astr/&strlent to a translated inline C function'sconst char *parameter is not marshalled —strfails in codegen,&strpasses the header address (D47 §16.3c) #1589 (astr/&strlent to a translated inline C function'sconst char *is not marshalled — the fixture header avoids that shape), Sema: the "unsafe global access … single-thread proof" warning is located in whatever file was current (a<facade …>line) and fires on<c_import …>translations #1590 (the "unsafe global access … single-thread proof" warning is mislocated and fires on<c_import …>translations).:devstage1:behav_c_facade_libc_system_headersandbehav_c_import_overlay_memchrfail to build (std.re'smemchrvs the Curated libc contract overlay for c_import modeled surfaces #379 buf_in wrapper); thepre_d_build_runnerfixtures need the release binary. Verified on a stage-6 worktree.