Repository navigation
Description
Summary
The facade spec (§16.2b) has no clause for a polled tagged message: a C API that hands the program a record whose integer tag says which struct a payload pointer points to, and whose size field bounds it. Steam's manual callback dispatch is the case at hand. Without a clause, a downstream program has to read the payload with unsafe casts and dereferences even when everything else about the library is modeled.
§16.2b.9 Callbacks covers C calling into a With function (callback-scope handles, borrowed arguments, userdata). It does not cover the reverse shape, where the program pulls messages and C never calls it. A search of docs/spec/016_ffi.md for tagged, discriminated or payload forms finds only the variadic discriminant rule (§16.2b, "Discriminated variadic contracts"), which is about arguments, not received records.
The case: Steamworks manual dispatch (WIPE, src/steam.w)
use c_import("steam/steam_api_flat.h", lang: "c++", link: "steam_api", no_methods: true)
SteamAPI_ManualDispatch_RunFrame(self.pipe)
unsafe:
var msg = CallbackMsg_t {}
while SteamAPI_ManualDispatch_GetNextCallback(self.pipe, &raw mut msg):
if msg.m_iCallback == GameOverlayActivated_t_k_iCallback and msg.m_pubParam != null and msg.m_cubParam >= OVERLAY_BYTES:
let event = msg.m_pubParam as *const GameOverlayActivated_t
let active = (*event).m_bActive != 0
...
else if msg.m_iCallback == UserStatsStored_t_k_iCallback and msg.m_pubParam != null and msg.m_cubParam >= STORED_BYTES:
let event = msg.m_pubParam as *const UserStatsStored_t
...
else if msg.m_iCallback == SteamShutdown_t_k_iCallback:
...
SteamAPI_ManualDispatch_FreeLastCallback(self.pipe)
The facts the program knows and the compiler can't see:
CallbackMsg_t.m_iCallbackis a tag. Each callback struct carries its own tag as a constant (GameOverlayActivated_t_k_iCallback, …), and the tag selects the payload type.m_pubParampoints to a payload of that type, andm_cubParamis its size in bytes. The program checks the size before reading.- The payload is borrowed from the dispatch. It is valid from
GetNextCallbackuntilFreeLastCallback, and it must not outlive that call. FreeLastCallbackmust follow every successfulGetNextCallback, before the next one.
Every other unsafe site in WIPE's Steam binding (init and status, the interface pointers, string and buffer parameters, borrowed origin text) maps onto existing clauses: resource … from … ok … drop, of … lend, buffer param … len …, out param, and returns borrow CStr from. A Steam facade can model all of those today. The callback pump is the only part that has to stay unsafe.
The same shape elsewhere
This isn't specific to Steam. Any pull-model event API with a tagged payload has it: SDL_PollEvent filling an SDL_Event union discriminated by type, Win32 MSG with message/wParam/lParam, X11 XEvent with type, and libinput_get_event with libinput_event_get_type.
What a clause would need to state
This list is the facts, not a syntax proposal:
- The tag: which field (or call) gives the discriminant.
- The cases: for each tag value (a constant from the import), the payload type and where the payload lives (a pointer field, or the union member).
- The bound: which field gives the payload size, and that a case is rejected, not read, when the size is short.
- The lifetime: the payload is borrowed from the producing call (
GetNextCallback) until the release call (FreeLastCallback), with the release required before the next produce. - Unknown tags: they surface as an "other" case carrying the tag and do nothing else.
With those facts, the program could match on a modeled message and get each case's payload as a borrowed, typed view, with no unsafe, no casts, and the size check and release enforced by the facade.
Acceptance
- A facade over the Steam manual-dispatch surface lets the pump above be written without
unsafe: match on the message, readGameOverlayActivated_tandUserStatsStored_tas borrowed views, release enforced. - A short payload (
m_cubParamless than the case's size) never reaches a case arm. - A payload view used after the release call is a compile error.
- An unknown tag is a case the program can match, not undefined behavior.
Found while modeling Steamworks for WIPE (withlang-dev/wipe), which builds with the live compiler.
Activity
ehartford commentedon Oct 16, 2026
The evidence for this clause ships with the library
The Steamworks SDK includes
sdk/public/steam/steam_api.json, a machine-readable description of the whole flat API (SDK 1.65 counted):callback_structs: 196 entries, each with itscallback_id. For example{"callback_id": 101, "struct": "SteamServersConnected_t", "fields": []}. That is the tag-to-payload table this issue asks a facade to state, for every callback the SDK defines. A facade built from it would not need anyone to write the cases by hand.interfaces: 34, with 921 flat methods. Each method has itsmethodname_flatand parameter annotations:array_count26,out_string_count16,out_array_count14,out_struct6, plusout_array_call,out_string,out_buffer_countandbuffer_count. Each interface has itsaccessors(for exampleSteamAPI_SteamInput_v007) andversion_string.callresult. These are async calls whose result comes back through the same manual dispatch as a tagged message (SteamAPI_ManualDispatch_GetAPICallResult), so they're this same shape a second time.For example,
GetConnectedControllersis described as{"paramname": "handlesOut", "paramtype": "InputHandle_t *", "out_array_count": "STEAM_INPUT_MAX_COUNT"}, which is exactly abuffer param … len …fact.Relation to D121 step 3 (#2424, "annotations the library ships"): that step reads
__attribute__((…))tokens through the Clang bridge. Steam's annotations are a JSON sidecar beside the headers, not attributes, so that reader doesn't see them. A sidecar reader would be a second source for the same evidence tier.What the JSON does not say, and a registry facts file would have to:
SteamAPI_InitFlatandSteamAPI_Shutdownas a resource with its status (k_ESteamAPIInitResult_OK), how long returned text such asGetStringForActionOrigin's stays valid, and the dispatch lifetime this issue describes (payload valid fromGetNextCallbackuntilFreeLastCallback).This is the evidence behind the game-toolkit plan's
with add steamstep (docs/plans/game-toolkit.md §3.2.1), which builds the Steam facade from the developer's SDK, so nobody writes one per project.docs: the game toolkit plan gains rule 10 (no unsafe in a game) and w…
ehartford commentedon Oct 16, 2026
Decision Brief (D98 — Normative Spec Addition to §16.2b)
1. Question
How should a
c facadeblock (§16.2b) declare a polled tagged message (such as SteamworksCallbackMsg_tfromSteamAPI_ManualDispatch_GetNextCallback/SteamAPI_ManualDispatch_FreeLastCallback, orSDL_PollEventoverSDL_Event) so that tag dispatch, payload size validation, payload borrow lifetime, release-before-next-poll, and unknown-tag handling are all enforced withoutunsafe?2. Recommendation & Why
Add a
message <Name> wraps <CRecord>item to §16.2b.9 (or §16.2b.9a Polled tagged messages):And for inline tagged unions (
SDL_PollEvent):Semantics:
from … release …):pipe.get_next_callback()->Option[CallbackMsg]) allocatesCallbackMsg_ton the stack, callsSteamAPI_ManualDispatch_GetNextCallback(pipe, &mut raw_msg), and returnsSome(msg)whenokholds orNoneotherwise.release <fn>is stated,CallbackMsgis a linear/ephemeral scoped guard bound to the receiver (pipe): itsDropcallsSteamAPI_ManualDispatch_FreeLastCallback(pipe)automatically at the end of thewhile let Some(msg) = pipe.get_next_callback():iteration (including oncontinue,break,?, orreturn), and the receiver (pipe) is borrowed formsg's scope so a secondget_next_callback()cannot run beforemsgis released.tag …,payload … size …,case …):match msg.kind():(or directmatch msg:projection):Variant(&PayloadType)when a payload type or unionfieldis declared;Variantwhen no payload is declared;Other(TagType)for any unrecognized tag value.payload <ptr_field> size <len_field>is stated, aVariant(&PayloadType)arm is entered only whenraw.ptr_field != null and raw.len_field >= sizeof[PayloadType](); a short or null payload never reaches the typed arm and instead yieldsOther(raw.tag).&PayloadTypeview projected frommsgcarriesmsgas its borrow origin. Using the payload view aftermsgdrops (i.e. afterFreeLastCallback) is a compile-time borrow error.Why:
unsafein user code.releasetheDropof the polledCallbackMsgguard makes forgettingFreeLastCallbackimpossible and naturally bounds&PayloadType's origin to the release point.steam_api.json's 196callback_structsentries inwith add steam.3. Alternatives & Why Not
pipe.free_last_callback()call required in user code, tracked by a typestate/linear check.continue/return. BindingFreeLastCallbackto the polled message guard's scope (Drop) is strictly safer and more ergonomic.m_pubParam/m_cubParam), leaving C union events (SDL_Event) to a separate construct.SDL_PollEventhas the exact same producer + tag + borrowed-case-payload shape; supportingfield <union_member>alongsidepayload <ptr> size <len>handles Steam, SDL, X11, and Win32 with one facade item.4. Proposed Normative Diff (
docs/spec/016_ffi.md)ehartford commentedon Oct 25, 2026
Triage 2026-10-25,
with v0.15.3.0(main a261b65): unchanged, and the next step is Eric's ruling (C interop, §16.2b). §16.2b has no clause for a polled tagged message; the decision brief above (D98 form) awaits a ruling.Spec v7.63: 'buffer field P remaining field N' (D210); D213 to D216 r…
ehartford commentedon Nov 18, 2026
Ruled, 2026-11-18 (D216): a
messageitem, withtag,case Name when CONST [field f | : Type](a range may state a family),payload P size N(non-null, large enough and aligned, elseOther), andrelease fas a guard that borrows the producer exclusively. The generated sum is ephemeral and open: amatchon it must have a wildcard arm, and an.Other(tag)arm that compares the tag with a constant that has a named case is warned. Aboolreturn means produced. Pointer fields inside a payload stay raw for now. Each case is cited; thread affinity of the poll is stated if contracts can, or recorded as a gap.ehartford commentedon Nov 25, 2026
Started on D216 (2026-11-25). Nothing is merged yet: per the ruling the spec words come to Eric as one diff with the implementation, so the work stays on a local branch (
d216-message) until it is whole.What exists today. Nothing of the item:
messagein the grammar is only the resource clause that names an error-text operation. A contract that writesmessage Event wraps SDL_Eventgets "expected 'resource', 'handle', 'fn', 'domain', …".Checked first, because the design rests on it: a sum whose cases hold views can be an ephemeral type today. This compiles and runs with the installed compiler (main):
So the generated type is ordinary rendered source, as a resource's is.
The pieces, in the order I am taking them
from f(out param N),tag F,case Name when CONST [field f | : Type], a rangewhen A..B,payload P size N,release f), as a new facade item node.SemaFacade): the record and its tag field exist and the tag is an integer; eachwhenconstant is a constant of the import; afieldis a member of the record (a union member for the SDL shape); a: Typeis a record of the import; no tag is claimed by two cases; the producer's out parameter is a pointer to the record and its return isbool.Other(tag), and the poll operation. For the pointer form, the non-null, size and alignment tests before a typed case; withrelease, the guard that borrows the producing resource exclusively.matchon the generated sum needs a wildcard arm (the sum is open), and the warning for an.Other(tag)arm that compares with a constant that has a named case. There is no open-sum notion in the compiler today, so this is new.Recorded gap, as the ruling asks: whether a contract can state "main thread only" for the poll. I have not looked yet.
ehartford commentedon Nov 25, 2026
Progress (2026-11-25), still local on
d216-message:Slices 1 and 2 are done. The item parses (both shapes, the range form, and C field names that are With keywords such as SDL's
type), and it is verified against the import: the record and an integer tag, a producer that fills a writable pointer to the record and returnsbool, each case's constant, ranges, no tag value under two cases,field fa member of the record,: Tonly with apayload, the payload's pointer and size fields,releaseonly with a payload,Otherreserved. Fifteen wrong contracts each get one error naming the line; they become the compile-error tests.The shape of the loop. The ruling fixes the contract's lines, not what the program writes. The shape I am building, to come to Eric in the diff:
The record lives in the generator; each iteration yields the ephemeral sum; with
release fthe generator calls it when the body returns, so "free before the next poll" is not the program's to remember. A hand-written version of what the renderer will emit runs today (three events, no leak under the debug allocator), so nothing new is needed below the facade for it.Something the ruling's context should know. D216 says "reading a union member is
unsafe, so every event loop was written underunsafe". That is not what the compiler does for an imported union:SemaCheck(the §16.4 check) exempts a C union on purpose ("a C union reads any arm: punning is what the C code it mirrors does"), and a program that writesraw.key.key = 5and readsraw.motion.xcompiles and prints 5 with nounsafe. So for SDL's shape the onlyunsafein a hand-written loop today is the poll call itself; the pointer form (Steam) does need it, for the cast and the dereference. The item is still what makes the tag-to-member pairing stated once, and I am not reopening the ruling; this is for the spec words, which should not claim the read is unsafe.ehartford commentedon Nov 25, 2026
D216 is built and waits only on the spec words. Branch
d216-message(local, seven commits on main, not pushed, as the ruling asks for one diff with the words).What is built
field f) and a payload pointer (: T,payload P size N,release f). A typed case in the pointer form is entered only when the pointer is non-null, large enough and aligned; otherwise it isOther(tag).for m in Name.poll(…): match mwith nounsafe. The producer's other parameters are the poll's;releaseruns after each body, an earlybreakincluded (test: 4 releases of 4).matchwithout_is an error, and an.Other(tag)arm that compares with a constant a case names is warned.Evidence
:unit-return-review,:ceremony-census,:self-audit,:native-compile-error-tests,:behavior-testsgreen; battery green. Tests:behav_d216_message_union,behav_d216_message_pointer, 22err_d216_*.with get c.sdl, the pinned package): a project contract overSDL_Event/SDL_PollEvent, each case cited fromSDL3/SDL_events.h, verifies; a program that queues a key press and a quit request receives.KeyDown(scancode A) and.QuitthroughEvent.poll().with getpackage and I have no pinned copy to cite from. The pointer form is tested against a header of the same shape.The words to bless
Proposed as a new subsection after §16.2b.9. Exact text:
16.2b.9a Polled messages
Some libraries hand the program a record it must ask for: the program
calls a function that fills the record, and an integer field of the record
says which of its parts is meaningful. A
messageitem states that pairingonce.
from f(out param N)names the function that fills the record and theparameter it fills, a writable pointer to the record.
freturnsbool:truemeans it produced a message.tag Fnames the integer field that selects the case.case Name when CONSTnames a case and the tag value that selects it;when A..Bnames every value fromAtoB. No tag value belongs totwo cases. A case carries nothing, a member of the record (
field f), orthe record a payload pointer points to (
: T).payload P size Nnames the pointer field and the field holding thepayload's size in bytes. A message that states it carries its cases as
: T.release fnames the function that ends the payload's life. It takeswhat
from's function was given, the record aside.A field is named as C names it, also when the name is a With keyword.
What the item presents. A sum
Namewith the stated cases and onemore,
Other(tag), for a tag value no case names; andName.poll(…),whose parameters are those of the
fromfunction without the record. Theprogram iterates it:
Each iteration polls once and stops when the function returns
false. Therecord belongs to the iteration, and a case's value is a view of it: the sum
is an ephemeral type (§5.5), and neither it nor a view taken from it
outlives the loop body. With
release, the release runs when the bodyends, however it ends, before the next poll.
A case stated
: Tis entered only when the pointer is not null, the sizeis at least the size of
T, and the pointer is aligned forT. Otherwisethe value is
Other(tag).The sum is open. A
matchon a message's sum must have a_arm.Other(tag)covers a tag the library adds later; it does not cover a case alater contract names, and a match that listed every case would stop
compiling when one is added. An
.Other(tag)arm that compares the tagwith a constant some case names is warned: the tag is never that value
there.
Verification (§16.2b.13). The record, the tag and every named field
exist; the tag is an integer; each
whenconstant is an integer constant ofthe import; the
fromfunction's parameter is a writable pointer to therecord and its return is
bool; a: Ttype is a record of the import;releasehas the parameters stated above. A line that does not hold is anerror.
Pointer fields inside a case's value are raw pointers (§16.1).
Four things to know before blessing
unsafe". For animported C union it is not (the checker exempts C unions on purpose).
The draft therefore does not say the item removes an
unsaferead forthe union shape; what it removes is the
unsafepoll call and, for thepointer form, the cast and dereference.
for m in Name.poll(…)) is my choice; the ruling fixedthe contract's lines only.
release f"borrows the producing resource exclusively" in the ruling.As built, the release runs at the end of each body (also on
break), so"free before the next poll" cannot be got wrong; but when the producer's
other parameter is a plain handle value (Steam's
HSteamPipeis aninteger), there is no resource to borrow, and nothing stops a second
pollloop nested inside the first. If the parameter is a facaderesource, the poll should take it
mut: not built yet.video): §16.2b.10 has no clause that says "this thread only", so the
poll is presented without it. Recorded as a gap, as the ruling asks.
Labelling
human attn needed: the words are yours. On a yes I apply them with the version and changelog, push, and open the PR.ehartford commentedon Nov 25, 2026
Ruled by Eric, 2026-11-25 (answers to briefs.md).
The words were not answered: the copy of the brief that was read still had a placeholder where the text goes. The full text is in
briefs.mdnow and in the comment above on this issue.One answer was given, on note 3: build the
mutborrow for a facade-resource parameter before landing, as the ruling asks. A producer with no resource to borrow is recorded as a gap. It matters only for the pointer form withrelease. That part is mine now; the label stays for the words.ehartford commentedon Nov 25, 2026
Ruled by Eric, 2026-11-25 (second answer of the day): yes to the words, with five edits; the loop shape stands.
when A..B: say "A and B included".payload's field is a pointer andsize's field is an integer; a: Tcase needs apayloadline, and areleaseline needs one too; a message does not mixfieldand: Tcases.release: say what its return is, or that it is ignored.Other(tag): the tag has the type of the tag field.releasewhosefromfunction takes no resource does not prevent a nested poll.The added sentence: yes, scoped to messages that state
release: "Where the message statesreleaseand a parameter of thefromfunction receives a facade resource,polltakes itmut: …". A union-form message copies its record, so its loop body may call the resource.Suggested, not a condition: for a
releasemessage with no resource to borrow, a per-message "loop active" flag that panics on re-entry closes the nested-poll hole (the outer body would otherwise hold a view of a payload the inner loop released, with nounsafe).Label removed. Mine now: the
mutpoll, the verification rules of edit 2, the re-entry flag, the edited words, then the PR.ehartford commentedon Nov 26, 2026
Ruled by Eric, 2026-11-25 (third answer): A. The guard is an
Atomicflag taken with one atomic swap or compare-and-swap (never a load then a store), cleared bydefer; rendered contract text is fixed so it can name a standard type, with its own test; a threaded test; then themutpoll for the resource case. The sentence, approved as written: