Repository navigation
Modeled C stage 5: production and status (ruling §15-§19) - #1426
Conversation
… generated error owns a failed-but-produced resource (#1427) Blessed by Eric 2026-09-23. RError is a generated error declaration (Failed / FailedWithResource / NothingProduced); the error owns and destroys a failed-but-produced resource and ? moves that ownership; a resource owned by an error admits raw access only until the facade can mark failure-state operations; the generated name collides loudly; no (status, Option[R]) constructor under ok; in-place with ok frees the pinned heap cell with no destruction call on failure. PR #1426 (stage 5) conforms. Co-authored-by: Eric Hartford <[email protected]>
…er's resource is owned by the error (Eric's ruling on #1426) Eric, 2026-09-23, on #1426: 1. A producer under `ok CONST` returns `Result[R, <R>Error]`. "Status OK, nothing produced" violates the C contract: it is an Err, as its own variant. 2. `<R>Error` is a rendered `error` declaration, so it composes with §10.9 and gets Display/Debug: error DatabaseError = | Failed(status: i32) | FailedWithResource(status: i32, resource: FailedDatabase) | NothingProduced(status: i32) The payload is `FailedDatabase`, not `Database`. The ruling's other requirement forces this: a failed resource admits only the operations the facade states are valid on the failure state, and no clause for that exists yet, so it admits none. The failed state is therefore rendered as its own type: type FailedDatabase { repr: *mut sqlite3 } impl Drop for FailedDatabase: move fn drop(): unsafe { sqlite3_close(self.repr) } It has no lend methods and no destroyers, only raw access to `.repr`. Its Drop runs the facade's `drop` exactly once, whether the error drops or whatever took the handle out of it drops. Calling an auto-method on it is an error that names the failure-state rule. A type named `<R>Error` or `Failed<R>` (or `R`) that the facade's module declares or imports is an error naming both declarations: the §10.9 written-variant collision rule at the type level. The prelude's implicit names are not imports (D29). 3. In-place `init` under `ok` has the same projection. The error has only `Failed(status)`, because a failed init produced nothing (§16.2b.3: "Drop is armed only when initialization establishes production"). This closes the hole where a failed init still handed back a dead `R` whose `destroys` methods ran the C destroyer on storage C never initialized. On failure a pinned resource's Box cell is freed with no destruction call; that is the one such path, and it is commented in facade_render_init. 4. Under `ok` the low-level `(status, Option[R])` constructor is not rendered: one call surface per production form. Without `ok` it stays. (Several success constants: #1432.) 5. Constructors keep the imported C name (`Database.sqlite3_open`). Presentation (`Database.open`) is §16.2b.11, stage 8. The comments say so. `ok` over several producers requires one status type, since there is one error type. Flipped (4b's `ok` in-place tests, now on the Result surface): - behav_c_facade_resource_in_place_arming; - da_c_facade_pinned_cell_destroy_then_free; - c_facade_in_place_renders (phase). behav_c_facade_pending_producer_warns now pins that `ok` draws no warning. New: - da_c_facade_error_owns_resource (debug-alloc lane, leak count=0, closes asserted inline): FailedWithResource propagated by `?` through two frames and then dropped closes once; matched and taken out, closed once by its new owner; Failed / NothingProduced close nothing; raw `db_tag(failed.repr)` compiles. - da_c_facade_failed_init_frees_cell: three failed inits, destroyer count 0, cells freed (leak count=0). - err_c_facade_{failed_state_no_methods, generated_name_same_module, generated_name_imported, generated_name_facade_resource, ok_no_low_level_surface, ok_status_types_differ}. §10.9 composition (`error AppError from DatabaseError`) is not in the fixture. Codegen mis-lays-out an enum whose payload type is declared later, and the rendered error is always later than the user's AppError (#1430).
3767cca to
7bb50f7
Compare
verify_facade_resources ran after pass 3 had moved the source context to the last declaration it visited — a rendered `<facade NAME>` file — so every resource-level diagnostic (a producer with no drop, a destroyer callable as a lend, a raw producer, ...) printed `--> <facade dbl>:8:1` and quoted a line of the rendering. Each resource now records its facade block's declaration index and the check sets the context to it (ruling §8: diagnostics carry the fact's provenance). Test: err_c_facade_resource_diag_location pins the resource's own file:line:col (the baseline stage1 printed <facade dbl>:8:1).
The rendered constructors bind locals — a direct-return producer's
`repr`, an in-place initializer's `repr` storage and `status` — and
spelled the C parameters as the header does, so a C parameter named
`repr` or `status` collided: With refuses shadowing, and the stage-4b
init constructor failed to check ("shadowing is not allowed for 'repr'",
then the Box handed to C as the int argument) for a facade that is
valid. facade_render_fresh picks a local name none of the constructor's
parameters uses; the names come from facade_render_param_names, the
same `__param_`-stripped spelling the parameters render with.
Test: behav_c_facade_production_local_names (a direct-return producer
taking `repr`, an in-place init taking `repr` and `status`; each
argument reaches C as written).
…get no constructor (ruling §15-§18)
Out-parameter production (ruling §16, spec §16.2b.4). `from p(out param N)`
now renders a constructor that initializes the slot to NULL, calls, and
inspects the slot: non-null is a produced resource owned at once, null is
none. That is production, not success, so with no status convention the
status is handed back unread beside it:
fn R.p(<params but the slot>) -> (S, Option[R]):
var slot: Repr = null
let status = unsafe { p(<args>, &raw mut slot, <args>) }
(status, if slot == null: None else: Some(R { repr: slot, live: true }))
A void producer yields `Option[R]`. A failed call that still produced (a
failed sqlite3_open's handle, ruling §18) is `(status, Some(r))`: the
caller owns it and its Drop runs the destroyer exactly once.
Verification (§61 "producer return/out parameter matches", "status
constant is compile-time"; spec §16.2b.13):
- out-parameter production over a by-value representation is an error:
it has no NULL to inspect; the help names `init <fn>(self)`;
- a slot C cannot write (`db * const *`) is an error;
- an out-parameter producer still raw beyond its slot (an undescribed
`int *`, a raw status return) is an error, as a direct-return one was;
- `ok` with no producer that returns a status (only direct returns, a
void out-parameter producer, no producer) is an error, and `ok` over a
non-integer status (producer or init) is an error.
Dependent producers (spec §16.2b.6, "unknown independence means
dependency"). A producer that receives a resource's representation, or
whose resource states `borrows`, produces a dependent resource; dependency
is the plan's stage 6. Before this, a direct-return producer under
`borrows param 0` rendered a constructor that dropped the dependency —
`Tokens.tk_new(text)` could outlive the text it borrows (checked on the
baseline stage1) — and a direct-return child was refused with advice
("describe it with an fn item") no fn item could satisfy. Such a producer
now renders no constructor and the resource says why, with the resolved C
parameter (§57), as a warning: the program is still correct without the
constructor and nothing unsafe is exposed.
`ok` over a status-returning out-parameter producer: its Result-shaped
projection (§16.2b.4) is not yet ruled, so that producer renders no
constructor and the resource says so. (The low-level constructor without
the projection would leave the clause unread.)
The net: every producer of a verified resource has its `R.<producer>` or
is one of those pending cases; anything else is a loud renderer defect.
FacadeRender.w facade_render_producer_pending and SemaFacade.w
facade_producer_pending make the same classification.
Tests:
- behav_c_facade_out_param_production: success with a handle, failure
with none, failure that still produced (closed once by Drop), success
that produced nothing, a void producer, moves through calls; the C side
counts closes and non-NULL slots on entry (0);
- behav_c_facade_production_local_names gains the out-parameter case
(a slot named `slot`, a parameter named `status`);
- da_c_facade_production_forms (debug-alloc lane, leak count=0): all three
forms with the C bodies translated into the program, so the
representation's malloc/free are in the ledger — a missed destroy is a
LEAK, a second one a DOUBLE FREE (both confirmed by negative controls);
- behav_c_facade_pending_producer_warns (stage2 p7 runner): the
dependency and `ok` warnings, and `Database.db_new` still rendered;
- err_c_facade_{out_param_by_value_repr,out_param_const_slot,
out_producer_still_raw,ok_direct_return,ok_void_out_producer,
ok_status_not_integer,ok_init_status_not_integer,ok_no_producer}: each
accepted silently by the baseline stage1.
…er's resource is owned by the error (Eric's ruling on #1426) Eric, 2026-09-23, on #1426: 1. A producer under `ok CONST` returns `Result[R, <R>Error]`. "Status OK, nothing produced" violates the C contract: it is an Err, as its own variant. 2. `<R>Error` is a rendered `error` declaration, so it composes with §10.9 and gets Display/Debug: error DatabaseError = | Failed(status: i32) | FailedWithResource(status: i32, resource: FailedDatabase) | NothingProduced(status: i32) The payload is `FailedDatabase`, not `Database`. The ruling's other requirement forces this: a failed resource admits only the operations the facade states are valid on the failure state, and no clause for that exists yet, so it admits none. The failed state is therefore rendered as its own type: type FailedDatabase { repr: *mut sqlite3 } impl Drop for FailedDatabase: move fn drop(): unsafe { sqlite3_close(self.repr) } It has no lend methods and no destroyers, only raw access to `.repr`. Its Drop runs the facade's `drop` exactly once, whether the error drops or whatever took the handle out of it drops. Calling an auto-method on it is an error that names the failure-state rule. A type named `<R>Error` or `Failed<R>` (or `R`) that the facade's module declares or imports is an error naming both declarations: the §10.9 written-variant collision rule at the type level. The prelude's implicit names are not imports (D29). 3. In-place `init` under `ok` has the same projection. The error has only `Failed(status)`, because a failed init produced nothing (§16.2b.3: "Drop is armed only when initialization establishes production"). This closes the hole where a failed init still handed back a dead `R` whose `destroys` methods ran the C destroyer on storage C never initialized. On failure a pinned resource's Box cell is freed with no destruction call; that is the one such path, and it is commented in facade_render_init. 4. Under `ok` the low-level `(status, Option[R])` constructor is not rendered: one call surface per production form. Without `ok` it stays. (Several success constants: #1432.) 5. Constructors keep the imported C name (`Database.sqlite3_open`). Presentation (`Database.open`) is §16.2b.11, stage 8. The comments say so. `ok` over several producers requires one status type, since there is one error type. Flipped (4b's `ok` in-place tests, now on the Result surface): - behav_c_facade_resource_in_place_arming; - da_c_facade_pinned_cell_destroy_then_free; - c_facade_in_place_renders (phase). behav_c_facade_pending_producer_warns now pins that `ok` draws no warning. New: - da_c_facade_error_owns_resource (debug-alloc lane, leak count=0, closes asserted inline): FailedWithResource propagated by `?` through two frames and then dropped closes once; matched and taken out, closed once by its new owner; Failed / NothingProduced close nothing; raw `db_tag(failed.repr)` compiles. - da_c_facade_failed_init_frees_cell: three failed inits, destroyer count 0, cells freed (leak count=0). - err_c_facade_{failed_state_no_methods, generated_name_same_module, generated_name_imported, generated_name_facade_resource, ok_no_low_level_surface, ok_status_types_differ}. §10.9 composition (`error AppError from DatabaseError`) is not in the fixture. Codegen mis-lays-out an enum whose payload type is declared later, and the rendered error is always later than the user's AppError (#1430).
|
Battery (seed-driven, new seed, with :drop-audit/:move-audit) rebased on main (head 836bb35, pushed): build ok, :fixpoint ok, :drop-audit ok, :move-audit ok; :test red only on debug-alloc-tests / |
7bb50f7 to
836bb35
Compare
… with no methods; an in-place ok error has only Failed (#1468) Blessed by Eric 2026-09-23, from implementing the ok projection (#1426): a Database payload could be moved out of the error with every method, so raw-access-only needs a distinct type; a successful in-place init always produced the resource, so NothingProduced cannot occur there. Co-authored-by: Eric Hartford <[email protected]>
|
Ready under the D56 rule: its battery (build, :fixpoint, :drop-audit, :move-audit green) had one :test red, main's known #1424, whose fix (#1425/#1428 in stack #1466) has since merged; the spec amendments it needs are blessed (#1468). A confirming battery on current main is running (build and :fixpoint already green); I'll post it here. |
|
Confirming battery (seed-driven, new seed, cold c_import cache, with :drop-audit/:move-audit) on main 0378a68 + stage 5 (4882b1e1): build ok, :fixpoint ok, :drop-audit ok, :move-audit ok, :test ok (no reds), :test-green ok, :last-green ok. Confirms the merge. |
Modeled C stage 5 (docs/modeled-c-implementation-plan.md; ruling §15–§19, §57, §61, §65; spec §16.2b.4, §16.2b.8, §16.2b.13), with Eric's ruling on the
ok CONSTprojection (2026-09-23, on this PR).Draft. Iterate-tier evidence only:
:dev,:stage2, targeted tests,:move-auditand:drop-audit. No:fixpoint/:testbattery has run. The branch is rebased on main at 04e4934. The seed is at 7c3ed983.What each production form renders to
Direct return (4a/4c). A NULL return produced nothing. The facade's
fromis the trusted evidence that a non-null return is the resource (§19).Out parameter, no
ok. Ruling §16: NULL slot, call, inspect. "(status, Option[Resource]) is meaningful even when the status convention is unknown". A void producer yieldsOption[R].Out parameter, with
ok SQLITE_OK(the ruling). The low-level pair above is not rendered beside it: one call surface per production form.In place, with
ok Z_OK(the ruling).StreamErrorhas onlyFailed(status). On a failed init the pinned Box cell is freed as ordinary storage, with no destruction call; this is the one such path. Withoutok, a status-returning init still yields(status, R), and a void init yieldsR.Where this deviates from, or adds to, the ruling's sketch
FailedWithResourcepayload isFailedDatabase, notDatabase.Databasewould carry everyDatabaselend method, so the failed state needs its own type.FailedDatabasehas no methods. Its Drop runs the facade'sdropexactly once, and.repris available under the raw C rules..repr. The variant names are exactly as ruled.Failedonly, with noNothingProduced. The ruling said "noFailedWithResource". For in-place init,okstatus means the resource was produced, soNothingProducedcan never be constructed. A variant that cannot occur would still have to be matched.Ritself. It covers<R>ErrorandFailed<R>as ruled, and additionally a user type named like the resource. That collided silently since 4a, with the last declaration winning. Duplicate type declarations in general are still not diagnosed by the compiler; see "Filed" below.okover several producers requires one status type, because there is one error type. Fixture:err_c_facade_ok_status_types_differ.§61 checks (each one a compile-error fixture)
Out-parameter production and
ok:okwith a direct-return, void, or missing producer;okover a non-integer producer or init status;Projection surface:
err_c_facade_failed_state_no_methods;err_c_facade_generated_name_{same_module,imported,facade_resource};ok:err_c_facade_ok_no_low_level_surface;err_c_facade_resource_diag_location.Behavior fixtures and witnesses
da_c_facade_error_owns_resource(debug-alloc lane; closes asserted inline; the translated Cmalloc/freeare in the ledger):FailedWithResourcepropagated by?through two frames, then dropped: closed exactly once.FailedDatabasepushed into a Vec: closed once when the Vec drops.FailedandNothingProduced: nothing to close.db_tag(failed.repr)compiles.da_c_facade_failed_init_frees_cell: three failed pinned inits leave the destroyer count at 0 with every cell freed (leak count 0). A live stream is destroyed once.da_c_facade_production_forms,behav_c_facade_out_param_production,behav_c_facade_production_local_names: theok-less forms.behav_c_facade_resource_in_place_arming,da_c_facade_pinned_cell_destroy_then_free,c_facade_in_place_renders.sqlite3.h(with get c.sqlite33.53.4, scratch project, not committed), withfrom sqlite3_open(out param 1)/drop sqlite3_close/ok SQLITE_OK:open("/nonexistent/…")?returnsErr(FailedWithResource(14, failed)).sqlite3_errmsg(failed.repr)returns "unable to open database file".sqlite3_memory_used()returns exactly to its baseline once the error drops.--debug-alloc: leak count 0.Evidence (iterate tier, new stage2)
*c_facade*tests pass.*c_import*,*retain*andspec_ss16*tests, 88 pass. The one failure isd_acceptance/behav_retained_cstring_owned_ok, aprint_i32import error that fails the same way on main.debug_drop checkover the four facade debug-alloc fixtures: PASS.:move-audit: 15 cells, 0 FAIL, 0 DIFF.:drop-audit: 176 cells, 0 non-PASS, 0 regressions.analyze audit:allshows two kinds of violation on the new fixtures, and both reproduce without any facade on main:Box.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);?'s projection-type violation, which fires on any?over aResult(analyze audit:all fails on every ?? / unwrap_or: a downcast place typed as the enum vs codegen projecting the variant struct #1381, commented).bzip2_main.wruns "bzip2 UAT passed".sqlite3_main.wchecksok.build/release_uat_fixtures/andexamples/are untouched (§66).docs/with-specification.mdis untouched.Filed while doing this
Codegen.wdeclare_enum_type,abi_size_of(payload_ty)in declaration-order pass 0b.Outer.Inner(InnerE.A(7))reads back as 0. When it is a struct, the compiler hits an LLVMTypeSizecrash.<R>Erroralways follows the user'serror AppError from DatabaseError, so that composition hits the same bug and crashes codegen with a DisplayBUG:.enum Conn: Open(db: Database)crashes the compiler today (since stage 4).Dropvalue whose bytes are all zero looks like the reset sentinel. Its destructor is skipped, e.g.Fd { n: 0 }pushed into a Vec is never closed. Facades are safe by construction (live: true, and a non-NULL failed handle). This is the §2.5.1 mechanism, so it needs a ruling.okmay list several success constants (SQLITE_OK/ROW/DONE) #1432 — facadeokmay list several success constants (SQLITE_OK/ROW/DONE) (ruling §17). Not implemented.unsafe. This is the warning the fixtures print.errordeclaration's generated Display leaks, not only IoError's.Flip: none of the UAT/examples. The three flipped tests above are this stage's own 4b tests.