Skip to main content

#[cgp_producer]

Define a Producer provider from an input-free function.

Overview​

In Context-Generic Programming (CGP), #[cgp_producer] is for the degenerate member of the handler family: a computation that takes no input and yields a value from nothing. CGP enables pluggable trait implementations in Rust, and this macro builds one from an input-free function. A constant, a default, a seed for a pipeline. It is the input-free sibling of #[cgp_computer], and like that macro it lets you write a plain function and have the provider synthesized for you:

#[cgp_producer]
fn magic_number() -> u64 {
42
}

That produces the provider struct MagicNumber and an impl of Producer, the family member whose method takes only a context (the type the method runs on) and a phantom Code tag, with no input value at all.

A dedicated macro is worth having because a producer can stand in for any handler: a handler that ignores its input behaves as a producer with an unused parameter. So the macro wires the generated provider into every member of the family, and one function definition answers produce, compute, try_compute, compute_async, handle, and their by-reference forms, every one of them yielding the same value regardless of what it is handed.

Usage​

Apply the attribute to a free function. It takes an optional provider name:

#[cgp_producer]
fn magic_number() -> u64 {
42
}

#[cgp_producer(TheAnswer)]
fn magic_number() -> u64 {
42
}

Omitted, the provider struct takes the function name in PascalCase: magic_number becomes MagicNumber, and a raw identifier loses its r#, so r#loop becomes Loop. Given, the argument is used verbatim. The function's return type becomes the producer's output, and an omitted return type is ().

The function is constrained tightly, to exactly what a producer can be. Each restriction is enforced at expansion time with its own message:

RestrictionWhy
No parameters, and no selfA producer takes no input and has no receiver.
Not asyncThe producer trait is synchronous.
No generic parametersThere is nothing to infer them from.
No impl Trait return typeThe generated impl's output type has to be nameable.

That last restriction is the one most likely to cause trouble, and it is the biggest difference from #[cgp_computer], which carries generics through fine. A producer has no input, so a type parameter would be determined by nothing at all.

Examples​

One function, read back through every shape the family offers:

use cgp::prelude::*;
use cgp::core::error::ErrorTypeProviderComponent;
use cgp::extra::handler::{Producer, Computer, TryComputer, Handler};

#[cgp_producer]
pub fn magic_number() -> u64 {
42
}

pub struct App;

delegate_components! {
App {
ErrorTypeProviderComponent: UseType<String>,
}
}

pub fn demo() {
// The single `magic_number` definition answers every shape, each yielding 42.
assert_eq!(MagicNumber::produce(&App, PhantomData::<()>), 42);
assert_eq!(MagicNumber::compute(&App, PhantomData::<()>, ()), 42);
assert_eq!(MagicNumber::try_compute(&App, PhantomData::<()>, "ignored"), Ok(42));

// The future resolves to Ok(42).
let _future = MagicNumber::handle(&App, PhantomData::<()>, ());
}

The computer and handler forms accept an input of any type and discard it, since the underlying producer takes none. App is an environmental context with no fields. The error type wired into it lets the fallible forms build their Result, and the produced value is always Ok.

The typical use is as the first step of a pipeline, where a producer seeds the value the later steps transform. With Double a #[cgp_computer] that doubles its input, and CanCompute, ComputerComponent, and PipeHandlers imported from cgp::extra::handler, App.compute(PhantomData::<()>, ()) returns 84:

delegate_components! {
App {
ComputerComponent:
PipeHandlers<Product![
MagicNumber,
Double,
]>,
}
}

When to use it​

Use #[cgp_producer] when a pipeline step needs no input. That is all it is for, and within it there is nothing simpler.

  • Use #[cgp_computer] as soon as there is an input, even a trivial one. It is the same macro with the restrictions lifted, and it handles generics, async, and Result returns.
  • Write the provider by hand with #[cgp_impl] when the value comes from the context. This is the boundary that matters. A #[cgp_producer] function has no receiver, so it cannot read a field, name an abstract type, or call another trait. It can only return something it computes from nothing. A producer that draws on its context is an impl of Producer written with #[cgp_impl], where self is the context and #[implicit] works normally. In practice that covers most producers, which makes this macro narrower than it first looks: it is for constants and pure seeds.
  • Use ReturnInput rather than a producer that ignores its input. If the goal is to pass a value through a pipeline unchanged, that combinator says so directly.
  • Do not use the handler family at all for a plain constant. A const or a function is clearer unless the value is being composed into a pipeline or dispatched on a Code tag.

Under the hood​

The macro's expansion is the function unchanged, a provider impl of Producer, and a delegate_components! block wiring the whole family. It builds the input for #[cgp_new_provider] and delegate_components! itself and runs their code in place, so what it emits is already their expansion, with every name written as a full path. The blocks below show that input, which is the readable form. From this function:

#[cgp_producer]
pub fn magic_number() -> u64 {
42
}

it produces the base impl, whose method ignores both of its parameters and calls the function:

#[cgp_new_provider]
impl<__Context__, __Code__> Producer<__Context__, __Code__> for MagicNumber {
type Output = u64;

fn produce(_context: &__Context__, _code: PhantomData<__Code__>) -> Self::Output {
magic_number()
}
}

#[cgp_new_provider] declares pub struct MagicNumber; and derives the IsProviderFor impl, whose parameter tuple here holds just the code tag. The context and code parameters carry the reserved names __Context__ and __Code__.

Then the wiring, which reaches all the other components:

delegate_components! {
MagicNumber {
[
ComputerComponent,
ComputerRefComponent,
TryComputerComponent,
TryComputerRefComponent,
AsyncComputerComponent,
AsyncComputerRefComponent,
HandlerComponent,
HandlerRefComponent,
]:
PromoteProducer<Self>,
}
}

A couple of things differ from #[cgp_computer]'s block. ComputerComponent is in the list, because a producer does not implement it directly. A computer takes an input and the producer has none, so the promotion discards it. And the operator is : rather than ->, delegating each component straight to PromoteProducer<Self> rather than to that bundle's own entry for the key. PromoteProducer then wires ComputerComponent to a promoter that drops the input and calls produce, and derives the remaining members from there.

Unlike #[cgp_computer], the expansion has no variation. Because the function cannot be async, cannot be generic, and is not inspected for a Result return, there is exactly one base trait and one bundle for every #[cgp_producer]: the output type is taken as written, whether or not it happens to be a Result.

Formal grammar​

The attribute argument is a single optional provider name, in the Rust Reference's notation:

CgpProducerArgs -> ProviderName?

ProviderName -> IDENTIFIER

Omitted, the provider struct takes the function name converted to PascalCase; a given IDENTIFIER is used verbatim. The annotated function is plain Rust, constrained to a producer's shape (no parameters, no async, no generics, and no impl Trait return type), as described in Usage.

Common Mistakes​

Each shape restriction has its own message, so the macro tells you which one you broke:

error: Producer functions cannot have parameters
error: Producer functions cannot be async
error: Producer functions must have empty generic parameters
error: Producer functions cannot return `impl Trait`

For the first two, #[cgp_computer] is the macro that accepts them. For the third there is no macro alternative: write the provider by hand. For the fourth, name the returned type.

The function cannot reach the context, so a producer that needs a field or an abstract type is not expressible this way at all. That rules out most real producers, which is worth knowing before reaching for the macro: write an impl of Producer with #[cgp_impl] instead.

A Result return is not interpreted, and this is the most confusing case on the page. Unlike #[cgp_computer], the macro does not inspect the output for fallibility, so a #[cgp_producer] returning Result<T, E> produces a Producer whose Output is that Result, and the fallible members wrap it again rather than treating it as failure:

producer produce = Err("nope")
producer try_compute = Ok(Err("nope"))

That Ok(Err(..)) is a success carrying an error, so it short-circuits nothing and a pipeline downstream keeps going. If the production can fail, write a TryComputer or Handler provider by hand instead.

The fallible forms still need an error type on the context. try_compute and handle name the context's abstract error, so a context lacking an ErrorTypeProviderComponent fails on those members while produce and compute work. Note also that the wiring key is not in the prelude: it has to be imported from cgp::core::error, and forgetting that reports the component as an unresolved type rather than as a missing import.

The ideas behind it:

  • Handlers — the computation family, and where the input-free member fits.

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.