Skip to content

Inside try blocks, if_then_some_else_none triggers even if the Some branch contains ? #17596

Description

@ronnodas

Summary

Usually if_then_some_else_none does not trigger if the "then" branch producing a Some has control flow, but this seems to not work as expected with ? inside try blocks. I have not tried other control-flow operations like continue or break.

Lint Name

if_then_some_else_none

Reproducer

I tried this code (playground):

#![feature(try_blocks)]
#![deny(clippy::if_then_some_else_none)]

fn foo(x: u32) -> Option<Option<u32>> {
    try {
        if x > 0 {
            Some(x.checked_sub(2)?)
        } else {
            None
        }
    }
}

I saw this happen:

error: this could be simplified with `bool::then`
  --> src/main.rs:6:9
   |
 6 | /         if x > 0 {
 7 | |             Some(x.checked_sub(2)?)
 8 | |         } else {
 9 | |             None
10 | |         }
   | |_________^ help: try: `(x > 0).then(|| x.checked_sub(2)?)`
   |
   = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#if_then_some_else_none
note: the lint level is defined here
  --> src/main.rs:2:9

If the suggested replacement is made then there is a compiler error about the closure not returning a Try type.

I expected to see this happen:
The lint should not trigger.

Version


Additional Labels

@rustbot label +I-suggestion-causes-error

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 haveI-suggestion-causes-errorIssue: The suggestions provided by this Lint cause an ICE/error when applied

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions