Sum!
A type-level sum, the dual of Product!.
Overview
In Context-Generic Programming (CGP), Sum![A, B, C] represents a choice among several
types as a single type. CGP uses it to describe the shape
of an enum, the list of its variants, the way Product! describes the fields of a
struct.
The pairing is exact and worth remembering. A Product! holds a value for every element at once, which is
a record. A Sum! holds a value for exactly one element, which is a tagged union:
Sum![u32, String, bool]
Like its dual it is built from a recursive list, and that recursion makes variant-by-variant
operations possible. Because an enum's variants are exposed as a single sum type through
HasFields, a provider can be written once to match on, dispatch over, or construct
any enum's variants without naming the concrete enum, by walking the nested branches. This is the basis for
CGP's extensible-variant machinery, where each variant is handled by descending the chain rather than by
writing a match against a fixed enum.
You essentially never write Sum! by hand. An enum's variant list is generated by
#[derive(HasFields)] or the extensible-data derives; the value of knowing
the construct is being able to read it in an expansion or an error.
Usage
The macro takes a comma-separated list of types, which may be empty, and a trailing comma is allowed. It is used wherever a type is expected:
Sum![u32, String, bool]
Sum![] // the empty sum
Each listed type is one possible variant, and a value of the sum type carries exactly one of them.
There are no options and no value-level counterpart: unlike Product!, which has
product!, a sum has no literal macro. A value is built with Either's own constructors, as
Either::Right(Either::Left(b)) for the second variant, or, for a derived enum, through
FromVariant.
Examples
The primary appearance is the variant list an enum derives, where each branch pairs a variant name with its payload:
use cgp::prelude::*;
#[derive(HasFields)]
pub enum Shape {
Circle(f64),
Rectangle { width: f64, height: f64 },
}
// generated, among other impls:
// impl HasFields for Shape {
// type Fields = Sum![
// Field<Symbol!("Circle"), f64>,
// Field<Symbol!("Rectangle"), Product![
// Field<Symbol!("width"), f64>,
// Field<Symbol!("height"), f64>,
// ]>,
// ];
// }
A couple of things to notice. The variant names are Symbol!
type-level strings, exactly as field names are. And a
variant's payload follows its fields, so an enum's full shape is a sum of variants whose payloads may
themselves be records:
- A single unnamed field is the payload type itself, as
Circle(f64)givesf64. - Named fields nest a
Product!ofFieldentries, asRectangledoes. - Several unnamed fields nest a
Product!keyed byIndex, soPair(f64, f64)givesProduct![Field<Index<0>, f64>, Field<Index<1>, f64>]. - A unit variant carries
Nil.
Generic code walks the Sum! to find which variant a value holds, then walks a nested Product! to
reach that variant's fields. #[derive(HasFields)] accepts all four shapes; the variant derives that
build and take apart values accept only the first, as Common Mistakes explains.
A standalone sum can be written directly, which is mostly useful for illustration:
type Token = Sum![u32, String, bool];
When to use it
Let the derives write it. That is the honest recommendation for this construct: unlike
Product!, which you write by hand for handler pipelines, Sum! has no everyday hand-written
use.
- Use
#[derive(CgpData)]or#[derive(HasFields)]on the enum, which generates the list from the variants you already declared. Writing it out means restating the enum, and the two will drift. - Use
Enum!where code has to name a variant list, in a bound or an impl:Enum! { Circle(f64), Rectangle { width: f64, height: f64 } }is the list above, written as an enum body. - Never hand-write the list.
Sum!expands toEither<A, Either<B, Void>>, and writing it out is longer and identical in meaning. - Use
Product!for a collection rather than a choice. They are duals: every element versus exactly one. A type error is the usual consequence of confusing them, which is at least loud. - Use a plain
enumandmatchwhen the variant set is closed and known. The machinery is worth using when independent code has to handle variants it did not define, or when the variant set is open. For a fixed enum consumed in one place, amatchis clearer and free.
Under the hood
Sum! expands to a right-nested chain of Either, terminated by Void:
// before
Sum![A, B, C]
// after
Either<A, Either<B, Either<C, Void>>>
The two building blocks differ from the product list in being branching rather than pairing.
Either<Head, Tail> is an enum with two cases: Left(Head) selects the head type, and Right(Tail) defers to
the rest of the chain. So a value of Either<A, Either<B, Either<C, Void>>> is Left for an A,
Right(Left(..)) for a B, and Right(Right(Left(..))) for a C.
The terminator is Void, an empty enum that can never be constructed, and choosing it rather than Nil is
the essential decision here. Reaching the Void position would mean the value matched none of the listed
types, which is impossible. So the type system knows the chain is exhausted. An empty Sum![] is therefore
Void: a type with no values.
That is precisely the asymmetry with Product!. A product terminates in Nil because an empty
record is a perfectly good value; a sum terminates in Void because an empty choice is uninhabited, there
being nothing to pick. Void functions as the never type, used here to close a sum off.
Why it matters beyond tidiness: this gives generic variant handling compile-time exhaustiveness
without a wildcard arm. As an extractor rules each variant out, it marks that variant's payload as
Void, so code that has handled every variant is left holding a value that cannot exist. The
compiler accepts discharging it without a fallback case. Add a variant to the enum without handling
it, and the remainder becomes inhabited again, so the code stops compiling. Generic code gets the
guarantee a concrete match gives.
The macro builds the chain by folding the element types right to left onto Void.
Formal grammar
The input is a possibly-empty comma-separated list of types, in the Rust Reference's notation:
SumInput -> ( Type ( `,` Type )* `,`? )?
Type is the Rust grammar's type production, and the list may be empty (Sum![]) or carry a trailing comma.
The macro is used in type position, and each listed type is one possible variant of the sum.
Common Mistakes
The empty sum is uninhabited, not empty-but-usable. Sum![] is Void, so a function claiming to return one
can never return at all. That is deliberate and occasionally useful, but it is not the analogue of an empty
collection.
A one-element sum is still a wrapper. Sum![T] is Either<T, Void>, a distinct type from T, so it needs
constructing and destructuring like any other.
Variant order is part of the type. Sum![A, B] and Sum![B, A] are unrelated. In practice the entries are
name-tagged Fields and the operations match on names, so this bites less than it might.
But the types are still different, and a cast between two enums works through the name matching rather than
by position.
The variant derives need each variant to hold one unnamed field or none.
#[derive(CgpData)], CgpVariant, ExtractField, and FromVariant
accept a unit variant with the payload Nil, but reject a multi-field or struct-like variant with
fields, while #[derive(HasFields)] accepts all of them:
error: Expected variant to contain exactly one unnamed field, or no fields
That is a restriction of those derives rather than of Sum! itself, and it is why richer payloads are
wrapped in a dedicated struct, as Rectangle(Rectangle): constructing or extracting a variant hands
over its payload as one value, so the payload has to be a single type.
Related constructs
Product!— the dual, for a collection rather than a choice.Enum!— writes aSum!of named variants as an enum body.- Type-level lists — the
Either/Voidtypes the expansion builds. Field— what the branches usually are, pairing a variant name with its payload.Symbol!— the name half of a branch.HasFields— the trait exposing an enum's shape as one of these sums.#[derive(CgpData)]— the derive that generates it, with the variant machinery.FromVariantandExtractField— constructing and taking apart a variant generically.CanUpcast— converting between two enums that share variants.
The ideas behind it:
- Extensible variants — the variant representation this list encodes.
Source
- Entry point:
sum.rs - The fold onto
Void:types/sum.rs - Runtime
EitherandVoid:cgp-field/src/types/sum.rs
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.