diff --git a/crates/ruff_linter/src/rules/mccabe/rules/function_is_too_complex.rs b/crates/ruff_linter/src/rules/mccabe/rules/function_is_too_complex.rs index 065ca04cf62c1..8c3124af30710 100644 --- a/crates/ruff_linter/src/rules/mccabe/rules/function_is_too_complex.rs +++ b/crates/ruff_linter/src/rules/mccabe/rules/function_is_too_complex.rs @@ -96,8 +96,8 @@ fn get_complexity_number(stmts: &[Stmt]) -> usize { complexity += get_complexity_number(orelse); } Stmt::Match(ast::StmtMatch { cases, .. }) => { - complexity += 1; for case in cases { + complexity += 1; complexity += get_complexity_number(&case.body); } } @@ -429,4 +429,19 @@ def with_lock(): assert_eq!(get_complexity_number(&stmts), 2); Ok(()) } + + #[test] + fn match_case() -> Result<()> { + let source = r" +def f(): + match a: + case 30: + print('foo') + case _: + print('bar') +"; + let stmts = parse_suite(source)?; + assert_eq!(get_complexity_number(&stmts), 3); + Ok(()) + } } diff --git a/crates/ruff_linter/src/rules/pylint/rules/too_many_branches.rs b/crates/ruff_linter/src/rules/pylint/rules/too_many_branches.rs index e252d1762d436..409c85f109b2c 100644 --- a/crates/ruff_linter/src/rules/pylint/rules/too_many_branches.rs +++ b/crates/ruff_linter/src/rules/pylint/rules/too_many_branches.rs @@ -176,10 +176,11 @@ fn num_branches(stmts: &[Stmt]) -> usize { .sum::() } Stmt::Match(ast::StmtMatch { cases, .. }) => { - 1 + cases - .iter() - .map(|case| num_branches(&case.body)) - .sum::() + cases.len() + + cases + .iter() + .map(|case| num_branches(&case.body)) + .sum::() } // The `with` statement is not considered a branch but the statements inside the `with` should be counted. Stmt::With(ast::StmtWith { body, .. }) => num_branches(body), @@ -278,6 +279,19 @@ else: Ok(()) } + #[test] + fn match_case() -> Result<()> { + let source: &str = r" +match x: # 2 + case 0: + pass + case 1: + pass +"; + test_helper(source, 2)?; + Ok(()) + } + #[test] fn for_else() -> Result<()> { let source: &str = r" diff --git a/crates/ruff_linter/src/rules/pylint/rules/too_many_statements.rs b/crates/ruff_linter/src/rules/pylint/rules/too_many_statements.rs index 51167264c13cd..d2dbf632ac67f 100644 --- a/crates/ruff_linter/src/rules/pylint/rules/too_many_statements.rs +++ b/crates/ruff_linter/src/rules/pylint/rules/too_many_statements.rs @@ -90,6 +90,7 @@ fn num_statements(stmts: &[Stmt]) -> usize { Stmt::Match(ast::StmtMatch { cases, .. }) => { count += 1; for case in cases { + count += 1; count += num_statements(&case.body); } } @@ -233,6 +234,21 @@ def f(): Ok(()) } + #[test] + fn match_case() -> Result<()> { + let source: &str = r" +def f(): + match x: + case 3: + pass + case _: + pass +"; + let stmts = parse_suite(source)?; + assert_eq!(num_statements(&stmts), 6); + Ok(()) + } + #[test] fn many_statements() -> Result<()> { let source: &str = r"