Repository navigation
Modeled C stage 6: dependency (ruling §26-§30) - #1519
Merged
Merged
Conversation
added 2 commits
September 23, 2026 17:28
A producer that receives modeled resources now gets its constructor, and
what it produces depends on them (spec §16.2b.6: "unknown independence
means dependency"). Stage 5 rendered no constructor for such a producer and
warned at the resource; that warning is replaced.
Rendering (compiler/FacadeRender.w). A received resource is presented to
the constructor as a borrow `&P` and handed to C as `p.repr` (or the pinned
cell's address); the raw handle of a modeled resource is never a
constructor parameter. A dependent resource is the plan's ephemeral struct
holding a view of each parent:
type Statement = ephemeral { parent: &Database, repr: *mut sqlite3_stmt, live: bool }
fn Statement.sqlite3_prepare_v2(db: &Database, zSql: str, nByte: c_int, pzTail: *mut *const i8) -> (c_int, Option[Statement]):
var slot: *mut sqlite3_stmt = null
let status = unsafe { sqlite3_prepare_v2(db.repr, zSql, nByte, &raw mut slot, pzTail) }
(status, if slot == null: None else: Some(Statement { parent: db, repr: slot, live: true }))
so the ordinary origin and ephemeral analysis (§21.1, §22) enforces the
dependency; no reference count or generation check is added (ruling §29).
`independent` renders an ordinary resource; `borrows param N` names
exactly the parents of the producer stated before it (a `from` or the
`init`); several parents are several view fields; a parent some producers
lack is `Option[&P]`; an in-place resource's `init` may receive its parent.
Facts and verification (SemaFacade.w, ruling §61, §57). `borrows` names a
parameter of the producer before it and never its out slot or storage;
the parameter must receive a modeled resource (With does not invent an
origin, §16.2b.7); `independent` with `borrows` is refused; a received
representation several resources wrap names the candidates; a received
shape a borrow cannot present (a pointer to a pointer resource's handle, a
pinned representation by value) and a `preinit` receiving a resource are
errors naming the resolved C parameter. A net checks the rendered type is
ephemeral exactly when the facts say the resource is dependent.
The call site publishes the parent origin. A constructor's effect summary
is inferred from its body, and the rendered constructors are spliced after
every user declaration, so every call was checked before the body it
calls and tied nothing (#1473 is the general declaration-order bug). The
facade states the dependency, so the constructor's signature carries it as
a declared summary (apply_facade_dependency_effects), the way D39 declares
an interface's origin.
Diagnostics (§8, §57). Rule 6, Rule 7, the returned-view escape and the
mutation-while-viewed errors on a value carrying a dependent facade
resource add what it depends on, the producer, the resolved C parameter
and the evidence ("stated by 'borrows param 0' in facade sqlite" or
"conservative default of facade dbf: unknown independence means
dependency"), and, for a conservative dependency, the `independent` /
`borrows` help (§8's own example).
Rule 7 (Sema.w). "Implicit drop is a use" now covers a view binding whose
type carries a Drop value — `Option[S]`, `(i32, Option[S])`, `Vec[S]` of an
ephemeral Drop `S` — not only `S` itself: an `Option[Statement]` declared
before its database was accepted and finalized after the close. A move or
consumption of the origin (`drop(db)`, `let moved = db`, a `move fn`
destroyer) is reported at the move ("after `db` is moved"); it was reported
at the view's declaration with the origin's symbol id as the node.
Ruling §30. A type storing a dependent resource is the §5 ephemeral-storage
error, reported for a facade resource with its dependency and a fix that
compiles: `type App { db: Database, stmt: Statement }` gets
"help: borrow the parent instead of owning it, so App lives no longer than
it: `type App = ephemeral { db: &Database, stmt: Statement }`".
Not rendered, and said so loudly (open questions for a ruling):
- `ok` on a dependent resource's out-parameter producer: its
failed-but-produced resource would be a dependent value inside
`<R>Error.FailedWithResource`; no constructor, warning at the resource.
- `returns borrow R from param N`: collected and verified, but the
borrowed modeled value has no With type; the operation stays raw C,
warning at the fn item.
Tests: behav_c_facade_child_drop_order (destroy-order witness on every
path), behav_c_facade_dependency_forms (independent, borrows, two parents,
optional parent, in place), behav_c_facade_statement_cache (§30's cache
and the App fix-it compile and run), da_c_facade_child_before_parent
(debug allocator, leak count 0, order asserted), 22 compile-error fixtures
(Rule 6/7 at the right site with §57 notes, §30, §61), two pure-With Rule
7 fixtures; behav_c_facade_pending_producer_warns rewritten for the new
warnings; behav_c_facade_parses/_facts_verify stop combining
`independent` with `borrows` on one resource.
…ders `Borrowed<R>` (ruling §18, §26) The two surfaces the first stage-6 commit left unrendered, resolved from existing canon (Eric, 2026-09-23, on #1519). `ok` on a dependent resource's out-parameter producer (ruling §18: "A facade-specific error type may itself temporarily own the failure-state resource where required"). The generated `<R>Error` never owns a dependent child: an error escapes scopes and a dependent value cannot, so it is not required here and cannot be done. D51's asymmetry test settles the fallback — a failing call that still produced a child has it destroyed at once by the facade's `drop`, exactly once, and returns `Err(Failed(status))`; a NULL slot with a failed status is `Failed`; success with NULL is `NothingProduced`. So `ok SQLITE_OK` on `sqlite3_prepare_v2` renders `Result[Statement, StatementError]` with `StatementError = Failed | NothingProduced` and no `FailedStatement`: fn Statement.sqlite3_prepare_v2(db: &Database, zSql: str, nByte: c_int, pzTail: *mut *const i8) -> Result[Statement, StatementError]: var slot: *mut sqlite3_stmt = null let status = unsafe { sqlite3_prepare_v2(db.repr, zSql, nByte, &raw mut slot, pzTail) } if status != SQLITE_OK: if slot == null: return Err(StatementError.Failed(status)) unsafe { sqlite3_finalize(slot) } return Err(StatementError.Failed(status)) if slot == null: return Err(StatementError.NothingProduced(status)) Ok(Statement { parent: db, repr: slot, live: true }) The stage-5 "no constructor is rendered" warning is gone with the pending producer it reported. `returns borrow R from param N` (ruling §26: "The result: has no Drop; cannot outlive the named origin; cannot independently be consumed or destroyed. Nullable borrowed returns become Option of the borrowed modeled value"). The borrowed modeled value is the distinct type `Borrowed<R>` (D59's precedent): ephemeral, holding a view of the resource param N receives, carrying R's lend methods over the same `repr` and none of its destroyers or Drop; the operation is a lend method of the resource its first parameter receives, returning `Option[Borrowed<R>]`: type BorrowedDatabase = ephemeral { origin: &Statement, repr: *mut sqlite3 } impl BorrowedDatabase: fn sqlite3_errmsg() -> *const i8: unsafe { sqlite3_errmsg(self.repr) } impl Statement: fn sqlite3_db_handle() -> Option[BorrowedDatabase]: let repr = unsafe { sqlite3_db_handle(self.repr) } if repr == null: None else: Some(BorrowedDatabase { origin: self, repr: repr }) Verified (§61): the origin parameter receives exactly one resource, the first parameter does (so the operation has a resource to be a method of), and every item borrowing R names one origin resource — `Borrowed<R>` holds one view type, and a borrowed value with several origin types is refused rather than given a second type. `Borrowed<R>` joins the generated names a same-named type collides with. The net checks the type and the method were rendered, and the method's signature carries the origin as a declared summary, as the constructors do. Rule 6/7 and outlive errors on a borrowed value name what it is borrowed from and the clause (§8, §57). Two analysis fixes the borrowed value needed, both general: - A call result depends on a VALUE argument's own storage (record_call_view_origins): the root was added only when the argument had no origins of its own, so a view returned from a method of an ephemeral value — a statement's borrowed database, a token from a `Parser` value — depended on the value's origins and not on the value, and outlived it (§21.1 Rule 6, §5.5). A reference argument stays transparent. Pure-With repro: `s.view()` on an ephemeral Drop `s`, `drop(s)`, use the view — accepted before. - Rule 7's "Drop value" test sees no destructor through a reference (type_owns_user_drop): `type_has_drop_impl(&W)` answers as for `W` (get_type_name looks through references, #1492), so a non-Drop view holding `&Statement` was reported as an implicit drop; it is reported as a view that outlives its origin. Tests: behav_c_facade_dependent_ok (each outcome with the destroy-order witness; `?` chains), da_c_facade_dependent_ok_failure_destroyed_once (debug allocator: a failure that produced is finalized exactly once, leak count 0, order asserted), behav_c_facade_borrowed_return (borrowed database through a statement; nullable → Option; no close through it), five borrowed-return compile-error fixtures (outlives its origin, origin dropped with the §57 note, destroyer not presented, stored in a struct, origin not a resource, two origin resources); behav_c_facade_pending_producer_warns rewritten: the check runs warning-free and `Row.rw_open` is a `Result[Row, RowError]`.
ehartford
force-pushed
the
modeled-c-stage6
branch
from
September 23, 2026 22:24
e0c4832 to
f55dff7
Compare
Contributor
Author
|
Battery green — head f55dff7 (rebased on main 02301f8, no diff change), driven by the pinned seed with a cold c_import cache, audits included because stage 6 adds ownership surfaces ( Ready to merge. |
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.
Modeled C stage 6 (docs/modeled-c-implementation-plan.md; ruling §26–§30, §8, §57, §60, §61, §65; spec §16.2b.6, §21.1 Rules 6/7, §22).
Draft. Iterate-tier evidence only (
:dev, targeted tests,:move-audit,:drop-audit). No:fixpoint/:testbattery has run. Stage 6 is alone in its batch (ownership analysis). Two commits, based on main at 02301f8; the seed is 7c3ed983.What a dependent producer renders to
Stage 5 rendered no constructor for a producer that receives another resource, and warned at the resource. It now renders one. The received resource is a borrow
&P, handed to C asp.repr. The product is the plan's ephemeral struct, holding a view of each parent. Against the realsqlite3.h, with the ruling's own clauses (from sqlite3_prepare_v2(out param 3)/drop sqlite3_finalize/borrows param 0):Because the dependency is an ordinary view, the ordinary analysis enforces it. The child is destroyed before its parent on every path. It cannot be returned past the parent or stored where the relationship is lost. The parent cannot be moved, destroyed or replaced while the child lives. No reference count or generation check is added (ruling §29).
The forms of dependency:
independentrenders an ordinary, storable resource.borrows param Nnames exactly the parents of the producer stated before it: afrom, or theinit.parent_0,parent_1).Option[&P].initmay receive its parent.The call site publishes the parent origin (the plan's "one gap"). A constructor's effect summary is inferred from its body. The rendered constructors are spliced after every user declaration, so every call to one was checked before its body: the summary was empty, and the dependency was not enforced. That is a general declaration-order bug, filed as #1473. The facade states the dependency, so the constructor signature now carries it as a declared summary, the way D39 declares an interface's origin.
Diagnostics (§8, §57)
Rule 6, Rule 7, returned-view escape, and mutation-while-viewed errors on a facade child now add:
independent/borrowshelp (§8's own example).For example, against the real
sqlite3.h:Without
borrows, the note reads "conservative default of facade dbf: unknown independence means dependency", and a help namesindependent.Two Rule 7 changes, both general and not facade-only:
Option[S],Vec[S]and tuples of it, not onlySitself. Before, anOption[Statement]declared before its database was accepted, and its statement was finalized after the close. Pure-With fixture:err_implicit_drop_option_view_declared_before_origin.dbis moved"). Before, it was reported at the view's declaration, and the origin's symbol id was passed where a node belonged.§30.
The fix-it compiles and runs (
behav_c_facade_statement_cache).§61 checks (each one a compile-error fixture)
borrowsnaming a parameter that receives no modeled resource: "With does not invent an origin" (§16.2b.7).borrowsnaming the out slot.independenttogether withborrows.preinitthat receives a resource.Each of these prints the resolved C parameter. A net under the renderer also requires that the rendered type is ephemeral exactly when the facts say the resource is dependent.
The two open surfaces, rendered per existing canon (commit 2)
Eric's reading of the canon (2026-09-23, on this PR): both are answered by the ruling as written.
1.
okon a dependent producer. Ruling §18: "A facade-specific error type may itself temporarily own the failure-state resource where required." It is not required here and cannot be done: an error escapes scopes, a dependent value cannot. So the generated<R>Errornever owns a dependent child. D51's asymmetry test settles the fallback: a failing call that still produced a child has it destroyed at once by the facade'sdrop(exactly once;da_c_facade_dependent_ok_failure_destroyed_oncewitnesses it under the debug allocator) and returnsErr(Failed(status)); a NULL slot with a failed status isFailed; success with NULL isNothingProduced. Against the real header,ok SQLITE_OKonsqlite3_prepare_v2renders:Real header:
SELEKT nonsensegivesFailed(1),""givesNothingProduced(0), a?chain works, memory returns to baseline, leak count 0. The stage-5 warning is gone.2.
returns borrow R from param N. Ruling §26: "The result: has no Drop; cannot outlive the named origin; cannot independently be consumed or destroyed. Nullable borrowed returns become Option of the borrowed modeled value." With D59's distinct-type precedent, the borrowed modeled value isBorrowed<R>: ephemeral, holding a view of the resource param N receives, carrying R's lend methods and none of its destroyers or Drop; the operation is a lend method of the resource its first parameter receives, and its result isOption[Borrowed<R>](unknown nullability is nullable, §16.2b.8):Real header:
stmt.sqlite3_db_handle()thensqlite3_errmsgthrough it prints "not an error";back.sqlite3_close_v2()is "unknown method for type 'BorrowedDatabase'"; keepingbackpaststmt's scope is the Rule 6 error anddrop(stmt)whilebackis used is the outlive error, each with the note "'BorrowedDatabase' is borrowed from the 'Statement' that 'sqlite3_db_handle' receives as param 0: *mut sqlite3_stmt p0 — stated by 'returns borrow Database from param 0' in facade sqlite". §61: the origin parameter and the first parameter each receive exactly one resource, and two items borrowing R from different resources are refused (oneBorrowed<R>, one origin type) rather than given a second type.Two general analysis fixes this needed:
record_call_view_originsadded the argument's root only when the argument had no origins of its own, so a view of an ephemeral receiver depended on the receiver's origins and not on the receiver, and outlived it. Pure-With repro (err_view_of_ephemeral_receiver_outlives_it):s.view()on an ephemeral Drops,drop(s), use the view — accepted before.type_owns_user_drop):type_has_drop_impl(&W)answers as forW(A&Pfield of amut selfreceiver is moved and blanked whenP: Drop— readingself.dbinto a child nulls the receiver's field (segfault) #1492's mechanism), so a non-Drop view holding&Statementwas reported as an implicit drop.Behavior fixtures and witnesses
behav_c_facade_child_drop_order. A counting C header,test/behavior/c_facade_children.h, logs every finalize and close, and each close records the statements still open. A finalize reads its database, and a closed database is marked. The statement is finalized before its database on every path:?;break;behav_c_facade_dependency_forms:independentsnapshot is kept past its database and stored in a struct;borrows param 0, the second database closes while the link lives;behav_c_facade_statement_cache. Ruling §30's compatible pattern: a cache that borrows the connection and owns its statements serves repeats from the cache, and finalizes everything before the close.da_c_facade_child_before_parent(debug-alloc lane). The same paths run under the debug allocator. The order is asserted and the leak count is 0.behav_c_facade_dependent_okandda_c_facade_dependent_ok_failure_destroyed_once(commit 2): every outcome of anokproducer of a dependent child, with the destroy-order witness; a failure that produced is finalized exactly once under the debug allocator.behav_c_facade_borrowed_return(commit 2): a borrowed database through a statement; nullable becomesOption; nothing is closed through it.behav_c_facade_pending_producer_warnsnow pins that the check runs warning-free, that a dependent producer has a constructor, and thatRow.rw_openis aResult[Row, RowError].behav_c_facade_parsesandbehav_c_facade_facts_verifyno longer stateindependentbesideborrowson one resource. That combination is now an error.sqlite3.h(with get c.sqlite33.53.4, scratch project, not committed;build/release_uat_fixtures/andexamples/untouched, §66):SELECT sum(v)returns 49.sqlite3_memory_used()returns exactly to its baseline after the scope, and again afterdb.sqlite3_close_v2()following a finalize.SQLITE_BUSY(5).--debug-allocreports leak count 0, and the program exits 0 under guard malloc.drop(db),db.sqlite3_close_v2(), returning the statement, andtype App { db, stmt }are each refused with the note namingparam 0: *mut sqlite3 db — stated by 'borrows param 0' in facade sqlite.Evidence (iterate tier, stage1 at this commit)
:dev(seed to stage1) and the fullbuildchain, which:move-auditand:drop-auditdepend on (seed, stage1, stage2, release), both pass.*c_facade*tests (behavior, compile_errors, phase, debug_alloc) plus six Rule 6/7 tests pass on the release binary, 130/130. On stage1,behav_c_facade_libc_system_headersfails exactly as on main (memchr), and the p7 runner fixture needs stage2.test/, run on stage1 against main's stage1 (ba2d5d1). This PR fails nothing that passes on main: 197 pass here, 190 on main. The 51 that still fail here also fail on main, mostlyd_acceptanceandnon_compliant/d22under the stage1 runner.debug_drop check(release) over the six facade fixtures: PASS, leak count 0.:move-audit(rerun after commit 2): 73 cells, 0 FAIL against expectations. It also shows 42 DIFF against the seed baseline: all of them arefield_*cells where the seed predates the strict field-move rule. The candidate's verdict columns are byte-identical to main's stage1 run with the same seed.:drop-audit(rerun after commit 2): 176 cells, 0 non-PASS, 0 regressions.analyze audit:all: passes onbehav_c_facade_child_drop_order,behav_c_facade_statement_cache,behav_c_facade_dependent_ok,behav_c_facade_borrowed_returnandda_c_facade_child_before_parent.behav_c_facade_dependency_formshas one violation: theBox.dropreceiver violation (analyze audit:all reports two pre-existing violations on any program that uses std.box (with_free marshalling fact, sig receiver requirement) #1300), which main reproduces onbehav_c_facade_resource_in_place_pinned.examples/**/*.wgive the samewith checkverdicts as on main.Filed while doing this
&Pfield of amut selfreceiver is moved and blanked whenP: Drop— readingself.dbinto a child nulls the receiver's field (segfault) #1492. A&Pfield of amut selfreceiver is moved and blanked whenP: Drop. Readingself.dbinto a child in amut fnnulls the field, and the next use segfaults. This is pre-existing and reproduces without facades.move _1.dbfollowed by_1.db = const zst. With a non-DropDbit iscopy _1.db.&*self.db.nullas a method-call argument gets no pointer type context: 's.m(null)' / 'S.k(null)' → 'null requires pointer type context' #1496.nullas a method-call argument gets no pointer type context (s.m(null),S.k(null)).with run/build(correct underwith check) #1498. Facade warnings point atfile:1:1underwith run/build, thoughwith checkplaces them correctly. Pre-existing since stage 5.Database.sqlite3_prepare_v2(…, ppStmt, …)).if v[i]:over a Vec[bool] element is rejected: 'if condition must be bool' (D22 contextual Copy not applied to conditions) #1472.if v[i]:over aVec[bool]element is rejected. The renderer binds a typed local instead.Flip: none. UAT fixtures and examples are untouched, and the spec is untouched.