rust-lang / rust-lang/rust

Compiler can't unify arg-position `impl Trait` into an HRTB

Open
#119,045 3 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

A-higher-ranked A-lifetimes A-trait-system C-discussion T-types
Dominant language
Rust
Stars
119k
Forks
16.1k
PR merge metrics
PR metrics pending

Description

It looks like using arg: impl Trait makes the compiler unable to generalize the entire function-type into HRTB (?), that is:

fn foo(_: &str) {
    //
}

fn bar(_: impl AsRef<str>) {
    //
}

fn zar<T>(_: T) {
    //
}

fn check(_: impl Fn(&str)) {
    //
}

fn main() {
    check(foo); // ok
    check(bar); // err (implementation not general enough)
    check(zar::<&str>); // err (ditto)
}

Using a no-op closure helps:

fn main() {
    check(|x| bar(x));
}

... but is somewhat inconvenient (spotted in the wild at https://github.com/clap-rs/clap/issues/4939).

Note that I'm reporting this is a bug, but I'm not really sure on the category here - it just feels like this code should pass type-checking, but maybe there's some deeper reason why it can't.

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 minimal Rust reproducer in the issue and compare the behavior of foo, bar, zar::<&str>, and the closure workaround when passed to check. Trace the compiler's function-type generalization and HRTB handling, then verify that the direct bar and zar cases type-check without regressing the existing examples.

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
Clearly specified
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.