Skip to content

Rust can't infer appropriate generics for function when it should #89242

Closed
@TheRawMeatball

Description

@TheRawMeatball

I was working on some generic code when I hit this bug, so I made this MRE:

use std::borrow::Borrow;

trait TraitA<'a> {
    type Return;
    fn get(&'a self) -> Self::Return;
}
trait TraitB<T>
where
    for<'a> <Self::TrA as TraitA<'a>>::Return: Borrow<T>,
{
    type TrA: for<'a> TraitA<'a>;
}
fn takes_trait_b<T: TraitB<String>>(x: T)
where
    for<'a> <T::TrA as TraitA<'a>>::Return: Borrow<String>,
{
}

impl<T: 'static> TraitB<T> for T {
    type TrA = Returner<T>;
}

struct Returner<T>(T);
impl<'a, T: 'static> TraitA<'a> for Returner<T> {
    type Return = &'a T;

    fn get(&'a self) -> Self::Return {
        &self.0
    }
}

fn test() {
    takes_trait_b::<String>(String::new());
    takes_trait_b(String::new());
}

(playground link: https://play.rust-lang.org/?version=nightly&mode=debug&edition=2018&gist=ce2ea68678f61b329a6cec59310c1aea)

I'd expect both calls to takes_trait_b to succeed, but the second call doesn't as rust seemingly tries to uphold the where clause for any possible T

This has been observed on rustc 1.57.0-nightly (aa8f2d432 2021-09-18)

Adding two extra where clauses makes both calls compile on stable, but this example still fails on nightly: https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=aaa115e139635787f9b033a1418c7f06

Seems like a regression.

Metadata

Metadata

Assignees

No one assigned

    Labels

    C-bugCategory: This is a bug.S-has-mcveStatus: A Minimal Complete and Verifiable Example has been found for this issueT-compilerRelevant to the compiler team, which will review and decide on the PR/issue.regression-from-stable-to-stablePerformance or correctness regression from one stable version to another.

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions