Coverage instrumentation attributes

The following attributes are used for controlling coverage instrumentation.

Note: Coverage instrumentation is controlled in rustc with the -C instrument-coverage compiler flag.

The coverage attribute

The coverage attribute indicates whether a function should include instrumentation for code coverage and show up in code coverage reports.

The attribute uses the MetaListIdents syntax to specify its behavior:

  • #[coverage(off)] indicates that all functions within an item, recursively, should not be instrumented, unless specified by another attribute.
  • #[coverage(on)] (the default) indicates that all functions within an item, recursively, should be instrumented, unless specified by another attribute.
#![allow(unused)]
fn main() {
#[coverage(off)]
fn example() {}

struct S;

#[coverage(off)]
impl S {
    #[coverage(on)]
    fn function_with_coverage() {}

    fn function_without_coverage() {}
}
}

The coverage attribute can only be controlled at the granularity of individual functions. It can be applied to functions, closures, associated functions, implementations, modules, or the crate root.

It is an error to specify the attribute on a trait function without a body.

When specified on a trait function, the attribute only applies to the default function body. Trait implementations do not inherit the setting from the trait definition.

It is an error to specify the #[coverage] attribute multiple times on the same item.

Coverage attributes on more deeply nested items take priority over attributes at a higher nesting level. For example, if a crate is marked #![coverage(off)], then functions inside that crate marked #[coverage(on)] will still have coverage.