Skip to content

Modeled C stage 12b: optional callbacks, items valid on the failed state, library-prefix presentation (#1618, #1612, #1610) - #1630

Merged
ehartford merged 5 commits into
fix-alias-callable-callfrom
modeled-c-stage12b
Sep 24, 2026
Merged

ehartford merged 5 commits into
fix-alias-callable-callfrom
modeled-c-stage12b

Conversation

@ehartford

@ehartford ehartford commented Sep 24, 2026 •

Copy link
Copy Markdown
Contributor

Three facade-language gaps the SQLite facade (stage 12, #1619) exposed, plus the #1621 refusal the UAT rewrite asked for. One commit per issue; derived decisions recorded in docs/modeled-c-implementation-plan.md under a new "Stage 12b" entry (no spec text touched).

Verification (iterate tier, stage1 from with build :dev at HEAD): check src/main.w ok; analyze audit:all on the new behavior fixtures: violations=0; the full c_facade/sqlite_facade fixture sweep (behavior, compile_errors, debug_alloc, phase) green, except: behav_c_facade_libc_system_headers.w, which fails identically on the untouched base c18fdfea (std.re's 3-arg memchr vs the #379 2-arg slice wrapper — pre-existing), and the two pre_d_build_runner _warns fixtures, which need a staged compiler a :dev-only worktree has not built.

Filed out of scope: #1626 (u as *const Unit traps codegen), #1627 (Some(place) moves where Option[&T] is expected).

@ehartford
ehartford force-pushed the modeled-c-stage12b branch 2 times, most recently from 68d2002 to ae79b68 Compare September 24, 2026 16:43
@ehartford
ehartford changed the base branch from main to fix-callable-alias-call September 24, 2026 16:43
@ehartford
ehartford added this pull request to stack #1637 September 24, 2026 16:43
Eric Hartford added 4 commits September 24, 2026 12:52
…ntation's struct name carries (`sqlite3_step` on `*mut sqlite3_stmt` is `stmt.step()`); the SQLite facade drops nine `rename`s (#1610)

Ruling §54 / spec §16.2b.11 permit prefix shortening silently under a
recognizable naming pattern. The convention shortened by the struct
name only (`sqlite3_stmt_`), which no SQLite statement function carries,
so every statement operation needed a `rename`. Each snake-case component
prefix of the struct name is now tried too (`sqlite3_` of `sqlite3_stmt`;
`g_hash_`, `g_` of `g_hash_table`), the longest match winning; a clash
still fails closed and Sema still notes it. The prefix comes from the
representation's own struct name, never another resource's, so a child's
producer presented on its parent keeps the parent's spelling (`db_new`
and `st_new` on `Database` do not clash). The one explicit override §66
asks for, `rename prepare`, stays.

The in-place fixtures over `z_stream` spelled `Stream.z_init`,
`s.z_end_v2()`: the rule now presents them as `Stream.init` and
`s.end_v2()` (the zlib case), and the seven fixtures spell that.

Fixture: behav_c_facade_presentation_library_prefix.w.
…state resource; `sqlite3_errmsg` renders on `FailedDatabase` (#1612)

Spec §16.2b.4: a resource owned by an error "admits raw access only,
unless the facade marks an operation as valid on the failure state"; D59
(amended): raw access only "until the facade can mark operations valid on
the failure state: `sqlite3_errmsg` is". The mark is the fn-item clause
`valid on failed`, named after the type it widens (`FailedDatabase`). The
renderer emits the lend or text view on `Failed<R>` over the same `repr`
under the name it has on `R`; Sema puts the same declared summary on it (a
view of the failed handle), refuses the mark on a resource with no failed
state or on anything stronger than a lend (a producing, destroying,
consuming, retaining or callback operation, or a borrowed-resource return),
and the unknown-method diagnostic on a failed state now names the clause.
SQLite documents exactly one such operation ("sqlite3_errmsg() … can be
used to obtain an English language description of the error following a
failure of any of the sqlite3_open() routines"), and the facade marks it.

Fixtures: behav_c_facade_valid_on_failed.w,
behav_sqlite_facade_failed_open_errmsg.w (the message after a failed open,
no `unsafe`), err_c_facade_failed_state_unmarked_item.w (an unmarked lend
stays unavailable), err_c_facade_valid_on_failed_no_failed_state.w.
…n "C" fn(&U, …)]` with its userdata `Option[&U]`; `sqlite3_exec` with no callback is `db.exec(sql, None, None, null)` (#1618)

Ruling §43 / spec §16.2b.8: where the header does not establish
nullability, the facade must, and `nullable -> Option`. The fn-item clause
`nullable param N` is that statement in the ruling's own word, and the
rendering is the one nullability already has. In this stage it is rendered
for one shape — the callback of a `callback param N userdata param M`
pairing that C uses during the call only: the callback is `Option` of the
typed callback and its userdata `Option[&U]`, absent with it, since the
userdata is what the callback receives; the rendered body passes NULL for
None. Sema binds `U` to Unit when both are `None`, refuses one without the
other at the call (a callback with no userdata would receive NULL where it
was promised `&U`), and refuses the clause on any other parameter rather
than rendering it as nothing (a raw pointer accepts `null` as C declares
it; `Option[&str]` / `Option[&R]` parameters are not modeled). SQLite
documents the callback as optional ("If the callback pointer to
sqlite3_exec() is NULL, then no callback is ever invoked"), so the facade
states it, and every DDL/DML statement runs with no callback and no
`unsafe`. The userdata is handed to C by transmute rather than `as *const
U as …`: with `U = Unit` that cast traps codegen (#1626).

Fixtures: behav_c_facade_callback_nullable.w,
behav_sqlite_facade_exec_no_callback.w,
err_c_facade_callback_nullable_no_userdata.w,
err_c_facade_nullable_not_callback.w; the end-to-end and captures fixtures
spell `Some(cb), Some(&ctx)` (`Some(ctx)` moves the place: #1627).
…s with a length is refused — a safe call over a raw buffer with no bounds is the partial model §16.2b.3 forbids (#1621)

A `lend` covers every parameter it does not name, so `fn compress / lend`
over `compress(Bytef *dest, uLongf *destLen, const Bytef *source, uLong
sourceLen)` checked clean and rendered a safe call with no contract
between `dest` and `*destLen`: a caller passing a capacity larger than its
array corrupted memory in safe code. No clause pairs a buffer with its
length yet (a ruling is pending on #1621), so until one exists an fn item
that states nothing stronger than a lend — hosted on a resource or not —
whose C signature has a buffer parameter the facade covers is an error
naming the parameter and #1621. A buffer is a pointer to bytes, scalars,
`void` or pointers, what a (ptr, len) pair spans; a pointer to a C record
is a handle, not a buffer, and its lend stays the stage-3 default. A
parameter receiving a modeled resource, a `const char *` input and a code
pointer stay covered. The SQLite facade has no such item (its text inputs
are `const char *`; `sqlite3_bind_blob` is not described). The stage-3
phase fixture's `db_count(char *label)` — exactly the hole — now takes a
`const char *`, the lent `str` it was meant to show.

Fixture: err_c_facade_lend_unpaired_buffer.w.
@ehartford
ehartford removed this pull request from stack #1637 September 24, 2026 16:53
@ehartford
ehartford changed the base branch from fix-callable-alias-call to fix-alias-callable-call September 24, 2026 16:53
@ehartford
ehartford added this pull request to stack #1642 September 24, 2026 16:53
@ehartford
ehartford removed this pull request from stack #1642 September 24, 2026 17:29
@ehartford
ehartford added this pull request to stack #1646 September 24, 2026 17:30
…init — the representation prefix z_ is stripped by the #1610 rule (the respell missed them)
@ehartford
ehartford marked this pull request as ready for review September 24, 2026 18:50
@ehartford
ehartford merged commit 5cab7ac into main Sep 24, 2026
@ehartford
ehartford deleted the modeled-c-stage12b branch September 24, 2026 18:51
ehartford added a commit that referenced this pull request Sep 27, 2026
…, repr(packed(N)); cast and Mutex view-escape fixes (#1788)

* Facade: a producer's `ok` lists several success statuses; `Ok` carries the one that matched (§16.2b.4, ruling Amendment 1)

Spec §16.2b.4 (D71 item 8): "When `ok` lists several constants, any of
them is success, and the `Ok` side carries the status that matched
alongside the produced value." The parser reads `ok C1, C2, …`; Sema keeps
the list (FacadeResource.ok_consts), verifies every constant as an
imported compile-time value (§16.2b.13), and refuses a constant listed
twice or a second `ok` clause, which before this was silently read in
place of the first.

Rendered success type (decided within the text): with one constant the
projection is unchanged, `Result[R, RError]`; with several it is
`Result[(S, R), RError]` — the status that matched, then the value, the
order of the pair the facade already renders without `ok`
(`(status, Option[R])`, an in-place `(status, R)`). Failure is
`status != C1 and status != C2`; the error type is unchanged. Both
status-reading production forms render it: an out-parameter producer and
an in-place `init`.

The ruling gives the list to a producer's `ok`. An fn item's `ok` — the
status contract of a copied-back length (D64) or a variadic setter (D66)
— names one, and a list there is refused rather than read as its first
constant.

Fixtures, each failing on the base (the list was a parse error; a second
`ok` was accepted): behav_c_facade_ok_several_statuses.w,
err_c_facade_ok_list_not_constant.w, err_c_facade_ok_list_on_fn_item.w,
err_c_facade_ok_stated_twice.w.

Fixes #1432

* Facade: `handle Name wraps *mut T` — a callback-scope handle whose `of` operations are its methods (§16.2b.9, ruling Amendment 1)

Spec §16.2b.9 (D71 item 10): "A foreign representation that exists only
for a callback's invocation (`sqlite3_context`, `sqlite3_value`) is
declared as a handle: nothing produces or destroys it, it has no `Drop`,
and it is borrowed for the callback's scope and cannot outlive it.
Operations on it are its methods, stated with `of` as for a resource."

- Parser: `handle Name wraps <type>` is a resource item whose one clause
  is the FACADE_CLAUSE_HANDLE marker, so `of Name`, hosting and
  presentation work as for a resource; a clause under it is refused.
- Sema: the representation is a pointer to a C record (never `void *` or
  text); an operation hosted on a handle is a lend — `destroys`,
  `consumes`, `retains` or a callback contract on it is refused; the
  rendered type is netted like a resource's.
- Renderer: `type Name = ephemeral { repr: <ptr> }` with the lends hosted
  on it, and no constructor, `live` bit or Drop. A callback parameter
  whose C type passes a handle's representation is presented with the
  handle in its place (`extern "C" fn(Context, c_int, …)`) and transmuted
  to C's type: a one-pointer aggregate travels as the pointer in every C
  ABI With targets (Codegen.w c_abi_direct_struct_param_type).
- Cannot outlive the callback: the handle is ephemeral, so global or heap
  storage, a non-ephemeral struct, or anything longer-lived is refused by
  the ordinary analysis; the storage diagnostic names the handle.
- Nothing produces it: a literal of a facade-rendered type, or a write to
  one of its fields, outside its rendering is refused. Without that a
  safe `Tally { repr: p }` put a chosen pointer under the handle's
  operations. The same hole existed for resources (`Database { repr:
  bogus, live: true }` had Drop close a chosen pointer in safe code), and
  the one check closes both.
- The contract view reports a handle as callback-scope.

The SQLite facade declares `handle Context wraps *mut sqlite3_context`
with `sqlite3_result_int` of it; the end-to-end fixture's SQL function now
sets its result through `ctx.result_int(42)` with no `unsafe`
(`SELECT shout()` is 42), and da_sqlite_facade_destroy_once and
err_sqlite_facade_retained_callback_captures spell the presented
callback type.

Not ruled, so left raw (reported): reading an argument
(`sqlite3_value **argv` is an array paired with argc, which no clause
presents) and a typed `sqlite3_user_data`.

Fixtures, each failing on the base (`handle` was a parse error; the
literal and the field write compiled): behav_c_facade_handle_callback.w,
behav_sqlite_facade_end_to_end.w, err_sqlite_facade_handle_escapes_callback.w,
err_c_facade_handle_literal.w, err_c_facade_handle_destroys.w,
err_c_facade_handle_void_repr.w, err_c_facade_resource_literal.w,
err_c_facade_resource_field_write.w.

Fixes #1611

* Facade: `valid on failed` presents a record view on the failed state too (§16.2b.4, ruling Amendment 1)

Ruling Amendment 1 (D71 item 9): "An operation the C contract documents
as valid on a failed resource is marked on its fn item with `valid on
failed`, and is presented on the failed-state type as well (`errmsg` on
`FailedDatabase` after a failed `sqlite3_open`). Without the mark the
failed resource admits raw access only."

Stage 12b (5cab7ac, #1630) built the mark for lends and text views, and
`sqlite3_errmsg` after a failed open is pinned by
behav_sqlite_facade_failed_open_errmsg.w; an unmarked operation stays
off `FailedDatabase` (err_c_facade_failed_state_unmarked_item.w). Checked
against the ruling, one presented operation shape was left out: a
borrowed record view (`returns borrow T from param 0`, D66) marked `valid
on failed` was accepted by Sema — which netted and summarized the
`Failed<R>` method — while the renderer skipped every item with a
borrowed return on the failed state, so the program failed with "no
method 'FailedDatabase.last' was rendered … a compiler defect". The
renderer now renders record views on `Failed<R>` like the other lends; a
borrowed-resource return stays refused (`Borrowed<R>` holds a view of a
live `R`). The comment that said no clause marks failed-state operations
is gone.

Fixture, failing on the base with that compiler-defect error:
behav_c_facade_valid_on_failed_record_view.w.

Fixes #1612

* @[repr(packed(N))]: every field's alignment capped at N; c_import emits it for #pragma pack(N) records (§16.4)

Spec §16.4 (D71 item 7): "`@[repr(packed(N))]`, with `N` a power of two,
caps every field's alignment at `N`: a field whose natural alignment
exceeds `N` is placed at alignment `N`, and the record's alignment is at
most `N`. … `c_import` emits it for such records (e.g. `BITMAPFILEHEADER`
under `pack(2)`). A reference to a field whose natural alignment exceeds
`N` is a compile error, as for `repr(packed)`."

- Parser: `@[repr(packed(N))]`, N a power of two from 1 to 65536, kept as
  log2(N)+1 in the type declaration's kind bits (type_decl_pack_cap); it
  implies repr(C). On a declaration that is not a struct it is refused,
  never dropped. The four copies of the struct-kind flag computation are
  one helper.
- Sema: the layout model (TypeLayout.w) caps each field's alignment —
  explicit or natural — at N, so offsets, size and alignment follow; the
  same model now gives `repr(packed)` alignment 1, where it reported the
  natural alignment (`align_of` of `@[repr(packed)] { u8, u32 }` was 4
  beside a size of 5). `&`/`&raw` of a field whose natural alignment
  exceeds N is an error; one within the cap is an ordinary reference.
  packed(N) does not combine with @[packed] or @[bitpacked].
- Codegen: a packed(N) body is an LLVM packed struct with explicit
  padding at the capped offsets, and its alignment, which LLVM's packed
  type cannot carry, is kept in struct_declared_align; a struct embedding
  one (or an @[align(K)] record, whose declared alignment LLVM also did
  not carry) is laid out by that declared alignment, padding included, so
  a C record holding a pack(2) record places it at 2 as clang does.
  Loads and stores whose address a GEP computes through an LLVM packed
  struct now get alignment 1 (LlvmBridge.w
  wl_relax_packed_access_alignment, before the cleanup passes): they had
  the accessed type's ABI alignment, a promise the address does not keep
  — true of `repr(packed)` fields too ("the compiler emits unaligned
  loads/stores").
- c_import: a struct placing a field below its natural alignment was
  imported opaque (#1396). It is now `@[repr(packed(N))]`, N its
  alignment, when the rule recomputed from clang's field sizes and
  natural alignments reproduces clang's offsets, size and alignment
  exactly; a record it does not reproduce stays opaque, never
  approximated. The bundle interface writer emits the attribute.

Fixtures, each failing on the base (the records were opaque; the
attribute parsed as `repr(packed)`, so the ordinary field reference and
the layout were wrong): behav_c_import_pragma_pack.w (pack(2) and pack(4)
records and an ordinary record embedding one, checked against clang's
sizeof, _Alignof and offsetof as enum constants, bytes at clang's
offsets, and values filled on each side), behav_repr_packed_n.w,
err_repr_packed_n_field_ref.w, err_repr_packed_n_not_power_of_two.w,
err_repr_packed_n_not_struct.w; behav_c_import_nested_records now
asserts its pack(2) record's size.

Fixes #1421

* Sema: `&T as *const T` is the reference's address, never its pointee read as one (§16.11, D22)

#1777: `r as *const i32` on `r: &i32` read the i32 and turned its value
into a pointer, so `unsafe { *p }` faulted. The facade renders a borrowed
userdata as `ud as *const U as *mut c_void`, so a callback with a scalar
userdata (`&i32`) faulted in safe code.

The owner is Sema's cast check (D65: Sema decides whether an operand
materializes). can_contextually_copy_ref already refuses a `&T` supplying
an owned `*T` ("a `&T` view never decays to `*T`"), but the fallback after
it — materialize the Copy pointee and let the cast convert, meant for
`page as i64` on a view — recorded the materialization for every cast
target, pointer targets included. A cast of a shared `&T` to `*const T` or
`*mut T` is now the reference relabeled into the raw domain, as the
explicit `&place as *T` already was (§16.11: "`&place as *T` remains the
blessed address-taking pointer spelling"); MIR lowers it with no
adjustment. Unchanged: a view whose pointee is the demanded pointer
(`&*mut u8` as `*mut u8`) supplies that pointer, and a non-pointer target
still materializes (`r as i64`). A `&U` cast to a pointer of another
pointee type keeps its current (materializing) meaning.

Audit: a temporary warning on every cast whose meaning changed, over
`with check src/main.w` and every lib/std and lib/facades module, found
none outside the new fixtures.

Fixtures, failing on the base (a fault reading through the pointer):
behav_ref_cast_to_raw_pointer.w (the issue's repro, f64, `*mut`, a Copy
struct, and the unchanged pointer-view and integer cases),
behav_c_facade_callback_scalar_userdata.w.

Fixes #1777

* Sema: a view stored through `&self` interior mutability is checked against the storage it lands in (§21.1, D22)

#1778: `Mutex.set(&self, value)` stores its value into the receiver while
the receiver is only borrowed, so no mutation of the receiver place showed
the store, and a view escaped into longer-lived storage unchecked:
`fn keep(h: &H): let x = 5; h.slot.set(Some(&x))` compiled, and so did a
callback storing its callback-scope handle (§16.2b.9) into the userdata.

Sema now sees the store. `Mutex.set` and `RwLock.write` join the storing
methods (method_arg_stores_value), and a value they store is checked
against the storage the receiver reaches — the root binding when it owns
it, and every place the root views (check_view_store_into_root):
- storage a local owns takes the view's origins, as `Vec.push` gives them
  to its vector, so a use of it after an origin dies is refused (§21.1
  rule 6); the receiver may be a field path (`h.slot`), not only a name;
- storage the caller owns (the receiver is, or views, a parameter or
  `self`) outlives the call, so a view of a local, or of a parameter
  other than the receiver's own, is refused there: nothing states that it
  lives as long. A view of the receiver's own origin stays allowed. A
  callback-scope handle gets a note naming §16.2b.9.
The same store happens when `with guard as mut v:` hands `v` back to the
mutex (ScopedMut.with_exit_mut behind `Mutex.enter_mut`), and is checked
the same way at the block's end.

Fixtures, failing on the base (each escape compiled clean; the handle
case was checked on the #1611 build, where it compiled):
err_mutex_set_view_escapes_call.w (the issue's repro),
err_rwlock_write_view_escapes_call.w, err_mutex_guard_view_escapes_call.w,
err_mutex_set_view_outlived_locally.w, err_c_facade_handle_escapes_through_mutex.w;
behav_mutex_set_view_scoped.w shows the uses that do not escape still
compile and run: a local mutex viewing earlier locals (set and guard
write-back), a view of the receiver's own origin, an owned value, and a
handle stored in a mutex local to the callback.

Fixes #1778

* Codegen: a record's embedded-alignment scan is a map lookup, not a layout query (#1430 regression from packed(N))

bbef40f (repr(packed(N)), #1421) made declare_struct_type decide whether
a record with no alignment annotations needs a padded body by asking
`declared_align_of(field) != abi_align_of(field)` for every field. Both
are layout queries, and one on a field whose LLVM type reaches a named
struct with no body yet — `JV { … Vec[JV] }`, the recursive type of
examples/json-parser and behav_field_view_of_borrowed_collection_returns
— tripped the #1430 guard: "layout requested for a type holding 'JV' by
value before 'JV' has a body", then code generation failed. Before
bbef40f the unannotated path made no layout query at all.

The condition is now `holds_declared_align(field)`: whether the field
type is, or is an array of, a struct in struct_declared_align — a map
lookup. A record with a declared alignment always has its body already
(its own declaration inserted it), so the lookup is complete, and no
layout is requested while bodies are still being defined. The padded
path's `declared_align_of` stays, as the old path's `abi_align_of` did.

behav_field_view_of_borrowed_collection_returns.w passes and
examples/json-parser builds on the fresh :dev stage1; the packed(N),
pragma-pack, @[align] and bitpacked fixtures pass.

---------

Co-authored-by: Eric Hartford <[email protected]>
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