Skip to content

Modeled C stage 7: strings, buffers, domains (ruling §31-§43) - #1597

Merged
ehartford merged 3 commits into
mainfrom
modeled-c-stage7
Sep 24, 2026
Merged

ehartford merged 3 commits into
mainfrom
modeled-c-stage7

Conversation

@ehartford

Copy link
Copy Markdown
Contributor

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-audit and :drop-audit (Drop of owned foreign text).

Commits: CStr as a view with to_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: :dev builds 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

  • §41 foreign strings, §32 resource-backed borrowed memory. CStr is 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: str and CStr share {ptr, len}), to_str_lossy() repairs with U+FFFD, to_owned() copies (lib/std/string.w; the validator is RFC 3629, in With).
  • §32, §26 precedent. returns borrow CStr from param N on an operation whose first parameter receives a resource renders a lend method R.op(...) -> Option[CStr] (and on Borrowed<R>), the CStr kept inside the resource's life by a declared summary — the stage 6 Borrowed<R> machinery, reused. None is NULL (§43: unknown nullability is nullable).
  • §42 owned foreign buffers and strings. A pointer resource over a C string (resource NoteText wraps *mut i8 / from strdup / drop free; libc's CHeapStr) exposes as_cstr() -> CStr, a view kept inside the resource's life. The foreign allocator pairing is untouched.
  • §40 static foreign data. returns static CStr → Option[CStr] with no origin. Only CStr is ruled for returns static; another type is an error naming §16.2b.7.
  • §33-§37 foreign-state domains. domain X process|thread|resource|static records a FacadeDomain with an origin symbol views depend on. returns borrow CStr from domain D (new spelling, composed from the ruling's returns borrow … from and preserves domain D). The coarse library of a domain (§34) is the set of <c_import …> translations of the functions its facade describes. errno is the documented example (behav_c_facade_domain_errno, the two err_c_facade_view_invalidated_by_* fixtures).
  • §38 preservation and invalidation. Unknown effect means invalidate: a call to a facade operation (rendered method, constructor, or the raw C function) invalidates every live view borrowed from each resource it receives and from each domain of its library, unless its fn item states 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.
  • §31 presented functions. A text-view return on a function that is no resource's method — getenv, strchr, strerror, 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 (Sema check_call; MirLower lower_call → prelude cstr_option_from_ptr). A borrowed-from-parameter result (strchr) depends on the str it was lent.
  • Flip. The Curated libc contract overlay for c_import modeled surfaces #379 overlay table 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 with returns borrow CStr from param 0 / from domain environ, plus strerror from its own domain, and states preserves on both domains for the pure string functions and getenv. behav_c_import_overlay_getenv_none, _strchr_borrowed and behav_cstr_from_ptr_to_owned are what an app developer writes: no unsafe, 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 0 on db_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

  1. Option[CStr], not Option[&CStr], is the rendered surface. Ruling §32: "Option[&CStr] is the conceptual shape". A &CStr is a thin pointer to a {ptr, len} record (codegen declare_builtin_cstr_type, gen_c_string_literal_ref), and C hands back only the bytes' pointer; a &CStr would need storage With invents, which §31 forbids ("With does not invent lifetimes … does not silently allocate a copy"). So the borrowed modeled value is the CStr view itself — exactly stage 6's reading of §26 for resources, where the borrowed modeled value is the by-value Borrowed<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 typed let m: Option[&CStr] would be refused, which at worst rejects a program.
  2. CStr is 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 a CStr by value.
  3. returns borrow CStr from domain D is the spelling for a domain-borrowed return; the ruling gives returns borrow R from param N (§26), domain D kind and preserves 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).
  4. A domain's coarse library (§34 "ordinarily link:") is the set of <c_import …> translations of the functions the declaring facade describes. Merging separate c_imports by identical link: 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.
  5. Invalidation targets are views, not dependent resources. §38 speaks of views; §27 dependency is lifetime. Invalidating a child statement on every lend of its connection would refuse prepare; exec; step, which no preserves on a child could restore.
  6. A hosted text-view method, or a constructor, invalidates by default; the ruling's own stage 6 fixture needed preserves param 0 on db_id. That is §38 applied to a fixture written before §38 was implemented.
  7. returns static is CStr only (§40 states returns static CStr); another type is an error rather than a silently raw return.
  8. Rendered C-string parameters are &str, not str (§3.8: a function that observes takes &T; D47: the extern lends). The origin of a from param N text view needs the borrow. A plain str consumed the caller's string (probe: CFile.fopen(path, "r") then print(path) printed empty — the associated-call check hole is Sema: a consuming str parameter of an associated call (T.make(p)) escapes the use-after-move check; a free call is diagnosed #1588).
  9. A presented call is not a wrapper function. A first version rendered 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 own extern fn strchr (the class that already makes the Curated libc contract overlay for c_import modeled surfaces #379 memchr buf_in wrapper fail behav_c_facade_libc_system_headers under a :dev stage1 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). rename on a presented item is refused.
  10. Thread domains. "A view borrowed from a thread-local domain inherits that thread restriction" (§36) — a CStr is 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

Eric Hartford 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`.
@ehartford

Copy link
Copy Markdown
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):

build        rc=0
:fixpoint    rc=0
:drop-audit  rc=0
:move-audit  rc=0
:test        rc=0   (no red targets)
:test-green  rc=0
:last-green  rc=0

Ready to merge.

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