Skip to content

False positive for question_mark lint with a pointer type #7910

Closed
@nicholasbishop

Description

@nicholasbishop

Lint name:
clippy::question_mark

I tried this code:

fn might_fail() -> Result<*mut u8, ()> {
    todo!();
}

pub fn ptr_stuff() -> *mut u8 {
    let ptr = if let Ok(ptr) = might_fail() {
        ptr
    } else {
        return core::ptr::null_mut();
    };
    unsafe { ptr.offset(1) }
}

I expected to see this happen: no warnings.

Instead, this happened:

warning: this if-let-else may be rewritten with the `?` operator
  --> src/lib.rs:6:15
   |
6  |       let ptr = if let Ok(ptr) = might_fail() {
   |  _______________^
7  | |         ptr
8  | |     } else {
9  | |         return core::ptr::null_mut();
10 | |     };
   | |_____^ help: replace it with: `might_fail()?`
   |

If you try to follow the suggestion that clippy makes, compilation fails:

error[E0277]: the `?` operator can only be used in a function that returns `Result` or `Option` (or another type that implements `std::ops::FromResidual`)
   --> src/lib.rs:6:27
    |
5   | / pub fn ptr_stuff() -> *mut u8 {
6   | |     let ptr = might_fail()?;
    | |                           ^ cannot use the `?` operator in a function that returns `*mut u8`
7   | |     unsafe { ptr.offset(1) }
8   | | }
    | |_- this function should return `Result` or `Option` to accept `?`
    |
    = help: the trait `std::ops::FromResidual<std::result::Result<std::convert::Infallible, ()>>` is not implemented for `*mut u8`
note: required by `std::ops::FromResidual::from_residual`
   --> /home/nicholasbishop/.rustup/toolchains/nightly-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/core/src/ops/try_trait.rs:339:5
    |
339 |     fn from_residual(residual: R) -> Self;
    |     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

Meta

Rust version (rustc -Vv):

rustc 1.58.0-nightly (ff0e14829 2021-10-31)
binary: rustc
commit-hash: ff0e14829e1806ca0d4226595f7fdf3e8658758f
commit-date: 2021-10-31
host: x86_64-unknown-linux-gnu
release: 1.58.0-nightly
LLVM version: 13.0.0

Metadata

Metadata

Assignees

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