Skip to main content

Expand

cargo cgp expand lets you inspect the Rust generated by a Context-Generic Programming (CGP) macro when its expansion would help explain a requirement or a wiring choice. The command is part of cargo-cgp and prints the crate after macro expansion. It also writes CGP's type-level constructs back in the form you used, making the generated code easier to read:

cargo cgp expand --lib

When to use it​

Use expand when an error message does not answer your question and the generated code might. These situations come up most often:

  • A diagnostic names a type you did not write: the message mentions IsProviderFor, a PathCons key, or a __Context__ parameter, and you want to see the impl it came from.
  • A wiring table does not resolve: you want its actual DelegateComponent keys and providers rather than inferring them from the table's syntax.
  • You are unsure what a construct emits: you want the exact where clauses of a provider, or to see which field a getter reads.
  • Two forms differ and only one compiles: you can expand both and compare the output.

What it looks like​

The Rectangle program from the Check page gives the expansion a concrete source to compare against. Restore its missing height field so the program compiles:

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,
pub height: f64,
}

delegate_components! {
Rectangle {
AreaCalculatorComponent: RectangleArea,
}
}

check_components! {
Rectangle {
AreaCalculatorComponent,
}
}

Asking for the Rectangle type gives its declaration and every impl written for it:

cargo cgp expand --lib --item Rectangle
pub struct Rectangle {
pub width: f64,
pub height: f64,
}
impl HasField<Symbol!("width")> for Rectangle {
type Value = f64;
fn get_field(
&self,
key: ::core::marker::PhantomData<Symbol!("width")>,
) -> &Self::Value {
&self.width
}
}
impl HasFieldMut<Symbol!("width")> for Rectangle {
fn get_field_mut(
&mut self,
key: ::core::marker::PhantomData<Symbol!("width")>,
) -> &mut Self::Value {
&mut self.width
}
}
impl HasField<Symbol!("height")> for Rectangle {
type Value = f64;
fn get_field(
&self,
key: ::core::marker::PhantomData<Symbol!("height")>,
) -> &Self::Value {
&self.height
}
}
impl HasFieldMut<Symbol!("height")> for Rectangle {
fn get_field_mut(
&mut self,
key: ::core::marker::PhantomData<Symbol!("height")>,
) -> &mut Self::Value {
&mut self.height
}
}
impl DelegateComponent<AreaCalculatorComponent> for Rectangle {
type Delegate = RectangleArea;
}
impl<
__Context__,
__Params__: ?Sized,
> IsProviderFor<AreaCalculatorComponent, __Context__, __Params__> for Rectangle
where
RectangleArea: IsProviderFor<AreaCalculatorComponent, __Context__, __Params__>,
{}
impl __CheckRectangle<AreaCalculatorComponent, ()> for Rectangle {}

You can trace the annotations through the listing. #[derive(HasField)] generated each field's accessors, while delegate_components! selected RectangleArea and forwarded its requirements. At the end, check_components! supplied the assertion that Rectangle can use the component.

Narrowing with --item​

Even this small crate expands to 156 lines, while the Rectangle selection above takes 49. To keep the relevant code together, --item accepts a ::-separated path to a module or item inside the crate:

cargo cgp expand --lib --item shapes # a module: its contents
cargo cgp expand --lib --item shapes::Rectangle # a type: its declaration and every impl for it
cargo cgp expand --lib --item AreaCalculator # a trait: its definition and every impl of it

A leading crate:: is accepted, so --item crate::shapes and --item shapes are the same request.

For a component, selecting the provider trait usually reveals most of the useful generated code. Here --item AreaCalculator includes the trait, its wiring blanket impl, the generated UseContext and RedirectLookup impls, and RectangleArea's implementation with its field requirements. Selecting CanCalculateArea instead shows the consumer trait and the blanket impl connecting it to the provider trait.

A path that matches nothing produces an error instead of falling back to the whole crate. Among cargo's progress lines, you will see:

error: no module or item matched `NoSuchThing`
note: the path names a module or item inside the crate being expanded, as in `contexts::app`; a leading `crate::` is accepted too

and finishes with:

error: no expansion was produced; see the errors above

Choosing a target​

Expansion operates on one target at a time. Since the command forwards target selection to cargo rustc, a package containing both a library and a binary needs an explicit choice:

cargo cgp expand --lib
cargo cgp expand --bin my-app
cargo cgp expand -p my-crate --lib

Without a choice, cargo declines, in a message that does not mention expand:

error: extra arguments to `rustc` can only be passed to one target, consider filtering
the package by passing, e.g., `--lib` or `--bin NAME` to specify a single target
error: no expansion was produced; see the errors above

The expansion goes to standard output, so it redirects and pipes like any other program's output:

cargo cgp expand --lib > expanded.rs
cargo cgp expand --lib | grep 'Symbol!'

cargo cgp expand --help prints the tool's own help for expand, which documents --item. That is the one argument expand reads itself, so for cargo's target-selection options, run cargo rustc --help.

Why not cargo-expand​

cargo-expand works on CGP code too. The difference becomes visible in type-level constructs: a general expander formats their compiler representation, while cargo cgp expand recovers CGP's shorthand.

For a field name, that compiler representation is a type-level string containing a type for each character. The height accessor begins like this before the shorthand is recovered:

impl ::cgp::macro_prelude::HasField<::cgp::macro_prelude::Symbol<6,
::cgp::macro_prelude::Chars<'h',
::cgp::macro_prelude::Chars<'e',
::cgp::macro_prelude::Chars<'i',
::cgp::macro_prelude::Chars<'g',
::cgp::macro_prelude::Chars<'h',
::cgp::macro_prelude::Chars<'t', ::cgp::macro_prelude::Nil>>>>>>>> for
Rectangle {

cargo cgp expand writes it back as Symbol!("height"), which is what you wrote. It does the same for the rest of CGP's type-level vocabulary: a list of handlers reads Product![StepOne, StepTwo] rather than a chain of Cons cells, a derived field list reads Struct! { width: f64, height: f64 }, and a namespace key reads Path!(@app.GreeterComponent).

Selecting by --item also keeps the relationships between Rust items together. A trait selection includes every implementation of that trait in the crate, wherever it was declared. This is useful when a question about wiring spans several generated implementations.

What to expect from the output​

The command expands the crate's other macros along with CGP's. That means the listing includes the generated code for #[derive(Debug)] and println! too; only the formatting of CGP's type-level constructs is specific to CGP.

To keep the listing readable, the tool removes the cgp::macro_prelude:: qualifiers inserted by the macros. Those names may then lack the paths needed to resolve in your crate, so the output is intended for inspection rather than pasting back as compilable source.

Expansion stops before type checking. This lets you inspect a broken program, but it also means that a wiring mistake can go unreported and the command can exit with 0 for code that does not type-check. Use cargo cgp check to verify the wiring itself.

An error before expansion finishes still fails the command with cargo's exit status. Many such failures, including a CGP macro rejecting its input, leave a partial expansion to read. Others, such as duplicate type definitions, unmatched macro_rules! calls, or unclosed delimiters, produce no expansion. Piping to a command that closes the stream early is allowed, so cargo cgp expand --lib | head is not treated as a failure.

Expansion uses the same pinned nightly and target/cgp directory as checking. The Check page explains the resulting build costs and how to choose the target directory.


An AI agent wrote this page using the CGP knowledge base, and its outputs were produced by running the commands. See How AI is used in this project.