Based on Cognitive Complexity by G. Ann Campbell.
Add complexity
to your Cargo.toml
.
[dependencies]
complexity = "0.1"
syn = "1"
You'll need to import the [Complexity
] trait, and probably some things from
[syn
].
rust
use complexity::Complexity;
use syn::{ItemFn, parse_quote};
Loops and branching increment the complexity by one each. Some syntax structures introduce a "nesting" level which affects certain sub items.
rust
let func: ItemFn = parse_quote! {
fn sum_of_primes(max: u64) -> u64 {
let mut total = 0;
'outer: for i in 1..=max { // +1
for j in 2..i { // +2 (nesting = 1)
if i % j == 0 { // +3 (nesting = 2)
continue 'outer; // +1
}
}
total += i;
}
}
};
assert_eq!(func.complexity(), 7);
Certain structures a rewarded. Particularly a match
statement, which only
increases the complexity by one no matter how many branches there are. (It does
increase the nesting level though.)
rust
let func: ItemFn = parse_quote! {
fn get_words(number: u64) -> &str {
match number { // +1
1 => "one",
2 => "a couple",
3 => "a few",
_ => "lots",
}
}
};
assert_eq!(func.complexity(), 1);
An example is provided to calculate and nicely print out the cognitive complexity of each function and method in an entire Rust file. See examples/lint-files.rs. You can run it on Rust files like this:
sh
cargo run --example lint-files -- src/
Licensed under either of
at your option.