Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

clippy::manual_map gives incorrect advice when dyn coercion is involved #7402

Closed
mcy opened this issue Jun 25, 2021 · 2 comments
Closed

clippy::manual_map gives incorrect advice when dyn coercion is involved #7402

mcy opened this issue Jun 25, 2021 · 2 comments
Labels
C-bug Category: Clippy is not doing the correct thing

Comments

@mcy
Copy link

mcy commented Jun 25, 2021

I tried this code:

trait T {}
struct K(Option<Box<dyn T>>);

fn compiles(k: &mut K) -> Option<&mut dyn T> {
    match &mut k.0 {
        Some(x) => Some(&mut **x),
        None => None,
    }   
}

Clippy suggests rewriting this to

fn advice(k: &mut K) -> Option<&mut dyn T> {
    k.0.as_mut().map(|x| &mut **x)
}

which fails to compile with the classic lifetime inference error:

error[E0308]: mismatched types
  --> src/lib.rs:13:5
   |
13 |     k.0.as_mut().map(|x| &mut **x)
   |     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ lifetime mismatch
   |
   = note: expected enum `Option<&mut dyn T>`
              found enum `Option<&mut (dyn T + 'static)>`
note: the anonymous lifetime defined on the function body at 12:14...
  --> src/lib.rs:12:14
   |
12 | fn advice(k: &mut K) -> Option<&mut dyn T> {
   |              ^^^^^^
   = note: ...does not necessarily outlive the static lifetime

In the latter case, Rust's type inference does not correctly infer that a coersion from dyn T + 'static to dyn T + '_ needs to happen.

Clippy should instead suggest

fn correct(k: &mut K) -> Option<&mut dyn T> {
    k.0.as_mut().map(|x| &mut **x as &mut dyn T)
}

(TBH, this might just be a rustc inference bug?)

Meta

  • cargo clippy -V: clippy 0.1.52 (9bc8c42 2021-05-09)
  • rustc -Vv:
    rustc 1.52.1 (9bc8c42bb 2021-05-09)
    binary: rustc
    commit-hash: 9bc8c42bb2f19e745a63f3445f1ac248fb015e53
    commit-date: 2021-05-09
    host: x86_64-unknown-linux-gnu
    release: 1.52.1
    LLVM version: 12.0.0
    
@mcy mcy added the C-bug Category: Clippy is not doing the correct thing label Jun 25, 2021
@ghost
Copy link

ghost commented Jun 26, 2021

We've fixed similar bugs by making the suggestion include as _ when necessary. match_as_ref does it for example. See #4437.

@Jarcho
Copy link
Contributor

Jarcho commented Mar 16, 2022

This no longer occurs. Would have to run backwards through releases to find which version fixed it.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
C-bug Category: Clippy is not doing the correct thing
Projects
None yet
Development

No branches or pull requests

3 participants