Skip to content

Incorrect Cognitive Complexity value when nesting for loops #11164

Open
@epic-64

Description

@epic-64

Summary

I tried the cognitive_complexity lint on a basic code example. The result does not match up.

Input:

fn main() -> Result<()> {
    for _i in 0..10 { // +1
        for _k in 0..10 { // +2
            for _l in 0..10 { // +3
                for _m in 0..10 { // +4
                    for _n in 0..10 { // +5
                        for _o in 0..10 { // +6
                            print!("")
                        }
                    }
                }
            }
        }
    }

    Ok(())
}

Expected result: 21
Actual Result: 7

Additional Details
To my understanding, the cognitive complexty of the main function is 21, as each for loop adds a value of 1, plus 1 for each level of nesting that it is already in.

However the warning I get says that it is 7:

warning: the function has a cognitive complexity of (7/1)
  --> src\main.rs:17:4
   |
17 | fn main() -> Result<()> {
   |    ^^^^
   |
note: the lint level is defined here
  --> src\main.rs:1:9
   |
1  | #![warn(clippy::cognitive_complexity)]
   |         ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
   = help: you could split it up into multiple smaller functions
   = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#cognitive_complexity

Reproducer

I tried this code:

cargo clippy

Given this source code:

fn main() -> Result<()> {
    for _i in 0..10 { // +1
        for _k in 0..10 { // +2
            for _l in 0..10 { // +3
                for _m in 0..10 { // +4
                    for _n in 0..10 { // +5
                        for _o in 0..10 { // +6
                            print!("")
                        }
                    }
                }
            }
        }
    }

    Ok(())
}

I expected to see this happen:
warning: the function has a cognitive complexity of (21/1)

Instead, this happened:
warning: the function has a cognitive complexity of (7/1)

Version

rustc 1.71.0 (8ede3aae2 2023-07-12)
binary: rustc
commit-hash: 8ede3aae28fe6e4d52b38157d7bfe0d3bceef225
commit-date: 2023-07-12
host: x86_64-pc-windows-msvc
release: 1.71.0
LLVM version: 16.0.5

Additional Labels

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    C-bugCategory: Clippy is not doing the correct thingL-nurseryLint: Currently in the nursery group

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions