Skip to content

region-outlives obligations lead to uninformative/undecipherable region inference failures #23581

@pnkfelix

Description

@pnkfelix

Consider this program:

use std::cell::Cell;
trait Foo { fn foo(&mut self); }
struct Pair<'a,'b> { x: &'a Cell<u8>, y: &'b Cell<u8> }

// This impl says it callers of `foo` on `Pair<'a,'b>` must ensure
// that 'b outlives 'a.
impl<'a, 'b:'a> Foo for Pair<'a, 'b> {
    fn foo(&mut self) {
        println!("pre  x: {} y: {}", self.x.get(), self.y.get());
        // 'b outlives 'a, so `&'b Cell<u8> <: &'a Cell<u8>`
        self.x = self.y;
        println!("post x: {} y: {}", self.x.get(), self.y.get());
    }
}

impl<'a,'b> Pair<'a,'b> {
    fn bar(&mut self) {
        self.foo();
    }
}

fn baz<'a,'b>(pa: &'a Cell<u8>, pb: &'b Cell<u8>) {
    let mut p = Pair { x: pa, y: pb };
    p.bar();
}

fn main() {
    let a = Cell::new(1);
    let b = Cell::new(2);
    let pa = &a;
    let pb = &b;
    baz(pa, pb);
}

This yields the following error (playpen):

<anon>:18:14: 18:19 error: cannot infer an appropriate lifetime for lifetime parameter `'b` due to conflicting requirements
<anon>:18         self.foo();
                       ^~~~~
<anon>:17:5: 19:6 help: consider using an explicit lifetime parameter as shown: fn bar(&mut self)
<anon>:17     fn bar(&mut self) {
<anon>:18         self.foo();
<anon>:19     }
error: aborting due to previous error
playpen: application terminated with error code 101

There is no mention of the region constraint on the impl providing foo that is causing calling foo from bar to fail.

cc @nikomatsakis

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-borrow-checkerArea: The borrow checkerA-diagnosticsArea: Messages for errors, warnings, and lintsC-enhancementCategory: An issue proposing an enhancement or a PR with one.D-confusingDiagnostics: Confusing error or lint that should be reworked.T-compilerRelevant to the compiler team, which will review and decide on the PR/issue.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions