Skip to content

Facade grammar: a C struct the caller allocates and passes by pointer (z_stream, lzma_stream, SDL_Rect) is 'parameter of unmodeled pointer type': 1831 functions in 17 libraries stay raw #3173

Done

Description

@ehartford

Part of #3115; the largest cluster of the #3116 survey: 'parameter of an unmodeled pointer type: pointer to an unmodeled record', 1831 functions across 17 of 20 drafted libraries (zlib deflate/inflate on *mut z_stream_s, xz_utils, sqlite3, sdl, libuv, …). These records are not resources (no producer or destroyer in the package): the caller owns the struct's storage and the function reads or fills it. The facade needs a shape for a by-pointer value record (&T / &mut T of a plain C struct, an out-param of it), so such functions present safely without a resource contract.

Activity

  1. added
    bug
    on Nov 9, 2026
  2. ehartford commented on Nov 9, 2026

    @ehartford
    ContributorAuthor

    Decision brief for Eric (no spec words proposed; draft only)

    The gap. 1538 functions in 21 of 22 drafted libraries are raw only because a parameter is a pointer to a record that is not a resource (deflate(z_stream *), SDL_GetRectIntersection(const SDL_Rect *, …), uv_loop_init(uv_loop_t *)). Largest single cluster after #3206.

    Two facts first (D110/D111). What the callee does: reads and/or writes the caller's struct during the call; some also keep its address (zlib's deflateInit_ stores state->strm = strm). Identity: a SDL_Rect is a value; a z_stream between deflateInit and deflateEnd is a resource living in caller storage. So the cluster is two shapes:

    • A. Value record lent for the call (const SDL_Rect *, png_color *, struct timeval *): read, or filled, never kept.
    • B. Init/end resource in caller storage (z_stream, lzma_stream, uv_loop_t, yaml_parser_t): X_init(T *) produces in place, X_end(T *) destroys, the address is retained in between (the struct must not move).

    1. What the others do (verified in .reference/): Swift bridges inout X to UnsafeMutablePointer<X> and X to UnsafePointer<X> for the call (docs/TypeChecker.md, conversions list); the pointer is valid only for the call, retention is the programmer's problem. Go's cgo allows passing a Go pointer if C does not keep it (cmd/cgo/doc.go, "Go code may pass a Go pointer to C provided…"), checked dynamically. Zig coerces &x to [*c]T. Rust (bindgen) leaves *mut T raw and unsafe. None models shape B; all leave "do not move it, call end" to the caller.

    2. What the spec says. §16.2b.5 has one vocabulary, for resource parameters (lend / consumes / destroys / retains). §16.2b.8 models buffers (buffer param P capacity param L inout → []mut u8) and text. §16.2b.4 produces a resource by return or out param N — of a pointer, not of caller storage. §15.1: &mut T is not safe With; mutation is mut self, an owned parameter or a returned value. Nothing presents a pointer to a plain record; nothing presents a resource whose storage is the caller's struct.

    3. Mission fit. "Raw C stays explicit, modeled C becomes humane, the programmer never becomes the build system." Law 4: nothing about retention may be inferred from a name; a proof or a stated fact only. Shape A is decided by a proof the drafter already makes (no store, no retaining sink). Shape B is a destruction contract and must be stated or proven as a producer/destroyer pair, never guessed from _init/_end.

    4. Prediction (one, committed).

    • A, read-only (const T *, record complete in the installed headers, retention proven absent): presented as &T, automatically, no clause. If the proof is wrong the program is unsafe, but that is the same trust every proven lend already carries (§16.2b.5 "Lend"). 85%.
    • A, written (T * filled or updated, not retained): presented by the forms §15.1 already has — an out-only record becomes the return value; an in-out record makes the function a mut fn of that record (§16.2a auto-method), never a &mut T parameter. 70%.
    • B: a new resource form whose representation is the record itself in pinned With storage, produced by an init function writing through out param N, dropped by the end function; stated in the facade (drafted when the init/end pair is proven: init stores into it, end frees what init allocated), never from names. This needs spec words, so it waits for you. 75% that you want it as a resource and not as "the user keeps a z_stream and promises".

    If A is as predicted it is delegable under D98 only in its read-only half (easy to reverse, no new ownership rule); the written half and B touch ownership and stay yours.

  3. ehartford commented on Nov 9, 2026

    @ehartford
    ContributorAuthor

    Correction to the brief above: its last paragraph is wrong. D98 excludes C interop, ownership and safety, so no part of this is delegated; shape A (both halves) and shape B all wait for Eric's ruling.

  4. ehartford commented on Nov 10, 2026

    @ehartford
    ContributorAuthor

    Ruled by Eric, 2026-11-09 (D198, #3211). Shape A read-only: granted, with 'retention proven absent' including any pointer derived from the parameter (&rect->x kept in a static is retention). Shape A written: out-only becomes the return value; in-out becomes a mut fn of the record only when the record is no init/end resource (deflate(z_stream *) is shape B and must not be classified by this rule: check the record against the producer/destroyer pairs first). Shape B: granted, needs spec words: the resource is non-movable after production (a move is a compile error naming the init); the pair is stated or proven, never named (inflateInit/inflateEnd and deflateInit/deflateEnd over one z_stream are two resources); the pre-init value is a different type that init consumes, so reading a field before init is a type error.

  5. ehartford commented on Nov 10, 2026

    @ehartford
    ContributorAuthor

    Draft wording for blessing (D198; nothing below is implemented or merged)

    The ruling grants the behavior; a written facade still needs a way to say it, and §16.2b.11 a rule to present it. Draft, for Eric to edit or replace.

    §16.2b.5, a new paragraph after "Retain":

    Value records. A pointer parameter to a complete record that is not a resource's representation is described by what the callee does with the record:

    reads param 1                  // const T *: presented as &T
    fills param 2                  // T *, written, never read first: the operation returns T
    updates param 0                // T *, read and written: the operation is a mut fn of T
    

    Each asserts that the callee keeps neither the pointer nor any pointer derived from it (the address of a field kept in a static is retention). updates is refused when T is the representation of a resource (§16.2b.3): such a record is that resource, not a value. A draft states one of these only from a proof over the library's source (§16.2b.15); the parameter's spelling, const included, proves nothing about retention.

    §16.2b.11, one sentence: a reads parameter is a &T argument; a fills parameter leaves the parameter list and its record is the operation's result, beside a status result when the function returns one; an updates parameter is the receiver of a mut fn declared on T.

    Shape B (in-place resource), §16.2b.3, draft:

    In-place resources. resource R in T declares a resource whose representation is the record T itself, in storage With provides, produced by from init(out param N) and dropped as any resource is. Before production the storage is a T; production consumes it and yields R. An R is not movable: a move of it is an error that names the producing function. Two producer/destroyer pairs over one T are two resources.

    Open points I could not settle from the ruling: the spelling resource R in T; whether fills beside a status return is Result[T, E] under the facade's status rule or a tuple; whether "non-movable" is this resource form's property alone or a general pinned-value rule the storage-type campaign owns.

  6. ehartford commented on Nov 10, 2026

    @ehartford
    ContributorAuthor

    Words blessed by Eric and landed as spec v7.43 (D198's amendment). The draft above is superseded: keep the clause words (reads / fills / updates param N); resource R in T is dropped (the in-place form already exists); fills beside a status follows §16.2b.4 (Result[T, E] with ok, (status, T) without); nothing is made non-movable; one field per facts line; the hooks' context pointer is stated (field F of R is context). The compiler is NON-COMPLIANT until it implements them; implementation starts now.

  7. ehartford commented on Nov 10, 2026

    @ehartford
    ContributorAuthor

    Value records in a written facade are implemented (#3215, main 5daca38): reads (&T, or Option[&T] beside nullable), updates (a mut parameter), fills (the record joins the result under §16.2b.4's status rule), with the refusals §16.2b.5 states. Still to do: the drafter writing the clauses from proofs, so with get uses them (design notes in handoff.md: retention must cover pointers derived from the parameter, the record must have no identity anywhere in the package, and it must be complete in an installed header), and the contract view's rows.

  8. ehartford commented on Nov 10, 2026

    @ehartford
    ContributorAuthor

    A safety point the wording does not cover, found implementing the drafter half (for Eric).

    §16.2b.5 says each clause asserts that the callee keeps neither the pointer nor any pointer derived from it. It says nothing about a record that contains a pointer. freetype's FT_Outline_Get_CBox(const FT_Outline *) keeps nothing, so it would qualify as reads, yet its body follows outline->points. Presented as &FT_Outline, a safe call lets the caller choose where the callee reads: a With program can build an FT_Outline with any pointer in that field.

    What I did in the drafter (PR in flight): a draft states a value-record clause only for a flat record, one with no pointer or function pointer anywhere inside it (arithmetic types, enums, fixed arrays and defined records of such). That is conservative and enumerable, and it is the limit of what the draft can prove.

    What I did not do: change the checker. A hand-written reads param N on a record with a pointer field is still accepted, as the author's assertion. If you want that refused too, or want the paragraph to say the record's own pointers are the caller's responsibility, that is a sentence for §16.2b.5.

    Two other conditions the drafter adds beyond the words, both conservative: the record is complete in an installed header (or the user's import would not have it), and no function of the package produces, destroys or retains a pointer to that record type. The last one is broad: freetype stores FT_Vector arrays in an outline, so FT_Vector_Transform(FT_Vector *, const FT_Matrix *) stays raw although a single vector is a plain value. Telling an array pointer kept in a struct from one record's address kept by an init function is not something the evidence can do today.

  9. ehartford commented on Nov 10, 2026

    @ehartford
    ContributorAuthor

    Both halves are merged and measured (#3215 written facade, #3216 drafter; survey on main 5b952ef, table refreshed). 23 more functions present (1748 → 1771 of 7863): raylib +15, xz_utils +5, libuv +3.

    Why so few: of the functions raw for a record pointer,

    condition that failed functions libraries
    the record holds a pointer, or is not complete in an installed header 1406 18
    a unit of the package could not be read 142 3
    the record is a resource (something produces, destroys or retains a pointer to it) 39 4
    the body indexes it, moves the pointer, takes a part's address, or copies the pointer 13 1
    it is passed on to a function the proofs cannot clear 3 3

    The first row is where the cluster lives, and it is mostly shape B: z_stream, lzma_stream, bz_stream, uv_loop_t hold pointers and live between an init and an end. They are in-place resources (resource R wraps T with init), which the draft does not propose yet; §16.2b.3 now says it may only from a proof of the init and drop pair. That drafter work is the next real gain for this issue, and it is not started.

  10. ehartford commented on Nov 10, 2026

    @ehartford
    ContributorAuthor

    Ruling (Eric, 2026-11-10): a value record is flat — and the matrix he asked for

    Ruled: option A. The checker refuses reads / fills / updates on a record that holds a pointer or function pointer, in itself or in any record, union or array inside it; fills stays under the same rule. The clause also asserts the callee touches no memory but the record's own (the uintptr_t case is then a false facade, §16.2b.13). The words are not blessed until this matrix is read.

    Every row was run on the installed compiler (5b952eff7). No program contains unsafe. "Crashes" means it compiled and died reading address 4096.

    How a user's raw pointer reaches C Result
    Pointer parameter refused: needs unsafe
    Record by pointer, reads clause crashes (the original finding)
    Record by value, no facade at all crashes
    Record by value, function listed in a facade crashes
    Union by value, pointer member written through the integer member crashes
    Record by value holding a nested record / an array of pointers crashes
    Record by value holding a function pointer (Some(4096 as extern "C" fn…)) crashes
    Buffer of records that hold pointers (buffer … elements) crashes
    void * userdata on a callback registration refused: needs unsafe
    Variadic argument refused: needs unsafe
    Callback that returns a pointer or a pointer-holding record refused: needs unsafe

    Three more routes found while running it:

    • A record C produced, by value. let img = img_new(); img_free(img); img_free(img) compiles with no unsafe and double-frees. No forged pointer is needed: a pointer-holding record passed by value is an unmodeled resource that safe code can copy.
    • Field assignment. img.data = 4096 as *mut i32 on a record C returned, then a by-value call: crashes.
    • Integer cast to a function type, pure With, no C. Holder { f: 4096 as fn(i32) -> i32 } then (h.f)(1) compiles and jumps to 4096. A direct let f = 4096 as fn…; f(1) reaches codegen and fails LLVM verification.

    Also, by the spec's own words (§16.3 extern globals: "Access does not require unsafe"), safe code may assign a pointer-typed C global. I could not get a linkable one to run here, so that row is read from the spec and Sema accepting the assignment, not from a crash.

    One owner decides the by-value rows: Sema.ci_type_requires_raw_contract treats a parameter as raw only when its own type is a pointer, reference, slice or function type; it does not look inside a record.

    Done on branch flat-value-records: the checker refuses the three clauses and buffer … elements on a non-flat record or element (six fixtures, each shown failing on main first).

    Not done, needs Eric: the by-value rows. Applying the flat rule there makes GetImageColor(image, x, y) and UnloadImage(image) in uat/fixtures/raylib_spiral_main.w require unsafe (Image holds void *data).

  11. ehartford commented on Nov 10, 2026

    @ehartford
    ContributorAuthor

    Ruling 2 (Eric, 2026-11-10): by value, A alone — and what running it found

    Ruled: a parameter passed by value whose type holds a pointer is a pointer parameter; the function is raw unless a facade models that type. No construction gate. Function casts (integer, pointer, or another signature → function) require unsafe. Assigning a C global whose type holds a pointer is raw. Returning such a record stays safe.

    Matrix re-run with the rule applied (stage1 of branch byvalue-pointer-params; no unsafe in any program):

    Route Result under A
    Record by value, no facade refused: raw c_import call
    Union / nested record / array of pointers / function-pointer field, by value refused
    C-produced record by value (double free, field overwrite) refused
    Buffer of records that hold pointers refused by the elements check
    void * userdata on a callback registration refused (was already)
    Variadic argument refused (was already)
    Flat record by value (Pt { x, y }) still safe
    Record by value, function merely listed in a facade with no clause still accepted — gap, to close in the rule layer

    Count (condition 3). Every UAT fixture (fetched fresh, scenario steps applied), the three C-importing examples and their tests, the blog posts, the README and the homepage: exactly 2 calls go raw, both in uat/fixtures/raylib_spiral_main.w: GetImageColor(image, x, y) and UnloadImage(image). sdl, sqlite3, zlib, libcurl, bzip2, libxml2, examples/spiral, examples/c-interop, examples/nebula: 0.

    Two facts that block condition 1 (fixture byte for byte):

    1. The fixture's only import is use c_import("raylib.h"). A fetched package's facade reaches a program only through use facades.<name> (§16.2b.15); I confirmed a bogus item appended to .with/deps/c/raylib/6.0/facade.w is not even read when the fixture is checked. So no facade, drafted or from registry facts, can model Image for this program as written.
    2. A by-value token resource (§16.2b.3) presents its operations as methods (Picture.new(), p.get(0), Drop). The imported names (LoadImageFromScreen, GetImageColor, UnloadImage) stay the raw C functions. The fixture calls the imported names.

    Stopped here per condition 1. Layer 1 (flat-value-records, gate green) is unaffected.

  12. ehartford commented on Nov 18, 2026

    @ehartford
    ContributorAuthor

    Needs Eric: this is the shape of a contract clause, so the words are his.

    Where it stands. D198 already gives a by-pointer value record three clauses on an fn item: reads param N, fills param N and updates param N (§16.2b.5), and a record with a pointer field is refused as a value record ("a value record is flat"). The 1831 functions are mostly the records that rule excludes: z_stream, lzma_stream and the like hold pointers (next_in, next_out, an allocator) and are caller-allocated, with an init/end pair rather than a producer and a destroyer.

    The question for a ruling. What a caller-allocated record with pointer fields is: (a) a resource whose representation is the record by value, produced by init f(self) over zeroed storage and dropped by its end function, with its pointer fields described by buffer pairings on the operations that read them; or (b) something new. (a) needs no new grammar for the record itself (init f(self) exists), but deflate(strm, flush) reads next_in/avail_in and writes next_out/avail_out through fields, and no clause today pairs a buffer with a field. That field-level buffer pairing is the missing piece either way.

    Not started: the clause is a grant (it says how many bytes C may read and write through a field).

  13. ehartford commented on Nov 21, 2026

    @ehartford
    ContributorAuthor

    Brief for Eric: drafting in-place resources (the rest of this issue)

    Built, on a local branch (inplace-draft), not merged. The drafter proposes resource R wraps T with init and drop from a proof, and a test covers three init shapes. Nothing below lands until you rule, because each item decides what a draft may make safe.

    Measured first. Six real libraries (zlib, bzip2, xz, libyaml, libuv, expat) drafted with and without the change: the new proof drafts 0 in-place resources on them. The reasons are the questions:

    Library What the source shows What stops a draft
    zlib, bzip2 two init/end pairs over one stream record the end frees through the record's own hook field (zfree, bzfree), and the registry states no role for it; two pairs need stating
    xz about 12 initializers, one end (lzma_end frees strm->internal) one resource with many constructors; a second init clause is not modeled
    libyaml one end per record, initializers through macros into nested fields a unit could not be read; the proof follows one field level

    1. What the others do

    Nothing comparable: Swift, Go, Zig and Rust's bindgen hand the caller the struct and the rule "call end, do not move it" (the earlier brief on this issue has the citations). No one drafts this.

    2. What the spec says

    • §16.2b.3: "A draft proposes an init and drop pair for an in-place resource only from a proof over the library's source, never from the functions' names." It does not say what the proof is.
    • §16.2b.4: without ok, an in-place init that returns a status yields (status, R) with R live. With ok, a failed init yields Err and the end function never runs.
    • §31 grammar: status = "ok" CONST { "," CONST }. A constant's name only; ok 0 does not parse.
    • §31.8.1 facts files state from, drop and destroys on a resource. Not init.
    • The grammar lets init repeat. The checker took the second and dropped the first silently (fixed on its own branch: now an error).

    3. Mission fit

    Law 4 and D51: a destruction contract is stated or proven, never named. D198: a proof about C is enumerable. Your ruling on this issue: "the pair is stated or proven, never named (inflateInit/inflateEnd and deflateInit/deflateEnd over one z_stream are two resources)".

    4. The five questions, each with one prediction

    A. The pair proof. A draft states init f(self) / drop g when all of these hold: every unit was read; an installed header defines the record; no function produces or destroys a pointer to it; f gives one field of the record a fresh allocation nothing else keeps (every store into that field is NULL or that allocation); g takes the record alone and hands that same field to a destroyer; and exactly one f and one g exist for the record. Prediction: you accept this as the proof. 80%.

    B. An init that returns a status. Drafting it without ok would leave the resource live after a failed init, and g would run on storage f never filled. So the draft states ok K or nothing. The proof of K is structural: no goto or label in the body; the last statement is return K, an integer constant; the store into the field is a statement of the body itself, not nested; every return written before that store returns a constant other than K. Prediction: accept. 75%. It is narrow by design: zlib's deflateInit2_ ends in return deflateReset(strm), which this does not prove.

    C. ok with a literal. return 0; proves K = 0, but ok takes a name. Allow ok 0 (an integer literal) in the grammar? Prediction: yes. 85%. Without it, an init that returns a bare literal stays raw and the report says why.

    D. A facts file may state an in-place resource (init f(self), ok K, drop g under resource, each line cited), checked against the same proofs wherever the source allows and refused when the source contradicts it. This is what zlib, bzip2 and xz need: their pairs must be stated. Prediction: yes. 85%. It needs the §31.8.1 words.

    E. Several init clauses on one resource, each a constructor, as several from are today (xz: lzma_easy_encoder, lzma_stream_decoder, … over one lzma_stream, one lzma_end). Each init carries its own ok. Prediction: yes. 80%. It needs a sentence saying which init an ok belongs to; I would bind it to the init above it, as borrows binds to the producer above it.

    If A to E go as predicted, the order of work is: land the proofs (A, B), then C, then D and E together, then write the registry facts for zlib, bzip2 and xz and re-run the survey.

  14. ehartford commented on Nov 22, 2026

    @ehartford
    ContributorAuthor

    Progress (2026-11-21): the rulings on C, D, E and the two fixed forms are landed.

    Remaining here, in order: re-run the survey (stated against drafted), then land the draft proofs A and B with the failed-allocation condition; then the field-buffer brief.

  15. ehartford commented on Nov 22, 2026

    @ehartford
    ContributorAuthor

    Survey re-run (2026-11-21), with the facts landed and the draft proofs A and B built (branch in battery):

    Library (pinned) In-place resources stated Drafted by proof
    zlib 1.4 2 (Inflater, Deflater) 0
    bzip2 1.0.8 2 (Compressor, Decompressor) 0
    xz 5.8.4 1 (Stream, two initializers) 0
    libyaml 0.2.5 0 0; the report names two near misses (yaml_document_s, yaml_emitter_s: an end is found, no init, and a unit could not be read)
    libuv 1.53.0 0 0
    expat 2.10.0 0 0

    So, as the first survey predicted, the proof drafts none of these six: zlib and bzip2 have two pairs over one record, xz has many initializers and one end, and these packages are linked as prebuilt binaries, where the result is evidence only. The stated pairs are what make them usable. The draft proof is for the simple library with one init and one end over one record; its test covers a named status, a literal status, a void init, and the refusal when the end's destroyer is not known to accept NULL.

    Next: libyaml, libuv and expat facts (stated pairs), then the field-buffer brief.

  16. ehartford commented on Nov 25, 2026

    @ehartford
    ContributorAuthor

    State, 2026-11-25. The field-buffer rule this thread still lists as a brief to write is ruled and in the spec: D231, buffer field P remaining field N [reads] (§16.2b.5), used by zlib's registry facts. So nothing here waits on a ruling. Left, all implementation: the stated pairs for libuv 1.53.0 and expat 2.10.0, then the survey again. #3177 is closed and #3174 was ruled today (D235), so the library issues that name those three as blockers now wait on this issue and on #3174's proof.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    bug

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions