51. Variadic functions and types take a pack that is called like any argument list, walked by metaprograms and proved once; foreign bindings are generated from tables¶
Date: 2026-11-23
Status: Accepted (2026-11-23, after two revisions with Dean's answers, recorded under "Answers" below and folded into the decision)
Context¶
Dean (2026-11-23): "we need the equivalent of variadic functions that are provably safe. We should have language features for generic variadic functions and types, like C++ gives us, but with more straightforward syntax through metaprograms."
Three things need variadics now:
- C functions.
open,fcntl,ioctlandsyscallare C variadic functions. ADR 0050 needssyscallfor io_uring, andPia.Sys.Fsneedsopenwith a mode. Apple arm64 passes variadic arguments on the stack, while named arguments go in registers, so declaringopenwith a fixed third parameter gives the wrong ABI. x86_64 System V also needs%alset to the number of vector registers a variadic call uses. Pia's FFI today takes only fixed integer, bool and buffer parameters (genForeign). - Generic code over any number of types.
when_all (a, b, c)in ADR 0050 completes with the values of all its senders and the union of their error sets.formattakes any number of arguments of types that meetFormat.apply,tuple_cat,std::getby type and argument forwarding for constructors are the same shape. - Types over any number of types. An operation state for
when_allholds one child per sender, andstd::variant<Ts...>is a sum over a list of types.
C++ answers with parameter packs: typename... Ts, pack expansions f(xs)... in a dozen syntactic positions, fold expressions (... + xs), sizeof..., and recursion through partial specialisation or if constexpr. They are powerful, but the syntax is irregular. Pack indexing only arrived in C++26, and an error inside an expansion surfaces at instantiation. C varargs (va_list) are unchecked: the callee trusts the caller's count and types, which is the root of format-string bugs.
ADR 0040, section 9, already decided that tuples are a core type and that tuple types are the type lists for variadic code, "without a separate pack feature", and said core tuples need their own ADR. This is that ADR. It also covers the parts section 9 left open: how generic code walks a tuple and is proved, variadic types, and foreign varargs.
Decision¶
1. Core tuples¶
This section builds what ADR 0040 section 9 specifies, unchanged:
(a, b, c)is a tuple value, and(u8, str, bool)is its type, since types are values.()isunit. There is no one-element tuple.t.0,t.1: positional access, checked at compile time.- A tuple is an anonymous record with fields
0,1, ... It has the same layout, ownership,moved,@linear, borrow and contract rules as a record, and struct-of-arrays buffers. Two tuple types with the same element types are the same type. Eq,OrdandHashare structural, proved once (ADR 0043).
2. A variadic function is called like any other function¶
The last parameter of a function may be a pack, written ..., with its type a deduced type parameter:
(* Designed syntax. *)
let print (ts : type where All Format ts) (w : borrowed inout writer) (xs : ...ts) : unit = ...
print w x name 42u8 (* ts = (u32, str, u8), deduced *)
print w (* ts = (), an empty pack *)
- The call site is ordinary application. A pack takes every argument that follows the fixed ones in that application. An application ends where it always ends: at a closing parenthesis, an operator,
;,then,inand so on. Soprint w x name 42u8is one call with three pack arguments, andprint w (f x) yis one call with two. Nothing about the call says the function is variadic. - Inside the body, the pack is a tuple.
xshas the tuple typets. Its elements arexs.0,xs.1and so on, orxs.[u8]by type, which is the one element of typeu8and a type error when there is not exactly one (C++'sstd::get<T>; types are values, so a type is an index like any other). The pack can be passed on whole, so ADR 0040's tuple decision still holds: a pack is a tuple, and only the parameter is marked. - Passing a tuple as a pack is
...tat the call:print w ...pair. This is how one variadic function forwards its pack to another, as C++'sf(xs...)does. - Partial application goes through the expected type. When a variadic call is in a place that expects a function, such as an argument whose parameter type is
u32 -> unit, the call is partial, and the expected function's parameters close the pack. Somap (print w) xspassesprint was a function of one argument, withtsdeduced as(t)frommap's parameter, andfor_each (print w prefix) xsfixes the first element too. When nothing expects a function, the call is complete, andprint wprints nothing. Binding thatunitresult to a name is warned about by thevariadic_unit_bindinglint (ADR 0037), because it is probably a partial application that was meant. This is the same deduction from the expected type that generic results already use (docs/irgen.md). - Variadic function values.
bind_front print wkeeps the pack open: it is a function object whoseapplyis itself variadic, so a later call can pass any number of arguments.Pia.Fnhas the usual combinators over packs:bind_front,bind_back,compose,flip,apply(a function and a tuple, asstd::apply) andunpack(a function of a tuple, turned into a variadic one). TheFunctionconcept (ADR 0044) takes a pack of argument types,Function f (...args) r, so higher-order functions can accept variadic function values and be proved once over them. All c tsis a prelude concept over pack types: every element type meetsc. Concepts are already values that type-level metaprograms take (ADR 0046).
3. Packs are walked by metaprograms, not by recursion¶
Code never recurses over a pack. Two kinds of metaprogram do the walking instead.
Type-level metaprograms over a list of types. The builtin elements ts gives a pack type's element types as a metaprogram list, and tuple_of xs builds a pack type from a list. Everything else is the list functions metaprograms already have, map, fold and length (docs/meta.md):
let meta size (ts : type) : usize = length (elements ts)
(* when_all's value and error types (ADR 0050). *)
let meta values_of (ss : type) : type = tuple_of (map value_of (elements ss))
let meta errors_of (ss : type) : type = fold (let (a) (e) => a | e) never (map error_of (elements ss))
These are total by the rule tactics already follow (docs/meta.md): the only recursion is map and fold over the components of a parameter.
A loop over a pack, unrolled by expansion. In code, a for over a pack runs its body once for each element, and the expansion stamps out one copy of the body per element, as Zig's inline for does. x has each element's own type in its copy:
let print (ts : type where All Format ts) (w : borrowed inout writer) (xs : ...ts) : unit
ensures written_count w = old (written_count w) + size ts
= for i, x in xs
invariant written_count w = old (written_count w) + i
do format w x done
The library's Pia.Core.Pack is written the same way: map, fold, apply, cat, get by type and zip. C++'s fold expressions become fold, sizeof... becomes size, and pack indexing becomes xs.i with a constant i, or xs.[t] by type.
4. Proved once, though compiled per element¶
The loop above is proved once, as an ordinary loop. Its body is proved for an abstract position i and an abstract element type element i ts, which is an abstract sort constrained only by Format, because All Format ts says that much of every element (ADR 0043). The invariant is the induction over positions, exactly as for for i in 0 .. n. Each unrolled copy is then discharged by that one proof, as an instance of a generic is.
So a variadic function is proved and checked once, at its definition, for every pack, and errors are reported there rather than at an instantiation (ADR 0034's definition check). That closes C++'s gap, where a pack expansion fails only when instantiated. Codegen still compiles straight-line code: print w a b c becomes three calls of format, with no loop and no run-time dispatch.
5. Variadic types¶
A generic type's last type parameter may be a pack too, and an instance is written like any other generic application, when_all_sender a b c. Its fields use type-level metaprograms over the pack:
(* when_all's operation state: one child operation per sender (ADR 0050). *)
let when_all_op (r : type) (ss : ...type where All Sender ss) = type {
children : tuple_of (map (let (s) => op_of s (child_receiver r)) (elements ss));
results : tuple_of (map (let (s) => option (value_of s)) (elements ss));
rcv : r;
}
A sum over a pack is one_of ts, C++'s std::variant<Ts...>: a value that holds exactly one element of the pack, and knows which. It is a core anonymous sum, with no constructor names, because types are values and the type of the active element is enough to tell the alternatives apart:
let reading = one_of u32 str (option u8)
let describe (w : borrowed inout writer) (r : reading) : unit =
match r with
| (n : u32) -> format w n
| (s : str) -> format w s
| (o : option u8) -> format_opt w o
let r : reading = 42u32 (* injected: the expected type is a one_of *)
(* Generic over the alternatives: one arm, proved once for an abstract element. *)
let show (ts : type where All Format ts) (w : borrowed inout writer) (v : one_of ...ts) : unit =
match v with
| x -> format w x
matchon the active element's type is how aone_ofis read. Arms are type patterns, and thematchmust cover every element type, or end in an arm that binds the rest generically. That one generic arm isvisit, with no library function needed.- Element types must be distinct (answer 5), which
one_ofchecks with a type-leveldistinct ts, so a type always names exactly one alternative. A variant whose alternatives share a type, such as twou32s that mean different things, is a named variant (type | Celsius of u32 | Kelvin of u32), which says what each one means. v.[u32]is the element when it is au32, with the preconditionholds v u32, a spec function that amatcharm or anif holds v u32establishes.index vis the position of the active type in the pack.- Layout is a tag and the largest element, as for named variants, and
Eq,OrdandHashcome from the elements, as for tuples.
6. Foreign bindings: variadic C calls, and declarations generated from tables¶
A C variadic function is declared once, with a pack. A pack in a foreign declaration is restricted to C-promoted types, and each call passes whatever its arguments are, with the ABI emitted for that call:
(* open(2): the mode is read only when O_CREAT or O_TMPFILE is set. *)
let open (ts : type where All CPromoted ts) (path : cstr) (flags : i32) (mode : ...ts) : i32
requires (flags & o_creat <> 0) = (size ts = 1)
requires size ts = 1 ==> element 0 ts = u32
ensures result >= -1
= extern "open"
open path o_rdonly (* 2 arguments *)
open path (o_creat | o_wronly) 420u32 (* 3 arguments; 420 is 0644 *)
- Calls use the variadic ABI. Codegen emits each call as a variadic LLVM call with the argument types of that call, so Apple arm64 puts the pack on the stack and x86_64 sets
%al. CPromotedholds fori32,u32,i64,u64,isize,usize, buffers (passed as pointers) and, once floats land,f64. A narrower integer or aboolfails the constraint with a message that says to widen it, because C would promote it and the callee would read anint. A record fails it, because C cannot pass a struct through...portably.- The contract decides what a call may pass. What the C function reads depends on its other arguments, as
openreads a mode only withO_CREAT. So the declaration'srequiresrelates the pack's size and element types (size ts,element i ts) and values (mode.0) to the other arguments, and every call proves it. This is the "provably safe" part: theva_argreads that C trusts become goals. cstris a[u8]refined to end in a NUL byte, whichPia.Sysbuilds and proves. It is not a new core type.- Pia functions are never C-variadic. Pia's own variadic functions take packs, which are tuples, and nothing in Pia makes or reads a
va_list. Exporting a variadic function to C is not supported. - Format strings stay in Pia.
printfand its family are not declared.Pia.Text.Formatuses section 2, withrequires placeholders fmt = size ts, which the verifier folds whenfmtis a literal. So a format string with the wrong number of arguments is a failed goal, not a crash.
Declarations are generated from the platform's headers, with contracts beside them. POSIX alone needs a few hundred declarations, most of them per target, so Pia.Sys.Posix writes none of them by hand. Writing them as tables by hand would drift from the platforms, so they are generated:
- A generator reads the headers.
tools/bindingsruns the pinned clang on a list of headers for one target (<fcntl.h>,<sys/socket.h>,<linux/io_uring.h>and so on), with-ast-dump=json, and writeslib/Pia/Sys/Gen/<target>.pia: every function's C signature, including whether it is variadic, every constant (O_CREAT,EAGAIN,SYS_io_uring_enter), and every struct's size, alignment and field offsets (sockaddr_in,kevent,epoll_event,io_uring_sqe). Nothing in it is written by hand. - The generated files are checked in, and CI keeps them honest. A build cross-compiling for a target needs that target's bindings without its SDK, so the files are in the repository. Each CI job regenerates the file for its own platform from the real headers and fails if it differs from the checked-in one. Drift is a red build on the platform that drifted.
- Contracts are a hand-written overlay. Headers carry types, not promises, so a contract table beside the generated file says what each manual page guarantees. It has one row per symbol: the manual page, the contract clauses, the Pia modifiers of each parameter (
out mutable [u8]forread's buffer,cstrfor a path), the condition that decides a variadic pack (openreadsmodeonly withO_CREAT), and attributes such as@blocking. Theposixmetaprogram joins each overlay row with its generated signature and stamps out the declaration, asbit_familystamps outPia.Core.Bit(lib/Pia/Core/Bit.pia). An overlay row that names a symbol the header lacks, or whose parameters do not match the generated signature, is a compile error. A symbol with no overlay row is declared without a contract, so it can be called only asunsafe(stdlib.md). - The overlay is shared, and the generated files are per target.
@targetpicks the generated file (ADR 0049). The overlay's rows hold for both platforms, unless a row is marked for one target. A system call on Linux is a row whose symbol issyscalland whose number comes from the generatedSYS_constant, so no number is written by hand. macOS has no system-call rows, because the library goes through libSystem there. - The trust report lists overlay rows. Every generated declaration is a trusted foreign contract. The report names its overlay row and manual page, and the header and target it was generated from, so an audit reads the overlay.
Implementation steps¶
- Foreign bindings first (section 6), since ADR 0050's I/O stack and
Pia.Sys(#55, #57) need them:tools/bindingsand the generated files for both targets, the CI regeneration check, the contract overlay and theposixmetaprogram, and variadic calls. Until packs exist (step 3), an overlay row with a pack is stamped out as one fixed declaration per arity (openandopen_mode), with the variadic ABI. That restriction is internal to the bindings and goes away in step 4. - Core tuples (section 1): syntax, sema as anonymous records, IRGen, codegen and the verifier through the record paths, patterns,
t.0,t.[type], and the structural instances. - Pack parameters and calls (section 2):
...tsparameters, deduction, the argument-collection rule, partial application from the expected type,...tspreading, andAllandCPromoted. - Walking packs (sections 3 and 4):
elementsandtuple_of,forover a pack with its expansion, the proof against an abstract element, and unrolled codegen. Foreign packs replace the per-arity declarations. Pia.Core.PackandPia.Fn's combinators:map,fold,apply,cat,getandzip;bind_front,bind_back,compose,flipandunpack, withFunctionover packs; andPia.Text.Formaton top.- Variadic types (section 5): pack type parameters, then
one_ofwith type-patternmatch.
Consequences¶
- A variadic call looks like any other call, partial application included, and a variadic definition looks like an ordinary loop. The only new syntax is
...on the pack parameter and on a spread argument. - There is no recursion over packs, in types or in code. Type-level work is list metaprogramming, and code-level work is a loop that expansion unrolls.
- Variadic code is proved and checked once, at its definition. Each call still compiles to straight-line code.
one_ofis a core anonymous sum read by matching on types, sostd::variantneeds no constructor names, novisitfunction and no index-based access.- Calls to C varargs are typed by their arguments, checked against C's promotion rules, and constrained by contracts, with the ABI right on both targets.
- Foreign signatures, constants and layouts cannot drift from the platforms, because CI regenerates them from each platform's headers. Only the contracts are written by hand, and the trust report audits them.
Answers¶
Dean's answers to the first revision's questions (2026-11-23):
- Partial application of variadic functions is wanted, with higher-order functions and combinators. Section 2 does this through the expected type, with
bind_frontand friends for function values that keep the pack open. ...rather than.....is already the range operator, and open-sided ranges are planned (u32{1..}, #153). A prefix..nrange would then read the same as a spread..ninf ..n....costs one token, cannot clash with any range, and is what C++ and JavaScript readers expect for packs and spreads.- Index by type, and
matchon the alternatives.xs.[u8]indexes a pack by type, since types are values.one_ofis read by amatchon the active element's type (section 5), not through positional constructors. - Generate the bindings from the headers to avoid drift, with contracts in a hand-written overlay (section 6).
Dean's answers to the second revision's questions (2026-11-23):
one_ofrequires distinct element types, so a type names exactly one alternative. Two alternatives that share a type are a named variant.let g = print wwith no expected type is a complete call. A lint,variadic_unit_binding, warns when theunitresult of a variadic call is bound to a name, since that is probably a partial application that was meant.
Prior art¶
| Source | What Pia takes |
|---|---|
| C++11 parameter packs, C++17 fold expressions, C++26 pack indexing | the capabilities: variadic functions and types, folds, size and indexing |
C++ std::tuple, std::apply, std::variant |
tuples as the pack value, apply, sums over a type list |
C++'s std::bind_front, Haskell's uncurry |
combinators over argument lists |
Zig's inline for over tuples and comptime type lists |
a loop over a pack unrolled per element, and types computed by ordinary compile-time code |
Rust's libc crate and bindgen |
per-target bindings generated from headers, and why types from headers are not contracts |
Go's zerrors_* and zsysnum_* tables, generated per platform |
constants and system-call numbers as per-target data, checked against the platform |
GCC's format attribute |
argument checking for format strings, here as a proved requires |