Skip to content

bool::then -> bool::then_some within unnecessary_lazy_eval can suggest fixes that can panic #9814

Closed
@alokedesai

Description

@alokedesai

Summary

The bool::then -> bool::then_some suggestions for unnecessary_lazy_eval can be problematic if the underlying body of the closure is not actually trivial. See repro below for a concrete example.

This is especially problematic because cargo clippy --fix will auto-fix this, which can inadvertently cause a new panic.

Lint Name

unnecessary_lazy_eval

Reproducer

I tried this code:

let foo : usize = 0;
let option = (foo > 0).then_some(|| foo - 1)

I saw this happen:

warning: unnecessary closure used with `bool::then`

This is incorrect, since bool:then will panic in a case where then_some would not have.

I expected to see this happen:
No clippy warning suggested.

Version

rustc 1.65.0 (897e37553 2022-11-02)
binary: rustc
commit-hash: 897e37553bba8b42751c67658967889d11ecd120
commit-date: 2022-11-02
host: aarch64-apple-darwin
release: 1.65.0
LLVM version: 15.0.0

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