Skip to main content

#[use_provider]

Depend on another provider by name, importing the provider trait it must satisfy.

Overview​

In Context-Generic Programming (CGP), #[use_provider] declares that an implementation depends on another implementation, by importing the provider trait the inner provider must satisfy. CGP enables pluggable trait implementations in Rust, and #[use_provider] is how one implementation names another it builds on. An implementation with such a dependency is a higher-order provider: a wrapper that scales whatever an inner calculator produces, or a retry layer over whatever performs a request.

#[use_provider(InnerCalculator: AreaCalculator)]

That reads as InnerCalculator is an AreaCalculator for this context, and it is the provider-side counterpart to #[uses]. #[uses] imports a consumer trait (or an ordinary Rust trait) that the context must satisfy. #[use_provider] imports a provider trait that a named provider must satisfy for the context. The context is the type the implementation runs against. Both attributes read as importing a dependency. They differ only in whether the dependency is a trait of the context or a provider.

The inner provider is a named type rather than a method on the context, so the body calls it as an associated function and passes the context:

let base_area = InnerCalculator::area(self);

#[use_provider] writes the bound behind that call. It does not rewrite the call. Writing self.area() instead would route through whatever provider the context has itself wired for AreaCalculator, which is a different choice and usually not what a higher-order provider wants.

Usage​

#[use_provider(...)] takes a provider, a colon, and the trait bounds it must satisfy:

#[use_provider(InnerCalculator: AreaCalculator)]

InnerCalculator is the provider, usually a generic parameter of the implementation, and AreaCalculator is the provider trait it must satisfy. The trait may carry further arguments of its own, lifetimes included, as in #[use_provider(Inner: Namer<'a>)], and the macro keeps them after the context argument it inserts.

The form to use depends on whether one provider must satisfy several traits, or several providers must each satisfy one.

One provider, several traits: join them with +.

#[use_provider(Inner: AreaCalculator + PerimeterCalculator)]

Several providers: one attribute each, stacked.

#[use_provider(A: AreaCalculator)]
#[use_provider(P: PerimeterCalculator)]

Stacking is the intended form here rather than a fallback, because the parser does not accept a comma-separated list of provider-and-trait pairs (see Common Mistakes). This differs from #[uses] and #[use_type], where commas are the preferred way to carry several entries, so remember #[use_provider] as the exception.

#[use_provider] is accepted on #[cgp_impl] and on #[cgp_fn], and it works the same way on both. On any other host, such as a #[cgp_component] trait, nothing reads the attribute, and the compiler reports cannot find attribute `use_provider` in this scope.

Examples​

The typical use is a wrapper parameterized by whatever it wraps. Given a component and a plain implementation of it:

use cgp::prelude::*;

#[cgp_component(AreaCalculator)]
pub trait CanCalculateArea {
fn area(&self) -> f64;
}

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

a scaling wrapper takes the inner implementation as a parameter, declares it with #[use_provider], and calls it by name:

#[cgp_impl(new ScaledArea<InnerCalculator>)]
#[use_provider(InnerCalculator: AreaCalculator)]
impl<InnerCalculator> AreaCalculator {
fn area(&self, #[implicit] scale_factor: f64) -> f64 {
let base_area = InnerCalculator::area(self);
base_area * scale_factor * scale_factor
}
}

A context then composes the two when it wires the component, and ScaledArea<RectangleArea> computes a rectangle's area and scales it. Rectangle is a value context, the shape being measured, and it carries the fields both layers read:

#[derive(HasField)]
pub struct Rectangle {
pub width: f64,
pub height: f64,
pub scale_factor: f64,
}

delegate_components! {
Rectangle {
AreaCalculatorComponent: ScaledArea<RectangleArea>,
}
}

check_components! {
Rectangle {
AreaCalculatorComponent,
}
}

Because the wrapper never names a particular inner implementation, the same ScaledArea composes over any of them. The composition is itself a type, so type ScaledRectangle = ScaledArea<RectangleArea>; is a complete way to name the combination.

The attribute is also useful for depending on one specific implementation rather than a parameter. A #[cgp_fn] does exactly that when it wants a named implementation instead of whatever the context has wired:

#[cgp_fn]
#[use_provider(RectangleArea: AreaCalculator)]
pub fn rect_area(&self) -> f64 {
RectangleArea::area(self)
}

When to use it​

Use #[use_provider] whenever an implementation depends on another implementation by name, in preference to writing the bound by hand. You read the explicit Inner: AreaCalculator<Self> form in generated code and older wiring rather than write it.

The choice against its neighbours turns on what the implementation depends on, and one distinction is easy to miss because both spellings compile.

  • A trait of the context is #[uses], which imports a consumer trait or an ordinary trait the context satisfies. #[use_provider] imports a provider trait instead, one that a separate provider satisfies for the context.
  • Whatever the context already chose needs no attribute at all. Calling self.area() in the body routes through the context's own wiring, which is a different dispatch from InnerCalculator::area(self): the method call asks the context, and the associated-function call names an implementation statically. Use #[use_provider] only when you want the named implementation.
  • A choice made per type rather than fixed is dispatch rather than parameterization, so it belongs in the wiring: the open statement of delegate_components! maps each type to its own implementation.

A default of UseContext on the parameter, as in pub struct IterSum<Inner = UseContext>(...), makes an unparameterized IterSum fall back to the context's own wiring, so a context can use the wrapper without naming a base case. This option matters when you write the provider struct by hand.

Under the hood​

A provider trait is not shaped like the consumer trait it came from. The original Self moves into an explicit leading type parameter for the context, so the real bound on an inner provider is InnerCalculator: AreaCalculator<Self>. The consumer trait has no counterpart for that context argument. #[use_provider] writes that <Self> for you: it inserts the context type as the provider trait's leading argument and appends the completed bound to the where clause. Nothing else changes, and the macro emits the body as written. From the ScaledArea example:

#[cgp_impl(new ScaledArea<InnerCalculator>)]
#[use_provider(InnerCalculator: AreaCalculator)]
impl<InnerCalculator> AreaCalculator {
fn area(&self, #[implicit] scale_factor: f64) -> f64 {
InnerCalculator::area(self) * scale_factor * scale_factor
}
}

the macro emits the provider implementation with the argument filled in:

impl<__Context__, InnerCalculator> AreaCalculator<__Context__>
for ScaledArea<InnerCalculator>
where
__Context__: HasField<Symbol!("scale_factor"), Value = f64>,
InnerCalculator: AreaCalculator<__Context__>,
{
fn area(__context__: &__Context__) -> f64 {
let scale_factor: f64 = __context__
.get_field(PhantomData::<Symbol!("scale_factor")>)
.clone();

InnerCalculator::area(__context__) * scale_factor * scale_factor
}
}

The Self you wrote in the attribute is the context, so it appears as __Context__ here, the reserved name the surrounding macro inserted. Writing #[use_provider(InnerCalculator: AreaCalculator)] is therefore exactly equivalent to writing where InnerCalculator: AreaCalculator<Self> by hand.

The bound also reaches the provider's IsProviderFor impl, and because it names the component's own provider trait, that impl gains a matching InnerCalculator: IsProviderFor<AreaCalculatorComponent, __Context__, ()> bound as well. That is how a dependency missing inside the inner provider surfaces through the wrapper when the context is checked. A component that carries a lifetime does not get this counterpart, a known defect described under #[cgp_provider].

On a #[cgp_fn] the same insertion happens. Because that macro's implementation is written for the context, the bound reads with Self directly:

impl<__Context__> RectArea for __Context__
where
RectangleArea: AreaCalculator<Self>,
{
fn rect_area(&self) -> f64 {
RectangleArea::area(self)
}
}

The macro leaves the body untouched in both. The call stays InnerCalculator::area(__context__), passing the context as the first argument, because that is the shape the provider trait's method has.

Formal grammar​

The attribute argument is one provider and the provider traits it must satisfy, in the Rust Reference's notation:

UseProviderArgs -> ProviderType `:` ( ProviderBound ( `+` ProviderBound )* `+`? )?

ProviderType -> Type
ProviderBound -> TypePath GenericArgs?

The provider and the colon are required. ProviderType names the generic parameter the inner provider occupies, and each ProviderBound is the provider trait to require of it, written without its leading context argument, which the attribute inserts. The bound list may end with a +, and it may even be empty: #[use_provider(Inner:)] parses and adds a where Inner: predicate that requires nothing.

Those productions carry the restrictions that account for every parse failure this attribute produces. ProviderBound is a path with plain generic arguments, not a full TypeParamBound, so a turbofish or an associated-type binding in that position does not parse: AreaCalculator<Output = f64> fails with associated bindings (`Name = ...`) are not allowed in type arguments. A bound of that shape belongs in the block's own where clause. And the argument holds exactly one provider, because the +-separated bound list runs to the end of the attribute, so a comma after the first pair lands where a + was expected. That makes this attribute the one exception to the comma-separated convention its siblings follow: bind several inner providers by stacking one attribute each. See Common Mistakes.

Common Mistakes​

A comma-separated list of pairs is not accepted. Writing two providers in one attribute is a parse error, because after the first trait the parser is looking for a + to continue that provider's bounds:

error: expected `+`
|
| #[use_provider(A: AreaCalculator, P: PerimeterCalculator)]
| ^

Use one attribute per provider instead. This is the opposite of the convention for #[uses] and #[use_type], which do take comma-separated lists, so the habit from those attributes leads to this error.

The provider and the trait are both required. The attribute does not accept a bare provider name, and omitting the bound reports the missing colon:

error: expected `:`
|
| #[use_provider(RectangleArea)]
| ^

The attribute does not rewrite call sites. It never turns self.area() into InnerCalculator::area(self), so a body that calls the method on self compiles but does something different: it dispatches through the context's own wiring rather than through the parameter. When the intent is to use the inner implementation, write the associated-function call.

  • #[cgp_impl] and #[cgp_fn] — the two hosts.
  • #[cgp_component] — generates the provider trait whose argument is filled in.
  • #[uses] — the counterpart for a bound on the context rather than on a provider.
  • UseContext — the usual default for an inner-provider parameter.
  • delegate_components! — where a composed wrapper is wired.
  • check_components! — its #[check_providers(...)] form checks each layer of a nested stack separately, which localizes a broken layer.

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.