Skip to main content

cgp_namespace!

Define a reusable, inheritable wiring table that many contexts can join.

Overview​

In Context-Generic Programming (CGP), every context (the type the method runs on, which supplies the values it needs as its fields) spells out its own wiring entry by entry with delegate_components! alone. Two contexts that should share the same providers repeat the same lines, and a table grows with the number of components until the wiring is the largest thing in the file.

CGP enables pluggable trait implementations in Rust, and a namespace is where a group of those choices gets a name other contexts can adopt. cgp_namespace! lifts a table out of any one context and gives it that name:

cgp_namespace! {
new AppNamespace {
// shared wiring lives here
}
}

A context then joins it with one line inside its own table, after which every lookup it does not wire directly falls through to the namespace. Its own entries fill the paths the namespace leaves open, so a namespace behaves like a base configuration each context completes: most of the wiring for free, and a handful of choices where they matter. A context cannot replace an entry the namespace binds; see Common Mistakes.

That inherit-and-complete behaviour is why a namespace is how CGP expresses presets. There is no separate preset construct: a library publishes a namespace that binds what every application shares and leaves open what each chooses, and an application joins it and supplies those choices. Namespaces can also inherit from one another, so a base can be extended into a richer one that every downstream context picks up.

One structural point saves confusion later: a namespace is not a context. It is a trait, named after the namespace, carrying a Delegate associated type and implemented once per key. Nothing instantiates it, and it holds no wiring of its own at the context level; it only says where a lookup should go next.

Usage​

The body resembles a delegate_components! table with an optional header. The new keyword tells the macro to emit the namespace's trait and its backing struct:

cgp_namespace! {
new MyNamespace {
FooProviderComponent =>
@MyFooComponent,
}
}

Omit new only when the trait and struct are already declared elsewhere.

The two entry forms​

A namespace body accepts two kinds of entry, and they do different things.

EntryMeaning
Key => @pathRedirect. Asked for Key, look up @path instead. The provider is decided wherever the path lands.
Key: ProviderBind. Asked for Key, resolve straight to Provider, as in delegate_components!.

Redirection makes namespaces composable: because a lookup is keyed by a path rather than a bare component name, a whole subtree can be rerouted at once, and a context can fill one path the namespace leaves open without disturbing the rest. Paths are written with the @ sigil as dotted sequences, such as @MyFooComponent, @app.ErrorRaiserComponent, and @cgp.core.error, where lowercase segments become type-level strings and capitalized segments name types. Path! covers the syntax in full.

The rest of the body grammar​

A namespace body is parsed by the same code as a delegate_components! table, so everything that macro accepts parses here: all three operators, all three key forms (including bracketed list keys and @-path keys with their […] and {…} groups), per-key generics, and the leading open, namespace, and for statements. That page documents each of them; what follows is only what differs here.

The entry itself means something different. A delegate_components! entry records a choice for a context; a namespace entry records where a lookup for a key should go next, for any context that later joins. That is why the two forms in the table above are the ones worth writing, and why the others are mostly not:

  • -> direct delegation still projects through the value's own table, so it names a concrete table inside a definition that is meant to be table-generic.
  • open Component; is accepted and generates exactly what Component => @Component, generates; it is occasionally a convenient spelling for rooting a component's route at its own name.
  • namespace Other; is accepted, but inheritance is written with the : ParentNamespace header above. That is the form the override rule and the cycle diagnostics are defined in terms of.
  • A nested table value, UseDelegate<new Inner { … }>, works, and is the one legacy form with a reason to keep in a namespace: the macro lifts the inner table out into its own struct and impls, so every context joining the namespace inherits the per-type dispatch without restating it. It still needs #[derive_delegate] on the component, as it does anywhere.

Inheriting from a parent​

Name a parent after a colon in the header, and the child resolves everything the parent does plus its own entries:

cgp_namespace! {
new ExtendedNamespace: BaseNamespace {
@cgp.core.error =>
@app,
}
}

The parent may itself be parameterized, and may be named by a path. The child's entries sit beside everything it inherits: they may add keys the parent does not resolve, but not redefine one it does, as Common Mistakes explains. A path-rewriting entry like the one above qualifies when the parent routes the @cgp.core.error prefix onward without binding it, as a parent inheriting DefaultNamespace does for CGP's error components, and it reroutes a whole subtree of those routes rather than a single component.

A namespace with nothing of its own to add may stop at the header. The braces are optional when the body would be empty, which is the usual shape of a namespace that exists only to inherit:

cgp_namespace! {
new ExtendedNamespace: BaseNamespace
}

This is the same as writing {} after the parent, and new BaseNamespace on its own, with no parent and no braces, emits only the trait and struct. Only the end of the input may follow the header; any other token there is an expected curly braces error. Without new, a header-only ExtendedNamespace: BaseNamespace emits only the inheritance impl, so it compiles only where the ExtendedNamespace trait and its __ExtendedNamespaceComponents struct are already declared. The shorthand is this macro's alone, since delegate_components! keeps its braces even when its table is empty.

The other two halves: registering, and joining​

Defining a namespace is only one part of the pattern. A component registers into one with the #[prefix(...)] attribute on its trait, which puts that component's lookups under a path:

#[cgp_component(ShowImpl)]
#[prefix(@show in AppNamespace)]
pub trait CanShow {
fn show(&self) -> String;
}

A context joins one with a namespace header inside its own table, after which unwired lookups forward through it:

delegate_components! {
MyApp {
namespace AppNamespace;

@show.ShowImplComponent: ShowWithDebug,
}
}

Another statement form, for <T, Provider> in SomeTable { … }, reads each entry of another lookup table and emits one mapping per entry, which is how per-type defaults are pulled in wholesale.

Examples​

A complete namespace, end to end: a component registered under a prefix, a namespace to hold the route, and a context that joins it and supplies the provider at the prefixed path.

use cgp::prelude::*;

#[cgp_component(ShowImpl)]
#[prefix(@show in AppNamespace)]
pub trait CanShow {
fn show(&self) -> String;
}

#[cgp_impl(new ShowWithDebug)]
#[uses(core::fmt::Debug)]
impl ShowImpl {
fn show(&self) -> String {
format!("{:?}", self)
}
}

cgp_namespace! {
new AppNamespace {}
}

#[derive(Debug)]
pub struct MyApp;

delegate_components! {
MyApp {
namespace AppNamespace;

@show.ShowImplComponent: ShowWithDebug,
}
}

check_components! {
MyApp {
ShowImplComponent,
}
}

Reading the resolution: MyApp.show() looks up ShowImplComponent, finds no direct entry, falls through to AppNamespace, which redirects to the path @show.ShowImplComponent, and MyApp's own table binds that path to ShowWithDebug. The division of labour is the point. The namespace owns the route; the context owns the provider. A second context joins the same namespace and supplies a different provider at the same path, with nothing duplicated between them.

Inheritance composes the same way. ExtendedNamespace resolves everything its parent does, so a context joining the child inherits the whole chain:

cgp_namespace! { new BaseNamespace {} }

cgp_namespace! { new ExtendedNamespace: BaseNamespace }

delegate_components! {
MyApp {
namespace ExtendedNamespace;

@show.ShowImplComponent: ShowWithDebug,
}
}

When to use it​

Use a namespace when the same wiring is repeated across contexts, or when a top-level table has grown too long to read. Those are the problems it solves, and below that threshold it costs more than it saves: a namespace adds a layer of indirection between a component and its provider, which is one more hop for a reader tracing what runs.

A few lighter tools cover most cases, and it is worth knowing where each stops.

  • A plain delegate_components! table is right while each context's wiring is short and not shared. Most applications never outgrow this.
  • The open statement is the lightweight special case of the same path machinery, for dispatching one component on its type parameter directly on a context. It needs no namespace, no prefix, and no shared table; use it when the goal is per-type dispatch rather than shared wiring.
  • An aggregate provider, the new-keyword bundle, packages a group of wirings that contexts adopt by delegating named components to it, rather than by joining and inheriting. It is the more direct mechanism and the better choice for a small, explicitly-delegated bundle. A namespace is worth its extra machinery when there are many components, when inheritance is wanted, or when a library is publishing defaults for applications it does not know about.

A namespace and an aggregate provider also combine. A context that joins a namespace can forward a whole path to an aggregate provider in one entry, as @app.core.user: UserComponents, and the bundle then answers every component registered under that path. The lookup reaches the bundle keyed by the bare component name, so a bundle keyed by bare names needs nothing more. A bundle that groups several paths, such as a CoreComponents holding @app.core.user: UserComponents, is keyed by paths and must itself join the namespace, or the check fails reporting that CoreComponents has no DelegateComponent entry for the component's bare name.

A couple of things a namespace is not for. It will not make a single context's wiring shorter on its own; the entries still have to exist somewhere. And it is not how one component gets per-type dispatch, which is open's job; the two do not combine on the same component, as the Common Mistakes explain.

Under the hood​

cgp_namespace! emits, in order, an optional backing struct, an optional lookup trait, the structs of any nested tables, and then the impls: one inheritance impl first when a parent is named, one impl of the trait per entry, and the nested tables' own impls. From this input:

cgp_namespace! {
new MyNamespace {
FooProviderComponent =>
@MyFooComponent,
}
}

the new keyword emits a struct whose name wraps the namespace's, then the trait, which carries the table as a parameter and a single associated type:

pub struct __MyNamespaceComponents;

pub trait MyNamespace<__Table__> {
type Delegate;
}

Each => entry becomes an impl of that trait for the key, whose Delegate is a RedirectLookup aiming the table at the entry's path:

impl<__Table__> MyNamespace<__Table__> for FooProviderComponent {
type Delegate = RedirectLookup<__Table__, PathCons<MyFooComponent, Nil>>;
}

Read it back as: MyNamespace's delegate for FooProviderComponent is "look up the path MyFooComponent inside whatever __Table__ is". The namespace names no provider; it only reroutes, so the provider is decided wherever the path finally lands. A : entry skips the indirection and maps the key straight to a provider, one impl per key when the array form is used.

#[prefix(...)] is the other side of this, and it generates an impl of exactly the same shape for the component's marker, with the path ending at the component's own name. So #[prefix(@show in AppNamespace)] on a CanShow component routes ShowImplComponent to @show.ShowImplComponent, which is why a joining context binds that path rather than the bare component. The attribute's page shows the emitted impl.

When a parent is named, the macro prepends a blanket impl forwarding every key the parent resolves:

impl<__Table__, __Key__, __Value__> ExtendedNamespace<__Table__> for __Key__
where
__Key__: BaseNamespace<__ExtendedNamespaceComponents>,
__Key__: BaseNamespace<__Table__, Delegate = __Value__>,
{
type Delegate = __Value__;
}

For any key the parent resolves, the child resolves it to the same value. The child's own entries are emitted after this impl and sit beside it rather than overriding it, since Rust has no rule that lets a more specific impl win. A child entry must therefore be keyed on a path the parent does not resolve, and a longer path beneath one the parent resolves overlaps it too, because every path key ends in a wildcard.

A couple of naming details appear verbatim in errors and are worth recognizing: the table parameter is literally __Table__, and the inheritance impl uses __Key__ and __Value__. And every @ path is a type-level list built by Path!; expand resugars it to Path!(@…) form, while a raw compiler error prints the underlying list.

Formal grammar​

The body is a header and an optional table, in the Rust Reference's notation:

CgpNamespace -> Generics? `new`? NamespaceName ( `:` ParentNamespace )? ( `{` NamespaceBody `}` )?

NamespaceName -> IDENTIFIER GenericArgs?
ParentNamespace -> TypePath GenericArgs?

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

NamespaceBody is delegate_components!'s TableBody production unchanged, so its Statement and Mapping rules, covering every operator, every key form, and every value form, are defined on that page rather than restated here. The two a namespace normally uses are => to an @-path and : to a provider. The : between NamespaceName and ParentNamespace is the inheritance colon, distinct from a mapping's. NamespaceName becomes both a trait and, with new, a struct. The table is optional: a header followed by nothing is an empty NamespaceBody, and a header followed by anything other than { is a parse error.

Two statement forms in that shared production exist for this macro, because their job is joining a context's table to a namespace. A NamespaceStmt, namespace SomeNamespace;, forwards every unwired lookup through the named namespace. A ForStmt, for <T, Provider> in SomeTable where … { … }, binds a key variable and a provider variable, reads each entry of the table named after in, and emits one mapping per entry; its body admits only the : form, and its optional where clause is merged into every impl the loop generates. Like delegate_components!, the body accepts no attributes on any entry and rejects any it finds.

The #[prefix(...)] attribute, which registers a component into a namespace and is written on a #[cgp_component] trait, has a grammar of its own, given on its page.

Common Mistakes​

A context cannot override a path its namespace itself terminates. Joining with namespace N; emits a blanket DelegateComponent impl covering every path N resolves, so a direct entry for one of those paths is a second impl for the same key and the compiler rejects the overlap with E0119. A context can wire only a path the namespace routes to without binding, which is why the example above has the namespace own the route and the context own the provider. A path the namespace binds with a : entry or a #[default_impl] has to be changed in the namespace instead.

The same restriction stops a child namespace from redefining a key its parent resolves, and a more specific path does not escape it. With the parent routing @app => @base, a child entry @app.Seg => @child still overlaps, because the parent's key ends in a wildcard that covers @app.Seg:

error[E0119]: conflicting implementations of trait `ExtendedNamespace<_>` for type `PathCons<Symbol<3, Chars<'a', …>>, PathCons<Seg, _>>`

The Chars nest, which spells app, is shortened here.

Joining two namespaces on one context conflicts, for the same reason. Each namespace produces a blanket forwarding impl covering every key, so joining two collides them:

error[E0119]: conflicting implementations of trait `DelegateComponent<_>` for type `App`

A bare-key for loop (for <Key, Value> in Table { Key: Value }) alongside a namespace join collides the same way, which is why a loop's key is normally embedded in a path, as in @app.SomeComponent.Key: Value.

The namespace statement takes a bare name. A namespace from another module cannot be written as a path there: namespace some_mod::AppNamespace; fails with expected `;` at the ::. Import the namespace first and join it by its name. The inheritance header and a for loop's in clause both accept a path.

open does not combine with a prefixed component in a joined namespace. Once a component's lookups are routed under a prefix, open, which roots the route at the bare component name, does not reach those entries. Write the per-value entries with the full prefixed path instead.

A cyclic parent chain fails at both definitions, and a self-inheriting namespace at the macro. Two namespaces inheriting each other make the forwarding impl's where clause loop, and the compiler rejects it eagerly at both definitions:

error[E0275]: overflow evaluating the requirement `__Key__: A<__BComponents>`
note: required for `__Key__` to implement `B<__AComponents>`

A namespace inheriting itself, as in new A: A {} or new A: self::A {}, or another instance of itself, as in <T> new A<T>: A<u32> {}, is rejected by the macro, with the caret on the parent's name:

error: the namespace `A` cannot inherit from itself; name another namespace as its parent, or omit the parent

A parent written through any other path, such as crate::A, is not checked, since the macro cannot tell which item the path names, so that cycle reaches the compiler as an unconstrained-parameter error instead.

A registered component with no provider bound anywhere still compiles. If a #[prefix] routes a component into a namespace and nothing ever binds a provider at its path, the redirect lands on an empty slot and the context compiles regardless. Only a check_components! reports it, and what it reports is the path failing to resolve rather than a provider being absent:

error[E0277]: the trait bound `PathCons<Symbol<4, Chars<'s', …>>, PathCons<ShowImplComponent, Nil>>: AppNamespace<MyApp>` is not satisfied

The Symbol<4, …> is the prefix, show, with its Chars nest shortened here, so the message is saying "this route is not something the namespace resolves". This is the lazy-wiring problem in a namespace setting, and the answer is the same: check the context.

  • delegate_components! — where a context joins a namespace, and the source of the shared table grammar.
  • Path! — the @-path syntax namespace entries and #[prefix] use.
  • RedirectLookup — the provider every redirect resolves through.
  • DefaultNamespace — inherited and per-type default resolution, including #[default_impl(...)].
  • #[prefix(...)] — registers a component into a namespace under a path prefix, the other half of the pattern.
  • #[cgp_component] — the host of the #[prefix(...)] attribute.
  • DelegateComponent — the per-key table a redirect finally walks.
  • check_components! — the only thing that catches a route bound to nothing.

The ideas behind it:

  • Namespaces — the idea in full, including why presets need no separate construct.

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.