Skip to main content

#[derive_delegate]

Generate the UseDelegate dispatcher impl for a component. Superseded by the open statement.

info

Legacy: read, don't write​

#[derive_delegate] and the UseDelegate provider it generates are the older way to choose an implementation per type. A component does not need this attribute to be dispatched on a type parameter: the open statement of delegate_components! does the same job through machinery every component already has, without a separate table or a wrapper.

Prefer open for anything new. This page exists because you will meet the older form, including in the library's own error and handler components, which are still defined with this attribute, and because a component that keeps it stays compatible with existing wiring. The project expects to deprecate the attribute once open is shown to cover every dispatch case.

Overview​

In Context-Generic Programming (CGP), #[derive_delegate] generates the dispatcher for a component that is generic over a type parameter. CGP enables pluggable trait implementations in Rust, and this attribute is the older way to choose one per type. Such a component usually wants a different implementation per value of the parameter: Rectangle handled one way, Circle another. Something has to look at the type and pick. Written by hand, that dispatcher is an implementation of the provider trait that reads a lookup table, finds the entry for the type, and forwards every method to it. That code is mechanical and identical in shape for every component, differing only in which parameter is the key. The attribute writes it for you:

#[cgp_component(AreaCalculator)]
#[derive_delegate(UseDelegate<Shape>)]
pub trait CanCalculateArea<Shape> {
fn area(&self, shape: &Shape) -> f64;
}

A context then points the component at UseDelegate over a table naming one implementation per shape, and the generated dispatcher does the lookup. (The context is the type the method runs on, and it also owns the wiring.)

open replaced this because the indirection turned out to be unnecessary. Every #[cgp_component] already generates a RedirectLookup impl, and open routes through that instead. So the per-type entries live on the context itself, the wiring does not name a second table type, and the component does not need an attribute.

Usage​

#[derive_delegate] takes a wrapper type parameterized by the trait generic to dispatch on:

#[derive_delegate(UseDelegate<Shape>)]

UseDelegate is the type that will carry the lookup table, and Shape is the trait parameter used as the key. The key may also be a parenthesized tuple when the table should be keyed on more than one parameter at once:

#[derive_delegate(UseDelegate<(Code, Input)>)]

To dispatch on several parameters independently, repeat the attribute, one per dispatcher. Each names its own wrapper type, and the macro uses only the parameter in that wrapper's brackets as its key. The rest flow through unchanged:

#[cgp_component(Computer)]
#[derive_delegate(UseDelegate<Code>)]
#[derive_delegate(UseInputDelegate<Input>)]
pub trait CanCompute<Code, Input> {
type Output;

fn compute(&self, _code: PhantomData<Code>, input: Input) -> Self::Output;
}

UseDelegate is the wrapper CGP provides, but the machinery is not tied to it. Any struct of the same shape works, so you add a second, independent dispatcher by defining your own wrapper. A user-defined pub struct UseInputDelegate<Components>(pub PhantomData<Components>); is all the second line above needs.

The attribute belongs on a #[cgp_component] trait and only makes sense for one that has generic parameters.

Examples​

A dispatching component, two implementations, and a context that routes each shape to its own:

use cgp::prelude::*;

#[cgp_component(AreaCalculator)]
#[derive_delegate(UseDelegate<Shape>)]
pub trait CanCalculateArea<Shape> {
fn area(&self, shape: &Shape) -> f64;
}

pub struct Rectangle { pub width: f64, pub height: f64 }
pub struct Circle { pub radius: f64 }

#[cgp_impl(new RectangleArea)]
impl AreaCalculator<Rectangle> {
fn area(&self, shape: &Rectangle) -> f64 {
shape.width * shape.height
}
}

#[cgp_impl(new CircleArea)]
impl AreaCalculator<Circle> {
fn area(&self, shape: &Circle) -> f64 {
core::f64::consts::PI * shape.radius * shape.radius
}
}

The wiring names the wrapper and defines its table in place:

pub struct MyApp;

delegate_components! {
MyApp {
AreaCalculatorComponent:
UseDelegate<new AreaCalculatorComponents {
Rectangle: RectangleArea,
Circle: CircleArea,
}>,
}
}

MyApp now implements CanCalculateArea<Rectangle> through RectangleArea and CanCalculateArea<Circle> through CircleArea, which a check confirms for both shapes:

check_components! {
MyApp {
AreaCalculatorComponent: [Rectangle, Circle],
}
}

MyApp is an environmental context and the component is parameter-targeted: the shape is the parameter, and MyApp carries only the wiring.

Write the same result without the attribute instead. Drop #[derive_delegate] from the component and let the context open it:

delegate_components! {
MyApp {
open AreaCalculatorComponent;

@AreaCalculatorComponent.Rectangle: RectangleArea,
@AreaCalculatorComponent.Circle: CircleArea,
}
}

This form does not need a wrapper, a second table type, or an attribute on the component. The two forms dispatch on the same parameter and resolve to the same implementations.

When to use it​

Do not add #[derive_delegate] to a new component. Use the open statement of delegate_components!, which needs neither an attribute nor a table type.

A few situations still involve the attribute, though none of them is a reason to write it on a new component.

  • Keeping compatibility with existing wiring. The attribute makes UseDelegate<new Table { … }> wiring possible, so removing it from a published component is a breaking change for any downstream user who wires that way. Removing it is still the right direction, but it is a breaking change to schedule rather than a cleanup to make in passing.
  • Dispatch on a later parameter. This needs no attribute either. The RedirectLookup impl that open resolves through appends every type parameter of the component to the lookup path, so a key with one segment per parameter dispatches on any of them. @ComputerComponent.<Code> Code.Circle selects by the input whatever the code, which is what a UseInputDelegate<Input> table does.
  • Reading existing code. CGP's own error and handler components are defined with this attribute, so UseDelegate tables appear in wiring you did not write. Understanding the form matters more than being able to author it.

Under the hood​

Each #[derive_delegate] adds one provider impl to everything #[cgp_component] already emits. It is the ordinary forwarding shape, except that the lookup key is the dispatch parameter rather than the component name. From the AreaCalculator example:

impl<__Context__, Shape, __Components__, __Delegate__>
AreaCalculator<__Context__, Shape> for UseDelegate<__Components__>
where
__Components__: DelegateComponent<(Shape), Delegate = __Delegate__>,
__Delegate__: AreaCalculator<__Context__, Shape>,
{
fn area(__context__: &__Context__, shape: &Shape) -> f64 {
__Delegate__::area(__context__, shape)
}
}

Reading it back: UseDelegate<Components> is a provider for any Shape whose entry in Components names something that is itself a provider for that Shape, and the method forwards. The Components type is the inner table, and DelegateComponent is the same trait ordinary wiring is made of, which is why you write the table with delegate_components! like any other.

The parenthesized key and the reserved generic names are worth recognizing in the real output. The macro wraps the key list in parentheses, so a multi-parameter key becomes a tuple: a UseDelegate<(Code, Input)> declaration produces DelegateComponent<(Code, Input), …> with no other change. With one parameter, the parentheses in DelegateComponent<(Shape), …> are only grouping, and Rust reads the key as the bare Shape. That is why the table's entries are written as Rectangle: RectangleArea rather than as one-element tuples. A trailing comma is kept, so #[derive_delegate(UseDelegate<(Shape,)>)] does key on the one-element tuple, and its table entries are then written (Rectangle,): RectangleArea. And the generics carry reserved names: the table is __Components__ and the looked-up entry __Delegate__, alongside the provider trait's own __Context__.

The dispatcher comes with a matching IsProviderFor impl under the same where clause, like the component's other generated provider impls, so a dependency missing inside the looked-up provider is still reported by name.

A component's supertraits carry into the dispatcher. The provider trait records each supertrait as a Context: predicate, and because the dispatcher reuses the provider trait's generics that predicate appears here too, so a component declaring an error type through #[use_type] yields a dispatcher whose where clause also requires __Context__: HasErrorType.

When several #[derive_delegate] attributes are present, the macro generates one impl per attribute, each keyed on its own parameter and otherwise identical. The impls are independent, so a context may dispatch on either or nest one table inside the other.

Formal grammar​

The attribute argument is a wrapper name and the parameters to key on, in the Rust Reference's notation:

DeriveDelegateArgs -> Wrapper `<` KeyParams `>`

Wrapper -> IDENTIFIER

KeyParams -> IDENTIFIER
| `(` IDENTIFIER ( `,` IDENTIFIER )* `,`? `)`

Both parts are required. Wrapper is a bare identifier rather than a path, so a wrapper reached through a module path has to be imported first. KeyParams are identifiers, not types: each must name a generic parameter the trait declares, and a type expression such as Vec<u8> in that position does not parse. The parenthesized form must list at least one parameter (the parser rejects an empty () with expect non-empty tuple list of identifiers in use_delegate_spec). A single parameter is keyed as the bare type whether it is written Shape or (Shape), and as a one-element tuple only when written with a trailing comma, (Shape,). The attribute may be repeated, once per dispatcher.

Common Mistakes​

The key must be a generic parameter the trait actually declares. The attribute names it by identifier, so a parameter that is not in scope on the trait is reported as an unresolved type rather than as anything about dispatch:

error[E0425]: cannot find type `Shape` in this scope
|
| #[derive_delegate(UseDelegate<Shape>)]
| ^^^^^ not found in this scope

The usual cause is putting the attribute on a component that has no type parameter to dispatch on, where there is nothing for it to do. The macro does not check the name against the trait's parameters, so a name that happens to resolve to a type in scope is accepted and used as a fixed key instead.

One component gets one dispatch mechanism. Wiring the same component both with open and with a UseDelegate table is a coherence conflict, because each produces its own table entry for that key. A wiring entry expands to two impls, and both of them collide, so the compiler reports the conflict twice, once for IsProviderFor and once for DelegateComponent. The DelegateComponent report is the readable one, because its trait argument names the component at issue:

error[E0119]: conflicting implementations of trait `DelegateComponent<AreaCalculatorComponent>`
for type `App`
|
| open AreaCalculatorComponent;
| ----------------------- first implementation here
|
| AreaCalculatorComponent:
| ^^^^^^^^^^^^^^^^^^^^^^^ conflicting implementation for `App`

Pick one per component. The related restriction is that open does not combine with a joined namespace where the component carries a #[prefix(...)]: its lookups are already routed under that path, so the per-type entries have to be written with the full prefixed path instead.

The ideas behind it:

  • Dispatching — the per-type routing this attribute is the legacy mechanism for.

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.