Skip to content

manual_filter wrongly suggesting filter when match has side-effects #9766

Closed
@badboy

Description

@badboy

Summary

The manual_filter lint's (#9451) suggestion can cause side-effect code to be removed.
While the code can be rewritten to use filter correctly, the current suggestion will change the meaning of the code and is therefore wrong.

Lint Name

manual_filter

Reproducer

I tried this code:

pub fn test() {
    let reason = Some("reason");
    let allowed = vec![
        "reason", "other"
    ];

    let corrected_reason = match reason {
        Some(reason) => {
            if allowed.contains(&reason) {
                Some(reason)
            } else {
                println!("Invalid reason: {reason:?}");
                None
            }
        }
        None => None,
    };

    println!("{corrected_reason:?}")
}

I saw this happen:

❯ cargo +beta clippy
    Checking clippy-manual-filter v0.1.0 (/Users/jer/projects/rust/clippy-manual-filter)
warning: manual implementation of `Option::filter`
  --> src/lib.rs:7:28
   |
7  |       let corrected_reason = match reason {
   |  ____________________________^
8  | |         Some(reason) => {
9  | |             if allowed.contains(&reason) {
10 | |                 Some(reason)
...  |
16 | |         None => None,
17 | |     };
   | |_____^ help: try this: `reason.filter(|&reason| allowed.contains(&reason))`

I expected to see this happen:

Either not triggering that lint or if it triggers suggesting something that doesn't remove the side-effect line (println).

Version

rustc 1.66.0-beta.1 (e080cc5a6 2022-11-01)
binary: rustc
commit-hash: e080cc5a659fb760c0bc561b722a790dad35b5e1
commit-date: 2022-11-01
host: aarch64-apple-darwin
release: 1.66.0-beta.1
LLVM version: 15.0.2

Additional Labels

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    C-bugCategory: Clippy is not doing the correct thingI-false-positiveIssue: The lint was triggered on code it shouldn't have

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions