rust-lang / rust-lang/rust

function call inference incorrectly handles autoderef chains which encounter infer

Open
#146,437 1 comment 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

A-inference T-compiler T-types
Dominant language
Rust
Stars
119k
Forks
16.1k
PR merge metrics
PR metrics pending

Description

fn main() {
    let mut x: Option<Box<_>> = None;
    loop {
        if let Some(x) = x {
            x();
            break;
        } else {
            let str = String::new();
            x = Some(Box::new(move || drop(str)));
        }
    }
}

This results in

error[E0525]: expected a closure that implements the `Fn` trait, but this closure only implements `FnOnce`
 --> src/main.rs:9:31
  |
5 |             x();
  |             --- the requirement to implement `Fn` derives from here
...
9 |             x = Some(Box::new(move || drop(str)));
  |                               ^^^^^^^      --- closure is `FnOnce` because it moves the variable `str` out of its environment
  |                               |
  |                               this closure implements `FnOnce`, not `Fn`
  |
  = note: required for `Box<{closure@src/main.rs:9:31: 9:38}>` to implement `Fn()`

When typechecking the function call x() we only test whether Box<?infer>: Fn results in an error. It does not so that's what we select for the call.

This differs from the way method selection works where autoderef chains encountering inference variables result in ambiguity errors.

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start with the provided reproducer and the function-call type-checking path where Box<?infer>: Fn is tested. Compare that behavior with method selection when autoderef encounters inference variables. Done means the function call no longer selects an incorrect Fn requirement and the reproducer is covered by a regression test.

Written by the indexing model from the issue text.

Assessment

Tech stack
rust
Domain
compilers
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.