Skip to main content

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
The Context-Generic Programming logo
Rust rejects the overlapping implementations
// 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 implementation
With CGP, both encoders compile
use 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.

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 check leads 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.