Context-Generic Programming
A language extension for Rust, with pluggable trait implementations at compile-time.
Still ordinary Rust: a library on the stable toolchain, with provider selection resolved at compile time, adopted one trait at a time.
cargo add cgp
// Rust allows only one of these. `String` is both `Display` and
// `AsRef<[u8]>`, so the compiler has no principled way to choose.
pub trait CanEncode {
fn encode(&self) -> Vec<u8>;
}
impl<T: Display> CanEncode for T {
fn encode(&self) -> Vec<u8> { self.to_string().into_bytes() }
}
impl<T: AsRef<[u8]>> CanEncode for T { // error[E0119]
fn encode(&self) -> Vec<u8> { self.as_ref().to_vec() }
}
error[E0119]: conflicting implementations of trait `CanEncode`
|
7 | impl<T: Display> CanEncode for T {
| -------------------------------- first implementation here
...
11 | impl<T: AsRef<[u8]>> CanEncode for T { // error[E0119]
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ conflicting implementationuse cgp::prelude::*;
#[cgp_component(Encoder)] // generates the provider trait Encoder
pub trait CanEncode {
fn encode(&self) -> Vec<u8>;
}
#[cgp_impl(new EncodeAsText)] // a provider: one named implementation
#[uses(Display)]
impl Encoder {
fn encode(&self) -> Vec<u8> { self.to_string().into_bytes() }
}
#[cgp_impl(new EncodeAsBytes)]
#[uses(AsRef<[u8]>)]
impl Encoder {
fn encode(&self) -> Vec<u8> { self.as_ref().to_vec() }
}
// Each type names the implementation it uses:
delegate_components! { u64 { EncoderComponent: EncodeAsText } }
delegate_components! { String { EncoderComponent: EncodeAsText } }
delegate_components! { Vec<u8> { EncoderComponent: EncodeAsBytes } }
CGP gives each encoder a name. Here, String selects EncodeAsText and Vec<u8> selects EncodeAsBytes.
For each type, a call to encode() still selects a single encoder.
Why the encoders overlap
String implements both Display and AsRef<[u8]>, so it qualifies for both implementations of CanEncode in the first example. Rust rejects the pair because a call to encode() on a string would be ambiguous. The rule that keeps trait implementations unique for a given type is called coherence. You rely on it whenever you write a bound like T:Β Display and let the compiler find the implementation.
In plain Rust, one way to keep both encoders is to wrap the data in a different newtype for each case. With CGP, the crate that defines an encoder gives the implementation its own type, called a provider. Each data type can then select a provider for its encoder, as String does above. Bypassing coherence explains the rules and other ways to handle overlap.
Choosing an encoder for String fixes that choice for the whole program. To choose per application, you can select the provider on a type that represents the application. That type is called a context, and you can define as many contexts as you need. Consumer and provider traits shows an application and its test choosing different providers.
Reusing providers across applications
Once each application can choose its providers, you can reuse the same implementations in different combinations. CGP's main features build on that choice.

One Interface, Many Implementations
The two encoders above coexist because each one lives on its own provider type, and each type names the one it uses.
Zero-Cost Abstraction
Provider selection resolves at compile time into a direct call, without a container or a vtable lookup.
Type-Safe Wiring
A provider states its needs, as#[uses(Display)]does above, and acheck_components!assertion or a use of the component fails the build when a context lacks one.
Abstract Over Every Dependency
Core logic names abstract error, runtime, and I/O types, and each context supplies concrete ones, so the core builds forno_stdwhere the chosen implementations allow.
The Overview describes each feature in more detail.
More than trait implementations
Beyond choosing implementations, you can use CGP to choose the types they work with, write generic code for structs and enums, and combine steps into a pipeline.
- Abstract typesA context chooses types such as its error or runtime, so you do not have to declare them as separate parameters at every layer.
- Extensible records and variantsAdd a derive to a struct or enum to let generic code build and match its fields and variants.
- HandlersCombine synchronous or async steps into a pipeline, then change individual steps as needed.
What it costsβ
Use a plain trait when one implementation is enough. When you need several, weigh the flexibility of choosing providers against the work it adds.
- More declarations
- Components, providers, and wiring add code that a plain trait does not need.
- Compile-time work
- The compiler has extra macros to expand and types to check.
- Verbose raw errors
- Raw wiring errors are long, but
cargo cgp checkleads with the root cause for the classes it recognizes, and the tool does not yet reshape every class. - A young ecosystem
- CGP has a small ecosystem and limited community support. If you use it on a mission-critical project, expect to investigate some problems on your own. Its error toolchain,
cargo-cgp, is also an early release. - Learning time
- It takes time to learn how to choose and connect providers. If you use a coding assistant, CGP's agent skill helps it use the terminology, interpret diagnostics, and connect providers. You still need to review the code it writes.
To see whether those costs are worthwhile, try CGP in a small part of your project where you already use different implementations. If you are unsure where to start, Modularity Hierarchy explains when a plain trait is enough and when providers help.
Where to go next
Start with a working example, explore how providers fit together, or see how other projects use them.
- Try itQuickstartInstall CGP and run a program, then follow the Hello World tutorial.
- Understand the ideaBypassing coherenceExplore why coherence matters, then see how CGP works in Consumer and provider traits.
- Decide whether it fitsModularity HierarchyLearn when a simpler tool is enough, and explore projects built with CGP.
- Go deeperOverviewTake a tour of the features, compare CGP with related approaches, or read the blog.
- Help build itContributeJoin the discussions, or improve the code and the documentation.