complexity 0.1.0

Calculate cognitive complexity of Rust code.
Documentation

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::Complexity;
use syn::{ItemFn, parse_str};

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(code)?;
assert_eq!(func.complexity(), 7);

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(code)?;
assert_eq!(func.complexity(), 1);

License

Licensed under either of

at your option.