Based on Cognitive Complexity by G. Ann Campbell.
Getting started
Add complexity
to your Cargo.toml
.
[dependencies]
complexity = "0.1"
syn = "1"
You'll need to import the Complexity
trait, and probably some parts of
syn
.
use Complexity;
use ;
Loops and branching increment the complexity by one each. Additionally,
continue
and break
statements increment the complexity by one.
let code = r#"
fn sum_of_primes(max: u64) -> u64 {
let mut total = 0;
'outer: for i in 1..=max {
for j in 2..i {
if i % j == 0 {
continue 'outer;
}
}
total += i;
}
}"#;
let func: ItemFn = parse_str?;
assert_eq!;
However, a match
only increases the complexity by one no matter how many
branches there are.
let code = r#"
fn get_words(number: u64) -> &'static str {
match number {
1 => "one",
2 => "a couple",
3 => "a few",
_ => "lots",
}
}"#;
let func: ItemFn = parse_str?;
assert_eq!;
License
Licensed under either of
- Apache License, Version 2.0 (LICENSE-APACHE or http://www.apache.org/licenses/LICENSE-2.0)
- MIT license (LICENSE-MIT or http://opensource.org/licenses/MIT)
at your option.