Skip to content

Modeled C: a callback contract (callback param N userdata param M) can only be stated on a function whose first parameter is a modeled resource; a free function with a callback (tally_each) has no safe spelling #1644

Closed

Description

@ehartford

Found respelling examples/c-interop to the facade surface (PR #1640, branch examples-c-interop).

vendor/tally.h:

/* Calls `visit` once per value, handing `context` back each time. */
void tally_each(const int *values, int count, void (*visit)(void *context, int value), void *context);

This is §16.2b.9's during-the-call callback with userdata — the same shape as sqlite3_exec's row callback, which the SQLite facade states as callback param 2 userdata param 3 and the compiler renders as db.exec(sql, Some(on_row), Some(ctx), …) with the callback typed extern "C" fn(&U, …). On tally_each the same clause is refused:

fn 'tally_each': a callback contract is presented as a method of the resource its first parameter receives, and param 0: *const i32 values receives no modeled resource (§16.2b.9)

The contract is real regardless of the receiver: C borrows the callback and its userdata for the call and hands the userdata back typed. A callback contract on a free function should render a free safe function (tally_each(values, visit, ctx)) rather than a method, the way a lend on a free function does. (tally_each also needs the element-count buffer pairing of the sibling issue for its first two parameters; both are needed before the call leaves unsafe.)

A second observation from the same example: the rendered callback receives &U, which is right for the borrow, but a callback that collects (the example pushes every value into a Vec[i32]) has no safe spelling through &U — the raw version threads &raw mut seen through the void *. Whether that is a mut-capable userdata clause or an interior-mutability type in std is a design question; noting it here so the collecting-callback case is not lost.

Spec: §16.2b.9. The example's src/facades/tally.w names this gap beside the declaration; src/tally.w keeps the raw call.

Activity

  1. ehartford commented on Sep 27, 2026

    @ehartford
    ContributorAuthor

    Already fixed on main by a0cd734 (#1675): a callback contract on a free function renders a free safe function; the issue's tally_each shape prints 11 12 13 on main 76cf0bf. The second observation (a callback that collects through &U) is a design question, filed separately if needed.

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

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions