liveBook · Manning

Cargo check

As explained in Write Powerful Rust Macros

cargo check is a Cargo command that compiles a Rust project for error checking without producing a final executable.

cargo check compiles a Rust project for error checking without producing a final executable. With procedural macros, it checks the macro library and the generated code only when a consuming application uses the macro. section 3.2

Checking generated code

A typo such as TokenStrea in the macro library is caught by cargo check. However, invalid tokens generated by quote!, such as `fn this should not work () {}`, can pass there; running cargo check in the outer application reports the syntax error at the derive macro invocation. section 3.2

Use cargo check diagnostically by separating these cases:

  • Check the procedural macro library for errors in its own Rust code. section 3.2
  • Check a consuming application to validate the Rust code emitted by the macro. section 3.2
  • Combine cargo check with cargo expand when an attribute macro produces a confusing type error, such as a missing return in Err(...). section 7.8.2
#[proc_macro_derive(Hello)]
pub fn hello(item: TokenStream) -> TokenStream {
    let add_hello_world = quote! {
        fn this should not work () {}
    };

    add_hello_world.into()
}

Inspect the intentionally invalid generated function to see why checking the consuming application matters. section 3.2

How Write Powerful Rust Macros covers it

How deep it goes
Explains the boundary between library and generated-code checking, but defers full generated-code inspection to cargo expand.
Examples
Uses a misspelled TokenStream type, invalid quote! output, and a missing return in a Result-producing macro.
What it assumes
Assumes familiarity with Rust compilation, procedural macros, TokenStream, quote!, and Result types.
What you can do after
Diagnose macro errors by checking both the library and consuming application, then inspect expanded output with cargo expand.
How it connects
Connects compilation checking with procedural macros, derive macros, attribute macros, compiler errors, and cargo expand.

Also explained in

Compare how 2 books explain cargo check →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Write Powerful Rust Macros. The section links point to the parts of the book it draws on.