Skip to content

D71 facade rulings: ok lists, valid on failed, callback-scope handles, repr(packed(N)); cast and Mutex view-escape fixes - #1788

Merged
ehartford merged 7 commits into
batch2-rulings-langfrom
batch2-rulings-facade
Sep 27, 2026
Merged

ehartford merged 7 commits into
batch2-rulings-langfrom
batch2-rulings-facade

Conversation

@ehartford

@ehartford ehartford commented Sep 27, 2026 •

Copy link
Copy Markdown
Contributor

Stack layer 2. Implements D71 #1432 #1612 #1611 #1421; fixes #1777 (&T as *const T took the value) and #1778 (views escaping through Mutex.set / RwLock.write / guard write-back); closes a hole where safe code could construct a facade resource literal. Filed #1779 #1783. Draft until green.

Eric Hartford added 6 commits September 27, 2026 06:41
…s 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
…f` 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
…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
…ts 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
…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
…ainst 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
@ehartford
ehartford added this pull request to stack #1793 September 27, 2026 11:01
@ehartford ehartford changed the title batch2 rulings facade D71 facade rulings: ok lists, valid on failed, callback-scope handles, repr(packed(N)); cast and Mutex view-escape fixes Sep 27, 2026
…yout 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.
@ehartford

Copy link
Copy Markdown
Contributor Author

Battery GREEN on the stack top 57410c94 (docs-csharplang-shape, folds #1787→#1792): with run tools/battery.w — src/main build ok, :battery-checks (seed-driver, fixpoint, test-with-audits incl. drop/move audits, user-programs-safe, last-green) rc=0 in 1574 s. Pre-battery gate green on the same tip: full build, stage1 self-check of src/main.w, build.w with the fresh binary, abi-hash, unit-return-review, spec-inventory, examples-tests, c-migrator-basic-tests, deep-debug-tool-tests. Merge order: gh stack merge 1792 --yes --squash.

@ehartford
ehartford marked this pull request as ready for review September 27, 2026 14:33
@ehartford
ehartford merged commit bb571e6 into main Sep 27, 2026
@ehartford
ehartford deleted the batch2-rulings-facade branch September 27, 2026 14:34
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.

Miscompile: r as *const i32 with r: &i32 reads the value and turns it into a pointer (a facade callback with scalar userdata segfaults in safe code)

1 participant