Skip to main content

automatically_derived

Attribute automatically_derived 

Source
Expand description

The automatically_derived attribute is used to indicate that an impl block is automatically generated by a derive macro. It has no direct effect, but it may be used by tools and diagnostic lints, such as Clippy, to detect these automatically generated implementations.

Example:

// Given #[derive(Clone)] on struct Example, the derive macro may produce:
#[automatically_derived]
impl ::core::clone::Clone for Example {
    fn clone(&self) -> Self { Example }
}

The attribute may only be applied to an impl block.

Because code generated by a macro becomes part of the source code representation of the crate that calls the macro, diagnostic lints for the expanded macro will be emitted in the caller’s workspace (whereas warnings generated while building dependencies not in the local workspace are suppressed by Cargo). This may be undesirable, so the author of the macro can use the automatically_derived attribute to hint to tools that the generated code is not written by the caller (and that tools should not render warnings for it).

For example, this impl block lacks #[automatically_derived]:

// Suppose this impl block is the output of a derive macro
impl ::core::cmp::PartialEq for Example {
    fn eq(&self, other: &Self) -> bool { true }
    fn ne(&self, other: &Self) -> bool { !(self == other) }
}

In the example above, Clippy will emit the following warning:

warning: re-implementing `PartialEq::ne` is unnecessary
 --> src/lib.rs:7:9
  |
4 |         fn ne(&self, other: &Self) -> bool { !(self == other) }
  |         ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  |
  = help: for further information visit https://rust-lang.github.io/rust-clippy/rust-1.98.0/index.html#partialeq_ne_impl
  = note: `#[warn(clippy::partialeq_ne_impl)]` on by default

However, if the derive macro were written so that it outputs #[automatically_derived] on the impl block, as below, then Clippy will not emit the above partialeq_ne_impl lint:

// Suppose this impl block is the output of a derive macro
#[automatically_derived]
impl ::core::cmp::PartialEq for Example {
    fn eq(&self, other: &Self) -> bool { true }
    fn ne(&self, other: &Self) -> bool { !(self == other) }
}

The automatically_derived attribute should be preferred over the allow attribute for suppressing unintended user-facing diagnostics in automatically generated code.

For more information, see the Reference on the automatically_derived attribute.