1
Fork 0

Auto merge of #117967 - adetaylor:fix-lifetime-elision-bug, r=lcnr

Fix ambiguous cases of multiple & in elided self lifetimes

This change proposes simpler rules to identify the lifetime on `self` parameters which may be used to elide a return type lifetime.

## The old rules

(copied from [this comment](https://github.com/rust-lang/rust/pull/117967#discussion_r1420554242))

Most of the code can be found in [late.rs](https://doc.rust-lang.org/stable/nightly-rustc/src/rustc_resolve/late.rs.html) and acts on AST types. The function [resolve_fn_params](https://doc.rust-lang.org/stable/nightly-rustc/src/rustc_resolve/late.rs.html#2006), in the success case, returns a single lifetime which can be used to elide the lifetime of return types.

Here's how:
* If the first parameter is called self then we search that parameter using "`self` search rules", below
* If no unique applicable lifetime was found, search all other parameters using "regular parameter search rules", below

(In practice the code does extra work to assemble good diagnostic information, so it's not quite laid out like the above.)

### `self` search rules

This is primarily handled in [find_lifetime_for_self](https://doc.rust-lang.org/stable/nightly-rustc/src/rustc_resolve/late.rs.html#2118) , and is described slightly [here](https://github.com/rust-lang/rust/issues/117715#issuecomment-1813115477) already. The code:

1. Recursively walks the type of the `self` parameter (there's some complexity about resolving various special cases, but it's essentially just walking the type as far as I can see)
2. Each time we find a reference anywhere in the type, if the **direct** referent is `Self` (either spelled `Self` or by some alias resolution which I don't fully understand), then we'll add that to a set of candidate lifetimes
3. If there's exactly one such unique lifetime candidate found, we return this lifetime.

### Regular parameter search rules

1. Find all the lifetimes in each parameter, including implicit, explicit etc.
2. If there's exactly one parameter containing lifetimes, and if that parameter contains exactly one (unique) lifetime, *and if we didn't find a `self` lifetime parameter already*, we'll return this lifetime.

## The new rules

There are no changes to the "regular parameter search rules" or to the overall flow, only to the `self` search rules which are now:

1. Recursively walks the type of the `self` parameter, searching for lifetimes of reference types whose referent **contains** `Self`.[^1]
2. Keep a record of:
   * Whether 0, 1 or n unique lifetimes are found on references encountered during the walk
4. If no lifetime was found, we don't return a lifetime. (This means other parameters' lifetimes may be used for return type lifetime elision).
5. If there's one lifetime found, we return the lifetime.
6. If multiple lifetimes were found, we abort elision entirely (other parameters' lifetimes won't be used).

[^1]: this prevents us from considering lifetimes from inside of the self-type

## Examples that were accepted before and will now be rejected

```rust
fn a(self: &Box<&Self>) -> &u32
fn b(self: &Pin<&mut Self>) -> &String
fn c(self: &mut &Self) -> Option<&Self>
fn d(self: &mut &Box<Self>, arg: &usize) -> &usize // previously used the lt from arg
```

### Examples that change the elided lifetime

```rust
fn e(self: &mut Box<Self>, arg: &usize) -> &usize
//         ^ new                ^ previous
```

## Examples that were rejected before and will now be accepted

```rust
fn f(self: &Box<Self>) -> &u32
```

---

*edit: old PR description:*

```rust
  struct Concrete(u32);

  impl Concrete {
      fn m(self: &Box<Self>) -> &u32 {
          &self.0
      }
  }
```

resulted in a confusing error.

```rust
  impl Concrete {
      fn n(self: &Box<&Self>) -> &u32 {
          &self.0
      }
  }
```

resulted in no error or warning, despite apparent ambiguity over the elided lifetime.

Fixes https://github.com/rust-lang/rust/issues/117715
This commit is contained in:
bors 2024-07-18 13:33:38 +00:00
commit 5753b30676
19 changed files with 522 additions and 47 deletions

View file

@ -2175,13 +2175,17 @@ impl<'a: 'ast, 'b, 'ast, 'tcx> LateResolutionVisitor<'a, 'b, 'ast, 'tcx> {
// Handle `self` specially.
if index == 0 && has_self {
let self_lifetime = self.find_lifetime_for_self(ty);
if let Set1::One(lifetime) = self_lifetime {
elision_lifetime = match self_lifetime {
// We found `self` elision.
elision_lifetime = Elision::Self_(lifetime);
} else {
Set1::One(lifetime) => Elision::Self_(lifetime),
// `self` itself had ambiguous lifetimes, e.g.
// &Box<&Self>. In this case we won't consider
// taking an alternative parameter lifetime; just avoid elision
// entirely.
Set1::Many => Elision::Err,
// We do not have `self` elision: disregard the `Elision::Param` that we may
// have found.
elision_lifetime = Elision::None;
Set1::Empty => Elision::None,
}
}
debug!("(resolving function / closure) recorded parameter");
@ -2201,15 +2205,55 @@ impl<'a: 'ast, 'b, 'ast, 'tcx> LateResolutionVisitor<'a, 'b, 'ast, 'tcx> {
/// List all the lifetimes that appear in the provided type.
fn find_lifetime_for_self(&self, ty: &'ast Ty) -> Set1<LifetimeRes> {
struct SelfVisitor<'r, 'a, 'tcx> {
/// Visits a type to find all the &references, and determines the
/// set of lifetimes for all of those references where the referent
/// contains Self.
struct FindReferenceVisitor<'r, 'a, 'tcx> {
r: &'r Resolver<'a, 'tcx>,
impl_self: Option<Res>,
lifetime: Set1<LifetimeRes>,
}
impl<'a> Visitor<'a> for FindReferenceVisitor<'_, '_, '_> {
fn visit_ty(&mut self, ty: &'a Ty) {
trace!("FindReferenceVisitor considering ty={:?}", ty);
if let TyKind::Ref(lt, _) = ty.kind {
// See if anything inside the &thing contains Self
let mut visitor =
SelfVisitor { r: self.r, impl_self: self.impl_self, self_found: false };
visitor.visit_ty(ty);
trace!("FindReferenceVisitor: SelfVisitor self_found={:?}", visitor.self_found);
if visitor.self_found {
let lt_id = if let Some(lt) = lt {
lt.id
} else {
let res = self.r.lifetimes_res_map[&ty.id];
let LifetimeRes::ElidedAnchor { start, .. } = res else { bug!() };
start
};
let lt_res = self.r.lifetimes_res_map[&lt_id];
trace!("FindReferenceVisitor inserting res={:?}", lt_res);
self.lifetime.insert(lt_res);
}
}
visit::walk_ty(self, ty)
}
// A type may have an expression as a const generic argument.
// We do not want to recurse into those.
fn visit_expr(&mut self, _: &'a Expr) {}
}
/// Visitor which checks the referent of a &Thing to see if the
/// Thing contains Self
struct SelfVisitor<'r, 'a, 'tcx> {
r: &'r Resolver<'a, 'tcx>,
impl_self: Option<Res>,
self_found: bool,
}
impl SelfVisitor<'_, '_, '_> {
// Look for `self: &'a Self` - also desugared from `&'a self`,
// and if that matches, use it for elision and return early.
// Look for `self: &'a Self` - also desugared from `&'a self`
fn is_self_ty(&self, ty: &Ty) -> bool {
match ty.kind {
TyKind::ImplicitSelf => true,
@ -2228,19 +2272,9 @@ impl<'a: 'ast, 'b, 'ast, 'tcx> LateResolutionVisitor<'a, 'b, 'ast, 'tcx> {
impl<'a> Visitor<'a> for SelfVisitor<'_, '_, '_> {
fn visit_ty(&mut self, ty: &'a Ty) {
trace!("SelfVisitor considering ty={:?}", ty);
if let TyKind::Ref(lt, ref mt) = ty.kind
&& self.is_self_ty(&mt.ty)
{
let lt_id = if let Some(lt) = lt {
lt.id
} else {
let res = self.r.lifetimes_res_map[&ty.id];
let LifetimeRes::ElidedAnchor { start, .. } = res else { bug!() };
start
};
let lt_res = self.r.lifetimes_res_map[&lt_id];
trace!("SelfVisitor inserting res={:?}", lt_res);
self.lifetime.insert(lt_res);
if self.is_self_ty(ty) {
trace!("SelfVisitor found Self");
self.self_found = true;
}
visit::walk_ty(self, ty)
}
@ -2271,9 +2305,9 @@ impl<'a: 'ast, 'b, 'ast, 'tcx> LateResolutionVisitor<'a, 'b, 'ast, 'tcx> {
Res::Def(DefKind::Struct | DefKind::Union | DefKind::Enum, _,) | Res::PrimTy(_)
)
});
let mut visitor = SelfVisitor { r: self.r, impl_self, lifetime: Set1::Empty };
let mut visitor = FindReferenceVisitor { r: self.r, impl_self, lifetime: Set1::Empty };
visitor.visit_ty(ty);
trace!("SelfVisitor found={:?}", visitor.lifetime);
trace!("FindReferenceVisitor found={:?}", visitor.lifetime);
visitor.lifetime
}