Skip to main content

CGP v0.8.0 - cargo-cgp, new documentation, and namespaces

Β· 43 min read
Soares Chen
Creator of Context-Generic Programming

Context-Generic Programming (CGP) v0.8.0 is out! This release is about making CGP easier to learn and maintain. It introduces cargo-cgp, a new tool for one of CGP's longest-standing problems: compile errors that describe the code the macros generated rather than the code you wrote. cargo-cgp explains those errors in your terms. When a provider needs a field your type lacks, for example, it can tell you which field to add, and the expanded documentation explains why the provider needs it. Later, as your application grows, the new namespaces let you choose the providers for a whole group of components in one wiring entry.

CGP is a language extension for Rust, with pluggable trait implementations at compile-time. It is an ordinary library on stable Rust: applications select providers through wiring that resolves to static calls, and you can adopt it one component at a time. The Overview explains the model.

I'll start with cargo-cgp and the new documentation, then work through namespaces using a social-media application. The namespace walkthrough is the longest part, so you can read the tooling and documentation news on their own if you prefer. Allow about 35 minutes for the full post, including the code, or jump to the section you need:

Diagnosing wiring with cargo-cgp​

Since CGP began, verbose and confusing compiler errors have been one of the largest obstacles to adopting it. Leave out a field or a component binding, and the error message can name a generated trait or show a field name encoded as a Rust type. The compiler checks the Rust produced by macro expansion, so its explanation can be far removed from the code where we made the mistake.

For a newcomer, that can mean learning advanced Rust traits and generics, along with CGP's internals, just to diagnose a small mistake. You might understand the program you are trying to write and still have little idea why it does not compile. Because the difficulty lies in how the compiler reports the expanded code, better syntax alone cannot address it.

So I built cargo-cgp v0.1.0, CGP's new error toolchain, to report those errors in terms of the code you wrote. cargo cgp check checks CGP code and explains a missing dependency through the fields, components, and providers involved, leading with the root cause. It does not yet reshape every class of error, though, so some still reach you in the compiler's own words. When you want to look deeper, cargo cgp expand shows the Rust that the macros generated.

Find a missing field​

Let's try it on a small mistake from the area-calculation tutorial. We have an area provider that multiplies width by height, and a Rectangle that supplies only width. Here, the rectangle itself is the context: it is the value the operation acts on, and its fields supply the provider's inputs.

Save this library example as src/lib.rs in a Cargo package using cgp = "0.8.0":

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,
// missing `height` field
}

delegate_and_check_components! {
Rectangle {
AreaCalculatorComponent: RectangleArea,
}
}

The table selects RectangleArea, whose #[implicit] arguments read the rectangle's fields. Because we used delegate_and_check_components!, the compiler checks those dependencies at the wiring entry. Run cargo cgp check, and it points to the field we forgot:

error[E0277]: [CGP-E001] missing field `height` on `Rectangle`
--> src/lib.rs:23:9
|
23 | AreaCalculatorComponent: RectangleArea,
| ^^^^^^^^^^^^^^^^^^^^^^^
|
= note: root cause: [CGP-E110] missing field `height` on `Rectangle`
this is required through the dependency chain:
[CGP-E101] consumer trait impl `CanCalculateArea` for context `Rectangle`
└─ [CGP-E102] provider trait impl `AreaCalculator` with context `Rectangle` for provider `RectangleArea`
└─ [CGP-E110] missing field `height` on `Rectangle`
= help: add the field `height: f64` to `Rectangle`

The help line gives us the edit, height: f64. To see why the provider needs it, the dependency tree takes us back through RectangleArea to the area operation. For comparison, plain cargo check describes the same mistake through generated traits and a nested Symbol type:

Compare the output from cargo check
error[E0277]: the trait bound `Rectangle: CanUseComponent<AreaCalculatorComponent>` is not satisfied
--> src/lib.rs:23:9
|
23 | AreaCalculatorComponent: RectangleArea,
| ^^^^^^^^^^^^^^^^^^^^^^^ unsatisfied trait bound
|
help: the trait `HasField<Symbol<6, Chars<'h', Chars<'e', Chars<'i', Chars<'g', Chars<_, cgp::macro_prelude::Chars<'t', Nil>>>>>>>>` is not implemented for `Rectangle`
but trait `HasField<Symbol<5, Chars<'w', Chars<'i', Chars<'d', Chars<'t', Chars<_, Nil>>>>>>>` is implemented for it
--> src/lib.rs:17:9
|
17 | pub width: f64,
| ^^^^^
note: required for `RectangleArea` to implement `IsProviderFor<AreaCalculatorComponent, Rectangle>`
--> src/lib.rs:8:1
|
8 | #[cgp_impl(new RectangleArea)]
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
= note: required for `Rectangle` to implement `CanUseComponent<AreaCalculatorComponent>`
note: required by a bound in `__CanUseRectangle`
--> src/lib.rs:21:1
|
21 | / delegate_and_check_components! {
22 | | Rectangle {
23 | | AreaCalculatorComponent: RectangleArea,
24 | | }
25 | | }
| |_^ required by this bound in `__CanUseRectangle`
= note: this error originates in the attribute macro `cgp_impl` which comes from the expansion of the macro `delegate_and_check_components` (in Nightly builds, run with -Z macro-backtrace for more info)

Following that suggestion, we add the missing field:

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

The wiring check now passes, and the provider can read both fields to calculate the area. Fixing the mistake did not require decoding the type-level spelling of height.

To produce this explanation, cargo-cgp wraps a nightly compiler and uses the Rust compiler's API to inspect the failed dependencies. It can follow their chain using information that would be difficult to recover from the printed diagnostic alone. That access is why the tool has its own compiler-linked driver.

Try the checker​

With cargo and rustup available, you can install the tool and set up its compiler-linked driver, then check your own project. The install needs Rust 1.96 or newer, and the tool is tested on Linux only so far:

cargo install --locked cargo-cgp
cargo cgp setup
# Run this from your CGP project's directory:
cargo cgp check

cargo cgp setup installs the tool's pinned nightly and builds the matching driver. That nightly runs only cargo-cgp's checks, so your application keeps its normal toolchain for ordinary cargo builds. CGP itself still compiles on stable Rust, and you can use it without installing cargo-cgp at all.

Use plain cargo to build, run, and test applications. cargo-cgp supplies check for diagnostics and expand for reading the Rust generated by macros, with CGP's type-level constructs restored to readable notation. The installation guide covers setup, updates, and the Nix alternative, and the cargo-cgp v0.1.0 release notes list what this first release supports.

Expanded documentation and AI agent support​

A release post can show you an interesting feature and still leave you unsure how to use it in your own program. For too long, CGP left readers in that position. Most explanations lived in blog posts like this one, with each post introducing features as they arrived. There was little room to explain every construct or give readers a complete account of how the pieces fit together.

CGP is a side project, and finding the time to fill those gaps has been difficult. Writing a comparable body of documentation entirely by hand would likely take me months of full-time work. I do not expect to have that time in the near future, and waiting would leave readers facing the same gaps.

Advances in AI and agentic coding made it practical to take on that work. Agents, primarily Claude Code, wrote much of the new documentation under my direction, over many iterations of planning and revision. If a blog post leaves you wanting more detail, you can now turn to:

  • Reference: look up a construct's accepted syntax, examples, and generated code.
  • Concepts: work through ideas such as provider composition, abstract types, and namespaces.
  • Comparisons: connect CGP to approaches you already know from other programming languages, with the limits of each comparison explained.
  • Projects: follow the code and patterns of CGP projects highlighted in earlier blog posts.
  • The /cgp skill: give an AI assistant the foundations to help you read and write CGP, as described below.
  • The knowledge base: explore the fuller record written for agents working on CGP itself, including its implementation and documentation.

Across more than 360 pages, the website now contains roughly 365,000 words of documentation prose, excluding code blocks and the mirrored skill files. At 300 words per printed page, that would be about 1,200 pages before code listings.

I understand why readers may be skeptical of AI-written explanations. A word count says little about their usefulness, and I would not expect a one-shot prompt to produce useful material at this scale. The planning, source checks, and repeated revisions are essential to the quality I am aiming for. I encourage you to read the pages and tell me where an explanation is vague, incorrect, or reads like generic AI output.

How the documentation is written​

I direct the work, set the rules, and choose what gets documented. The process starts with the knowledge base, where agents record how CGP works and check claims about syntax and macro expansions against the implementation, tests, and expansion snapshots. That account becomes the basis for the website pages, which agents write and revise against the project's writing guides.

When a page needs an update, the agent can pick up from the same record. That saves me time because each revision starts from what the record already holds about CGP. The knowledge-base overview explains how the record supports the project.

I review the pages myself, though not all in the same depth. I read in full every page that explains CGP's ideas or the decisions behind its design, which includes the Concepts pages and the blog posts. The reference pages for individual constructs follow their writing guides, and I spot-check them. But neither kind of review catches everything. Like the source checks, it can miss mistakes, so the knowledge base can still contain errors. I remain responsible for what the project publishes.

I would like to explore the methodology further in a dedicated follow-up post. For now, How CGP's Documentation Is Written explains the process and where its checks stop. The AI disclosure describes who writes and reviews the documentation, tooling, and core library.

Optional help from the /cgp skill​

If you already work with an AI assistant, try exploring a small CGP example together. With the /cgp skill loaded, you can ask it to explain an unfamiliar wiring entry, trace which provider a method uses, or help investigate a compiler error. This gives you a way to explore the internal details as they become relevant, with explanations suited to your Rust experience.

The skill gives the assistant a condensed guide to current CGP: the consumer/provider model, wiring, dependency declarations, and debugging with cargo-cgp. It can help the assistant investigate macro expansions and guide you through installing and using the checker. For deeper questions, it can consult the fuller knowledge-base record.

Before it works on your code, the skill checks which cgp release your project uses and tells you when that differs from the release it describes. You still need to review and verify the assistant's suggested code. The installation page explains how to install the skill in your agent, and Using the Knowledge Base with Your Agent covers deeper investigation. Neither is required to use CGP.

Grouping component wiring with namespaces​

The release also introduces namespaces, for grouping components as an application grows.

When an application has only a few components, writing out its delegate_components! table is straightforward. Each time we split behavior into another component, though, we add a routing entry. Eventually, someone opening the application has to sort through a long list of bindings before they can see which ones belong together. The implementations have become more reusable, but the configuration has become harder to follow.

I have tried a few ways to address this difficulty. Provider bundles collect implementations, but applications still have to list the components they forward to each bundle. The earlier preset system reduced some repetition too, with limitations I will return to below.

With namespaces, we can now give those groups names and select their implementations together. I'll work through a social-media application whose production and test configurations share a PostgreSQL-backed core but use different content filters. By the end, that difference will be visible in one wiring entry.

If you have already maintained a large wiring table, you may prefer to jump to the namespace syntax or the migration guide. Otherwise, let's start with the small application and see how its wiring grows.

Start with a manager per domain​

Suppose we are building a social-media service that manages users and posts. We need a database handle and a place to choose the implementations the service uses, so our context will represent the application. This is a different role from the earlier Rectangle, where the context was the data being operated on.

The snippets illustrate wiring rather than a complete web service. They assume use cgp::prelude::*; and omit domain type declarations and database query bodies. The web-app walkthrough follows the same example, and its compiling source uses placeholder database operations.

Our service starts with one manager trait for users and another for posts.

#[cgp_component(UserManager)]
pub trait CanManageUser {
fn create_user(&self, username: &str, email: &Email) -> Result<User, Error>;

fn get_user(&self, user_id: &UserId) -> Result<User, Error>;

fn update_user_data(&self, user_id: &UserId, user_data: &UserData) -> Result<(), Error>;
}

#[cgp_component(PostManager)]
pub trait CanManagePost {
fn create_post(&self, title: &str, content: &str) -> Result<Post, Error>;

fn get_post(&self, post_id: &PostId) -> Result<Post, Error>;

fn update_post(&self, post_id: &PostId, content: &str) -> Result<(), Error>;

fn delete_post(&self, post_id: &PostId) -> Result<(), Error>;
}

The methods describe what the service can do. Adding #[cgp_component] lets us write their implementations separately from the application that uses them: it generates a provider trait such as UserManager and a wiring key such as UserManagerComponent. The application will choose a provider through that key.

Choosing a manager provider chooses all its methods together. A component can hold several methods, associated types, and constants, just like an ordinary trait, and grouping the user operations keeps this first version simple. As the service grows, we will see where choosing those methods together becomes inconvenient.

For the PostgreSQL implementations, each method declares the database handle it needs as an implicit argument. The providers can then work with any application supplying that dependency:

#[cgp_impl(new PostgresUserManager)]
impl UserManager {
fn create_user(
&self,
#[implicit] database: &PostgresDb,
username: &str,
email: &Email,
) -> Result<User, Error> {
// ...
}

fn get_user(
&self,
#[implicit] database: &PostgresDb,
user_id: &UserId,
) -> Result<User, Error> {
// ...
}

fn update_user_data(
&self,
#[implicit] database: &PostgresDb,
user_id: &UserId,
user_data: &UserData,
) -> Result<(), Error> {
// ...
}
}

#[cgp_impl(new PostgresPostManager)]
impl PostManager {
fn create_post(
&self,
#[implicit] database: &PostgresDb,
title: &str,
content: &str,
) -> Result<Post, Error> {
// ...
}

fn get_post(
&self,
#[implicit] database: &PostgresDb,
post_id: &PostId,
) -> Result<Post, Error> {
// ...
}

fn update_post(
&self,
#[implicit] database: &PostgresDb,
post_id: &PostId,
content: &str,
) -> Result<(), Error> {
// ...
}

fn delete_post(
&self,
#[implicit] database: &PostgresDb,
post_id: &PostId,
) -> Result<(), Error> {
// ...
}
}

Any context with the required PostgreSQL database field can reuse these providers. If we wanted a SQLite-backed application, we could write SqliteUserManager and SqlitePostManager against the same interfaces and select those instead.

For our production application, we supply the database field and choose the PostgreSQL managers:

#[derive(HasField)]
pub struct ProductionApp {
pub database: PostgresDb,
}

delegate_and_check_components! {
ProductionApp {
UserManagerComponent: PostgresUserManager,
PostManagerComponent: PostgresPostManager,
}
}

Both managers share one dependency: the database field that #[derive(HasField)] makes available to their implicit arguments. The combined delegation-and-check macro verifies that ProductionApp can use the selected providers. For now, those two entries cover all the user and post operations.

Add dependencies as the service grows​

Now suppose the service needs to reject censored usernames and spam posts. Before inserting a user or a post, its manager must consult a filter. We can add a component for each check and declare the manager's dependency on its consumer trait with #[uses]:

#[cgp_component(UsernameCensor)]
pub trait CanCensorUsername {
fn username_is_censored(&self, username: &str) -> Probability;
}

#[cgp_component(SpamMessageDetector)]
pub trait CanDetectSpamMessage {
fn message_is_spam(&self, message: &str) -> Probability;
}

#[cgp_impl(new PostgresUserManager)]
#[uses(CanCensorUsername)]
impl UserManager {
fn create_user(
&self,
#[implicit] database: &PostgresDb,
username: &str,
email: &Email,
) -> Result<User, Error> {
if self.username_is_censored(username) > Probability::new(0.8) {
return Err(Error::InvalidUsername);
}

// ...
}

// ...
}

#[cgp_impl(new PostgresPostManager)]
#[uses(CanDetectSpamMessage)]
impl PostManager {
fn create_post(
&self,
#[implicit] database: &PostgresDb,
title: &str,
content: &str,
) -> Result<Post, Error> {
if self.message_is_spam(content) > Probability::new(0.8) {
return Err(Error::InvalidMessage);
}

// ...
}

// ...
}

Each manager compares its filter's score with a rejection threshold before writing to the database. The #[uses] attribute declares the new trait dependency, while #[implicit] database still supplies the database handle. The remaining manager methods are omitted here.

In production, filtering might involve an AI model or a cloud service. We would rather not make those calls every time we test the rest of the application. A deterministic string-matching filter lets tests run more quickly while keeping the same PostgreSQL managers:

#[derive(HasField)]
pub struct ProductionApp {
pub database: PostgresDb,
// ... // AI client credentials
}

delegate_and_check_components! {
ProductionApp {
UserManagerComponent: PostgresUserManager,
PostManagerComponent: PostgresPostManager,
UsernameCensorComponent: AiUserCensor,
SpamMessageDetectorComponent: AiSpamMessageDetector,
}
}

#[derive(HasField)]
pub struct TestApp {
pub database: PostgresDb,
}

delegate_and_check_components! {
TestApp {
UserManagerComponent: PostgresUserManager,
PostManagerComponent: PostgresPostManager,
UsernameCensorComponent: DummyUserCensor,
SpamMessageDetectorComponent: DummySpamMessageDetector,
}
}

Both contexts supply the database field and select the same managers. Only the filter entries differ, so tests can exercise the database implementations with deterministic filtering.

The wiring has grown along with the dependency tree. Each context now has four entries, so the two contexts together already have eight to keep in step, even in this small service.

Split independently reusable operations​

Adding CanCensorUsername to the user manager looked straightforward. But that bound belongs to the whole PostgresUserManager implementation, so even get_user now requires a context with a censor. Retrieving a user never runs the filter. The dependency arrives because retrieval and creation share a provider. The post manager has the same problem with spam detection, and every unrelated dependency we add makes the managers harder to maintain and test.

As we add operations, the domain boundaries become less obvious too. get_user_profile_picture might fit in the user manager, but it could need an entirely different set of dependencies. get_user_posts concerns both users and posts. Naming a manager after an entity does not settle which operations are useful to group together.

There is also a reason to keep the caller's interface narrow. Deleting a user is destructive, and we may not want every piece of code that works with users to be able to do it. Yet if we added delete_user to the manager, even generic code that only retrieves users would gain access to deletion. Giving retrieval its own trait lets that code ask for exactly the operation it needs, and nothing more.

That points to a simple but powerful pattern that CGP makes practical: splitting each manager into fine-grained traits, each holding one operation or a few closely related ones. Each provider can then declare only the dependencies it uses. For the user operations, that gives us:

#[cgp_component(UserCreator)]
pub trait CanCreateUser {
fn create_user(&self, username: &str, email: &Email) -> Result<User, Error>;
}

#[cgp_component(UserGetter)]
pub trait CanGetUser {
fn get_user(&self, user_id: &UserId) -> Result<User, Error>;
}

#[cgp_component(UserUpdater)]
pub trait CanUpdateUser {
fn update_user_data(&self, user_id: &UserId, user_data: &UserData) -> Result<(), Error>;
}

The user-creation provider needs the censor, while the getter needs only the database:

#[cgp_impl(new CreateUserWithPostgres)]
#[uses(CanCensorUsername)]
impl UserCreator {
fn create_user(
&self,
#[implicit] database: &PostgresDb,
username: &str,
email: &Email,
) -> Result<User, Error> {
if self.username_is_censored(username) > Probability::new(0.8) {
return Err(Error::InvalidUsername);
}

// ...
}
}

#[cgp_impl(new GetUserWithPostgres)]
impl UserGetter {
fn get_user(&self, #[implicit] database: &PostgresDb, user_id: &UserId) -> Result<User, Error> {
// ...
}
}

GetUserWithPostgres can be used with a database alone, while CreateUserWithPostgres keeps its censor dependency. A caller bounded by CanGetUser can retrieve users without depending on creation or deletion. The same split gives us separate post-creation, retrieval, update, and deletion components.

Separate filtering from database access​

Splitting the components solved the getter's problem, but CreateUserWithPostgres still does two jobs: it checks the username, then inserts the user into PostgreSQL. Only the insert has anything to do with the database. If we added a provider for SQLite, it would have to repeat the same check. Because creation now has a component of its own, we can move the check into a wrapper instead, and apply it to whichever user-creation provider we choose:

#[cgp_impl(new FilterCensoredUsername<InnerCreator>)]
#[uses(CanCensorUsername)]
#[use_provider(InnerCreator: UserCreator)]
impl<InnerCreator> UserCreator {
fn create_user(&self, username: &str, email: &Email) -> Result<User, Error> {
if self.username_is_censored(username) > Probability::new(0.8) {
return Err(Error::InvalidUsername);
}

InnerCreator::create_user(self, username, email)
}
}

#[cgp_impl(new CreateUserWithPostgres)]
impl UserCreator {
fn create_user(
&self,
#[implicit] database: &PostgresDb,
username: &str,
email: &Email,
) -> Result<User, Error> {
// ...
}
}

The wrapper rejects censored names, then hands an allowed request to InnerCreator::create_user. Its #[use_provider] attribute requires that inner provider to support user creation for the same context. Because it takes another provider as a parameter, we call FilterCensoredUsername a higher-order provider.

CreateUserWithPostgres can now focus on constructing the SQL insert query. When wiring the application, we can select it directly or add filtering with FilterCensoredUsername<CreateUserWithPostgres>. A local-first application could instead select FilterCensoredUsername<CreateUserWithSqlite> and reuse the same filter. Changing the database would not require copying the username check.

FilterSpamMessage<InnerCreator> applies the same separation to post creation. It uses CanDetectSpamMessage to reject spam, then forwards an allowed post to its inner PostCreator. The wiring can therefore choose FilterSpamMessage<CreatePostWithPostgres> independently of the database provider's implementation.

Count the cost of the separation​

With dependencies isolated and filters reusable, the individual providers are easier to work with. The production wiring, however, now has to select seven CRUD operations and two filters:

delegate_components! {
ProductionApp {
UserCreatorComponent:
FilterCensoredUsername<CreateUserWithPostgres>,
UserGetterComponent:
GetUserWithPostgres,
UserUpdaterComponent:
UpdateUserWithPostgres,
PostCreatorComponent:
FilterSpamMessage<CreatePostWithPostgres>,
PostGetterComponent:
GetPostWithPostgres,
PostUpdaterComponent:
UpdatePostWithPostgres,
PostDeleterComponent:
DeletePostWithPostgres,
UsernameCensorComponent:
AiUserCensor,
SpamMessageDetectorComponent:
AiSpamMessageDetector,
}
}

Splitting the managers took our wiring table from four entries to nine, and a real application might have dozens or hundreds. Imagine opening that table for the first time. To learn how the application handles users, you have to pick the user bindings out of the list, and everything else reads as noise that hides what ProductionApp actually does. The application then looks far more complex than it is, which is one reason long wiring tables have made CGP harder to adopt.

The table shows us too much at once. If we break it into smaller groups, a reader can take the wiring one piece at a time, so let's start by collecting the user bindings into a provider bundle of their own:

delegate_components! {
new PostgresUserComponents {
UserCreatorComponent:
FilterCensoredUsername<CreateUserWithPostgres>,
UserGetterComponent:
GetUserWithPostgres,
UserUpdaterComponent:
UpdateUserWithPostgres,
}
}

With new PostgresUserComponents, we declare an aggregate provider: its table delegates each operation to another provider. A reader can examine the user wiring on its own, without the post operations and filters alongside it. We can collect those into PostgresPostComponents and AiContentFilterComponents in the same way.

Back in the application, we forward the components to their bundles using array keys:

delegate_components! {
ProductionApp {
[
UserCreatorComponent,
UserGetterComponent,
UserUpdaterComponent,
]:
PostgresUserComponents,
[
PostCreatorComponent,
PostGetterComponent,
PostUpdaterComponent,
PostDeleterComponent,
]:
PostgresPostComponents,
[
UsernameCensorComponent,
SpamMessageDetectorComponent,
]:
AiContentFilterComponents,
}
}

The bundles make each group easier to read, but they do not shorten what the application has to list. Its table still names all nine components, now split across three lists, and each list repeats the keys its bundle already holds. So adding a user operation takes two edits: one to the user bundle, and another to every application that delegates to it. In a large codebase, that second edit could mean many places. We would rather tell the application to use PostgresUserComponents for β€œall user components,” but that group has no name we can wire.

Why the earlier grouping approaches were insufficient​

Ideally, the configuration would say something like this, with a key for each group:

delegate_components! {
ProductionApp {
???: // all user components
PostgresUserComponents,
???: // all post components
PostgresPostComponents,
???: // all content filter components
AiContentFilterComponents,
}
}

The ??? keys are the hard part. Each entry in the table becomes a trait implementation for one key, so UserCreatorComponent: … gives the application one implementation that answers lookups for user creation. A key that stood for all user components would need to produce one implementation per component in the group, and Rust's trait system has no way to expand a single entry like that. So CGP needs another way to recognize a group: either its own lookup rules, or a macro that expands the group into its keys. Namespaces take the first route, but the macro route is worth a look first.

One possibility would be a helper macro that supplied the list of keys for each group. That would let us write a hypothetical table like this:

delegate_components! {
ProductionApp {
all_user_components!():
PostgresUserComponents,
all_post_components!():
PostgresPostComponents,
all_content_filter_components!():
AiContentFilterComponents,
}
}

Here, all_user_components!() would expand to [UserCreatorComponent, UserGetterComponent, UserUpdaterComponent], with corresponding lists for posts and filters. Like the ??? keys above, these helpers are pseudocode rather than supported syntax.

Unfortunately, this runs into the order in which Rust expands macros. Rust expands them lazily, from the outside in, so delegate_components! runs first and receives all_user_components!() as literal tokens. At that point the helper has not expanded, and the component list does not exist yet. The table would need eager expansion, where a macro expands the macros inside its input before reading it, and stable Rust offers no way for a macro to do that. Even if it did, CGP would still have to generate helpers like all_user_components! and export them so that their names and imports keep working in other crates, and Rust's macro system has limited support for that.

My earlier preset system tried to solve the same problem, but it supported only a hierarchy like single inheritance. A context could inherit one preset, such as a user preset, and Rust's coherence restrictions then stopped it from also inheriting an independent post preset. I also experimented with combining several presets through macros, but the lack of eager macro expansion, together with the way imports and aliases resolve inside macro output, made that approach tedious to use.

Those attempts helped clarify what I wanted from the feature: an application should be able to name a group and choose its implementation bundle without enumerating every key. In v0.8.0, namespaces express that choice through trait resolution and paths. Existing preset users can find the conversion in the migration section.

Give component groups a path​

We can now replace the ??? keys with paths that name the user, post, and content-filter groups. With the component prefixes registered, our application table becomes:

delegate_components! {
ProductionApp {
namespace DefaultNamespace;

@app.core.user: PostgresUserComponents,
@app.core.post: PostgresPostComponents,
@app.extra.content_filter: AiContentFilterComponents,
}
}

The namespace DefaultNamespace; statement connects these paths to our components. Each component registers a route in the built-in DefaultNamespace, as we will do in a moment with #[prefix], and the statement tells the table to follow those routes. Namespaces are opt-in, so without this statement the table ignores the registered routes. A lookup for UserCreatorComponent, for example, follows a route that begins with @app.core.user, so it reaches the entry that selects PostgresUserComponents. Adding another user operation to the user group therefore leaves this table unchanged. The individual bindings still live in the bundles, while the application chooses only which groups it uses. Later, we will also define a namespace of our own.

To make this work, we give each component a prefix using #[prefix]. For CanCreateUser, we register @app.core.user in the built-in DefaultNamespace:

#[cgp_component(UserCreator)]
#[prefix(@app.core.user in DefaultNamespace)]
pub trait CanCreateUser {
fn create_user(&self, username: &str, email: &Email) -> Result<User, Error>;
}

CGP appends the component marker to this prefix. Once a context joins the namespace, a lookup for UserCreatorComponent follows the route to @app.core.user.UserCreatorComponent.

The getter and updater belong to that group too, so we register them under the same prefix. For the getter, that means:

#[cgp_component(UserGetter)]
#[prefix(@app.core.user in DefaultNamespace)]
pub trait CanGetUser {
fn get_user(&self, user_id: &UserId) -> Result<User, Error>;
}

Post operations get their own @app.core.post prefix:

#[cgp_component(PostCreator)]
#[prefix(@app.core.post in DefaultNamespace)]
pub trait CanCreatePost {
fn create_post(&self, title: &str, content: &str) -> Result<Post, Error>;
}

Finally, the filter components register under @app.extra.content_filter, also in DefaultNamespace. These registrations name the groups without choosing any providers for them. That choice stays with each application, so production, tests, and a SQLite variant can share the same routes and still select different bundles.

Group paths hierarchically​

Production and tests both use the PostgreSQL user and post operations. Rather than select those bundles separately in each application, we can collect them under their shared parent, @app.core. The paths are hierarchical: @app.core.user sits under @app.core, which sits under @app. An intermediate bundle can therefore gather the core operations, while another gathers the extras:

delegate_components! {
new PostgresCoreComponents {
namespace DefaultNamespace;

@app.core.user: PostgresUserComponents,
@app.core.post: PostgresPostComponents,
// other core components
}
}

delegate_components! {
new ProductionExtraComponents {
namespace DefaultNamespace;

@app.extra.content_filter: AiContentFilterComponents,
// other extra components
}
}

Notice that these intermediate bundles also join DefaultNamespace. When a lookup reaches a bundle, it receives the bare component key, and the namespace statement redirects that key to the paths in the bundle's own table. Our earlier leaf bundles use bare component names already, so they do not need that statement.

The production configuration now selects two groups:

delegate_components! {
ProductionApp {
namespace DefaultNamespace;

@app.core: PostgresCoreComponents,
@app.extra: ProductionExtraComponents,
}
}

A single entry for @app.core now covers both core groups. Because paths are hierarchical, it matches every route beneath that prefix, so user and post lookups both reach it, and so would a core group we add later. Take UserCreatorComponent again. Its route, @app.core.user.UserCreatorComponent, begins with @app.core, so ProductionApp forwards the lookup to PostgresCoreComponents. Inside that bundle, the namespace statement routes the component a second time, which brings it to the @app.core.user entry and on to PostgresUserComponents.

For testing, the core stays the same. Only the extras entry changes, selecting DummyExtraComponents for deterministic filtering:

delegate_components! {
TestApp {
namespace DefaultNamespace;

@app.core: PostgresCoreComponents,
@app.extra: DummyExtraComponents,
}
}

For a local configuration, we could make the other choice: keep the production filters and select a SQLite-backed core:

delegate_components! {
LocalApp {
namespace DefaultNamespace;

@app.core: SqliteCoreComponents,
@app.extra: ProductionExtraComponents,
}
}

In each case, one entry tells us how the configuration differs from production. TestApp changes the extras, while LocalApp changes the core. With flat tables, we would have to compare the individual component entries, perhaps written in different orders, to reach the same conclusion. We can now read those decisions directly from the wiring.

The selected providers still need their dependencies. Each context must supply the required fields and other traits, and the hypothetical SQLite core would need its corresponding database handle.

Check the completed configuration​

Will these providers work together? A delegate_components! block can compile before Rust has checked the providers' dependencies. We can ask Rust to check them now with check_components!, naming the components we need on the concrete application.

check_components! {
ProductionApp {
UserCreatorComponent,
UserGetterComponent,
UserUpdaterComponent,
PostCreatorComponent,
PostGetterComponent,
PostUpdaterComponent,
PostDeleterComponent,
UsernameCensorComponent,
SpamMessageDetectorComponent,
}
}

Apply the same nine-component check to TestApp and any local variant. Earlier stages need checks matching their components: before splitting the managers, for example, check UserManagerComponent and PostManagerComponent.

The check lists the individual operations, even though the wiring now routes them in groups. A group entry only says where a lookup goes, so the check confirms that every operation we rely on actually resolves. Run it on the real application context, which supplies the database field and the other dependencies. An aggregate provider is only a bundle of implementations, so checking a bundle as if it were the application would ask it for dependencies that only the context can supply.

The namespace documentation explains the lookup model, and the delegate_components! reference covers the path syntax.

Sharing default implementations​

So far, we have organized the wiring around choices we might want to change: PostgreSQL or SQLite, production or test filters. Bundles work well for that arrangement. We could add a PostgresWithLoggingCoreComponents variant, for example, and select the logging-backed core in the same place.

But an application starting out with PostgreSQL may have little reason to define interchangeable database bundles yet. Early in a project, developers often prefer one implementation per feature, tied to its interface on purpose, because that keeps the application easy to reason about. If several contexts should always use the same user and post implementations, having each one select those bundles repeats a choice that never varies. We can instead record those choices once in a namespace and leave only the varying parts to each context. These are default implementations.

I see defaults as a way to adopt CGP gradually. Ordinary traits may already be enough for a single-crate application with one implementation of each operation. If that application later needs more modularity, it can move code into CGP components and record its initial provider choices as defaults. Bundles can follow when there are useful groups to swap.

Let's keep the routes we already registered in DefaultNamespace and define a configuration namespace that inherits them using the new cgp_namespace! macro:

cgp_namespace! {
new DefaultAppComponents: DefaultNamespace
}

DefaultAppComponents starts with the prefixes and any default bindings supplied by its parent. We can add our application-specific choices here without changing what other namespaces select. Every context that joins this configuration namespace will share those choices.

For a simple provider, we can place its binding beside its implementation. Add #[default_impl] to our earlier GetUserWithPostgres definition:

#[cgp_impl(new GetUserWithPostgres)]
#[default_impl(@app.core.user.UserGetterComponent in DefaultAppComponents)]
impl UserGetter {
fn get_user(&self, #[implicit] database: &PostgresDb, user_id: &UserId) -> Result<User, Error> {
// ... query the database
}
}

The implementation now declares that DefaultAppComponents uses it at @app.core.user.UserGetterComponent. If we prefer to collect the bindings in one place, we can write the same choice in the namespace body instead:

cgp_namespace! {
DefaultAppComponents {
@app.core.user.UserGetterComponent: GetUserWithPostgres,
}
}

These are alternative ways to register the same binding, so writing both would create a conflict. The namespace body looks like a delegate_components! table, but its choices apply to every context that joins the namespace. We bind the provider at the full path because the bare key is already taken. The route inherited from DefaultNamespace uses UserGetterComponent to send lookups on to @app.core.user.UserGetterComponent, so a second entry for the bare key would conflict with it.

These defaults are fixed choices. Once the namespace binds a provider, a joining context or inheriting namespace cannot override it, even with a more specific entry. A context also cannot disable just one default while retaining the rest of that namespace. So a choice that should vary between contexts belongs on a path the namespace leaves open, as we will do with the filters below.

There is also a constraint on where we write the registration. With a prefixed path, the binding must live in the crate that owns the namespace, here DefaultAppComponents. The path expands to CGP's PathCons type, and owning a component marker nested inside that type does not satisfy Rust's orphan rules. An unprefixed local component marker has different ownership rules, covered by the #[default_impl] reference.

Bind composite providers in the namespace body​

FilterCensoredUsername is generic over its inner provider. For this configuration, we want to choose both the wrapper and its PostgreSQL implementation. We can assemble that complete provider choice directly in the namespace body:

cgp_namespace! {
DefaultAppComponents {
@app.core.user.UserCreatorComponent:
FilterCensoredUsername<CreateUserWithPostgres>,
}
}

After we bind the remaining user and post providers in the same way, the application only needs to choose its filters. For this example, our production wiring then becomes:

delegate_components! {
ProductionApp {
namespace DefaultAppComponents;

@app.extra.content_filter: AiContentFilterComponents,
}
}

Every context that joins DefaultAppComponents gets its user and post providers from it. We left the filter path open so a test context can select DummyContentFilterComponents there instead.

Choose how much wiring to share​

We kept the prefixes in DefaultNamespace and the provider choices in DefaultAppComponents for a reason. Another configuration, such as a SQLite one, can then inherit the same routes without also inheriting PostgreSQL choices it could not override. So the routes belong in a base namespace, and the fixed choices in a configuration namespace that inherits it.

If we later need to replace one of these fixed defaults, we choose a namespace that leaves its destination open. We could return to the base DefaultNamespace and supply the required bindings explicitly, as in the earlier bundle examples.

While the application lives in one crate, #[default_impl] conveniently keeps each binding beside its implementation. Once providers move into crates of their own, that attribute would sit in a crate that does not own the namespace, which the ownership rule above forbids. So we move the bindings into the configuration namespace's body instead, and the namespace's crate assembles the providers from there.

There is room to start with direct wiring, share fixed choices through defaults, and introduce interchangeable bundles as the application needs them. I would choose whichever arrangement makes the current decisions easiest to see, rather than build the full hierarchy in anticipation of future growth.

Other improvements​

Namespaces are the largest change, but several smaller additions also make CGP easier to write, read, and use in more kinds of crates. You can use these without following the full application refactoring above:

  • Choose a provider per type with open. If a generic component needs one provider for a rectangle and another for a circle, you can put those selections directly in the context's table. You do not need to declare a namespace or a nested UseDelegate table. The delegate_components! reference shows the syntax.
  • Assemble separate tables with for. A backend and an API surface may each have their own table of defaults. You can bring entries from another namespace table onto a path in your context, keeping those concerns independently defined. See namespace statements.
  • Keep implementation details out of trait parameters. Sometimes a #[cgp_fn] body needs a generic type only because it reads a field of that type. With #[impl_generics], the implementation can infer the type from the implicit field without adding a parameter to the generated trait.
  • Write data shapes as declarations. A field list is easier to recognize when it looks like the struct or enum it describes. Struct! and Enum! provide that notation, and cargo-cgp uses it when displaying shapes too.
  • Use fieldless variants directly. If an enum contains a state such as Closed, you can now use the extensible-variant derives without giving it a placeholder payload. The derives accept Closed, Closed(), and Closed {}, representing the payload as Nil. A no_std crate using the mutable extractor must have Box in scope.
  • Build without the standard library. With its default features, cgp needs neither std nor an allocator, so it fits a no_std crate on a target without either. The two error providers that format an error into a String, DebugError and DisplayError, need the new alloc feature.
  • Borrow any string field. An #[implicit] name: &str argument now reads any field whose type implements AsRef<str>, such as String, Box<str>, or Cow<'static, str>, where v0.7.0 required a String. An Option<&str> argument reads an Option of any of them.
  • Document what the macros generate. Every macro that declares a public item gives it a short doc line when you write none, so a crate can turn on #![warn(missing_docs)] without the lint flagging a component marker or a provider struct. A provider trait's doc also names its component key, so hovering the trait in an editor shows the key to import.
  • Get help with a missing component key. A provider written as impl Greeter needs the key GreeterComponent in scope, so a provider in another module imports the key along with the trait. If you forget, cargo cgp check reports CGP-E041 and offers a fix that adds the use line. You can also skip the import by naming the trait by its path, as the #[cgp_impl] reference explains.

For the smaller changes, such as clearer errors from the handler macros and the restrictions this release lifts, see the v0.8.0 release notes.

Breaking changes and migration​

Upgrading from v0.7.0 needs source changes. The largest is the removal of presets, which namespaces replace in this release, and most applications will also need explicit imports for items that used to come from the prelude. The v0.8.0 release notes list every change, with the upgrade steps in order.

Two projects built with CGP move to v0.8.0 at the same time. cgp-serde 0.3.0 can now serialize and deserialize enums, and Hypershell 0.2.0 assembles its language from a namespace instead of presets. If your code builds on either, the cgp-serde v0.3.0 and Hypershell v0.2.0 release notes give the upgrade steps.

Replace presets with namespace configuration​

The preset system described earlier is removed in v0.8.0. Its shared provider choices can become namespace bindings, while groups that need to remain interchangeable can become aggregate providers selected through paths.

The following v0.7.0 example defines a preset and inherits it into a context. This is old syntax and does not compile with v0.8.0:

cgp_preset! {
PostgresUserComponents {
UserCreatorComponent:
FilterCensoredUsername<CreateUserWithPostgres>,
UserGetterComponent: GetUserWithPostgres,
UserUpdaterComponent: UpdateUserWithPostgres,
}
}

#[cgp_inherit(PostgresUserComponents)]
pub struct ProductionApp {
pub database: PostgresDb,
}

delegate_components! {
ProductionApp {
// The inherited preset supplies the user-component entries.
// Other component bindings go here.
}
}

A configuration namespace can preserve the preset's fixed user-provider choices. Register the user components under @app.core.user in DefaultNamespace, using the #[prefix(... in DefaultNamespace)] attributes shown earlier. Then replace the preset with this namespace:

cgp_namespace! {
new PostgresAppNamespace: DefaultNamespace {
@app.core.user.UserCreatorComponent:
FilterCensoredUsername<CreateUserWithPostgres>,
@app.core.user.UserGetterComponent: GetUserWithPostgres,
@app.core.user.UserUpdaterComponent: UpdateUserWithPostgres,
}
}

The migrated context must also supply the censor required by its creation wrapper. Register UsernameCensor under @app.extra.content_filter in DefaultNamespace. With the user components and filter registered, replace the inheritance attribute with explicit delegation on the context:

#[derive(HasField)]
pub struct ProductionApp {
pub database: PostgresDb,
}

delegate_components! {
ProductionApp {
namespace PostgresAppNamespace;

@app.extra.content_filter.UsernameCensorComponent: AiUserCensor,
}
}

check_components! {
ProductionApp {
UserCreatorComponent,
UserGetterComponent,
UserUpdaterComponent,
UsernameCensorComponent,
}
}

The example above deliberately checks only the migrated user group and its filter. Add the post operations and any other dependencies your application uses.

An aggregate provider keeps the user-provider group interchangeable. If configurations need that variation, retain PostgresUserComponents using delegate_components! { new PostgresUserComponents { ... } } and select it with @app.core.user: PostgresUserComponents, as in the main walkthrough. Choose between this configurable bundle arrangement and the fixed namespace bindings above according to what should vary.

The removed preset constructs and their replacements are:

Removed constructWhat to use
cgp_preset!A configuration namespace for shared fixed choices, or an aggregate provider for a selectable group.
#[cgp_inherit]A namespace ...; statement and explicit path entries inside delegate_components!.
#[wrap_provider]Explicit aggregate providers and delegation entries.
#[cgp::re_export_imports]Ordinary Rust imports for the types used in namespace or delegation tables.
IsPresetRemove bounds on the preset marker. Generic code that queries a namespace uses that namespace's generated lookup trait.
replace_with!Nothing. The macros that presets generated expanded through it, so remove any call you wrote yourself.

Import what the prelude no longer exports​

cgp::prelude now exports only the names CGP code usually writes: the macros, the derives, PhantomData, and a few traits and providers such as HasErrorType, CanRaiseError, UseType, and DefaultNamespace. The code the macros generate reaches CGP's items through a separate cgp::macro_prelude, so the prelude no longer has to carry those items. If your code names one of the dropped items through the glob import, the compiler reports that it cannot find it, and you import it from its module:

use cgp::core::component::DelegateComponent;
use cgp::core::field::traits::HasField;
use cgp::extra::handler::{Computer, ComputerComponent};

The dropped names come from these modules:

  • Wiring traits such as DelegateComponent and IsProviderFor: cgp::core::component.
  • Field-access traits and type-level types such as Cons, Nil, and Index: the modules under cgp::core::field.
  • HasType and TypeProvider: cgp::core::types.
  • The handler family, with its traits, keys, and providers: cgp::extra::handler.

A derive does not need its trait imported, so #[derive(HasField)] still works through the prelude, while a HasField bound or a .get_field() call needs the import. A provider for a handler trait such as Computer imports its key, ComputerComponent, beside the trait, because the provider's header names the key, as Other improvements describes.

Raw compiler output changes slightly as a result. Where v0.7.0 printed a type such as cgp::prelude::Chars, the compiler can now print cgp::macro_prelude::Chars, as in the cargo check comparison above.

The type-level types also lose their Greek-letter names. v0.7.0 declared them as Ο€, Ξ΅, Οƒ, ΞΈ, ΞΆ, ψ, Ξ΄, and Ο‰, with Cons, Nil, Either, Void, Chars, Symbol, Index, and Field as aliases, and the prelude exported both spellings. Only the English names remain, so code that wrote a Greek name switches to the English one, imported from cgp::core::field::types. Raw compiler output changes with them, printing Cons<…> and Chars<…> where v0.7.0 printed Ο€<…> and ΞΆ<…>.

Turn on alloc for the formatting error providers​

The default features of cgp are now empty, so the library builds without std or an allocator. In v0.7.0, the defaults turned on DebugError and DisplayError, the error providers that format an error into a String. If your wiring uses either, turn on the alloc feature:

[dependencies]
cgp = { version = "0.8.0", features = ["alloc"] }

Update attribute syntax and direct dependencies​

The associated-type separator in #[use_type] changes from :: to .:

// v0.7.0
#[use_type(HasErrorType::Error)]

// v0.8.0
#[use_type(HasErrorType.Error)]

Equality imports use the new separator too. Write #[use_type(HasErrorType.{Error = AppError})]. An import from another context changes shape as well, with the context named after in: #[use_type(@Types::HasScalarType::Scalar)] becomes #[use_type(HasScalarType.Scalar in Types)]. The #[use_type] reference covers each form.

A component that generates a UseDelegate dispatcher moves the derive_delegate key of #[cgp_component] into an attribute of its own, one per dispatcher:

// v0.7.0
#[cgp_component {
provider: AreaCalculator,
derive_delegate: UseDelegate<Shape>,
}]

// v0.8.0
#[cgp_component(AreaCalculator)]
#[derive_delegate(UseDelegate<Shape>)]

A new component does not need either form, because the open statement from Other improvements dispatches it per type.

The extra-feature macro crates are renamed from cgp-extra-macro and cgp-extra-macro-lib to cgp-macro-extra and cgp-macro-extra-lib. Update direct dependencies on those crates. Imports through cgp::prelude keep their names.

Self-contained handler-macro expansions may leave imports unused. Remove imports the compiler reports when they existed only for the old expansion.

#[cgp_auto_dispatch] rejects attribute arguments and typed receivers such as self: Box<Self>. It previously ignored the arguments or miscompiled those receivers.

The new Struct! and Enum! prelude exports can make a macro name ambiguous. Qualify the call if another glob import provides the same name.

DelegateComponent, IsProviderFor, HasField, and HasFieldMut no longer carry custom #[diagnostic::on_unimplemented] messages. Plain cargo check now reports an unmet bound on them in the compiler's own wording, and cargo cgp check rewrites those errors into its own summary. If a test compares compiler output, as a UI test does, update the messages it expects.

Check error-backend behavior​

cgp-error-eyre enables eyre's automatic default-handler installation and tracks the caller of raise_error and wrap_error.

cgp-error-std changes how wrapped errors are displayed. Ordinary Display prints only the outer detail, while alternate Display and Debug include the chain. This avoids duplicated sources when a reporter walks source() itself. Update output assertions that depend on the old formatting.

The minimum anyhow and eyre dependencies rise to 1.0.104 and 0.6.14 respectively. The backend READMEs in the CGP repository describe their use.

Try one part of your application​

We started with two manager choices and ended with applications that could share a core, change their filters, or use a different database. Namespaces let the top-level wiring express those choices even as we split the implementations into smaller pieces. I hope that makes similar refactorings easier to follow in your own projects, with cargo-cgp and the new documentation there to help when something is unclear.

CGP still takes time to learn. Its ecosystem is small, and I still have work to do on the tooling and documentation. My suggestion is to try it on one problem you already have. If you already use CGP, try grouping one area of your wiring while keeping its component checks in place. If you are new to CGP, the Quickstart provides a smaller starting point.

I would appreciate hearing where you still struggle to trace an implementation, understand a diagnostic, or follow an explanation. Those examples will help me decide what to improve next. You can share them in GitHub Discussions. Thank you for reading and trying CGP.


I wrote the draft of this post, and an AI agent revised its prose and checked its code and claims against the CGP knowledge base. See How AI is used in this project.