Skip to main content

delegate_components!

Build a context's wiring table, naming the provider that implements each of its components.

Overview​

In Context-Generic Programming (CGP), #[cgp_component] separates the trait callers use from the trait implementations target, which leaves one question open: for a given type, which implementation supplies the behavior? delegate_components! answers it. You give it a type and a list of entries, the component name as the key and the chosen provider as the value, and it records that choice on the type. CGP enables pluggable trait implementations in Rust, and delegate_components! is where a context picks them.

delegate_components! {
Rectangle {
AreaCalculatorComponent: RectangleArea,
}
}

Think of the result as a table: a compact list saying which implementation supplies each trait. But one point needs precision, because the analogy suggests a wrong conclusion. This looks like an object's method table, but the compiler resolves it entirely at compile time: the keys and values are types, the lookup happens during trait resolution, and the result monomorphizes to a direct call. The compiled program contains neither a table nor dynamic dispatch, and the binary holds nothing for a provider you did not choose.

The type that carries this table is a context: the type that owns the wiring. Often it is a type standing for your whole application, whose job is to carry choices rather than data. struct App; without fields is a perfectly good context. Sometimes, as above, it is the data type itself.

You need a macro here because each entry expands to two impls rather than one. Besides the impl that stores the choice, the macro emits a second one that forwards the chosen provider's own dependencies back through the table. So a missing transitive requirement produces a usable error instead of one that does not name the cause. Under the hood shows both.

Usage​

The macro takes a target type and a brace-delimited body. The body holds any number of statements followed by any number of mappings, and a mapping is a key, an operator, and a value, chosen independently. This section covers the target forms first, then the operators, the key forms, the value forms, and the statements.

Every one of these forms combines with the others inside a single block. A table routinely opens a component for per-type dispatch, joins a namespace, and still maps plain component names to providers alongside them. The only ordering rule is that statements come first.

The simplest table needs none of that:

delegate_components! {
Rectangle {
AreaCalculatorComponent: RectangleArea,
}
}

Defining the target at the same time​

A leading new keyword makes the macro declare the target struct as well. A target with parameters, as in <T> new MyComponents<T> { … }, is declared with a PhantomData field over them. The target's parameters take their kinds from the leading generic list, so <const N: usize> new ArrayTable<N> { … } declares ArrayTable<const N: usize>, and the PhantomData field covers only the lifetime and type parameters.

delegate_components! {
new GeometryComponents {
AreaCalculatorComponent: RectangleArea,
PerimeterCalculatorComponent: RectanglePerimeter,
}
}

Use this form to build an aggregate provider: a zero-sized provider whose only job is to hold a table dispatching each component to a sub-provider, so that other contexts can delegate a whole group of components to it as one unit. An aggregate provider is a provider, not a context. It forwards each component's provider trait onward, and a call never resolves with the bundle in the context position. So you must wire it with plain delegate_components! and never with delegate_and_check_components!. That macro's check asks whether the bundle can use each component as a context, so it proves nothing either way.

One table for a family of types​

A leading generic list makes the whole table generic, wiring every instantiation at once:

delegate_components! {
<T> MyContext<T> {
AreaCalculatorComponent: RectangleArea,
}
}

The operators​

The operator between a key and its value decides what the entry resolves to. The parser accepts any operator with any key form. The notes below say which pairings are worth writing.

OperatorReads asThe entry resolves to
Key: ProviderName a providerthat provider, exactly as written
Key -> TableDelegate directlywhatever Table's own entry for Key holds
Key => @pathRedirectwherever the path lands, resolved later

Nearly all wiring uses :, and the rest of this page's examples assume it unless they say otherwise.

-> is direct delegation. Instead of naming a provider it forwards the lookup one hop into another table, and the macro adds a bound requiring that the named table actually has an entry for that key. This is how one table adopts a single choice from another rather than repeating it:

delegate_components! {
new ScaledGeometryComponents {
AreaCalculatorComponent:
ScaledAreaCalculator<RectangleArea>, // the provider *is* this scaled calculator
PerimeterCalculatorComponent ->
GeometryComponents, // the provider is whatever GeometryComponents wires for perimeter
}
}

Compare the two lines, because the difference is easy to miss. The : entry names ScaledAreaCalculator<RectangleArea> outright, so ScaledGeometryComponents scales the area calculation. The -> entry reaches into GeometryComponents's table and copies out whatever it holds for PerimeterCalculatorComponent, so the perimeter stays exactly as GeometryComponents already computes it, unscaled.

=> is redirection. It sends the lookup along a type-level path rather than to a provider, so the place where the path finally lands decides the provider. On a context, that path names a slot in the context's own table, so you can point several components at one shared slot and answer them from a single entry:

delegate_components! {
App {
[AreaCalculatorComponent, PerimeterCalculatorComponent] =>
@shared,

@shared: RectangleGeometry,
}
}

The open statement below uses this same mechanism: open AreaCalculatorComponent; is another spelling of AreaCalculatorComponent => @AreaCalculatorComponent, and generates the same impl. The other use of => is rerouting a whole path prefix at once, which is a namespace concern more than a per-context one.

The key forms​

A single key is one component name, and may carry generics of its own: <Shape> ShapeAreaCalculatorComponent<Shape>: SumAreas adds a parameter to that entry alone, for a component whose marker carries the trait's parameter through the name: key of #[cgp_component]. Those generics may carry bounds, as in <Shape: Clone>, but not defaults.

A list key is a bracketed list, expanding to one entry per name so several components share one value:

delegate_components! {
MyComponents {
[
AreaCalculatorComponent,
PerimeterCalculatorComponent,
]: RectangleGeometry,
ColorComponent: SolidColor,
}
}

Each bracketed element is a full key, so an element may carry its own generics: in [WidthKey<T1>, <T2> HeightKey<T1, T2>]: RectangleValue<T1> only the second key introduces T2. The list itself takes no generic list, so <T> [WidthKey<T>, HeightKey] fails with expected square brackets; put the parameter on the element that uses it. The list is a key form rather than an operator, so [A, B] -> SomeTable and [A, B] => @somewhere are as legal as [A, B]: Provider. The -> form adopts several of another table's entries at once, and the => form points several components at one shared slot.

A path key is an @-prefixed route rather than a bare name, and it addresses a slot behind a redirect: the per-value slots an open statement opens, or the prefixed routes a namespace registers. @AreaCalculatorComponent.Rectangle: RectangleArea stores RectangleArea where the AreaCalculatorComponent redirect lands when the dispatch type is Rectangle. Segments follow Path!'s convention: a lowercase, non-primitive identifier becomes a type-level string, and anything else names a type. A segment may also carry generics, as in @SomeComponent.<'a, T> &'a T: SomeProvider.

Two grouping forms expand one path key into several, and they are not interchangeable:

  • […] groups alternatives for one segment, and the path may continue after it. @app.[AreaCalculatorComponent, PerimeterCalculatorComponent].[u64, String]: RectangleGeometry writes four entries: the cartesian product of the two groups.
  • {…} groups whole remainders, and ends the path. Its elements may be different lengths and may nest further groups, which lets one entry cover routes of different shapes.
delegate_components! {
App {
namespace ExtendedNamespace;

@app.{
ErrorRaiserComponent.{&'static str, String},
ErrorWrapperComponent,
}: RaiseFrom,
}
}

Remember it this way: […] is a choice within a segment and {…} is a choice of tails.

Every bracketed or braced list on this page, the list key and open { … } included, may also be empty. An empty list produces no entries and no error, so a list emptied by an edit compiles silently.

The value forms​

A value is normally a type: the provider, or the table a -> forwards into. One other form exists, and it is legacy.

info

Legacy: read, don't write​

Older code dispatches per type by nesting a table inside a UseDelegate value instead of using the open statement below. Prefer open for anything new: it needs neither a separate table type nor a wrapper. This page keeps the form because you will see it in existing code, including in CGP's own error and handler components, which are still defined this way.

Nesting a table inside a UseDelegate value looks like this:

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

A few details of the form are easy to miss. The inner braces hold a full table body, so an inner table accepts everything an outer one does, nesting included. The wrapper is not fixed to UseDelegate: the macro accepts any wrapper named by a single identifier, so a component whose #[derive_delegate] names a wrapper of your own, such as a UseDelegate2 keyed on a tuple of its parameters, is wired the same way. A qualified name such as cgp::prelude::UseDelegate<new …> is not recognized as this form and fails with expected `,` at the inner table's name, so import the wrapper instead. And the inner table's name may carry generics, which a per-entry generic on the outer key threads into:

delegate_components! {
new MyComponents {
<T> WidthKey<T>: UseDelegate<new WidthValue<T> {
HeightKey: HeightValue<T>,
}>,
}
}

That list declares the inner struct's parameters, so a const parameter is written with its kind, as in <const N: usize> ArrayKey<N>: UseDelegate<new ArrayTable<const N: usize> { … }>.

One prerequisite is not visible in either snippet: the component must carry #[derive_delegate(UseDelegate<Shape>)], which generates the dispatch impl the wrapper resolves through. Leave it off and the table still expands, then fails at the check with E0277, an unsatisfied IsProviderFor on UseDelegate<…> that never mentions the missing attribute.

Choosing a provider per type: the open statement​

When a component is generic over a type parameter, you usually want a different provider for each value of it. The open statement folds those per-value entries straight into the context's own table. The per-type wiring on this page therefore dispatches a generic CanCalculateArea<Shape>, whose provider trait is AreaCalculator<Context, Shape>, rather than the parameterless component the opening example wires:

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

A leading open …; header opens one or more components, and @-path entries then assign a provider per key:

delegate_components! {
MyApp {
open AreaCalculatorComponent;

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

Braces are optional when opening a single component, so open AreaCalculatorComponent; and open { AreaCalculatorComponent }; are the same. The braced list is needed to open several at once, and a braceless header naming more than one component fails with expected `;` at the first comma.

A key has one path segment per type parameter of the component, so open dispatches on any of them. The redirect appends every type parameter to the lookup path, in declaration order, so a lookup of CanCompute<Code, Input> follows @ComputerComponent.Code.Input. A lifetime parameter adds no segment. A key that stops after the first segment matches that value of the first parameter with every value of the rest, and a per-entry generic in a segment matches any value there. A handler can therefore be chosen by its input alone, by its code alone, or by both:

delegate_components! {
MyApp {
open ComputerComponent;

@ComputerComponent.<Code> Code.Circle: DescribeCircle,
@ComputerComponent.Area.Rectangle: RectangleArea,
@ComputerComponent.Perimeter.Rectangle: RectanglePerimeter,
}
}

A Circle input reaches DescribeCircle whatever code the caller passes, while a Rectangle input is dispatched on both parameters. This replaces the legacy UseInputDelegate table, and a UseDelegate table nested around UseInputDelegate tables.

A shorter key covers every longer key beneath it. Each key ends in a wildcard, and a generic segment matches every value in its position. So @ComputerComponent.Area overlaps @ComputerComponent.Area.Rectangle, and it also overlaps @ComputerComponent.<Code> Code.Circle, which covers Area among its codes. Within one table, key a first-parameter value either on its own or per later parameter, never both.

open does not need an extra attribute on the component, because it works through the RedirectLookup impl that every #[cgp_component] already generates. It is a lightweight special case of the full namespace feature, suited to a context wiring its own components directly, and it does not combine with a joined namespace where the component carries a #[prefix(...)].

The namespace statements​

The remaining statements opt a context into a cgp_namespace!, and that page describes them in full, since they are most often written there.

namespace SomeNamespace; joins the namespace, so every lookup the table does not wire directly falls through to it. The name is a bare identifier, so import a namespace from another module first: namespace some_mod::SomeNamespace; fails with expected `;` at the ::. for <T, Provider> in SomeTable { … } reads each entry of another lookup table and emits one mapping per entry, which is how a context adopts per-type defaults wholesale. Its body holds only : mappings, and an optional where clause on the loop constrains the entries it wires.

Statements come first​

Every statement must precede every mapping. Putting one after a mapping is a parse error, so the message names the unexpected token rather than the ordering rule. Beyond that the order is free: several statements may appear in any order, and they mix freely with the mappings that follow.

delegate_components! {
App {
open AreaCalculatorComponent;

PerimeterCalculatorComponent -> GeometryComponents,

[ColorComponent, LabelComponent]: DefaultStyle,

@AreaCalculatorComponent.{Rectangle, Circle}:
ShapeArea,

@AreaCalculatorComponent.[Square, Triangle]:
PolygonArea,
}
}

Read as a whole, that is still one table. Every line lowers to the same pair of impls. The forms differ only in how many entries a line produces and in what each entry resolves to.

Attributes​

The macro does not accept attributes anywhere: not on the table, not on a key, and not on a key inside a for loop or a nested table. It rejects the first one it finds with unsupported attribute: …, naming the attribute, rather than ignoring it. Attribute-driven variants such as #[check_params(...)] and #[skip_check] belong to delegate_and_check_components!.

Examples​

A component, a provider, and a context wired to use it, with a check that the wiring resolves. Rectangle is a value context here: the shape whose area the component computes is the same type that owns the wiring.

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
}
}

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

delegate_components! {
Rectangle {
AreaCalculatorComponent: RectangleArea,
}
}

check_components! {
Rectangle {
AreaCalculatorComponent,
}
}

fn print_area(rect: &Rectangle) {
println!("area = {}", rect.area());
}

The benefit shows up when a second context wants the same trait answered differently. It writes its own provider and its own table entry, and the code that calls area() does not change:

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

#[derive(HasField)]
pub struct Square {
pub side: f64,
}

delegate_components! {
Square {
AreaCalculatorComponent: SquareArea,
}
}

check_components! {
Square {
AreaCalculatorComponent,
}
}

Rectangle and Square now both implement CanCalculateArea, through different providers reading different fields. A function generic over CanCalculateArea serves both without knowing that any of it happened. Each context's choice stays one line a reader can search for, and finding that line tells them which implementation runs.

When one context needs a different provider per type rather than one provider outright, the component carries the type as a parameter, as the generic CanCalculateArea<Shape> under Usage does. The wired type changes role with it: MyApp is an environmental context, a type that stands for one set of choices and holds no shape of its own, so each provider reads the shape from its argument. The context opens the component, fills the slots, and checks each shape it wires:

pub struct MyApp;

delegate_components! {
MyApp {
open AreaCalculatorComponent;

@AreaCalculatorComponent.Rectangle: RectangleArea,
@AreaCalculatorComponent.{Circle, Ellipse}: CurveArea,
}
}

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

When to use it​

Use delegate_components! whenever a context needs to choose providers, which is any time you use #[cgp_component] at all. The real decision is not whether to wire but how to check the wiring, because CGP's wiring is lazy: a table with a missing or wrong entry still compiles, and the failure only surfaces later, where the trait is used.

  • Pair it with check_components! for anything beyond simple wiring. A separate check gives you full control over what it asserts: concrete parameters for generic keys, per-provider layers, and opened or namespaced wiring. This is why larger codebases keep the two macros apart.
  • Use delegate_and_check_components! when you are getting started or the wiring is plain Component: Provider entries. It fuses the two so you cannot forget the check. It accepts this whole grammar, but it derives checks only from : and -> mappings keyed on a component name, so it wires opened, redirected, and namespaced entries and leaves them unchecked without a warning.
  • Use plain delegate_components! without a check for an aggregate provider (the new-keyword form). That target is a provider other contexts delegate to rather than a context in its own right, so a context-side check on it asks the wrong question: it either passes vacuously or blames the bundle for requirements a real context would have met. Verify it through a context that delegates to it instead.

Two more choices inside the table have a clear default. Prefer the open statement over the legacy nested UseDelegate table for per-type dispatch, because it needs neither a separate table type nor a wrapper. And use a namespace rather than a longer table once the same wiring is repeated across contexts, or once one table has grown too long to read. Below that threshold, the extra hop costs more than it saves.

Never leave a context's wiring unchecked. The macro you use to check it depends on how complicated the wiring is, but the need for a check does not.

Under the hood​

Each entry becomes a pair of impls. From the single-entry table above, the DelegateComponent impl records the choice:

impl DelegateComponent<AreaCalculatorComponent> for Rectangle {
type Delegate = RectangleArea;
}

That impl alone is the whole lookup. The provider blanket impl generated by #[cgp_component] reads it, so Rectangle inherits AreaCalculator<Rectangle> from RectangleArea, and the consumer blanket impl then gives Rectangle the CanCalculateArea trait. The hand-written equivalent of one wiring entry is exactly that block.

The IsProviderFor impl forwards the provider's requirements:

impl<
__Context__,
__Params__: ?Sized,
> IsProviderFor<AreaCalculatorComponent, __Context__, __Params__> for Rectangle
where
RectangleArea: IsProviderFor<AreaCalculatorComponent, __Context__, __Params__>,
{}

This is why missing dependencies stay diagnosable. RectangleArea's own IsProviderFor impl carries the where bounds it needs, so an unsatisfied requirement flows back through this forwarding impl to the point of use. Note that these parameters are literally named __Context__ and __Params__ in the emitted code. __Params__ is ?Sized, as it is on the trait, so a component used at an unsized parameter such as str, whose parameter tuple (Life<'a>, str) is unsized, still resolves through the table.

Every other form on this page lowers to that same pair. A form changes only how many pairs one line produces and what the Delegate type is.

A list key repeats the pair per name. A table pairing [AreaCalculatorComponent, PerimeterCalculatorComponent] with RectangleGeometry, alongside a ColorComponent: SolidColor entry, yields three DelegateComponent impls and three matching IsProviderFor impls.

A -> mapping projects through the value's table, and adds the bound that makes the projection well-formed:

impl DelegateComponent<PerimeterCalculatorComponent> for ScaledGeometryComponents
where
GeometryComponents: DelegateComponent<PerimeterCalculatorComponent>,
{
type Delegate = <GeometryComponents as DelegateComponent<PerimeterCalculatorComponent>>::Delegate;
}

A => mapping wires a RedirectLookup over the table and the path. Against a plain key the path is complete, so AreaCalculatorComponent => @shared gives RedirectLookup<Table, Path!(@shared)>. Against a path key, both sides instead end in a shared wildcard parameter, so an entry like @cgp.core.error => @app rewrites one path prefix to another and passes everything beyond it through unchanged.

The open statement expands to a redirect plus per-value entries stored on the context itself. The header wires the component to a RedirectLookup rooted at the component name inside MyApp's own table:

impl DelegateComponent<AreaCalculatorComponent> for MyApp {
type Delegate = RedirectLookup<MyApp, Path!(@AreaCalculatorComponent)>;
}

AreaCalculatorComponent => @AreaCalculatorComponent, produces this same impl, byte-for-byte. Each @AreaCalculatorComponent.Rectangle: RectangleArea entry then stores its provider in that same table under a path key:

impl<__Wildcard__>
DelegateComponent<PathCons<AreaCalculatorComponent, PathCons<Rectangle, __Wildcard__>>>
for MyApp
{
type Delegate = RectangleArea;
}

The RedirectLookup impl appends the dispatch parameter onto the path and reads the result back, so MyApp: CanCalculateArea<Rectangle> resolves to RectangleArea.

The tail of that key is a generic __Wildcard__ parameter rather than Nil, and this makes it work. The entry matches any path beginning with this component and this dispatch type, whatever the lookup appends after it. So one entry answers the redirect without having to predict the exact length of the path reaching it.

Know one display difference before you compare these listings against your own expansion. Both paths above are PathCons lists, but cargo cgp expand prints them differently. It resugars the header's redirect target to Path! form while leaving the per-entry key as the raw list, so the same kind of type appears in two spellings in one expansion.

A grouped path key expands to the cartesian product, one impl pair per combination, each keyed on a full prefix ending in __Wildcard__. So @app.[AreaCalculatorComponent, PerimeterCalculatorComponent].[u64, String]: RectangleGeometry emits four pairs, and a braced group does the same with whole tails rather than single segments, producing keys of different lengths.

A nested-table value lifts its inner table out into its own definition, wiring the outer entry to UseDelegate over the generated type. So the legacy form is equivalent to writing two separate delegate_components! blocks, the inner one carrying new. Its per-value entries key on the same parameter open keys on. The only difference is that they live in a separate table type.

The namespace statements share one lowering: an impl generic over a __Key__ and a __Value__, bounded on the namespace trait with a Delegate = __Value__ binding. This makes the namespace's answer the context's answer. A bare namespace DefaultNamespace; produces the blanket form:

impl<__Key__, __Value__> DelegateComponent<__Key__> for App
where
__Key__: DefaultNamespace<App, Delegate = __Value__>,
{
type Delegate = __Value__;
}

A for loop produces the same shape once per mapping in its body, plus any predicates its where clause adds.

Formal grammar​

In the Rust Reference's notation:

DelegateComponents -> Generics? `new`? TargetType `{` TableBody `}`

TargetType -> Type

TableBody -> Statement* ( Mapping ( `,` Mapping )* `,`? )?

Statement -> OpenStmt | NamespaceStmt | ForStmt

OpenStmt -> `open` ( `{` ( Type ( `,` Type )* `,`? )? `}` | Type ) `;`

NamespaceStmt -> `namespace` IDENTIFIER `;`

ForStmt -> `for` `<` IDENTIFIER `,` IDENTIFIER `>` `in` TypePath WhereClause?
`{` ( NormalMapping ( `,` NormalMapping )* `,`? )? `}`

Mapping -> NormalMapping
| Key `->` ProviderValue
| Key `=>` PathValue

NormalMapping -> Key `:` ProviderValue

Key -> SingleKey | MultiKey | PathKey
SingleKey -> Generics? Type
MultiKey -> `[` ( SingleKey ( `,` SingleKey )* `,`? )? `]`
PathKey -> Generics? `@` PathHead

PathHead -> KeySegment ( `.` PathHead )?
| `[` ( KeySegment ( `,` KeySegment )* `,`? )? `]` ( `.` PathHead )?
| `{` ( PathHead ( `,` PathHead )* `,`? )? `}`

KeySegment -> Generics? PathSegment

PathValue -> `@` PathSegment ( `.` PathSegment )*

PathSegment -> Type

ProviderValue -> Type
| IDENTIFIER `<` `new` InnerTable `>`

InnerTable -> IDENTIFIER BoundFreeGenerics? `{` TableBody `}`

A leading Generics list makes the table generic over the target, and new additionally emits the target struct. The operator choice is independent of the key form: : maps a key to a provider, -> delegates to the value's own entry for that key, and => redirects along a path. NormalMapping is named separately because a ForStmt body admits only that form.

The grouping forms inside a PathHead differ in what they group and in whether the path may continue. A bracketed group holds alternative segments for one position and may be followed by . and more path. A braced group holds alternative whole remainders and terminates the path, which is why only the braced form can nest. Both expand to the cartesian product with the rest of the path.

The segment productions differ in what they permit, which is why they are named apart. A KeySegment (inside a PathKey) may carry its own generic list, and the macro merges the parameters of every segment along one path onto that entry's impls. A PathSegment (inside a PathValue, the right-hand side of a =>) cannot carry a generic list or a group. It is Path!'s own production, which keeps the two in step. And every Generics list on a key is an impl-position list, so the parser accepts a bound (<T: Clone> WidthKey<T>: WidthProvider) and rejects a parameter default: <T = u32> fails with invalid impl generics syntax.

A ProviderValue's nested-table form carries a full TableBody, so an inner table accepts every form an outer one does. Its wrapper is a bare IDENTIFIER, not a path. An InnerTable is an identifier with an optional generic list rather than a full TargetType, because a nested table always names a fresh struct the macro declares. Its BoundFreeGenerics is a definition-position list of lifetimes, type parameters, and const parameters: it allows neither bounds nor defaults, so put a bound on the entry's own generics instead. Because the list declares the struct's parameters, a const is written with its kind, as ArrayTable<const N: usize>, and a bare N declares a type parameter. The value parser tries the nested-table form speculatively and falls back to reading the whole value as a plain type, so a bound or a default on the inner table and a qualified wrapper all fail the same misleading way, with expected `,` at the inner table's name.

The remaining rules restate points made above. An OpenStmt may omit its braces when opening exactly one component. A MultiKey takes no generic list of its own, only its elements do. Every bracketed and braced list may be empty, and then produces no entries. Every Statement precedes every Mapping. cgp_namespace! describes NamespaceStmt and ForStmt. The macro does not accept attributes anywhere and rejects any it finds.

Common Mistakes​

Wiring is lazy. A table with a missing entry, or one naming a provider whose own dependencies are unmet, still compiles. The failure appears later, at the place where code uses the trait, often as a long error naming types you did not write. The answer is to check the table (see check_components!) and to read failures through cargo cgp check in place of cargo check. cargo cgp check leads with the root cause for the classes it recognizes, and the tool does not yet reshape every class.

Statements must lead the block, and getting it wrong produces a misleading message. Once the parser has consumed the statements it expects only mappings, so it reads the open keyword as a key and then complains about the component name where it wanted an operator:

error: expected `:`

The caret sits on the component being opened, so the message blames it rather than the misplaced open, and never mentions the ordering rule.

[…] and {…} in a path are not the same group. A bracketed group holds alternatives for one segment and may be followed by more path. A braced group holds whole tails and ends the path. So @AreaCalculatorComponent.{String, u32}.bool: RectangleGeometry does not parse, and the message does not mention groups. It reports the trailing .bool sitting where the operator should be:

error: expected `:`

Use a bracketed group when the path must continue past the alternatives, and a braced group only at the end.

Naming a provider struct that does not exist is easy to do when you wrote a provider with #[cgp_impl] without the new keyword and never declared it separately. The error is E0425, cannot find type `SquareArea` in this scope, which names an unresolved type rather than anything about wiring. When no type of that name exists anywhere, cargo cgp check reports it as an undeclared provider, [CGP-E043]. A key that names a consumer trait, a component that exists but is not imported, a component guessed from a consumer trait's name, or a type in an @-path nothing declares gets one of the wiring-name codes, [CGP-E040] to [CGP-E042] or [CGP-E044]; a key the tool cannot settle, such as a misspelled component name, keeps the compiler's E0425. A provider or a type declared elsewhere but not imported keeps the compiler's message and its import suggestion.

A bare N in a nested table's generic list declares a type parameter. That list declares the inner struct, so <const N: usize> ArrayKey<N>: UseDelegate<new ArrayTable<N> { … }> gives ArrayTable a type parameter N, and passing the constant through fails with E0747, constant provided when a type was expected. Write the parameter with its kind, as new ArrayTable<const N: usize> { … }. A new target is different, because its list is the target's type arguments: <const N: usize> new ArrayTable<N> takes the kind from the leading generic list.

Two entries claiming one key conflict, and the compiler reports it as a coherence error, E0119, rather than as a wiring one. It arrives twice, once for each impl of the entry, with the caret on the later entry's key. This covers the obvious duplicate, an open header colliding with an explicit mapping for the same component, a generic <Shape> AreaCalculatorComponent<Shape> entry overlapping a specific AreaCalculatorComponent<Rectangle> one, and a path key covering a longer one, as @ComputerComponent.Area beside @ComputerComponent.Area.Rectangle or @ComputerComponent.<Code> Code.Circle. The same applies to a direct entry for a path a joined namespace itself binds: see cgp_namespace!.

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.