Repository navigation
Modeled C stage 9: callbacks and threads (ruling §44-§51) - #1606
Merged
Merged
Conversation
added 2 commits
September 24, 2026 00:11
…m here on; `ptr as Box[T]` takes it back (§16.2b.9 userdata)
….9-10) A callback contract — an fn item that retains a callback or its userdata (`retains … by param 0`), consumes userdata with a destroy callback (`consumes … destroyed_by`), types a callback's userdata (`callback param N userdata param M`), or says `callback_thread any` — is rendered as a method of the resource its first parameter receives, generic in the userdata type `U`: the callback is `extern "C" fn(&U, …)` (captureless, §12.4 — C receives the code pointer alone) and the userdata is `&U` for the call (§44), `U` owned by the resource until it is destroyed (§45: boxed, handed to C as the pointer, released after the destroyer by the resource's Drop), or `U` moved into C and destroyed by the callback the contract names (§24: the compiler supplies the destroy fn for `U`; the parameter is withheld). Reentrancy (§47) is by construction: no captures, the userdata a read view. Sema: `callback param N userdata param M` verified (callable; `void *`; the callback's one `void *` slot), never inferred from there being one of each (typing a `void *` is capability-granting); `consumes` of a `void *` with no destroy contract, a userdata both consumed and retained, `retains … by` a non-resource or a non-receiver, and `callback consumes` (not modeled) are errors; the callback argument is checked against the callback type with `U` bound from the userdata argument, whatever order C declares them; under `callback_thread any` the userdata type must be Send and Sync (§51). Thread capabilities (§48-§50): a facade resource is Send/Sync exactly as its `thread` clause says — thread-bound by default, never inferred from the representation — and a spawn_os capture of one names the clause to state. Fixtures: behavior for each rule, compile_errors with exact text, debug-alloc for consumed userdata destroyed once and retained userdata released once; behav_c_facade_facts_verify and _parses drop the clause combination that now contradicts itself.
Contributor
Author
|
Battery green — head 9122b2b on main d783366, pinned seed, cold c_import cache, audits included (consume-with-destroy-callback is drop scheduling): Ready to merge: |
ehartford
marked this pull request as ready for review
September 24, 2026 04:48
ehartford
pushed a commit
that referenced
this pull request
Sep 24, 2026
…trace_v2 present as methods (callback items render on the resource); the snapshot was recorded before #1606 landed
ehartford
added a commit
that referenced
this pull request
Sep 24, 2026
…d the audit lane (ruling §52) (#1615) * rt: foreign-state domain rows for every runtime foreign call (ruling §52, spec §16.2b.14) Each rt/*.w file that reaches a foreign symbol ends with an internal `c facade` block declaring the three libc domains — `domain errno thread`, `domain environ process`, `domain locale process` (ruling §33-§36) — and one `fn` row per foreign extern: every `extern fn` under `@[link_name]` or `@[import_module]`, and every one whose name is not an rt_*/with_* runtime symbol. A row's silence invalidates (§38: unknown effect means invalidate); `preserves domain D` appears only where the C standard says so, cited in each block's header: C11 7.5p3 (errno — any library function may set it; the accessor is the macro's lvalue, 7.5p2), C11 7.22.4.6 with POSIX setenv/unsetenv/putenv/getenv (environ), C11 7.11.1.1 (locale: setlocale, never called by the runtime). Win32, Winsock and WASI rows say nothing: the C standard does not describe them. The LLVM memory.size/grow intrinsics are not foreign calls. 385 rows over 12 files; each file still checks under --no-prelude, and the emitted object's text is byte-identical to the row-less one (the facade renders nothing: no resources, no methods). * test: runtime-domain-audit fixtures — three the lane must reject, one it must accept The lane proves it sees before it is trusted: `undeclared_extern.w` (a libc seam with no row), `no_facade.w` (foreign symbols, no facade), `missing_domain.w` (a facade that leaves one libc domain undeclared) each start with `//! expect-violation: <text>` the lane must report; `clean.w` (`//! expect-clean`) covers the runtime-internal externs the lane must ignore, the LLVM intrinsic, and comments inside the block. * build: runtime-domain-audit lane — a runtime foreign extern without a domain row is a red build (ruling §52) In the shape of libc-surface-check (build/compiler.w): for every rt/*.w, each foreign extern (@[link_name]/@[import_module], or a name outside rt_*/with_*) must have an `fn` row in the file's one `c facade` block, and the block must declare `domain errno thread`, `domain environ process`, `domain locale process`. The verdict names the extern, its C symbol and the facade the row belongs in. The compiler verifies what a row says when the file compiles; the lane verifies nothing is left unsaid. It then runs itself over test/runtime_domain_audit: each negative fixture must trip it and the clean one must pass, so a silent lane is itself red. A `:test` dependency beside libc-surface-check. * Sema: same-named domains of distinct facade blocks are one domain, a word-for-word restated fn item is one contract (ruling §35) With the runtime rows in, the dark rt-in-unit lane (WITH_RT_IN_UNIT, D30 R2b) parses every rt/*.w into one Sema and refused `domain errno thread` as "declared twice" — rt_core.w's block against darwin_aarch64.w's, and either against a program's libc facade — and then `fn rt_libc_exit` as "described twice" (four runtime files declare and describe that extern). Both refusals keyed identity by name across every facade in the unit. Ruling §35: a facade "may also merge domains from distinct imports when they refer to the same actual state". collect_facade_domain now merges a second declaration with the same name and scope into the first — every declaring block's functions touch the one domain (facade_domain_note_file consults the merged facade set) — refuses one block declaring it twice (identity is the block node, not the name: each runtime file's block is `libc`), and refuses a different scope: one state has one scope (§36). collect_facade_fn accepts a second block's word-for-word restatement of an fn item (the same facts, compared as words) and refuses different clauses: one function has one contract. Tests: behav_c_facade_domain_merged / err_c_facade_domain_merged_invalidated prove the merge is real (a bare fn in block B invalidates the text block A borrowed from errno); err_c_facade_domain_scope_conflict, err_c_facade_domain_twice, behav_c_facade_fn_restated, err_c_facade_fn_restated_differently pin the rest. `WITH_RT_IN_UNIT=1 with-stage1 check test/hello.w` is green again (green at the base, red with the rows before this). * LibcFacade: getenv does not preserve environ (C11 7.22.4.6p4) The toolchain libc facade stated `preserves domain environ` on `getenv`, so a program could hold one getenv view across a second getenv. C11 7.22.4.6p4: the returned string "may be overwritten by a subsequent call to the getenv function" — the second call invalidates the first view, and a `preserves` grants a capability the standard does not back (the ruling's test: never state what can create unsafety). The clause is deleted from `fn getenv` only; the runtime's own getenv rows (rt/*.w, ruling §52) already say the same. Every other row is unchanged. err_c_facade_getenv_view_invalidated pins the refusal; behav_c_facade_getenv_twice is the accepted spelling — copy the first out (`to_owned()`) before the second call. No existing fixture holds a getenv view across a second getenv (rg getenv test/ examples/ build/release_uat_fixtures/: two behavior tests, neither does). * contract-view snapshot: with stage 9 on main, create_function_v2 and trace_v2 present as methods (callback items render on the resource); the snapshot was recorded before #1606 landed * analyze: a semantic-snapshot request (contract, audit:contract) over a failed compilation is never ok — it prints the view and exits 1; the retained-no-owner contract fixture is a stage 9 compile error, so it becomes the refused-clause fixture --------- Co-authored-by: Eric Hartford <[email protected]>
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 9 of
docs/modeled-c-implementation-plan.md(ruling §44-§51; spec §16.2b.9-10), on top of stage 8 (main d783366). Two commits:Box.into_raw(std.box), then the stage.What lands
A callback contract — an fn item that retains a callback or its userdata (
retains … by param 0), consumes userdata with a destroy callback (consumes … destroyed_by), types a callback's userdata (callback param N userdata param M), or sayscallback_thread any— is rendered as a method of the resource its first parameter receives (compiler/FacadeRender.w facade_render_callback_methods), generic in the userdata typeU:extern "C" fn(&U, …): captureless (§12.4, D63 — C receives the code pointer alone); a bare fn or a captureless closure, checked against the callback type withUbound from the userdata argument whatever order C declares them (SemaCheck.wmethod-call path,SemaFacade.w facade_callback_expected_type);&U, borrowed for the call; an ephemeral view is accepted;mut fn … (app: U); the resource owns the userdata — boxed, handed to C as the cell's pointer — and its Drop releases every retained cell after the destroyer ran (the retaining origin never outlives what it retains, §25); a retained callback is a code pointer, nothing is kept for it;fn … (owned: U); the value moves into C in a Box cell and the compiler supplies the destroy fn forU(a captureless closure over the type parameter) in the withhelddestroyed_byparameter; With destroys it through no other path;&U), so a callback may read the resource through a view it was handed and can mutate nothing the exclusivity rules protect (behav_c_facade_callback_scopere-entersdb_totalthrough&Databasein the userdata);threadclause says (SemaCheck.w type_satisfies_thread_trait→facade_thread_caps_for): thread-bound by default,send(which requiresdrop_any_thread, stage 2's check) makes it Send,sharemakes it Sync, never inferred from the representation; aspawn_oscapture of a thread-bound resource names the facade's clause and the one to state;callback_thread any(§51): at each call the userdata type must be Send and Sync (facade_check_callback_arg).§61 verification added:
callback param N userdata param M(callable;void *; exactly onevoid *slot in the callback's signature; one userdata per item),consumesof avoid *with no destroy contract (never half-model, §9/§24),consumes … destroyed_byon anything but userdata, a userdata both consumed and retained,retains … bynaming a non-resource or a non-receiver parameter,retainsof anything but a callback / userdata / C string,callback_thread anyon an item with no callback, andcallback consumes(refused: not modeled). Every positional diagnostic prints the resolved C parameter (§57). The generic method's call effects (§38, stage 7) are attached to its concrete signature at the call (facade_note_callback_method_sig). Resolve adds the facade's std.box edge when an item keeps or hands C a userdata.Fixtures
Behavior:
behav_c_facade_callback_scope,_retained_callback,_consumes_destroyed_by,_thread_send,_callback_thread_any(headertest/behavior/c_facade_callbacks.h). Compile errors (exact text):err_c_facade_thread_bound_not_sent,_share_without_send_arc,_callback_thread_any_userdata_not_sync,_callback_capturing_closure,_retained_userdata_view(a callback-scope value cannot be retained past the call),_consumes_userdata_no_destroy,_userdata_consumed_and_retained,_callback_consumes_not_modeled,_callback_userdata_not_void,_callback_userdata_two_slots,_retains_by_non_resource. Debug-alloc:da_c_facade_consumed_destroyed_once,da_c_facade_retained_released_once(leak count=0; C destroys / the resource releases exactly once on every path). Flip:behav_c_facade_facts_verifyandbehav_c_facade_parsesdrop the clause combination that now contradicts itself (a userdata consumed and retained;callback consumes) and gain adb_watchitem with the retained/paired form.Verified with the stage1 built from this tree:
check src/main.wok;with build :devgreen; everybehav_c_facade_*,c_facade_*phase,err_c_facade_*/err_c_import_*andda_c_facade_*fixture green (thepre_d_build_runnerones need the release compiler, rc=127 on the base too;behav_c_facade_libc_system_headers/behav_c_import_overlay_memchrfail on the base identically — #1485).analyze audit:allon the new fixtures reports only #1300 (any std.box program). Battery not run.Derived decisions (the ruling is silent; each at worst removes capability)
callback param N userdata param M(ruling §45 pairs nothing; §24 pairs a destroy callback with its userdata by position). Typing avoid *as the caller'sUis capability-granting — a wrong pairing aliases a foreign object as a With value — so it is stated, never inferred from there being one callback and onevoid *. The userdata arrives in the callback's onevoid *parameter; a callback with several is refused. Adestroyed_bycallback needs no clause: its first parameter is the userdata (§24, verified since stage 2).extern "C" fnand only a captureless fn or closure coerces (§12.4/D63); state goes inU. Closures through the userdata slot (a per-signature extern "C" trampoline in codegen) are not built: D62's ownedmoveenvironment is not implemented yet (Amoveclosure sent to spawn_os keeps its environment in the caller's frame: a captured Drop value is destroyed on the creator thread after join, and one consumed inside the closure is dropped twice (D62, §12.4) #1605, A closure returned from a function reads its environment from the dead callee frame:fn mk(x: i32) -> fn() -> i32: () => x * 10gives garbage once mk is not inlined (§12.2 escaping closures) #1567, A closure returning a captured non-Copy local by value double-frees it (§2.3) #1481), so a retainedmove ||would be dropped from the caller's frame. The existing diagnostic stands ("capturing closure cannot coerce to extern "C" fn pointer"); themove ||fix-it named in the brief would mislead until the environment is owned.consumes … destroyed_bytransfers unconditionally. §24: "if registration can fail without taking ownership, the contract must state when transfer occurs; absent that evidence, With preserves caller ownership" — no clause spells conditional transfer, so the clause means C owns the value from the call on, whether or not the call reports success (sqlite3_create_function_v2's documented behavior). An API that keeps caller ownership on failure cannot be modeled yet; nothing is inferred.by param 0); by another parameter is refused, not silently a raw call. A retained C string keeps the Reject call-scoped str temporary for retained C-string params (§16.3c) #602 raw-call rule (not presented).callback consumes param N(§46) parses and is refused as not modeled — accepting it would have With release what the callback took.&Uuserdata there is nothing for the assertion to relax; a mutable re-entry is impossible by construction (the exclusivity error in the retained-view fixture's first draft:cannot mutate d while v is a live view into it).sharemakes the resource Sync;send(withdrop_any_thread) Send; ScopedSend follows Send (a scoped thread operates on the resource, so creator-bound stays out).callback_thread anyrequires the userdata Send and Sync (the callback reads it on any thread while the registering thread may hold it).Not implemented / found
moveclosure sent to spawn_os keeps its environment in the caller's frame: a captured Drop value is destroyed on the creator thread after join, and one consumed inside the closure is dropped twice (D62, §12.4) #1605 filed here: amoveclosure sent to spawn_os keeps its environment in the caller's frame; a consumed capture is dropped twice).behav_c_facade_thread_sendtherefore asserts the close after the frame and its closures only read their captures.callback consumes param N(§46): refused with a diagnostic, not modeled.const char *) stay C's types in the typed callback signature (noCStrpresentation inside callbacks); no unsafety, less capability.with -p's regex.replacereplaces the first match per line only (the sedgparity gap); noted, not filed here.