rust-lang / rust-lang/rust-clippy
`cognitive_complexity` lint includes code expanded from macro in calculated complexity
Nobody has claimed this yet.
- Dominant language
- Rust
- Stars
- 13.5k
- Forks
- 2.2k
- Avg merge
- 2d 10h
- Merged PRs (30d)
- 32
Description
Summary
Code expanded from macros should not count towards cognitive complexity. Instead, a macro call should have the same cognitive complexity as a function call.
Lint Name
cognitive_complexity
Reproducer
I tried this code:
#![warn(clippy::cognitive_complexity)]
// exact content of the macro is not important
macro_rules! create_4d_vec {
( $dim_1:literal, $dim_2:literal, $dim_3:literal, $dim_4:literal) => {
let mut vec = vec![vec![vec![vec![0; $dim_4]; $dim_3]; $dim_2]; $dim_1];
for a in 0..$dim_1 {
for b in 0..$dim_2 {
for c in 0..$dim_3 {
for d in 0..$dim_4 {
vec[a][b][c][d] = a + b + c + d;
}
}
}
}
};
}
fn foo() {
create_4d_vec!(1, 2, 3, 4);
create_4d_vec!(1, 2, 3, 4);
create_4d_vec!(1, 2, 3, 4);
create_4d_vec!(1, 2, 3, 4);
create_4d_vec!(1, 2, 3, 4);
create_4d_vec!(1, 2, 3, 4);
create_4d_vec!(1, 2, 3, 4);
}
I saw this happen:
warning: the function has a cognitive complexity of (29/25)
--> src/main.rs:18:4
|
18 | fn foo() {
| ^^^
|
= 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
I expected to see this happen:
Lint does not trigger.
Version
rustc 1.87.0-nightly (ecade534c 2025-03-14)
binary: rustc
commit-hash: ecade534c66478c51c5d3c1d3682dc4beb0ac972
commit-date: 2025-03-14
host: x86_64-unknown-linux-gnu
release: 1.87.0-nightly
LLVM version: 20.1.0
Additional Labels
@rustbot label +L-nursery
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Start with the cognitive_complexity lint implementation and run the provided macro reproducer to trace how expanded macro code contributes to the calculation. Done means a macro invocation contributes like a function call, the reproducer no longer triggers the lint, and existing cognitive-complexity behavior remains intact.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- rust
- Domain
- tooling
- Issue type
- Bug
- Difficulty
- 4/5
- Estimated time
- 3-5 days
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 45/100