Skip to content

Modeled C stage 5: production and status (ruling §15-§19) - #1426

Merged
ehartford merged 4 commits into
mainfrom
modeled-c-stage5
Sep 23, 2026
Merged

ehartford merged 4 commits into
mainfrom
modeled-c-stage5

Conversation

@ehartford

@ehartford ehartford commented Sep 23, 2026 •

Copy link
Copy Markdown
Contributor

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 CONST projection (2026-09-23, on this PR).

Draft. Iterate-tier evidence only: :dev, :stage2, targeted tests, :move-audit and :drop-audit. No :fixpoint/:test battery has run. The branch is rebased on main at 04e4934. The seed is at 7c3ed983.

Naming. Stage 5 renders the imported C name: Database.sqlite3_open, Stream.inflateInit. Presentation is §16.2b.11 and belongs to stage 8 (prefix shortening to Database.open, and rename). Nobody should copy sqlite3_open as the final spelling. The renderer's doc comments and the fixtures say this too.

What each production form renders to

Direct return (4a/4c). A NULL return produced nothing. The facade's from is the trusted evidence that a non-null return is the resource (§19).

fn Database.db_new(flags: i32) -> Option[Database]:
    let repr = unsafe { db_new(flags) }
    if repr == null: None else: Some(Database { repr: repr, live: true })

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 yields Option[R].

fn Database.sqlite3_open(filename: str) -> (i32, Option[Database]):
    var slot: *mut sqlite3 = null
    let status = unsafe { sqlite3_open(filename, &raw mut slot) }
    (status, if slot == null: None else: Some(Database { repr: slot, live: true }))

Out parameter, with ok SQLITE_OK (the ruling). The low-level pair above is not rendered beside it: one call surface per production form.

type FailedDatabase { repr: *mut sqlite3 }
impl Drop for FailedDatabase:
    move fn drop():
        unsafe { sqlite3_close(self.repr) }
error DatabaseError =
    | Failed(status: i32)
    | FailedWithResource(status: i32, resource: FailedDatabase)
    | NothingProduced(status: i32)
fn Database.sqlite3_open(filename: str) -> Result[Database, DatabaseError]:
    var slot: *mut sqlite3 = null
    let status = unsafe { sqlite3_open(filename, &raw mut slot) }
    if status != SQLITE_OK:
        if slot == null: return Err(DatabaseError.Failed(status))
        return Err(DatabaseError.FailedWithResource(status, FailedDatabase { repr: slot }))
    if slot == null: return Err(DatabaseError.NothingProduced(status))
    Ok(Database { repr: slot, live: true })

In place, with ok Z_OK (the ruling). StreamError has only Failed(status). On a failed init the pinned Box cell is freed as ordinary storage, with no destruction call; this is the one such path. Without ok, a status-returning init still yields (status, R), and a void init yields R.

error StreamError =
    | Failed(status: i32)
fn Stream.inflateInit() -> Result[Stream, StreamError]:
    var repr = Box.new(z_stream {})
    let status = inflateInit(repr.as_mut_ptr())
    if status != Z_OK: return Err(StreamError.Failed(status))
    Ok(Stream { repr: repr, live: true })

Where this deviates from, or adds to, the ruling's sketch

  1. The FailedWithResource payload is FailedDatabase, not Database.
    • The ruling requires that a failed-state resource admit only the operations the facade marks valid on the failure state. Its conservative default is raw access only, with no auto-methods.
    • A payload of type Database would carry every Database lend method, so the failed state needs its own type.
    • FailedDatabase has no methods. Its Drop runs the facade's drop exactly once, and .repr is available under the raw C rules.
    • Calling a method on it is an error that says why, with a help line pointing at .repr. The variant names are exactly as ruled.
  2. An in-place resource's error has Failed only, with no NothingProduced. The ruling said "no FailedWithResource". For in-place init, ok status means the resource was produced, so NothingProduced can never be constructed. A variant that cannot occur would still have to be matched.
  3. The collision rule also covers R itself. It covers <R>Error and Failed<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.
  4. ok over 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:

  • out-parameter production over a by-value representation;
  • a const slot;
  • a raw parameter beyond the slot;
  • ok with a direct-return, void, or missing producer;
  • ok over a non-integer producer or init status;
  • statuses of different types.

Projection surface:

  • a method called on the failed state: err_c_facade_failed_state_no_methods;
  • a generated name colliding with a same-module type, an imported type, or another facade resource: err_c_facade_generated_name_{same_module,imported,facade_resource};
  • the low-level tuple spelling under ok: err_c_facade_ok_no_low_level_surface;
  • resource diagnostics point at the facade block: err_c_facade_resource_diag_location.

Behavior fixtures and witnesses

  • da_c_facade_error_owns_resource (debug-alloc lane; closes asserted inline; the translated C malloc/free are in the ledger):
    • FailedWithResource propagated by ? through two frames, then dropped: closed exactly once.
    • Matched and the FailedDatabase pushed into a Vec: closed once when the Vec drops.
    • Failed and NothingProduced: nothing to close.
    • Raw db_tag(failed.repr) compiles.
    • Leak count 0.
  • 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: the ok-less forms.
  • Flipped to the Result surface: behav_c_facade_resource_in_place_arming, da_c_facade_pinned_cell_destroy_then_free, c_facade_in_place_renders.
  • Real sqlite3.h (with get c.sqlite3 3.53.4, scratch project, not committed), with from sqlite3_open(out param 1) / drop sqlite3_close / ok SQLITE_OK:
    • open("/nonexistent/…")? returns Err(FailedWithResource(14, failed)).
    • A raw sqlite3_errmsg(failed.repr) returns "unable to open database file".
    • sqlite3_memory_used() returns exactly to its baseline once the error drops.
    • Under guard malloc the program exits 0. A raw double-close control crashes (rc=139).
    • --debug-alloc: leak count 0.

Evidence (iterate tier, new stage2)

Filed while doing this

Flip: none of the UAT/examples. The three flipped tests above are this stage's own 4b tests.

ehartford added a commit that referenced this pull request Sep 23, 2026
… 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]>
ehartford pushed a commit that referenced this pull request Sep 23, 2026
…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).
Eric Hartford added 4 commits September 23, 2026 01:12
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).
@ehartford

Copy link
Copy Markdown
Contributor Author

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 / da_option_filter_observes_payload — main's known #1424 red, fixed by stack #1437. Stays draft until Eric blesses the two §16.2b.4 amendments this implementation needs (FailedDatabase as the failed-state type; the in-place ok error has only Failed); then it conforms.

ehartford added a commit that referenced this pull request Sep 23, 2026
… 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]>
@ehartford

Copy link
Copy Markdown
Contributor Author

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.

@ehartford
ehartford marked this pull request as ready for review September 23, 2026 12:43
@ehartford
ehartford merged commit ba2d5d1 into main Sep 23, 2026
@ehartford
ehartford deleted the modeled-c-stage5 branch September 23, 2026 12:44
@ehartford

Copy link
Copy Markdown
Contributor Author

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.

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.

1 participant