Hacker News

Context-Generic Programming v0.8.0 - Pluggable trait implementations for Rust

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 ` is not satisfied
 --> src/lib.rs:23:9
  |
23 |         AreaCalculatorComponent: RectangleArea,
  |         ^^^^^^^^^^^^^^^^^^^^^^^ unsatisfied trait bound
  |
help: the trait `HasField >>>>>>>` is not implemented for `Rectangle`
but trait `HasField >>>>>>` is implemented for it
 --> src/lib.rs:17:9
  |
17 |     pub width: f64,
  |         ^^^^^
note: required for `RectangleArea` to implement `IsProviderFor `
 --> src/lib.rs:8:1
  |
8  | #[cgp_impl(new RectangleArea)]
  | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  = note: required for `Rectangle` to implement `CanUseComponent `
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::p

Read on Hacker News ↗ ← Back to News

Comments

No comments yet. Start the discussion.