Search code examples
rustclap

Where are clap macros coming from if they are not being imported?


In the following code snippet, I'm not importing the macros clap and arg but they're still available to the code. Where are they coming from?

use clap::Parser;

#[derive(Parser, Debug)]
struct Arguments {
    #[clap(short, long)]
    first_part: Option<String>,
    #[arg(short, long)]
    second_part: Option<String>,
}

fn main() {
    let args = Arguments::parse();
    println!("{:?}", args);
}

Solution

  • These are not macros, but attributes.

    The confusion comes because derive is also an attribute, not a macro. Only that some derive implementations are implemented as macros. Remember that normal macros are recognized by the ! not by #, such as println!.

    About where these attributes come from? Well, attributes are never imported, these derive macro helper attributes are parsed either directly by any macro that may be in effect. Yes, this means that these attributes are not scoped and could, in theory, conflict between several crates. It hasn't happened that I know of, yet.