rust-clippy icon indicating copy to clipboard operation
rust-clippy copied to clipboard

`collapsible_match` suggestion causes error

Open xtqqczze opened this issue 7 months ago • 7 comments

Summary

collapsible_match incorrectly transforms an if into a guard without updating the else arm. If the else arm is not a wildcard (e.g., None), the result becomes non-exhaustive since guarded arms don’t count toward exhaustiveness.

Context: https://github.com/rust-itertools/itertools/commit/b1f0ba11472bf4bee126b49363b11dc0d6c490c8 Reproducer: https://rust.godbolt.org/z/15c5fPPxj

Reproducer

Code:

fn issue16860() -> Option<i32> {
    let x: Option<i32> = Some(1);
    match x {
        None => {},
        Some(v) => {
            if v > 0 {
                return Some(v);
            }
        },
    }
    None
}

Current suggestion:

fn issue16860() -> Option<i32> {
    let x: Option<i32> = Some(1);
    match x {
        None => {},
        Some(v) if v > 0 => {
            return Some(v);
        },
    }
    None
}
error[E0004]: non-exhaustive patterns: `Some(_)` not covered
  --> <source>:16:11
   |
16 |     match x {
   |           ^ pattern `Some(_)` not covered
   |
note: `std::option::Option<i32>` defined here
  --> /rustc/f53b654a8882fd5fc036c4ca7a4ff41ce32497a6/library/core/src/option.rs:597:0
  ::: /rustc/f53b654a8882fd5fc036c4ca7a4ff41ce32497a6/library/core/src/option.rs:605:4
   |
   = note: not covered
   = note: the matched value is of type `std::option::Option<i32>`
   = note: match arms with guards don't count towards exhaustivity
help: ensure that all possible cases are being handled by adding a match arm with a wildcard pattern or an explicit pattern as shown
   |
20 ~         },
21 ~         Some(_) => todo!(),
   |

Correct suggestion:

fn issue16860() -> Option<i32> {
    let x: Option<i32> = Some(1);
    match x {
        Some(v) if v > 0 => {
            return Some(v);
        },
        None | Some(_) => {},
    }
    None
}

Version

clippy 0.1.97 (f53b654a88 2026-04-30)

xtqqczze avatar Apr 15 '26 23:04 xtqqczze

I took a look — the second code path in collapsible_match.rs (if-to-guard collapsing, lines 128-193) transforms the arm into a guarded pattern but never touches the else arm. When the else arm is None => {} instead of _ => {}, the result is non-exhaustive because guards don't count toward exhaustiveness.

The fix would be to also replace the else arm's pattern with _ when it's not already a wildcard. I can send a PR.

JasmineLCY avatar Apr 16 '26 10:04 JasmineLCY

@rustbot claim

JasmineLCY avatar Apr 22 '26 11:04 JasmineLCY

Hello! I'm experiencing this bug as well but I disagree with the fix. In my org we deliberately avoid wildcard matches so that if, say, an Enum is modified to add a new variant, all the match statements using that enum would cause compiler errors until they're modified. Clippy automatically adding a wildcard match arm would be an undesired behavior in this context.

abliskovsky-agilebits avatar May 01 '26 15:05 abliskovsky-agilebits

That’s a good point. In general, the suggestion should avoid introducing a wildcard arm, or alternatively the lint should treat non-exhaustive cases as a false positive.

xtqqczze avatar May 01 '26 16:05 xtqqczze

I would like to propose that this Clippy suggestion causes a meaningful difference in the meaning of a match statement, and perhaps it should not be a lint at all

abliskovsky-agilebits avatar May 01 '26 16:05 abliskovsky-agilebits

I've updated the issue description to account for this.

xtqqczze avatar May 01 '26 16:05 xtqqczze

FYI -- I also initially hit a similar error here when running clippy --fix on Ruff as part of https://github.com/astral-sh/ruff/pull/24677/. The command aborted due to introducing a compiler error:

Output showing clippy --fix aborting
 % cargo clippy -p ty_python_semantic --fix --allow-dirty
   Compiling serde_core v1.0.228
    Checking thin-vec v0.2.18
   Compiling serde v1.0.228
    Checking indexmap v2.14.0
    Checking compact_str v0.9.0
    Checking tracing v0.1.44
   Compiling ruff_text_size v0.0.0 (/Users/alexwaygood/code/oss/ruff/crates/ruff_text_size)
    Checking regex-automata v0.4.14
    Checking getrandom v0.4.2
   Compiling camino v1.2.2
    Checking zip v0.6.6
    Checking ruff_annotate_snippets v0.1.0 (/Users/alexwaygood/code/oss/ruff/crates/ruff_annotate_snippets)
   Compiling ty_vendored v0.0.0 (/Users/alexwaygood/code/oss/ruff/crates/ty_vendored)
    Checking ruff_python_stdlib v0.0.0 (/Users/alexwaygood/code/oss/ruff/crates/ruff_python_stdlib)
   Compiling ruff_source_file v0.0.0 (/Users/alexwaygood/code/oss/ruff/crates/ruff_source_file)
    Checking rand v0.10.1
    Checking ordermap v1.2.0
    Checking bstr v1.12.1
    Checking regex v1.12.3
   Compiling ruff_python_trivia v0.0.0 (/Users/alexwaygood/code/oss/ruff/crates/ruff_python_trivia)
    Checking uuid v1.23.1
    Checking get-size2 v0.9.0
    Checking salsa v0.26.2
    Checking serde_with v3.20.0
    Checking serde_json v1.0.149
    Checking ruff_memory_usage v0.0.0 (/Users/alexwaygood/code/oss/ruff/crates/ruff_memory_usage)
   Compiling ruff_macros v0.0.0 (/Users/alexwaygood/code/oss/ruff/crates/ruff_macros)
    Checking ruff_diagnostics v0.0.0 (/Users/alexwaygood/code/oss/ruff/crates/ruff_diagnostics)
    Checking ty_static v0.0.1 (/Users/alexwaygood/code/oss/ruff/crates/ty_static)
    Checking ruff_index v0.0.0 (/Users/alexwaygood/code/oss/ruff/crates/ruff_index)
    Checking ruff_notebook v0.0.0 (/Users/alexwaygood/code/oss/ruff/crates/ruff_notebook)
    Checking ruff_python_ast v0.0.0 (/Users/alexwaygood/code/oss/ruff/crates/ruff_python_ast)
    Checking ruff_python_parser v0.0.0 (/Users/alexwaygood/code/oss/ruff/crates/ruff_python_parser)
    Checking ruff_python_literal v0.0.0 (/Users/alexwaygood/code/oss/ruff/crates/ruff_python_literal)
    Checking ruff_db v0.0.0 (/Users/alexwaygood/code/oss/ruff/crates/ruff_db)
    Checking ty_combine v0.0.0 (/Users/alexwaygood/code/oss/ruff/crates/ty_combine)
    Checking ty_module_resolver v0.0.0 (/Users/alexwaygood/code/oss/ruff/crates/ty_module_resolver)
    Checking ty_site_packages v0.0.0 (/Users/alexwaygood/code/oss/ruff/crates/ty_site_packages)
    Checking ty_python_core v0.0.0 (/Users/alexwaygood/code/oss/ruff/crates/ty_python_core)
    Checking ty_python_semantic v0.0.0 (/Users/alexwaygood/code/oss/ruff/crates/ty_python_semantic)
error: errors present after applying fixes to crate `ty_python_semantic`
 --> crates/ty_python_semantic/src/types/infer/builder/subscript.rs
  = cause: error[E0004]: non-exhaustive patterns: `Some(types::typevar::TypeVarBoundOrConstraints::Constraints(_))` not covered
              --> crates/ty_python_semantic/src/types/infer/builder/subscript.rs:717:27
               |
           717 |                     match typevar.typevar(db).bound_or_constraints(db) {
               |                           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ pattern `Some(types::typevar::TypeVarBoundOrConstraints::Constraints(_))` not covered
               |
           note: `std::option::Option<types::typevar::TypeVarBoundOrConstraints<'_>>` defined here
              --> /Users/alexwaygood/.rustup/toolchains/1.96-aarch64-apple-darwin/lib/rustlib/src/rust/library/core/src/option.rs:600:1
               |
           600 | pub enum Option<T> {
               | ^^^^^^^^^^^^^^^^^^
           ...
           608 |     Some(#[stable(feature = "rust1", since = "1.0.0")] T),
               |     ---- not covered
               = note: the matched value is of type `std::option::Option<types::typevar::TypeVarBoundOrConstraints<'_>>`
               = note: match arms with guards don't count towards exhaustivity
           help: ensure that all possible cases are being handled by adding a match arm with a wildcard pattern or an explicit pattern as shown
               |
           783 ~                         },
           784 +                         Some(types::typevar::TypeVarBoundOrConstraints::Constraints(_)) => todo!()
               |


           error: aborting due to 1 previous error


           For more information about this error, try `rustc --explain E0004`.
help: to report this as a bug, open an issue at https://github.com/rust-lang/rust-clippy/issues, quoting the full output of this command
help: to possibly apply more fixes, pass in the `--broken-code` flag
note: original diagnostics will follow:
warning: this `if` can be collapsed into the outer `match`
   --> crates/ty_python_semantic/src/types/infer/builder/subscript.rs:752:29
    |
752 | / ...                   if provided_type
753 | | ...                       .when_assignable_to(
754 | | ...                           db,
755 | | ...                           typevar_constraints.as_type(db),
...   |
781 | | ...                       specialization_types.push(Some(provided_type));
782 | | ...                   }
    | |_______________________^
    |
    = help: for further information visit https://rust-lang.github.io/rust-clippy/rust-1.96.0/index.html#collapsible_match
    = note: `#[warn(clippy::collapsible_match)]` on by default
help: collapse nested if block
    |
747 ~                         Some(TypeVarBoundOrConstraints::Constraints(typevar_constraints))
748 |                             // TODO: this is wrong, the given specialization needs to be assignable
...
759 |                                 .is_never_satisfied(db)
760 ~                             => {
761 |                                 if let Some(builder) = self
...
779 |                                 specialization_types.push(Some(Type::unknown()));
780 ~                             }
    |

warning: `ty_python_semantic` (lib) generated 1 warning (run `cargo clippy --fix --lib -p ty_python_semantic -- --no-deps` to apply 1 suggestion)
    Finished `dev` profile [unoptimized + debuginfo] target(s) in 24.24s

We've since set collapsible_match = "allow" in our workspace Cargo.toml, as we found this lint a little too opinionated to always have on (though a lot of the suggestions it produced were good!).

AlexWaygood avatar Jun 01 '26 12:06 AlexWaygood