Skip to content

C backend and modeled-C fixes: map loops, generic structs, view compares, warnings at real spans, memchr/macro collisions, contract audit, runtime domains - #1789

Merged
ehartford merged 12 commits into
batch2-rulings-facadefrom
batch2-emitc-modeledc
Sep 27, 2026
Merged

ehartford merged 12 commits into
batch2-rulings-facadefrom
batch2-emitc-modeledc

Conversation

@ehartford

@ehartford ehartford commented Sep 27, 2026 •

Copy link
Copy Markdown
Contributor

Stack layer 3. Fixes #1560 #1434 #1562 #1771 #1498 #1765 #1663 #1753 #1674; part of #1608 #1678. emit-c-smoke now runs a corpus through both backends. Stopped: #1484 (chain #1774 → re-migration → #1773), #1766 (closures in emit-C, plan filed). Draft until green.

@ehartford
ehartford added this pull request to stack #1793 September 27, 2026 11:01
@ehartford ehartford changed the title batch2 emitc modeledc C backend and modeled-C fixes: map loops, generic structs, view compares, warnings at real spans, memchr/macro collisions, contract audit, runtime domains Sep 27, 2026
Eric Hartford added 12 commits September 27, 2026 09:18
A comparison of two `&str` views compared their addresses in the C
backend: rvalue_text asked raw_pointer_binop_text first, and
type_is_raw_pointer_tid counts TY_REF, so `a == b` on two `&str`
parameters became `(uintptr_t)(_1) == (uintptr_t)(_2)` before the #785
content path below it could see the operands. The LLVM backend reads a
`&str` operand as the str it points at (mir_compare_dispatch_kind 1,
#293), and §11.7 says a view compares the value it observes; only raw
pointers compare by address. `<` on two `&str` views had the same fault
(#1137's class: the text ordering covered only two owned strs).

Now str_compare_text handles every comparison of two text operands, str
or `&str` in any mix, ahead of the raw-pointer path: `==`/`!=` through
with_str_eq_ref and the orderings through with_str_cmp_ref, each view
rendered as its pointee (str_value_text). The two partial paths it
replaces are gone.

The C backend had no behavior corpus: emit-c-smoke ran hello and four
inline programs. test/emit_c/*.w is that corpus now. For each fixture
the smoke runs `with test` (the LLVM backend against the fixture's
`//! expect-stdout:` lines), then `--emit-c`, the host C compiler over
the runtime objects, and the program, whose stdout must be the same
lines; every fixture is surveyed before the verdict. The smoke's inputs
include the directory, so a fixture edit reruns it.

Evidence (test/emit_c/str_view_compare.w, emitted, compiled and run):
base stage1 `false true true false true true` / `true false`; this
change `true true false true false true` / `true false`, as the LLVM
backend prints.

Fixes #1560
The C backend refused every `for (k, v) in map` ("HashMap traversal
lowering is not implemented; use the LLVM backend"), which since D44
includes the compiler's own source, so the emit-C lane of the compiler
stopped before writing any C.

MirLower.lower_for_hashmap already says what the loop is: MAP_CAPACITY
bounds a walk over the table's slots, MAP_SLOT_OCCUPIED skips an empty
one, and MAP_KEY_AT / MAP_VALUE_AT read an occupied slot where it lives.
The C backend now lowers those four intrinsics with the runtime
accessors the LLVM backend calls (with_hashmap_capacity,
with_hashmap_slot_occupied, with_hashmap_key_ptr_at,
with_hashmap_value_ptr_at; their prototypes join the fixed block in
rt_core's own spelling). A view destination (`&K`, `&V`) gets the slot's
address and a Copy value destination is loaded through it, as in the
LLVM lowering (§2.3: nothing non-Copy is duplicated). The destination
types are MirLower's typed temps (call_builtin_ret_tid), so the results
are stored rather than discarded.

Evidence (test/emit_c/map_traversal.w, emitted, compiled and run): base
stage1 refuses the emission with the message above; this change prints
`6 6` / `60 3`, as the LLVM backend does, for a HashMap[i32, str] and a
HashMap[str, i32].

Fixes #1434
…] is T* (#1562)

The C backend named every generic instance it does not model itself
(`Wrap_str_`, `Box_Node_`, `BTreeMap_i32__str_`) and never defined one:
collect_struct_types_from_tid collected only TY_STRUCT, payload enums,
tuples and the synthetic containers, so the first use failed at the C
compile ("unknown type name 'Wrap_str_'") — any user generic struct,
reached through a local, a method or a field. Had one been collected,
the definition pass would have read the instance's type-argument list
as a field list (TY_GENERIC_INST's d1/d2).

- An instance of a declared generic struct (its template is a TY_STRUCT;
  Sema.type_reflection_base_template) is collected, ordered after the
  by-value struct types of its fields, and defined from Sema's
  reflection: type_reflection_field_name / _type_frozen give the
  instance's fields and their instantiated types. Field projections on
  it type through the same reflection (generic_inst_field_tid at every
  place-typing site), and its moved-from reset is a compound literal.
  The dependency order counts such an instance as a by-value struct
  wherever a field, payload or tuple element holds one
  (tid_is_c_struct_value).
- std's `Box[T]` is not a struct to C: Sema and MIR treat it as the
  pointer to its T (a Box place dereferences, Box.new casts its `*mut T`
  to the Box), as the LLVM backend does (sema_type_to_llvm). c_type
  spells it `T*`, a deref projection through it types as T, and its T is
  collected.

Evidence (test/emit_c/generic_struct_instances.w: a user Wrap[T] with a
Debug impl and a method, a Node list through Option[Box[Node]], a
struct holding two Wrap instances, a BTreeMap[i32, str]): base stage1's
C does not compile (20 errors, unknown type names Wrap_i32_, Wrap_str_,
Box_Node_, BTreeMap_i32__str_); this change prints `wrapped` / `5` /
`3` / `7 x` / `2 a`, as the LLVM backend does.

Fixes #1562
An array-of-arrays literal in a function body (`[[1, 2], [3, 4]]`)
lowered to an aggregate whose operands are the rows, and the C backend
rendered them by name inside the temporary's initializer list
(`{ int32_t __with_arr_tmp[2][2] = {_1, _2}; ... }`). A row is a C
array, so the C did not compile ("incompatible pointer to integer
conversion ... 'int32_t[2]'"). aggregate_nested_array_assignment now
copies each row into the temporary and the temporary into the
destination; a flat array keeps its initializer list.

Found by #1484's startup initializers: pcre2's `[[u8; 21]; 17]` tables
are the first such aggregates every prelude program carries.

Evidence (test/emit_c/nested_arrays.w, emitted, compiled and run): base
stage1's C does not compile (4 errors); this change prints `3 2`, as the
LLVM backend does.

Fixes #1771
…eps its source text (#1498)

`with check` put a warning at its line (a facade presentation warning at
the `fn` item, ruling §8; a loop-concatenation warning at the `++`);
`with run` and `with build` put every warning at 1:1 over an empty
line. lldb on the base stage1 during `run`: render_warnings_frontend
asked source_for_file_id_frontend for file 0, which answers with the
Zcu's current_source_text — empty by then. The code generator took it:
Backend.w (all four codegen entries) did `cg.source_text = move
self.current_source_text`, and the MIR-phase Sema in Compilation.w did
`sema.source_text = move self.zcu.current_source_text`, and neither gave
it back; warnings are printed after the build, from the emptied Zcu.
(The per-unit codegen loop also handed every unit after the first an
empty text.) Each now takes a copy; the Zcu keeps the text it renders
diagnostics against. Not facade-specific, which is why the issue's
"not yet located" span mapping looked right under `check`.

Test: behav_warning_location_run_build.w runs `check`, `run` and `build`
over one program with a facade warning and a Sema warning and requires
both at their lines under each (the core prelude keeps the case off the
std.re corpus, which a case directory cannot see from a compiler that
does not embed it). Base stage1: `check` passes, `run` fails ("warnings
not at their lines", both at main.w:1:1); this change: all three pass.

Fixes #1498
A nullable callback's userdata parameter is `Option[&U]` (§16.2b.9), and
`U` is bound from that argument, so Sema.facade_prepare_callback_call
checked the argument with no expected type. `Some(x)` infers its enum
from the payload; `.Some(x)` needs an expected enum, so it failed with
"cannot infer the enum type for `.Some`" and then "cannot infer generic
method type parameter 'U'" — where §4's shorthand is the ordinary
spelling wherever an Option is expected.

The parameter's shape is known before `U`: facade_check_userdata_shorthand
checks the payload once, with no expected type (it binds `U`), types the
shorthand `Option[&P]` exactly as the call form's `Some(x)` is typed
there, and borrows the payload for the call through the same
payload_arg_auto_refs path (this constructor is the userdata's), so MIR
lowers `.Some(ctx)` to `Some(&ctx)`: a temporary is dropped at the end
of the statement and a place stays usable. A first cut typed the
shorthand `Option[P]`; MIR then moved the payload into the Option and
the callback received the Option's bytes (the test printed garbage and
leaked both Ctx values) — the typed form is the call form's, not a
second derivation of it. `.None` for the userdata was already the
absent-callback path (facade_arg_is_none).

Test: behav_c_facade_callback_userdata_shorthand.w (a temporary, a
place used twice, and `.None`, with the Drop lines where the call form
prints them). Base stage1: "cannot infer the enum type for `.Some`";
this change: passes.

Fixes #1765
…unction keeps both (#1663)

behav_c_facade_libc_system_headers.w fails under the seed-built stage1,
which compiles std.re from source: "function 'memchr' expects 2
argument(s), found 3" in lib/std/re/pcre2_match.w, the parameter
"expects []u8". The program c_imports <string.h>, whose `memchr`
CImport renders as a safe wrapper over the byte buffer (#379:
`memchr(__s: []u8, __c)`, the raw extern renamed and hidden), and
std.re.defs declares `memchr` as an extern of its own that pcre2_match
calls with a pointer and a length. One flat function table held one
declaration per name and a real fn beats an extern, so std.re's calls
were checked against the importer's wrapper.

They are two With declarations with two signatures, not one C symbol
declared twice. Zcu.displace_c_import_wrappers (after the c_imports are
expanded, beside displace_colliding_globals) displaces a c_import-
rendered fn whose name another module declares as an extern to its
importer's module-qualified identity — the same displacement other
modules' colliding fns take (#1350) — and the extern keeps the flat
name. Sema binds each module's call by §18.2 precedence
(resolve_displaced_fn_ident): the importer's to its wrapper, std.re's to
its own import.

Test: behav_c_import_wrapper_beside_module_extern.w calls the wrapper
from the program and matches a regex whose literal first code unit makes
pcre2 scan with its memchr. Base stage1: the arity error above; this
change passes, and behav_c_facade_libc_system_headers.w passes.

Fixes #1663
)

`use c_import("a.h")` then `use c_import("b.h")`, both `#define PI`,
failed with "failed to compile C header snippet: b.h". Three things
stood in the way of D70 (§18.2: the later import shadows the earlier,
and each stays reachable through its namespace, the header's file name
without `.h`):

- CImport deduplicates every emitted name across the c_imports of one
  compilation. b.h's PI was skipped because a.h had emitted a PI, so b's
  translation came back empty and b.PI could never resolve. A macro
  constant an earlier c_import defined is now emitted again by a later
  header that defines it: it is that import's own value. Constants are
  tracked per translation (g_ci_current_macro_consts, folded into
  g_ci_prior_macro_consts when the next translation starts, reset per
  compilation beside with_cimport_reset_names), so a macro one header
  redefines is still one constant of that import, and a name an earlier
  import declared as anything but a constant keeps the old dedup.
- An empty translation fell through to Zcu's hand-written `#include`
  fallback, meant for a compiler without libclang, which knows six
  system headers and reported everything else as a failure. When
  libclang is available and read the header without error, an empty
  result means the header adds nothing new; the import continues.
- displace_colliding_globals gave all of a module's c_imports one owner
  (`<path>/c_import`), so two imports' PI were a same-owner duplicate
  ("shadowing is not allowed"). Each c_import is now an owner of its own
  (keyed by its offset, as decl_is_c_import records it); the later PI is
  displaced, and Sema's existing §18.2 resolution (last_import_provider,
  import_position_of) binds bare PI to the last import and each
  namespace to its own.

Tests: behav_d70_c_import_same_macro.w and its _reversed twin import the
two headers in both orders and print the bare name and both namespaced
values. Base stage1: "failed to compile C header snippet:
behav_d70_second_header.h" (and, when the second header adds another
name so its translation is not empty, "namespace
'behav_d70_second_header' provides no 'PI'"); this change prints
`4 3 4 1` and `3 3 4 1`. The c_import, facade and D70 behavior and
compile-error fixtures (333 files) show no change beyond three p7 cases
that need the embedded std.re corpus and fail the same way on base
stage1.

Fixes #1753
#1678, part)

`static inline int probe(int n, ...) { va_list ap; va_start(ap, n);
int x = va_arg(ap, int); ... }` is omitted — c_import does not translate
va_arg — and a use of `probe` reported "inline body translation failed",
categorized raw-modelable: "declare a manual extern \"C\" binding and
call it under unsafe (§16.1)". A static inline function's only
definition is its body; there is no symbol for that extern to bind, so
the remedy cannot link. #1417 made the opaque-record omission in the
same branch inexpressible for that reason; the other three omissions
there still said raw-modelable.

Now a `static inline` function's omitted body is inexpressible (the
diagnostic points at a C shim or allow_untranslated); a non-static
inline, which may have an external definition elsewhere, stays
raw-modelable. The reason carries the translator's own bail message
(g_ci_bail_message) — "inline body translation failed: va_arg is not
supported" — instead of only that it failed.

Test: err_c_import_static_inline_variadic.w requires the reason and
refuses the manual-extern remedy. Base stage1: "missing expected check
error: inline body translation failed: va_arg is not supported" (it
said "inline body translation failed" and the extern remedy); this
change passes.

err_c_import_omitted_directional_raw.w pinned the old claim — a
`static inline` returning a function pointer "is reachable via the raw
surface" — which is false for the same reason (no symbol to bind). It
now uses a plain `inline` function, which may have an external
definition, so it still pins the raw-surface direction; the static case
is the new test's.

Not fixed here: translating the body. With has no definition form for a
C-variadic function (only `extern fn f(x, ...)` declarations) and no
va_arg reader; that is a language question for a ruling, and #1678
stays open for it.
…ucer on its parent projects past its out slot (#1674)

#1674: audit:contract reported `violations=0 ok` over a facade whose
rendered call carried C parameter indices — `touch(values, count,
owner)` presented as `touch(values, owner)` kept the owner's bit 2 on a
two-parameter bridge, and a stale view of the owner was accepted. #1675
projected those masks (facade_presented_touch_mask); the audit still
looked only at the source contracts, so it could not see the class.

audit:contract now checks each entry of Sema's facade_call_effects:
every invalidated parameter is one of that signature's parameters, and
one that holds a modeled resource — facade_param_receives for the raw C
signature, the presented parameter's type (facade_type_holds_resource)
for a rendered bridge, method or constructor.

On its first run it found a live case of the same class. A producer
rendered as a method of its parent (`d.st_new(flags, o)` for
`int st_new(db *, st **out, int flags, other *o)`) is registered twice
in facade_index_call_effects: by the hosted-method pass, which projects
fixed, buffer and destruction-callback parameters but not the out slot,
and by the constructor pass, which removes the slot. When an fn item
describes the producer, the hosted pass ran first and its mask won
(facade_add_call_effect keeps a signature's first registration): bits 1
and 3 on a three-parameter method, so `flags` was "invalidated" and `o`
was not, and a view of `o` survived the call. The SQLite-shaped
fixture's `db.prepare(...)` carried the out slot's bit 3 the same way,
harmlessly past its three parameters. The constructor pass now runs
first, so a producer's parent method takes the slot-aware mask.

Tests:
- err_c_facade_producer_on_parent_effect.w: the view of `o` read after
  `d.st_new(1, o)` is refused. Base stage1 and the audit-only stage1
  accept it; this change refuses it ("view `v` borrows from `o`, which
  `st_new` may have invalidated").
- test/contract/ok_effect_projection.w (+ .expected): a clean facade
  with both projections (a byte buffer's length, a producer's out slot);
  audit:contract and audit:all are ok. With the audit but not the
  reorder: 2 violations ("parameter 1, which holds no modeled
  resource"; "parameter 3, and it has 3"). The other contract fixtures'
  views are unchanged, and ok_sqlite_shaped's audit fails with the audit
  alone ("parameter 3, and it has 3") and is ok with the reorder.

Fixes #1674
… domains (#1608)

Stage 13 (ruling §52, spec §16.2b.14) gave every runtime foreign call a
row under the three libc domains the ruling names (errno thread, environ
process, locale process). #1608 listed the other process-global C state
the runtime's calls touch. Ruling §33 lists domains as examples ("Examples
include"), §35 lets a facade refine a coarse domain, and §36 gives the
scopes, so each is declared in every runtime facade and wired the way
stage 13 wired the three:

  signals     process — dispositions (sigaction; raise, kill, abort)
  signal_mask thread  — the calling thread's mask and alternate stack
                        (sigprocmask, sigaltstack)
  cwd         process — the working directory (chdir)
  fds         process — the descriptor table (open, close, dup2, fcntl,
                        socket, accept, mkstemp, opendir, closedir;
                        getaddrinfo and realpath may open descriptors of
                        their own; exec closes close-on-exec ones)
  rlimits     process — setrlimit
  children    process — the children and process group (fork, waitpid,
                        wait4, setpgid, exec)
  stdio       process — the streams' buffers and positions (fseeko)

In the POSIX/C facades (darwin, linux x86_64/aarch64, fiber_core_darwin,
rt_core, fiber_runtime, fiber_stubs, panic_runtime) a row preserves each
domain unless its C function (the extern's link_name) is one of the
interfaces POSIX.1-2017 names as altering it; the rows were written by a
one-off With rewrite keyed on those names (1574 lines, all additions).
The win32, UCRT and WASI facades declare the domains and, as stage 13
did for calls the C standard does not describe, state no `preserves`:
silence invalidates (§38). The runtime itself calls no PRNG (random
bytes come from arc4random_buf/getrandom/SystemFunction036/random_get),
so no runtime facade has a PRNG domain; std.libc's rand/srand and
whether the toolchain libc facade exposes any of these to user programs
(e.g. getcwd text borrowed from `cwd`) are the user-facing half of #1608,
which the ruling leaves to a facade that models them.

runtime-domain-audit (build/compiler.w) now requires the seven besides
the three in every runtime facade, and its messages name them.
test/runtime_domain_audit/missing_process_domain.w declares everything
but `domain cwd process`; the base audit stays silent on it ("the audit
stayed silent on its negative fixture ... got 0"), this one reports it.
The lane: 16 runtime files, 387 domain rows, 5 fixtures agree. The
darwin runtime objects build in :dev, and `with check --target` passes
for linux_x86_64, linux_aarch64, windows_x86_64, windows_aarch64 and
fiber_core_windows (wasm needs an SDK with the WebAssembly backend).

Part of #1608: the runtime half. Whether the toolchain libc facade exposes
any of these domains to user programs is the issue's open decision.
… resource (#1674 follow-up)

The #1674 audit's first battery run flagged the pinned in-place fixture
(behav_c_facade_resource_in_place_pinned.w, deep-debug-tool-tests
analyze-audit-in-place-pinned): "the rendered call of 'z_init'
invalidates views of its parameter 0, which holds no modeled resource".
The audit is right and the fixture is right; the effect index was wrong.

`init z_init(self)` is rendered as the constructor `Stream.init(ends,
misplaced)` with the storage slot — z_init's first C parameter — removed,
and the constructor pass indexes that signature slot-aware (nothing to
touch here: `ends` and `misplaced` hold no resource). But z_init also has
an fn item (`lend`), and facade_method_host answers Stream for its first
parameter, so the hosted-method pass registered the same signature as
`Stream.init`, a lend method with self at 0: the slot's bit 0 landed on
`ends`. Harmless to programs so far (no view is ever borrowed from an
`int *`), wrong by §16.2b.14, and invisible until the audit looked.
The hosted pass now skips a resource's init/preinit (facade_fn_is_init):
its signature is the constructor pass's.

Evidence: with the stage1 before this change, `analyze
behav_c_facade_resource_in_place_pinned.w audit:all` reports the
violation above; after, `violations=0 ok`, as does the drop-once twin,
every in-place/init/preinit behavior and compile-error fixture (13), and
the four clean contract fixtures. test/contract/ok_in_place_init.w
(+ .expected) pins it under contract-view-tests: 1 violation before, 0
after.
@ehartford
ehartford force-pushed the batch2-emitc-modeledc branch from f7f23c2 to 2525ea2 Compare September 27, 2026 13:28
@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 9c48fe2 into main Sep 27, 2026
@ehartford
ehartford deleted the batch2-emitc-modeledc branch September 27, 2026 14:34
ehartford pushed a commit that referenced this pull request Sep 28, 2026
…d effect, not a domain (§16.2b.14, D76, ruling Amendment 2)

Ruling Amendment 2 (§52, #1608): "Process-global C state over which no safe
view is presented (signal disposition and mask, the current directory, the
file-descriptor table, resource limits, process groups and children, the
stdio stream objects) is an effect the runtime audit records, not a domain.
It becomes a domain the first time a facade presents a safe view whose
validity it decides."

#1789 had declared the seven as domains in every runtime facade, with a
`preserves domain` line per row for each state the row does not alter —
rows no view's validity depended on, the ceremony the ruling removes. The
runtime facades (rt/*.w) now declare the three libc domains only; 1,764
lines go.

The record (build/compiler.w, runtime-domain-audit): the lane keys each
seam's effect on the C symbol it links, from the interfaces POSIX, Win32
and WASI name as altering each state (comp_process_state_alterers: chdir
the working directory, setrlimit the limits, fork/exec/waitpid the
children, open/close/dup2/socket/CreateFileW/path_open the descriptor
table, sigaction/sigprocmask/raise the signals, fseeko the streams; a call
that only reads — getcwd, getrlimit — records nothing), and writes the
record into its output, one line per seam: 112 seams today. It refuses:
  - a facade declaring one a domain while no facade the toolchain ships
    (rt/*.w, the libc facade) presents a view over it;
  - a facade presenting a safe view over one (`returns borrow … from domain
    S`) without declaring it a domain;
  - once one is a domain, a runtime facade not declaring it, and a row
    whose seam alters it stating `preserves domain S`.
The lane reads src/compiler/LibcFacade.w for the views it presents.

The compiler: `from domain S` / `preserves domain S` naming undeclared
process-global state keeps the unknown-domain error and says why, citing
§16.2b.14 (SemaFacade.w facade_unknown_domain_message).

Fixtures (the lane's): clean.w keeps the three domains only;
process_state_not_a_domain.w, process_state_view_without_domain.w,
process_state_domain_preserved_by_alterer.w (negative),
process_state_effect_recorded.w (a new `//! expect-record:` head: clean,
and the record holds the line); missing_process_domain.w, the inverted
rule, is removed. Compiler: err_c_facade_view_over_process_state_undeclared.w.

Evidence: runtime-domain-audit: 16 runtime files, 400 domain rows, every
foreign extern described; 112 seam(s) record a process-global effect
(D76); 8 fixtures agree.

Fixes #1608
ehartford added a commit that referenced this pull request Sep 28, 2026
…1779); process state is an audited effect (#1608) (#1841)

* Sema: a tuple literal holding an ephemeral value is ephemeral — Box.new((view, 2)) put the view on the heap (§5.1)

expr_is_ephemeral_value (SemaCheck.w), the predicate the #600 heap-escape
gate asks of a Box.new / Rc.new / Arc.new argument, had cases for struct,
array and map literals (#625) but none for a tuple literal, so a view
wrapped in a tuple moved into heap storage past its origin:

    let local = 5
    let b = Box.new((Keep { r: &local }, 2))    // accepted

The same holds through a generic body (`Box.new((x, 1))` with `x: T`, T
ephemeral). A tuple literal is now judged as the other literals are: by its
type (type_is_ephemeral_value already treats a tuple with an ephemeral
element as ephemeral) and by its elements.

Found through D76's generated callback wrapper, which boxes the userdata
beside the program's callbacks as a tuple: an ephemeral userdata borrowing
a local was handed to C, and the callback read the dead local through its
`&U` (printed 4, twice, for a local of 5).

Evidence: test/compile_errors/err_ephemeral_tuple_boxed.w — base stage1
`check` ok; this change "an ephemeral value cannot be stored on the heap".

* Sema: a type in expression position names no value — transmute[T](x) inside a closure panicked the capture walk

A closure body is walked for captures by expr_uses_symbol (SemaCheck.w),
which panics on a node kind it has no case for (#1570, #1598: a silent 0
would miss a capture). A call's type argument — `transmute[extern "C"
fn(i32) -> i32](p)`, `transmute[*const i64](q)` — reaches it as the index
of the callee's NK_INDEX, a type node, and there was no case for any type
node:

    panic at src/SemaCheck.w:27370:9: internal error: expr_uses_symbol has no case for node kind 127

A type names no value, so it captures nothing — except through a
`typeof(expr)` inside it, which is walked. The pointer the closure
transmutes is still captured.

Evidence: test/behavior/behav_transmute_type_arg_in_closure.w — base stage1
panics as above; this change prints 42 and 7. D76's generated callback
wrapper transmutes inside the closure C calls.

* Facade: a callback's arguments as &[Handle] and its registered user data as &U, through a wrapper the compiler generates (§16.2b.9, D76, ruling Amendment 2)

Ruling Amendment 2 (§44, #1779): "A clause on the registering function may
present a callback's argument vector as a slice of a callback-scope handle
(`argv paired with argc as &[Value]`) and its registered user data as the
value the facade boxed (`user_data as &U`). The compiler generates the
wrapper; both are valid for the callback's invocation only."

Clauses (Parser.w, Ast.w FACADE_CLAUSE_CALLBACK_ARGV / _USER_DATA). The
spelling names what the ruling's words leave to position, as every facade
reference does:

    fn sqlite3_create_function_v2
        consumes param 4 destroyed_by param 8
        retains param 5 by param 0
        callback param xFunc argv param 2 paired with argc param 1 as &[Value]
        user_data from sqlite3_user_data as &U

`argv`/`argc` index the callback's own parameters (C names none of a
function pointer's); `from <fn>` states which C function hands the pointer
back. Both are capability-granting, so stated, never inferred from a type's
shape or a name (D51): a wrong pairing reads past the vector, a wrong
accessor reads another pointer as `&U`.

Verification (SemaFacade.w collect_argv_clause, collect_user_data_clause,
verify_facade_wrapped_callbacks): the callback is callable; argv is `T **`
with `T *` the representation of exactly one handle, argc an integer, the
presented type `&[H]` (or `[]H`); the accessor takes exactly the handle and
returns `void *`; `user_data` needs a userdata the facade boxes (consumed
with its destroy callback, or retained); argv needs `user_data` (the only
channel from C's call back to the program's callback); each served
callback receives the handle once and is not also a `callback … userdata`
pairing.

Rendering (FacadeRender.w facade_render_wrapper and the D76 section
comment): the method boxes `(U, cb…)` — the userdata with the program's
callbacks as code pointers — hands C the box and one generated
`extern "C"` wrapper per callback that receives the accessor's handle (a
null callback stays null), and frees the box through the destroy
callback. The wrapper reads the box through the accessor, makes the slice
from C's vector and count (a negative count panics, naming the
operation), and calls the program's callback with the handles, the slice
and `&U`. The presented callback is `extern "C" fn(Context, &[]Value, &U)`
— captureless, as before — and Sema types it at each call with `U` bound
from the userdata argument (FacadeCallbackMethod.wrapped_params), so a
bare fn or a closure passes with no typed local and a capturing closure
is refused as for `db.exec`.

Valid for the invocation only: the slice and its handles are ephemeral and
`&U` a borrow, so global or heap storage is refused by the ordinary
analysis, and the diagnostic names the handle through a slice too
(facade_handle_in, type_mentions_facade_rendered). The userdata itself
must own what it holds: an ephemeral one is refused as the box's content
(the tuple rule of the previous commit).

The contract view reports each served callback's `arguments` and `user
data` facts with their clauses (AnalysisContract.w).

The SQLite facade (lib/facades/sqlite3.w) declares `handle Value wraps
*mut sqlite3_value` with `sqlite3_value_int` of it and the two clauses on
sqlite3_create_function_v2, quoting the header. The end-to-end test's SQL
function now reads its arguments and application data with no `unsafe`:
`fn shout(ctx: Context, args: &[Value], app: &AppData)`, `SELECT
shout(20, 22)` is 42, and it is registered by name, with no typed local.
The three other create_function_v2 tests spell the new callback type; the
captures test now gets the capture refusal its comment anticipated.

Tests, each failing on the base (the clauses were a parse error there):
behav_sqlite_facade_end_to_end.w, behav_c_facade_callback_argv_user_data.w
(portable: every argument, an empty NULL vector, a final callback, a null
callback, data destroyed once — clean under --debug-alloc),
err_c_facade_callback_args_escape.w, err_c_facade_callback_user_data_escapes.w,
err_sqlite_facade_function_args_escape.w, err_c_facade_callback_ephemeral_user_data.w,
err_c_facade_argv_needs_user_data.w, err_c_facade_user_data_boxes_nothing.w,
err_c_facade_argv_not_handle_vector.w, err_c_facade_user_data_accessor_not_void_ptr.w,
contract/ok_callback_arguments.w (+ .expected; audit:contract and audit:all
clean); updated: err_sqlite_facade_handle_escapes_callback.w,
err_sqlite_facade_retained_callback_captures.w, da_sqlite_facade_destroy_once.w
(leak count=0).

Fixes #1779

* Runtime audit: process-global state no safe view reaches is a recorded effect, not a domain (§16.2b.14, D76, ruling Amendment 2)

Ruling Amendment 2 (§52, #1608): "Process-global C state over which no safe
view is presented (signal disposition and mask, the current directory, the
file-descriptor table, resource limits, process groups and children, the
stdio stream objects) is an effect the runtime audit records, not a domain.
It becomes a domain the first time a facade presents a safe view whose
validity it decides."

#1789 had declared the seven as domains in every runtime facade, with a
`preserves domain` line per row for each state the row does not alter —
rows no view's validity depended on, the ceremony the ruling removes. The
runtime facades (rt/*.w) now declare the three libc domains only; 1,764
lines go.

The record (build/compiler.w, runtime-domain-audit): the lane keys each
seam's effect on the C symbol it links, from the interfaces POSIX, Win32
and WASI name as altering each state (comp_process_state_alterers: chdir
the working directory, setrlimit the limits, fork/exec/waitpid the
children, open/close/dup2/socket/CreateFileW/path_open the descriptor
table, sigaction/sigprocmask/raise the signals, fseeko the streams; a call
that only reads — getcwd, getrlimit — records nothing), and writes the
record into its output, one line per seam: 112 seams today. It refuses:
  - a facade declaring one a domain while no facade the toolchain ships
    (rt/*.w, the libc facade) presents a view over it;
  - a facade presenting a safe view over one (`returns borrow … from domain
    S`) without declaring it a domain;
  - once one is a domain, a runtime facade not declaring it, and a row
    whose seam alters it stating `preserves domain S`.
The lane reads src/compiler/LibcFacade.w for the views it presents.

The compiler: `from domain S` / `preserves domain S` naming undeclared
process-global state keeps the unknown-domain error and says why, citing
§16.2b.14 (SemaFacade.w facade_unknown_domain_message).

Fixtures (the lane's): clean.w keeps the three domains only;
process_state_not_a_domain.w, process_state_view_without_domain.w,
process_state_domain_preserved_by_alterer.w (negative),
process_state_effect_recorded.w (a new `//! expect-record:` head: clean,
and the record holds the line); missing_process_domain.w, the inverted
rule, is removed. Compiler: err_c_facade_view_over_process_state_undeclared.w.

Evidence: runtime-domain-audit: 16 runtime files, 400 domain rows, every
foreign extern described; 112 seam(s) record a process-global effect
(D76); 8 fixtures agree.

Fixes #1608

---------

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.

emit-c: == / != on two &str views compares addresses; LLVM compares contents

1 participant