#[cgp_computer]
Define a Computer provider from a plain function.
Overview
In Context-Generic Programming (CGP), computation is modeled as a family of components
varying along three axes: synchronous or async, fallible or not, taking an input or not. CGP enables
pluggable trait implementations in Rust, and this macro builds one from a plain function. A provider in that family is a struct with one or more impls threading a
context (the type the method runs on, which supplies the values it needs as its fields), a
phantom Code tag, and an Input. Written by hand for a computation as small as "add two numbers", that is
far more code than the task needs.
#[cgp_computer] lets you write just the computation:
#[cgp_computer]
fn add(a: u64, b: u64) -> u64 {
a + b
}
From that the macro produces the provider struct Add, an impl of the right base trait, and the wiring
that makes the same function answer the whole family. That wiring is the part worth understanding.
Add satisfies
compute, try_compute, compute_async, and handle, along with their by-reference forms, without you
implementing any of them.
That last property is the whole reason for the macro. The family exists so a provider can declare
exactly the properties it has, and the promotion combinators exist
so a simpler provider can stand in where a more capable one is expected: an infallible computation
is a fallible one that never fails, a synchronous one is an async one that never awaits.
#[cgp_computer] picks the narrowest base that fits your function and wires the promotions for the
rest, so you write one body and get every shape.
Usage
Apply the attribute to a free function. It takes an optional provider name:
#[cgp_computer]
fn add(a: u64, b: u64) -> u64 {
a + b
}
#[cgp_computer(MyAdder)]
fn add(a: u64, b: u64) -> u64 {
a + b
}
Omitted, the provider struct takes the function name in PascalCase: add becomes Add, and a raw
identifier loses its r#, so r#type becomes Type. Given, the argument is used verbatim.
The function's shape decides everything else:
- Its parameters become the input. Several parameters are collected into one tuple, so
fn add(a: u64, b: u64)has input(u64, u64). A single parameter's input is its bare type, and no parameters give(). Only the parameter types matter, so a destructuring pattern such as(a, b): (u64, u64)is accepted and the input is that tuple type. - Its return type becomes the output, and an omitted return type is
(). - It must not take
self. A handler provider has no receiver; the context is supplied separately by the handler machinery. - It must not use
impl Trait, in a parameter or the return type, since the generated impl's input and output types have to be nameable. Declare a generic parameter instead. - It may be
async, and it may return aResult. Those two choices select the base trait. - Its generics and
whereclause carry over to the generated impl, so the provider can itself be generic.
What the two axes select
The macro reads async-ness and Result-ness independently, and each combination picks a base trait and a
promotion bundle:
| Your function | Base trait | Promotion bundle |
|---|---|---|
fn f(..) -> T | Computer | PromoteComputer<Self> |
fn f(..) -> Result<T, E> | Computer | PromoteTryComputer<Self> |
async fn f(..) -> T | AsyncComputer | PromoteAsyncComputer<Self> |
async fn f(..) -> Result<T, E> | AsyncComputer | PromoteHandler<Self> |
The Result row is worth a careful read. The base trait stays Computer, and its Output is the
Result type as written. Only the bundle changes, and it makes try_compute and handle
surface the Ok/Err outcome as success or failure rather than handing back a Result as a plain value.
The macro recognizes a Result by its spelling, not its meaning: only a return type written
Result<T, E>, with Result as the whole path and two arguments, is fallible. Any other type is a
plain value, and a type that starts with Result in another form, such as a one-argument alias, is
rejected. Common Mistakes shows what each spelling does.
Examples
One function, every shape. The context here only has to supply the error type the fallible members need:
use cgp::prelude::*;
use cgp::core::error::ErrorTypeProviderComponent;
use cgp::extra::handler::{Computer, TryComputer, AsyncComputer, Handler};
#[cgp_computer]
fn add(a: u64, b: u64) -> u64 {
a + b
}
pub struct App;
delegate_components! {
App {
ErrorTypeProviderComponent: UseType<String>,
}
}
pub fn demo() {
// All four are answered by the single `add` definition.
assert_eq!(Add::compute(&App, PhantomData::<()>, (1, 2)), 3);
assert_eq!(Add::try_compute(&App, PhantomData::<()>, (1, 2)), Ok(3));
// These futures resolve to 3 and Ok(3).
let _future = Add::compute_async(&App, PhantomData::<()>, (1, 2));
let _future = Add::handle(&App, PhantomData::<()>, (1, 2));
}
App is an environmental context with no
fields.
Because the function returns a plain u64, the fallible forms always succeed. Switching it to return a
Result changes which bundle is wired and therefore what those forms mean, with no change at the call
sites:
#[cgp_computer]
fn add_with_error(a: u64, b: u64) -> Result<u64, String> {
a.checked_add(b).ok_or_else(|| "Overflow".to_string())
}
Now try_compute and handle propagate the Err when the addition overflows.
A generic function carries its parameters and bounds onto the provider, so one definition covers every type that satisfies them:
#[cgp_computer]
pub fn add_generic<T: core::ops::Add<Output = T>>(a: T, b: T) -> T {
a + b
}
When to use it
Use #[cgp_computer] when a step in a pipeline is naturally a function. That is the case it
exists for, and it is the simplest way into the handler family.
- Use
#[cgp_producer]when the computation takes no input. A constant, or a value drawn from the context alone. It is the input-free sibling and produces aProducer. - Write the provider by hand with
#[cgp_impl]when the body needs the context. This is the real boundary. A#[cgp_computer]function has no receiver and no access to the context, so it can only transform its inputs. The moment the computation needs a field, an abstract type, or another trait, it wants a provider impl ofComputerorHandlerwritten with#[cgp_impl], whereselfis the context and#[implicit]and#[uses]work normally. - Use
#[cgp_fn]when you want a method on the context, not a pipeline step. The two look similar and differ in what they produce:#[cgp_fn]gives a trait a context implements, called asself.thing();#[cgp_computer]gives a provider that gets wired into a handler component and composed with combinators. If you are not building a pipeline, use#[cgp_fn]instead. - Wire the handler combinators directly for composition. The macro
produces one step;
PipeHandlersand friends chain them.
One thing not to do is use the handler family just because an operation happens to transform a value. The
family is worth using when computations are composed: piped, dispatched on a Code tag, promoted between
variants. A single transform with one caller is a method.
Under the hood
The macro's expansion is the function unchanged, a provider impl of the base trait, and a
delegate_components! block wiring the rest of the 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,
and it compiles in a module that does not import cgp::prelude::*. The blocks below show that
input, which is the readable form. From this function:
#[cgp_computer]
fn add(a: u64, b: u64) -> u64 {
a + b
}
it produces the base impl, with the parameters collected into a tuple that the method destructures back apart:
#[cgp_new_provider]
impl<__Context__, __Code__> Computer<__Context__, __Code__, (u64, u64)> for Add {
type Output = u64;
fn compute(
_context: &__Context__,
_code: PhantomData<__Code__>,
(arg_0, arg_1): (u64, u64),
) -> Self::Output {
add(arg_0, arg_1)
}
}
#[cgp_new_provider] declares pub struct Add; and derives the
IsProviderFor impl, whose parameter tuple here is
(__Code__, (u64, u64)), the code tag and the input. The context and code parameters are introduced under
the reserved names __Context__ and __Code__, and the body ignores both.
Then the promotion wiring, which is the interesting half:
delegate_components! {
Add {
[
ComputerRefComponent,
TryComputerComponent,
TryComputerRefComponent,
AsyncComputerComponent,
AsyncComputerRefComponent,
HandlerComponent,
HandlerRefComponent,
] ->
PromoteComputer<Self>,
}
}
Note the -> operator rather than :. It delegates each key to the value's own entry for that key
rather than to the value itself, so Add inherits whatever PromoteComputer<Self> resolves each component
to. PromoteComputer is itself a table of single-step promoters.
ComputerComponent is absent from the list because Add implements it directly.
The other combinations differ only in which base trait is implemented and which bundle is named. An
async function implements AsyncComputer instead, its method is compute_async and awaits the call, and
it delegates a smaller set (AsyncComputerRefComponent, HandlerComponent, HandlerRefComponent), since
the synchronous members are not derivable from an async base. A Result-returning function keeps its base
trait and swaps the bundle to PromoteTryComputer<Self> or, when also async, PromoteHandler<Self>.
Generics flow through to the impl, appended ahead of the introduced __Context__ and __Code__
parameters, so add_generic<T> yields a provider generic over T carrying the T: Add<Output = T> bound. A
reference parameter is preserved too: fn to_string_ref<V: Display>(value: &V) -> String becomes a
Computer whose input tuple is (&V), and the bundle's by-reference entries make it serve the …Ref
components.
Formal grammar
The attribute argument is a single optional provider name, in the Rust Reference's notation:
CgpComputerArgs -> 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, and the macro reads its parameters, return type,
async-ness, generics, and where clause to choose the base trait and promotion bundle as described above.
Common Mistakes
The function cannot reach the context. There is no receiver and no context parameter in scope, so
#[implicit] arguments and #[uses] have nothing to attach to. A computation that needs anything from its
context is a provider impl written with #[cgp_impl], not a #[cgp_computer].
Several parameters become one tuple input. That is invisible when the provider is wired into a pipeline
that supplies the tuple, and very visible when calling the provider directly:
Add::compute(&App, PhantomData::<()>, (1, 2)) takes one argument, not two. A single-parameter function's
input is (T), which Rust treats as plain T.
The fallible forms need an error type on the context. try_compute and handle name the context's
abstract error, so a context wiring the provider without an
ErrorTypeProviderComponent fails on those members while compute works
fine. This is an error about the error type, arriving only for part of the family:
error[E0277]: the trait bound `App: DelegateComponent<ErrorTypeProviderComponent>` is not satisfied
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.
Only a Result<T, E> spelled exactly that way selects the fallible bundle. Any other spelling,
such as core::result::Result<u64, String> or anyhow::Result<u64>, is treated as a plain value,
so try_compute wraps the whole result in Ok instead of propagating its error. A one-argument
alias written Result<u64>, such as the one use anyhow::Result; brings in, is rejected, since
the macro cannot tell what it names:
error: A `Result` return type must be written as `Result<T, E>`, naming its error type
Write the full Result<T, E> form in a fallible computer's signature.
A Result function's error type must be the context's error type. The fallible bundles pass
the Err through unchanged rather than converting it, so a function returning
Result<u64, String> needs a context whose error type is String, and any other type fails the
fallible members:
error[E0271]: type mismatch resolving `<App as HasErrorType>::Error == String`
Convert inside the function, or write a TryComputer provider by hand that raises its own error
through the context.
A function with a receiver is rejected, with Computer functions cannot have a receiver.
impl Trait is rejected. In a parameter it fails with
Computer function parameters cannot use impl Trait; declare a generic parameter instead, and in
the return type with Computer functions cannot return impl Trait. A parameter's impl Trait is
shorthand for a generic parameter, so the fix is to write that parameter out.
A type parameter used only in the return type is rejected. The function's generics move onto the
generated impl, which names only the input type, so in
fn parse<T: FromStr>(value: String) -> Option<T> nothing fixes T, and the macro says so:
error: the parameter `T` appears in no argument type, so the generated `Computer` impl cannot determine it; take an argument whose type names `T`, or write the provider by hand as a `Computer` impl on a provider generic over `T`
Such a computation needs a Computer provider written by hand, whose struct can carry T.
A Result return changes the bundle, not the base trait. The Computer impl's Output is the
Result, so compute hands back a Result as an ordinary value while try_compute treats its Err as
failure. Both are available on the same provider, and which one a pipeline uses decides whether an error
short-circuits.
Related constructs
#[cgp_producer]— the input-free sibling, producing aProducer.Computer— the base component, with its by-reference and async variants.HandlerandTryComputer— the more capable members the promotions reach.- Handler combinators — the
Promote*bundles this wires, plusPipeHandlersandComposeHandlersfor composing steps. #[cgp_impl]— for a handler provider that needs its context.#[cgp_fn]— for a method on the context rather than a pipeline step.#[cgp_new_provider]— what the generated impl is emitted through.#[cgp_auto_dispatch]— generates per-variant computers from a trait.
The ideas behind it:
- Handlers — the computation family this provider joins, across its sync, fallible, and input-free axes.
Source
- Entry point:
cgp-macro-extra-lib/src/cgp_computer.rs - The parsing and code generation:
cgp-macro-extra-core/src/types/cgp_computer/, with theResult-versus-value detection inmaybe_result.rs - The base traits:
cgp-handler/src/components/ - The promotion bundles:
providers/promote_all.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.