Skip to main content

Product! & product!

A type-level list and its value-level counterpart.

Overview​

In Context-Generic Programming (CGP), Product![A, B, C] represents an ordered sequence of types as a single type. CGP uses it to describe the shape of a struct: the list of its fields, in order, as one type that generic code can reason about.

It is sometimes called an anonymous product type, because like a tuple it holds several things at once. The difference from a tuple is the one that matters: a Product! is built from a recursive list that generic code can take apart one element at a time:

Product![u32, String, bool]

That recursion makes structural, field-by-field operations possible at all. Because a struct's fields are exposed as a single list type through HasFields, a provider can be written once to walk, transform, or rebuild any struct's fields without naming the concrete struct, by recursing over the list. A plain tuple cannot be decomposed that way in generic code; the recursive list can.

The lowercase product![a, b, c] is the value-level half. Product! produces a type and is used in type position (associated types, bounds, aliases), while product! produces a value of the matching type and is used in expression position, mirroring Rust's own split between a struct type and a struct literal.

You mostly read these rather than write them. A struct's field list is generated by #[derive(HasFields)]; you write Product! by hand in a handler pipeline, listing the steps to run in order.

Usage​

Both macros take a comma-separated list, which may be empty, and a trailing comma is allowed:

Product![u32, String, bool] // a type
product![1u32, "hi".to_string(), true] // a value of that type
Product![] // the empty list type

The element lists line up positionally, so the value product! builds has exactly the type Product! builds over the corresponding element types.

Product! is used wherever a type is expected and product! wherever a value is expected. Nothing else about them varies: there are no options and no attributes.

Examples​

The commonest appearance by far is the field list a struct derives, where each element pairs a field name with its type:

use cgp::prelude::*;

#[derive(HasFields)]
pub struct Person {
pub name: String,
pub age: u8,
}

// generated, among other impls:
// impl HasFields for Person {
// type Fields = Product![
// Field<Symbol!("name"), String>,
// Field<Symbol!("age"), u8>,
// ];
// }

The names are Symbol! type-level strings and each entry is a Field, so the whole Product! is a complete type-level description of Person's layout. Generic code walks that list to build or read a Person without being written against Person. The derive emits the same list again for HasFieldsRef, over references, along with the ToFields, ToFieldsRef, and FromFields conversions.

You write Product! yourself in a handler pipeline, where the list is the program: the steps run left to right. Here Multiply<Tag> and Add<Tag> stand for computers that read a u64 field named by Tag, so MyContext computes ((input * foo) + bar) * baz:

delegate_components! {
MyContext {
ComputerComponent:
PipeHandlers<Product![
Multiply<Symbol!("foo")>,
Add<Symbol!("bar")>,
Multiply<Symbol!("baz")>,
]>,
}
}

A standalone list and a matching value can also be written directly, which is mostly useful for illustration:

type Row = Product![u32, String, bool];
let row: Row = product![1, "hi".to_string(), true];

When to use it​

Write Product! when a construct asks for a type-level list, which in practice means a handler pipeline or a provider list. Everywhere else it is generated for you.

  • Never hand-write the list. Product! expands to Cons<A, Cons<B, Nil>>, and writing it out is strictly worse: longer, harder to change, and identical in meaning. The same holds for Sum!'s list.
  • Use #[derive(HasFields)] for a struct's shape rather than declaring the list yourself. Writing it by hand means restating the struct, and the two will disagree eventually.
  • Use Struct! where code has to name a list of named fields, in a bound or an impl: Struct! { name: String, age: u8 } is this same Product! of Field entries, written as a struct body.
  • Use a tuple when nothing generic consumes it. A Product! is worth using only where code recurses over the list; for a fixed group of values passed between known functions, a tuple or a struct is clearer and needs no machinery.
  • Use Sum! for a choice rather than a collection. Product! holds a value for every element; Sum! holds one for exactly one. They are duals, and mixing them up produces a type error rather than a subtle bug.

Under the hood​

Product! expands to a right-nested chain of Cons, terminated by Nil:

// before
Product![A, B, C]

// after
Cons<A, Cons<B, Cons<C, Nil>>>

Both building blocks are ordinary types. Cons<Head, Tail> is a tuple struct holding the first element and the rest of the list (Cons<Head, Tail>(pub Head, pub Tail)), and Nil is a unit struct terminating it. Chaining through the tail gives a list of any length, and the empty Product![] is Nil. The macro builds the chain by folding the elements right to left onto Nil.

product! folds identically but produces a value, using Cons's tuple-struct constructor:

// before
product![a, b, c]

// after
Cons(a, Cons(b, Cons(c, Nil)))

Because Cons is a real struct and Nil a real unit struct, the result is an ordinary owned value whose type exactly matches what Product! builds over the same elements' types. There is no hidden layer between the two macros: they are the same fold at two levels.

What this means for reading errors: a mismatched field list is reported as a mismatch between two Cons chains, and the position where they diverge is the field that differs. An error mentioning Cons<u32, Cons<bool, Nil>> where you expected three fields is telling you the third entry is missing.

Formal grammar​

Both macros take a possibly-empty comma-separated list, in the Rust Reference's notation:

ProductInput -> ( Type ( `,` Type )* `,`? )?

ProductExpr -> ( Expression ( `,` Expression )* `,`? )?

ProductInput is the grammar of the type macro Product!, used in type position; ProductExpr is the grammar of the value macro product!, used in expression position. Type and Expression are the Rust grammar's productions. Both lists may be empty (Product![], product![]) or carry a trailing comma, and they line up positionally so a product! value has the type the corresponding Product! builds.

Common Mistakes​

Product! and product! differ only in case, and the compiler's complaint will not say so. Using the type macro in expression position fails inside the macro's own parser, which is expecting a type, so the message is a list of type-position tokens with no hint that the lowercase macro was wanted:

error: expected one of: `for`, parentheses, `fn`, `unsafe`, `extern`, identifier, `::`, `<`, `dyn`, square brackets, `*`, `&`, `!`, `impl`, `_`, lifetime

The reverse slip is no clearer. product! in type position expands to the constructor call Cons(u32, …), which rustc reads as a parenthesized type argument:

error[E0214]: parenthesized type parameters may only be used with a `Fn` trait

A one-element list is still a list. Product![T] is Cons<T, Nil>, which is a distinct type from T, so a pipeline of one step still needs the list, and unwrapping it is a type error rather than a no-op.

The empty list is Nil, a real value. That is the difference from Sum!, whose empty form is the uninhabited Void. An empty record exists; an empty choice cannot.

Element order is part of the type. Product![A, B] and Product![B, A] are unrelated types. For a field list this matters less than it sounds, because the entries are name-tagged Fields and the operations that consume them match on names. But for a handler pipeline the order is the execution order.

  • Sum! — the dual, for a choice among types rather than a collection of them.
  • Struct! — writes a Product! of named or positional Field entries as a struct body.
  • Type-level lists — the Cons/Nil types the expansion builds.
  • Field — what the entries usually are, pairing a name with a type.
  • Symbol! — the name half of a Field entry.
  • HasFields — the trait that exposes a struct's shape as one of these lists.
  • #[derive(HasFields)] — generates that list for you.
  • AppendProduct — the operations that combine and transform these lists.
  • Handler combinators — where Product! is written by hand, as a pipeline.

The ideas behind it:

Source​


An AI agent wrote this page using the CGP knowledge base. Its content was verified against the library's source. See How AI is used in this project.