resolve_lifetime: rustfmt

This commit is contained in:
Niko Matsakis
2017-12-11 09:00:05 -05:00
parent 33245fe682
commit d737ea7902
+725 -480
View File
@@ -30,11 +30,11 @@
use syntax_pos::Span;
use errors::DiagnosticBuilder;
use util::common::ErrorReported;
use util::nodemap::{NodeMap, NodeSet, FxHashSet, FxHashMap, DefIdMap};
use util::nodemap::{DefIdMap, FxHashMap, FxHashSet, NodeMap, NodeSet};
use std::slice;
use hir;
use hir::intravisit::{self, Visitor, NestedVisitorMap};
use hir::intravisit::{self, NestedVisitorMap, Visitor};
/// The origin of a named lifetime definition.
///
@@ -60,16 +60,26 @@ fn from_is_in_band(is_in_band: bool) -> Self {
#[derive(Clone, Copy, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable, Debug)]
pub enum Region {
Static,
EarlyBound(/* index */ u32, /* lifetime decl */ DefId, LifetimeDefOrigin),
LateBound(ty::DebruijnIndex, /* lifetime decl */ DefId, LifetimeDefOrigin),
EarlyBound(
/* index */ u32,
/* lifetime decl */ DefId,
LifetimeDefOrigin,
),
LateBound(
ty::DebruijnIndex,
/* lifetime decl */ DefId,
LifetimeDefOrigin,
),
LateBoundAnon(ty::DebruijnIndex, /* anon index */ u32),
Free(DefId, /* lifetime decl */ DefId),
}
impl Region {
fn early(hir_map: &Map, index: &mut u32, def: &hir::LifetimeDef)
-> (hir::LifetimeName, Region)
{
fn early(
hir_map: &Map,
index: &mut u32,
def: &hir::LifetimeDef,
) -> (hir::LifetimeName, Region) {
let i = *index;
*index += 1;
let def_id = hir_map.local_def_id(def.lifetime.id);
@@ -94,12 +104,11 @@ fn late_anon(index: &Cell<u32>) -> Region {
fn id(&self) -> Option<DefId> {
match *self {
Region::Static |
Region::LateBoundAnon(..) => None,
Region::Static | Region::LateBoundAnon(..) => None,
Region::EarlyBound(_, id, _) |
Region::LateBound(_, id, _) |
Region::Free(_, id) => Some(id)
Region::EarlyBound(_, id, _) | Region::LateBound(_, id, _) | Region::Free(_, id) => {
Some(id)
}
}
}
@@ -111,32 +120,34 @@ fn shifted(self, amount: u32) -> Region {
Region::LateBoundAnon(depth, index) => {
Region::LateBoundAnon(depth.shifted(amount), index)
}
_ => self
_ => self,
}
}
fn from_depth(self, depth: u32) -> Region {
match self {
Region::LateBound(debruijn, id, origin) => {
Region::LateBound(ty::DebruijnIndex {
depth: debruijn.depth - (depth - 1)
}, id, origin)
}
Region::LateBoundAnon(debruijn, index) => {
Region::LateBoundAnon(ty::DebruijnIndex {
depth: debruijn.depth - (depth - 1)
}, index)
}
_ => self
Region::LateBound(debruijn, id, origin) => Region::LateBound(
ty::DebruijnIndex {
depth: debruijn.depth - (depth - 1),
},
id,
origin,
),
Region::LateBoundAnon(debruijn, index) => Region::LateBoundAnon(
ty::DebruijnIndex {
depth: debruijn.depth - (depth - 1),
},
index,
),
_ => self,
}
}
fn subst(self, params: &[hir::Lifetime], map: &NamedRegionMap)
-> Option<Region> {
fn subst(self, params: &[hir::Lifetime], map: &NamedRegionMap) -> Option<Region> {
if let Region::EarlyBound(index, _, _) = self {
params.get(index as usize).and_then(|lifetime| {
map.defs.get(&lifetime.id).cloned()
})
params
.get(index as usize)
.and_then(|lifetime| map.defs.get(&lifetime.id).cloned())
} else {
Some(self)
}
@@ -150,7 +161,7 @@ fn subst(self, params: &[hir::Lifetime], map: &NamedRegionMap)
pub enum Set1<T> {
Empty,
One(T),
Many
Many,
}
impl<T: PartialEq> Set1<T> {
@@ -233,7 +244,7 @@ enum Scope<'a> {
/// we should use for an early-bound region?
next_early_index: u32,
s: ScopeRef<'a>
s: ScopeRef<'a>,
},
/// Lifetimes introduced by a fn are scoped to the call-site for that fn,
@@ -242,14 +253,14 @@ enum Scope<'a> {
/// e.g. `(&T, fn(&T) -> &T);` becomes `(&'_ T, for<'a> fn(&'a T) -> &'a T)`.
Body {
id: hir::BodyId,
s: ScopeRef<'a>
s: ScopeRef<'a>,
},
/// A scope which either determines unspecified lifetimes or errors
/// on them (e.g. due to ambiguity). For more details, see `Elide`.
Elision {
elide: Elide,
s: ScopeRef<'a>
s: ScopeRef<'a>,
},
/// Use a specific lifetime (if `Some`) or leave it unset (to be
@@ -257,10 +268,10 @@ enum Scope<'a> {
/// for the default choice of lifetime in a trait object type.
ObjectLifetimeDefault {
lifetime: Option<Region>,
s: ScopeRef<'a>
s: ScopeRef<'a>,
},
Root
Root,
}
#[derive(Clone, Debug)]
@@ -271,7 +282,7 @@ enum Elide {
/// Always use this one lifetime.
Exact(Region),
/// Less or more than one lifetime were found, error on unspecified.
Error(Vec<ElisionFailureInfo>)
Error(Vec<ElisionFailureInfo>),
}
#[derive(Clone, Debug)]
@@ -281,17 +292,18 @@ struct ElisionFailureInfo {
/// The index of the argument in the original definition.
index: usize,
lifetime_count: usize,
have_bound_regions: bool
have_bound_regions: bool,
}
type ScopeRef<'a> = &'a Scope<'a>;
const ROOT_SCOPE: ScopeRef<'static> = &Scope::Root;
pub fn krate(sess: &Session,
cstore: &CrateStore,
hir_map: &Map)
-> Result<NamedRegionMap, ErrorReported> {
pub fn krate(
sess: &Session,
cstore: &CrateStore,
hir_map: &Map,
) -> Result<NamedRegionMap, ErrorReported> {
let krate = hir_map.krate();
let mut map = NamedRegionMap {
defs: NodeMap(),
@@ -330,9 +342,15 @@ fn visit_nested_body(&mut self, body: hir::BodyId) {
let saved = replace(&mut self.labels_in_fn, vec![]);
let body = self.hir_map.body(body);
extract_labels(self, body);
self.with(Scope::Body { id: body.id(), s: self.scope }, |_, this| {
this.visit_body(body);
});
self.with(
Scope::Body {
id: body.id(),
s: self.scope,
},
|_, this| {
this.visit_body(body);
},
);
replace(&mut self.labels_in_fn, saved);
}
@@ -343,44 +361,45 @@ fn visit_item(&mut self, item: &'tcx hir::Item) {
intravisit::walk_item(this, item);
});
}
hir::ItemExternCrate(_) |
hir::ItemUse(..) |
hir::ItemMod(..) |
hir::ItemAutoImpl(..) |
hir::ItemForeignMod(..) |
hir::ItemGlobalAsm(..) => {
hir::ItemExternCrate(_)
| hir::ItemUse(..)
| hir::ItemMod(..)
| hir::ItemAutoImpl(..)
| hir::ItemForeignMod(..)
| hir::ItemGlobalAsm(..) => {
// These sorts of items have no lifetime parameters at all.
intravisit::walk_item(self, item);
}
hir::ItemStatic(..) |
hir::ItemConst(..) => {
hir::ItemStatic(..) | hir::ItemConst(..) => {
// No lifetime parameters, but implied 'static.
let scope = Scope::Elision {
elide: Elide::Exact(Region::Static),
s: ROOT_SCOPE
s: ROOT_SCOPE,
};
self.with(scope, |_, this| intravisit::walk_item(this, item));
}
hir::ItemTy(_, ref generics) |
hir::ItemEnum(_, ref generics) |
hir::ItemStruct(_, ref generics) |
hir::ItemUnion(_, ref generics) |
hir::ItemTrait(_, _, ref generics, ..) |
hir::ItemImpl(_, _, _, ref generics, ..) => {
hir::ItemTy(_, ref generics)
| hir::ItemEnum(_, ref generics)
| hir::ItemStruct(_, ref generics)
| hir::ItemUnion(_, ref generics)
| hir::ItemTrait(_, _, ref generics, ..)
| hir::ItemImpl(_, _, _, ref generics, ..) => {
// These kinds of items have only early bound lifetime parameters.
let mut index = if let hir::ItemTrait(..) = item.node {
1 // Self comes before lifetimes
} else {
0
};
let lifetimes = generics.lifetimes.iter().map(|def| {
Region::early(self.hir_map, &mut index, def)
}).collect();
let lifetimes = generics
.lifetimes
.iter()
.map(|def| Region::early(self.hir_map, &mut index, def))
.collect();
let next_early_index = index + generics.ty_params.len() as u32;
let scope = Scope::Binder {
lifetimes,
next_early_index,
s: ROOT_SCOPE
s: ROOT_SCOPE,
};
self.with(scope, |old_scope, this| {
this.check_lifetime_defs(old_scope, &generics.lifetimes);
@@ -414,11 +433,12 @@ fn visit_ty(&mut self, ty: &'tcx hir::Ty) {
let was_in_fn_syntax = self.is_in_fn_syntax;
self.is_in_fn_syntax = true;
let scope = Scope::Binder {
lifetimes: c.lifetimes.iter().map(|def| {
Region::late(self.hir_map, def)
}).collect(),
lifetimes: c.lifetimes
.iter()
.map(|def| Region::late(self.hir_map, def))
.collect(),
next_early_index,
s: self.scope
s: self.scope,
};
self.with(scope, |old_scope, this| {
// a bare fn has no bounds, so everything
@@ -442,7 +462,7 @@ fn visit_ty(&mut self, ty: &'tcx hir::Ty) {
self.visit_lifetime(lifetime_ref);
let scope = Scope::ObjectLifetimeDefault {
lifetime: self.map.defs.get(&lifetime_ref.id).cloned(),
s: self.scope
s: self.scope,
};
self.with(scope, |_, this| this.visit_ty(&mt.ty));
}
@@ -467,13 +487,17 @@ fn visit_ty(&mut self, ty: &'tcx hir::Ty) {
let parent_impl_id = hir::ImplItemId { node_id: parent_id };
let parent_trait_id = hir::TraitItemId { node_id: parent_id };
let krate = self.hir_map.forest.krate();
if !(krate.items.contains_key(&parent_id) ||
krate.impl_items.contains_key(&parent_impl_id) ||
krate.trait_items.contains_key(&parent_trait_id))
if !(krate.items.contains_key(&parent_id)
|| krate.impl_items.contains_key(&parent_impl_id)
|| krate.trait_items.contains_key(&parent_trait_id))
{
span_err!(self.sess, lifetime.span, E0657,
"`impl Trait` can only capture lifetimes \
bound at the fn or impl level");
span_err!(
self.sess,
lifetime.span,
E0657,
"`impl Trait` can only capture lifetimes \
bound at the fn or impl level"
);
}
}
}
@@ -484,15 +508,24 @@ fn visit_ty(&mut self, ty: &'tcx hir::Ty) {
// `abstract type MyAnonTy<'b>: MyTrait<'b>;`
// ^ ^ this gets resolved in the scope of
// the exist_ty generics
let hir::ExistTy { ref generics, ref bounds } = *exist_ty;
let hir::ExistTy {
ref generics,
ref bounds,
} = *exist_ty;
let mut index = self.next_early_index();
debug!("visit_ty: index = {}", index);
let lifetimes = generics.lifetimes.iter()
let lifetimes = generics
.lifetimes
.iter()
.map(|lt_def| Region::early(self.hir_map, &mut index, lt_def))
.collect();
let next_early_index = index + generics.ty_params.len() as u32;
let scope = Scope::Binder { lifetimes, next_early_index, s: self.scope };
let scope = Scope::Binder {
lifetimes,
next_early_index,
s: self.scope,
};
self.with(scope, |_old_scope, this| {
this.visit_generics(generics);
for bound in bounds {
@@ -500,9 +533,7 @@ fn visit_ty(&mut self, ty: &'tcx hir::Ty) {
}
});
}
_ => {
intravisit::walk_ty(self, ty)
}
_ => intravisit::walk_ty(self, ty),
}
}
@@ -510,8 +541,10 @@ fn visit_trait_item(&mut self, trait_item: &'tcx hir::TraitItem) {
if let hir::TraitItemKind::Method(ref sig, _) = trait_item.node {
self.visit_early_late(
Some(self.hir_map.get_parent(trait_item.id)),
&sig.decl, &trait_item.generics,
|this| intravisit::walk_trait_item(this, trait_item))
&sig.decl,
&trait_item.generics,
|this| intravisit::walk_trait_item(this, trait_item),
)
} else {
intravisit::walk_trait_item(self, trait_item);
}
@@ -521,8 +554,10 @@ fn visit_impl_item(&mut self, impl_item: &'tcx hir::ImplItem) {
if let hir::ImplItemKind::Method(ref sig, _) = impl_item.node {
self.visit_early_late(
Some(self.hir_map.get_parent(impl_item.id)),
&sig.decl, &impl_item.generics,
|this| intravisit::walk_impl_item(this, impl_item))
&sig.decl,
&impl_item.generics,
|this| intravisit::walk_impl_item(this, impl_item),
)
} else {
intravisit::walk_impl_item(self, impl_item);
}
@@ -552,7 +587,7 @@ fn visit_path(&mut self, path: &'tcx hir::Path, _: ast::NodeId) {
fn visit_fn_decl(&mut self, fd: &'tcx hir::FnDecl) {
let output = match fd.output {
hir::DefaultReturn(_) => None,
hir::Return(ref ty) => Some(ty)
hir::Return(ref ty) => Some(ty),
};
self.visit_fn_like_elision(&fd.inputs, output);
}
@@ -567,19 +602,22 @@ fn visit_generics(&mut self, generics: &'tcx hir::Generics) {
}
for predicate in &generics.where_clause.predicates {
match predicate {
&hir::WherePredicate::BoundPredicate(hir::WhereBoundPredicate{ ref bounded_ty,
ref bounds,
ref bound_lifetimes,
.. }) => {
&hir::WherePredicate::BoundPredicate(hir::WhereBoundPredicate {
ref bounded_ty,
ref bounds,
ref bound_lifetimes,
..
}) => {
if !bound_lifetimes.is_empty() {
self.trait_ref_hack = true;
let next_early_index = self.next_early_index();
let scope = Scope::Binder {
lifetimes: bound_lifetimes.iter().map(|def| {
Region::late(self.hir_map, def)
}).collect(),
lifetimes: bound_lifetimes
.iter()
.map(|def| Region::late(self.hir_map, def))
.collect(),
next_early_index,
s: self.scope
s: self.scope,
};
let result = self.with(scope, |old_scope, this| {
this.check_lifetime_defs(old_scope, bound_lifetimes);
@@ -593,18 +631,21 @@ fn visit_generics(&mut self, generics: &'tcx hir::Generics) {
walk_list!(self, visit_ty_param_bound, bounds);
}
}
&hir::WherePredicate::RegionPredicate(hir::WhereRegionPredicate{ref lifetime,
ref bounds,
.. }) => {
&hir::WherePredicate::RegionPredicate(hir::WhereRegionPredicate {
ref lifetime,
ref bounds,
..
}) => {
self.visit_lifetime(lifetime);
for bound in bounds {
self.visit_lifetime(bound);
}
}
&hir::WherePredicate::EqPredicate(hir::WhereEqPredicate{ref lhs_ty,
ref rhs_ty,
.. }) => {
&hir::WherePredicate::EqPredicate(hir::WhereEqPredicate {
ref lhs_ty,
ref rhs_ty,
..
}) => {
self.visit_ty(lhs_ty);
self.visit_ty(rhs_ty);
}
@@ -612,23 +653,31 @@ fn visit_generics(&mut self, generics: &'tcx hir::Generics) {
}
}
fn visit_poly_trait_ref(&mut self,
trait_ref: &'tcx hir::PolyTraitRef,
_modifier: hir::TraitBoundModifier) {
fn visit_poly_trait_ref(
&mut self,
trait_ref: &'tcx hir::PolyTraitRef,
_modifier: hir::TraitBoundModifier,
) {
debug!("visit_poly_trait_ref trait_ref={:?}", trait_ref);
if !self.trait_ref_hack || !trait_ref.bound_lifetimes.is_empty() {
if self.trait_ref_hack {
span_err!(self.sess, trait_ref.span, E0316,
"nested quantification of lifetimes");
span_err!(
self.sess,
trait_ref.span,
E0316,
"nested quantification of lifetimes"
);
}
let next_early_index = self.next_early_index();
let scope = Scope::Binder {
lifetimes: trait_ref.bound_lifetimes.iter().map(|def| {
Region::late(self.hir_map, def)
}).collect(),
lifetimes: trait_ref
.bound_lifetimes
.iter()
.map(|def| Region::late(self.hir_map, def))
.collect(),
next_early_index,
s: self.scope
s: self.scope,
};
self.with(scope, |old_scope, this| {
this.check_lifetime_defs(old_scope, &trait_ref.bound_lifetimes);
@@ -644,21 +693,42 @@ fn visit_poly_trait_ref(&mut self,
}
#[derive(Copy, Clone, PartialEq)]
enum ShadowKind { Label, Lifetime }
struct Original { kind: ShadowKind, span: Span }
struct Shadower { kind: ShadowKind, span: Span }
enum ShadowKind {
Label,
Lifetime,
}
struct Original {
kind: ShadowKind,
span: Span,
}
struct Shadower {
kind: ShadowKind,
span: Span,
}
fn original_label(span: Span) -> Original {
Original { kind: ShadowKind::Label, span: span }
Original {
kind: ShadowKind::Label,
span: span,
}
}
fn shadower_label(span: Span) -> Shadower {
Shadower { kind: ShadowKind::Label, span: span }
Shadower {
kind: ShadowKind::Label,
span: span,
}
}
fn original_lifetime(span: Span) -> Original {
Original { kind: ShadowKind::Lifetime, span: span }
Original {
kind: ShadowKind::Lifetime,
span: span,
}
}
fn shadower_lifetime(l: &hir::Lifetime) -> Shadower {
Shadower { kind: ShadowKind::Lifetime, span: l.span }
Shadower {
kind: ShadowKind::Lifetime,
span: l.span,
}
}
impl ShadowKind {
@@ -670,17 +740,20 @@ fn desc(&self) -> &'static str {
}
}
fn check_mixed_explicit_and_in_band_defs(
sess: &Session,
lifetime_defs: &[hir::LifetimeDef],
) {
fn check_mixed_explicit_and_in_band_defs(sess: &Session, lifetime_defs: &[hir::LifetimeDef]) {
let oob_def = lifetime_defs.iter().find(|lt| !lt.in_band);
let in_band_def = lifetime_defs.iter().find(|lt| lt.in_band);
if let (Some(oob_def), Some(in_band_def)) = (oob_def, in_band_def) {
struct_span_err!(sess, in_band_def.lifetime.span, E0688,
"cannot mix in-band and explicit lifetime definitions")
.span_label(in_band_def.lifetime.span, "in-band lifetime definition here")
struct_span_err!(
sess,
in_band_def.lifetime.span,
E0688,
"cannot mix in-band and explicit lifetime definitions"
).span_label(
in_band_def.lifetime.span,
"in-band lifetime definition here",
)
.span_label(oob_def.lifetime.span, "explicit lifetime definition here")
.emit();
}
@@ -689,21 +762,32 @@ fn check_mixed_explicit_and_in_band_defs(
fn signal_shadowing_problem(sess: &Session, name: ast::Name, orig: Original, shadower: Shadower) {
let mut err = if let (ShadowKind::Lifetime, ShadowKind::Lifetime) = (orig.kind, shadower.kind) {
// lifetime/lifetime shadowing is an error
struct_span_err!(sess, shadower.span, E0496,
"{} name `{}` shadows a \
{} name that is already in scope",
shadower.kind.desc(), name, orig.kind.desc())
struct_span_err!(
sess,
shadower.span,
E0496,
"{} name `{}` shadows a \
{} name that is already in scope",
shadower.kind.desc(),
name,
orig.kind.desc()
)
} else {
// shadowing involving a label is only a warning, due to issues with
// labels and lifetimes not being macro-hygienic.
sess.struct_span_warn(shadower.span,
&format!("{} name `{}` shadows a \
{} name that is already in scope",
shadower.kind.desc(), name, orig.kind.desc()))
sess.struct_span_warn(
shadower.span,
&format!(
"{} name `{}` shadows a \
{} name that is already in scope",
shadower.kind.desc(),
name,
orig.kind.desc()
),
)
};
err.span_label(orig.span, "first declared here");
err.span_label(shadower.span,
format!("lifetime {} already in scope", name));
err.span_label(shadower.span, format!("lifetime {} already in scope", name));
err.emit();
}
@@ -735,18 +819,22 @@ fn visit_expr(&mut self, ex: &hir::Expr) {
for &(prior, prior_span) in &self.labels_in_fn[..] {
// FIXME (#24278): non-hygienic comparison
if label == prior {
signal_shadowing_problem(self.sess,
label,
original_label(prior_span),
shadower_label(label_span));
signal_shadowing_problem(
self.sess,
label,
original_label(prior_span),
shadower_label(label_span),
);
}
}
check_if_label_shadows_lifetime(self.sess,
self.hir_map,
self.scope,
label,
label_span);
check_if_label_shadows_lifetime(
self.sess,
self.hir_map,
self.scope,
label,
label_span,
);
self.labels_in_fn.push((label, label_span));
}
@@ -756,36 +844,47 @@ fn visit_expr(&mut self, ex: &hir::Expr) {
fn expression_label(ex: &hir::Expr) -> Option<(ast::Name, Span)> {
match ex.node {
hir::ExprWhile(.., Some(label)) |
hir::ExprLoop(_, Some(label), _) => Some((label.node, label.span)),
hir::ExprWhile(.., Some(label)) | hir::ExprLoop(_, Some(label), _) => {
Some((label.node, label.span))
}
_ => None,
}
}
fn check_if_label_shadows_lifetime<'a>(sess: &'a Session,
hir_map: &Map,
mut scope: ScopeRef<'a>,
label: ast::Name,
label_span: Span) {
fn check_if_label_shadows_lifetime<'a>(
sess: &'a Session,
hir_map: &Map,
mut scope: ScopeRef<'a>,
label: ast::Name,
label_span: Span,
) {
loop {
match *scope {
Scope::Body { s, .. } |
Scope::Elision { s, .. } |
Scope::ObjectLifetimeDefault { s, .. } => { scope = s; }
Scope::Body { s, .. }
| Scope::Elision { s, .. }
| Scope::ObjectLifetimeDefault { s, .. } => {
scope = s;
}
Scope::Root => { return; }
Scope::Root => {
return;
}
Scope::Binder { ref lifetimes, s, next_early_index: _ } => {
Scope::Binder {
ref lifetimes,
s,
next_early_index: _,
} => {
// FIXME (#24278): non-hygienic comparison
if let Some(def) = lifetimes.get(&hir::LifetimeName::Name(label)) {
let node_id = hir_map.as_local_node_id(def.id().unwrap())
.unwrap();
let node_id = hir_map.as_local_node_id(def.id().unwrap()).unwrap();
signal_shadowing_problem(
sess,
label,
original_lifetime(hir_map.span(node_id)),
shadower_label(label_span));
shadower_label(label_span),
);
return;
}
scope = s;
@@ -795,32 +894,38 @@ fn check_if_label_shadows_lifetime<'a>(sess: &'a Session,
}
}
fn compute_object_lifetime_defaults(sess: &Session, hir_map: &Map)
-> NodeMap<Vec<ObjectLifetimeDefault>> {
fn compute_object_lifetime_defaults(
sess: &Session,
hir_map: &Map,
) -> NodeMap<Vec<ObjectLifetimeDefault>> {
let mut map = NodeMap();
for item in hir_map.krate().items.values() {
match item.node {
hir::ItemStruct(_, ref generics) |
hir::ItemUnion(_, ref generics) |
hir::ItemEnum(_, ref generics) |
hir::ItemTy(_, ref generics) |
hir::ItemTrait(_, _, ref generics, ..) => {
hir::ItemStruct(_, ref generics)
| hir::ItemUnion(_, ref generics)
| hir::ItemEnum(_, ref generics)
| hir::ItemTy(_, ref generics)
| hir::ItemTrait(_, _, ref generics, ..) => {
let result = object_lifetime_defaults_for_item(hir_map, generics);
// Debugging aid.
if attr::contains_name(&item.attrs, "rustc_object_lifetime_default") {
let object_lifetime_default_reprs: String =
result.iter().map(|set| {
match *set {
Set1::Empty => "BaseDefault".to_string(),
Set1::One(Region::Static) => "'static".to_string(),
Set1::One(Region::EarlyBound(i, _, _)) => {
generics.lifetimes[i as usize].lifetime.name.name().to_string()
}
Set1::One(_) => bug!(),
Set1::Many => "Ambiguous".to_string(),
}
}).collect::<Vec<String>>().join(",");
let object_lifetime_default_reprs: String = result
.iter()
.map(|set| match *set {
Set1::Empty => "BaseDefault".to_string(),
Set1::One(Region::Static) => "'static".to_string(),
Set1::One(Region::EarlyBound(i, _, _)) => generics.lifetimes
[i as usize]
.lifetime
.name
.name()
.to_string(),
Set1::One(_) => bug!(),
Set1::Many => "Ambiguous".to_string(),
})
.collect::<Vec<String>>()
.join(",");
sess.span_err(item.span, &object_lifetime_default_reprs);
}
@@ -835,8 +940,10 @@ fn compute_object_lifetime_defaults(sess: &Session, hir_map: &Map)
/// Scan the bounds and where-clauses on parameters to extract bounds
/// of the form `T:'a` so as to determine the `ObjectLifetimeDefault`
/// for each type parameter.
fn object_lifetime_defaults_for_item(hir_map: &Map, generics: &hir::Generics)
-> Vec<ObjectLifetimeDefault> {
fn object_lifetime_defaults_for_item(
hir_map: &Map,
generics: &hir::Generics,
) -> Vec<ObjectLifetimeDefault> {
fn add_bounds(set: &mut Set1<hir::LifetimeName>, bounds: &[hir::TyParamBound]) {
for bound in bounds {
if let hir::RegionTyParamBound(ref lifetime) = *bound {
@@ -845,67 +952,82 @@ fn add_bounds(set: &mut Set1<hir::LifetimeName>, bounds: &[hir::TyParamBound]) {
}
}
generics.ty_params.iter().map(|param| {
let mut set = Set1::Empty;
generics
.ty_params
.iter()
.map(|param| {
let mut set = Set1::Empty;
add_bounds(&mut set, &param.bounds);
add_bounds(&mut set, &param.bounds);
let param_def_id = hir_map.local_def_id(param.id);
for predicate in &generics.where_clause.predicates {
// Look for `type: ...` where clauses.
let data = match *predicate {
hir::WherePredicate::BoundPredicate(ref data) => data,
_ => continue
};
let param_def_id = hir_map.local_def_id(param.id);
for predicate in &generics.where_clause.predicates {
// Look for `type: ...` where clauses.
let data = match *predicate {
hir::WherePredicate::BoundPredicate(ref data) => data,
_ => continue,
};
// Ignore `for<'a> type: ...` as they can change what
// lifetimes mean (although we could "just" handle it).
if !data.bound_lifetimes.is_empty() {
continue;
}
// Ignore `for<'a> type: ...` as they can change what
// lifetimes mean (although we could "just" handle it).
if !data.bound_lifetimes.is_empty() {
continue;
}
let def = match data.bounded_ty.node {
hir::TyPath(hir::QPath::Resolved(None, ref path)) => path.def,
_ => continue
};
let def = match data.bounded_ty.node {
hir::TyPath(hir::QPath::Resolved(None, ref path)) => path.def,
_ => continue,
};
if def == Def::TyParam(param_def_id) {
add_bounds(&mut set, &data.bounds);
}
}
match set {
Set1::Empty => Set1::Empty,
Set1::One(name) => {
if name == hir::LifetimeName::Static {
Set1::One(Region::Static)
} else {
generics.lifetimes.iter().enumerate().find(|&(_, def)| {
def.lifetime.name == name
}).map_or(Set1::Many, |(i, def)| {
let def_id = hir_map.local_def_id(def.lifetime.id);
let origin = LifetimeDefOrigin::from_is_in_band(def.in_band);
Set1::One(Region::EarlyBound(i as u32, def_id, origin))
})
if def == Def::TyParam(param_def_id) {
add_bounds(&mut set, &data.bounds);
}
}
Set1::Many => Set1::Many
}
}).collect()
match set {
Set1::Empty => Set1::Empty,
Set1::One(name) => {
if name == hir::LifetimeName::Static {
Set1::One(Region::Static)
} else {
generics
.lifetimes
.iter()
.enumerate()
.find(|&(_, def)| def.lifetime.name == name)
.map_or(Set1::Many, |(i, def)| {
let def_id = hir_map.local_def_id(def.lifetime.id);
let origin = LifetimeDefOrigin::from_is_in_band(def.in_band);
Set1::One(Region::EarlyBound(i as u32, def_id, origin))
})
}
}
Set1::Many => Set1::Many,
}
})
.collect()
}
impl<'a, 'tcx> LifetimeContext<'a, 'tcx> {
// FIXME(#37666) this works around a limitation in the region inferencer
fn hack<F>(&mut self, f: F) where
fn hack<F>(&mut self, f: F)
where
F: for<'b> FnOnce(&mut LifetimeContext<'b, 'tcx>),
{
f(self)
}
fn with<F>(&mut self, wrap_scope: Scope, f: F) where
fn with<F>(&mut self, wrap_scope: Scope, f: F)
where
F: for<'b> FnOnce(ScopeRef, &mut LifetimeContext<'b, 'tcx>),
{
let LifetimeContext {sess, cstore, hir_map, ref mut map, ..} = *self;
let LifetimeContext {
sess,
cstore,
hir_map,
ref mut map,
..
} = *self;
let labels_in_fn = replace(&mut self.labels_in_fn, vec![]);
let xcrate_object_lifetime_defaults =
replace(&mut self.xcrate_object_lifetime_defaults, DefIdMap());
@@ -945,11 +1067,13 @@ fn with<F>(&mut self, wrap_scope: Scope, f: F) where
/// already in scope (for a fn item, that will be 0, but for a method it might not be). Late
/// bound lifetimes are resolved by name and associated with a binder id (`binder_id`), so the
/// ordering is not important there.
fn visit_early_late<F>(&mut self,
parent_id: Option<ast::NodeId>,
decl: &'tcx hir::FnDecl,
generics: &'tcx hir::Generics,
walk: F) where
fn visit_early_late<F>(
&mut self,
parent_id: Option<ast::NodeId>,
decl: &'tcx hir::FnDecl,
generics: &'tcx hir::Generics,
walk: F,
) where
F: for<'b, 'c> FnOnce(&'b mut LifetimeContext<'c, 'tcx>),
{
insert_late_bound_lifetimes(self.map, decl, generics);
@@ -962,28 +1086,32 @@ fn visit_early_late<F>(&mut self,
index += 1; // Self comes first.
}
match parent.node {
hir::ItemTrait(_, _, ref generics, ..) |
hir::ItemImpl(_, _, _, ref generics, ..) => {
hir::ItemTrait(_, _, ref generics, ..)
| hir::ItemImpl(_, _, _, ref generics, ..) => {
index += (generics.lifetimes.len() + generics.ty_params.len()) as u32;
}
_ => {}
}
}
let lifetimes = generics.lifetimes.iter().map(|def| {
if self.map.late_bound.contains(&def.lifetime.id) {
Region::late(self.hir_map, def)
} else {
Region::early(self.hir_map, &mut index, def)
}
}).collect();
let lifetimes = generics
.lifetimes
.iter()
.map(|def| {
if self.map.late_bound.contains(&def.lifetime.id) {
Region::late(self.hir_map, def)
} else {
Region::early(self.hir_map, &mut index, def)
}
})
.collect();
let next_early_index = index + generics.ty_params.len() as u32;
let scope = Scope::Binder {
lifetimes,
next_early_index,
s: self.scope
s: self.scope,
};
self.with(scope, move |old_scope, this| {
this.check_lifetime_defs(old_scope, &generics.lifetimes);
@@ -997,16 +1125,15 @@ fn next_early_index(&self) -> u32 {
let mut scope = self.scope;
loop {
match *scope {
Scope::Root =>
return 0,
Scope::Root => return 0,
Scope::Binder { next_early_index, .. } =>
return next_early_index,
Scope::Binder {
next_early_index, ..
} => return next_early_index,
Scope::Body { s, .. } |
Scope::Elision { s, .. } |
Scope::ObjectLifetimeDefault { s, .. } =>
scope = s,
Scope::Body { s, .. }
| Scope::Elision { s, .. }
| Scope::ObjectLifetimeDefault { s, .. } => scope = s,
}
}
}
@@ -1032,7 +1159,11 @@ fn resolve_lifetime_ref(&mut self, lifetime_ref: &hir::Lifetime) {
break None;
}
Scope::Binder { ref lifetimes, s, next_early_index: _ } => {
Scope::Binder {
ref lifetimes,
s,
next_early_index: _,
} => {
if let Some(&def) = lifetimes.get(&lifetime_ref.name) {
break Some(def.shifted(late_depth));
} else {
@@ -1041,8 +1172,7 @@ fn resolve_lifetime_ref(&mut self, lifetime_ref: &hir::Lifetime) {
}
}
Scope::Elision { s, .. } |
Scope::ObjectLifetimeDefault { s, .. } => {
Scope::Elision { s, .. } | Scope::ObjectLifetimeDefault { s, .. } => {
scope = s;
}
}
@@ -1055,13 +1185,16 @@ fn resolve_lifetime_ref(&mut self, lifetime_ref: &hir::Lifetime) {
let fn_id = self.hir_map.body_owner(body_id);
match self.hir_map.get(fn_id) {
hir::map::NodeItem(&hir::Item {
node: hir::ItemFn(..), ..
}) |
hir::map::NodeTraitItem(&hir::TraitItem {
node: hir::TraitItemKind::Method(..), ..
}) |
hir::map::NodeImplItem(&hir::ImplItem {
node: hir::ImplItemKind::Method(..), ..
node: hir::ItemFn(..),
..
})
| hir::map::NodeTraitItem(&hir::TraitItem {
node: hir::TraitItemKind::Method(..),
..
})
| hir::map::NodeImplItem(&hir::ImplItem {
node: hir::ImplItemKind::Method(..),
..
}) => {
let scope = self.hir_map.local_def_id(fn_id);
def = Region::Free(scope, def.id().unwrap());
@@ -1073,38 +1206,45 @@ fn resolve_lifetime_ref(&mut self, lifetime_ref: &hir::Lifetime) {
// Check for fn-syntax conflicts with in-band lifetime definitions
if self.is_in_fn_syntax {
match def {
Region::EarlyBound(_, _, LifetimeDefOrigin::InBand) |
Region::LateBound(_, _, LifetimeDefOrigin::InBand) => {
struct_span_err!(self.sess, lifetime_ref.span, E0687,
Region::EarlyBound(_, _, LifetimeDefOrigin::InBand)
| Region::LateBound(_, _, LifetimeDefOrigin::InBand) => {
struct_span_err!(
self.sess,
lifetime_ref.span,
E0687,
"lifetimes used in `fn` or `Fn` syntax must be \
explicitly declared using `<...>` binders")
.span_label(lifetime_ref.span,
"in-band lifetime definition")
explicitly declared using `<...>` binders"
).span_label(lifetime_ref.span, "in-band lifetime definition")
.emit();
},
}
Region::Static |
Region::EarlyBound(_, _, LifetimeDefOrigin::Explicit) |
Region::LateBound(_, _, LifetimeDefOrigin::Explicit) |
Region::LateBoundAnon(..) |
Region::Free(..) => {}
Region::Static
| Region::EarlyBound(_, _, LifetimeDefOrigin::Explicit)
| Region::LateBound(_, _, LifetimeDefOrigin::Explicit)
| Region::LateBoundAnon(..)
| Region::Free(..) => {}
}
}
self.insert_lifetime(lifetime_ref, def);
} else {
struct_span_err!(self.sess, lifetime_ref.span, E0261,
"use of undeclared lifetime name `{}`", lifetime_ref.name.name())
.span_label(lifetime_ref.span, "undeclared lifetime")
struct_span_err!(
self.sess,
lifetime_ref.span,
E0261,
"use of undeclared lifetime name `{}`",
lifetime_ref.name.name()
).span_label(lifetime_ref.span, "undeclared lifetime")
.emit();
}
}
fn visit_segment_parameters(&mut self,
def: Def,
depth: usize,
params: &'tcx hir::PathParameters) {
fn visit_segment_parameters(
&mut self,
def: Def,
depth: usize,
params: &'tcx hir::PathParameters,
) {
if params.parenthesized {
let was_in_fn_syntax = self.is_in_fn_syntax;
self.is_in_fn_syntax = true;
@@ -1116,7 +1256,9 @@ fn visit_segment_parameters(&mut self,
if params.lifetimes.iter().all(|l| l.is_elided()) {
self.resolve_elided_lifetimes(&params.lifetimes);
} else {
for l in &params.lifetimes { self.visit_lifetime(l); }
for l in &params.lifetimes {
self.visit_lifetime(l);
}
}
// Figure out if this is a type/trait segment,
@@ -1129,22 +1271,21 @@ fn visit_segment_parameters(&mut self,
};
DefId {
krate: def_id.krate,
index: def_key.parent.expect("missing parent")
index: def_key.parent.expect("missing parent"),
}
};
let type_def_id = match def {
Def::AssociatedTy(def_id) if depth == 1 => {
Some(parent_def_id(self, def_id))
Def::AssociatedTy(def_id) if depth == 1 => Some(parent_def_id(self, def_id)),
Def::Variant(def_id) if depth == 0 => Some(parent_def_id(self, def_id)),
Def::Struct(def_id)
| Def::Union(def_id)
| Def::Enum(def_id)
| Def::TyAlias(def_id)
| Def::Trait(def_id) if depth == 0 =>
{
Some(def_id)
}
Def::Variant(def_id) if depth == 0 => {
Some(parent_def_id(self, def_id))
}
Def::Struct(def_id) |
Def::Union(def_id) |
Def::Enum(def_id) |
Def::TyAlias(def_id) |
Def::Trait(def_id) if depth == 0 => Some(def_id),
_ => None
_ => None,
};
let object_lifetime_defaults = type_def_id.map_or(vec![], |def_id| {
@@ -1156,9 +1297,9 @@ fn visit_segment_parameters(&mut self,
Scope::Body { .. } => break true,
Scope::Binder { s, .. } |
Scope::Elision { s, .. } |
Scope::ObjectLifetimeDefault { s, .. } => {
Scope::Binder { s, .. }
| Scope::Elision { s, .. }
| Scope::ObjectLifetimeDefault { s, .. } => {
scope = s;
}
}
@@ -1171,17 +1312,20 @@ fn visit_segment_parameters(&mut self,
} else {
let cstore = self.cstore;
let sess = self.sess;
self.xcrate_object_lifetime_defaults.entry(def_id).or_insert_with(|| {
cstore.item_generics_cloned_untracked(def_id, sess)
.types
.into_iter()
.map(|def| {
def.object_lifetime_default
}).collect()
})
self.xcrate_object_lifetime_defaults
.entry(def_id)
.or_insert_with(|| {
cstore
.item_generics_cloned_untracked(def_id, sess)
.types
.into_iter()
.map(|def| def.object_lifetime_default)
.collect()
})
};
unsubst.iter().map(|set| {
match *set {
unsubst
.iter()
.map(|set| match *set {
Set1::Empty => {
if in_body {
None
@@ -1190,16 +1334,16 @@ fn visit_segment_parameters(&mut self,
}
}
Set1::One(r) => r.subst(&params.lifetimes, map),
Set1::Many => None
}
}).collect()
Set1::Many => None,
})
.collect()
});
for (i, ty) in params.types.iter().enumerate() {
if let Some(&lt) = object_lifetime_defaults.get(i) {
let scope = Scope::ObjectLifetimeDefault {
lifetime: lt,
s: self.scope
s: self.scope,
};
self.with(scope, |_, this| this.visit_ty(ty));
} else {
@@ -1207,15 +1351,20 @@ fn visit_segment_parameters(&mut self,
}
}
for b in &params.bindings { self.visit_assoc_type_binding(b); }
for b in &params.bindings {
self.visit_assoc_type_binding(b);
}
}
fn visit_fn_like_elision(&mut self, inputs: &'tcx [P<hir::Ty>],
output: Option<&'tcx P<hir::Ty>>) {
fn visit_fn_like_elision(
&mut self,
inputs: &'tcx [P<hir::Ty>],
output: Option<&'tcx P<hir::Ty>>,
) {
let mut arg_elide = Elide::FreshLateAnon(Cell::new(0));
let arg_scope = Scope::Elision {
elide: arg_elide.clone(),
s: self.scope
s: self.scope,
};
self.with(arg_scope, |_, this| {
for input in inputs {
@@ -1225,13 +1374,13 @@ fn visit_fn_like_elision(&mut self, inputs: &'tcx [P<hir::Ty>],
Scope::Elision { ref elide, .. } => {
arg_elide = elide.clone();
}
_ => bug!()
_ => bug!(),
}
});
let output = match output {
Some(ty) => ty,
None => return
None => return,
};
// Figure out if there's a body we can get argument names from,
@@ -1242,16 +1391,23 @@ fn visit_fn_like_elision(&mut self, inputs: &'tcx [P<hir::Ty>],
let body = match self.hir_map.get(parent) {
// `fn` definitions and methods.
hir::map::NodeItem(&hir::Item {
node: hir::ItemFn(.., body), ..
}) => Some(body),
node: hir::ItemFn(.., body),
..
}) => Some(body),
hir::map::NodeTraitItem(&hir::TraitItem {
node: hir::TraitItemKind::Method(_, ref m), ..
node: hir::TraitItemKind::Method(_, ref m),
..
}) => {
match self.hir_map.expect_item(self.hir_map.get_parent(parent)).node {
match self.hir_map
.expect_item(self.hir_map.get_parent(parent))
.node
{
hir::ItemTrait(.., ref trait_items) => {
assoc_item_kind = trait_items.iter().find(|ti| ti.id.node_id == parent)
.map(|ti| ti.kind);
assoc_item_kind = trait_items
.iter()
.find(|ti| ti.id.node_id == parent)
.map(|ti| ti.kind);
}
_ => {}
}
@@ -1262,13 +1418,19 @@ fn visit_fn_like_elision(&mut self, inputs: &'tcx [P<hir::Ty>],
}
hir::map::NodeImplItem(&hir::ImplItem {
node: hir::ImplItemKind::Method(_, body), ..
node: hir::ImplItemKind::Method(_, body),
..
}) => {
match self.hir_map.expect_item(self.hir_map.get_parent(parent)).node {
match self.hir_map
.expect_item(self.hir_map.get_parent(parent))
.node
{
hir::ItemImpl(.., ref self_ty, ref impl_items) => {
impl_self = Some(self_ty);
assoc_item_kind = impl_items.iter().find(|ii| ii.id.node_id == parent)
.map(|ii| ii.kind);
assoc_item_kind = impl_items
.iter()
.find(|ii| ii.id.node_id == parent)
.map(|ii| ii.kind);
}
_ => {}
}
@@ -1288,7 +1450,7 @@ fn visit_fn_like_elision(&mut self, inputs: &'tcx [P<hir::Ty>],
let has_self = match assoc_item_kind {
Some(hir::AssociatedItemKind::Method { has_self }) => has_self,
_ => false
_ => false,
};
// In accordance with the rules for lifetime elision, we can determine
@@ -1311,10 +1473,9 @@ fn visit_fn_like_elision(&mut self, inputs: &'tcx [P<hir::Ty>],
// Whitelist the types that unambiguously always
// result in the same type constructor being used
// (it can't differ between `Self` and `self`).
Def::Struct(_) |
Def::Union(_) |
Def::Enum(_) |
Def::PrimTy(_) => return def == path.def,
Def::Struct(_) | Def::Union(_) | Def::Enum(_) | Def::PrimTy(_) => {
return def == path.def
}
_ => {}
}
}
@@ -1328,7 +1489,7 @@ fn visit_fn_like_elision(&mut self, inputs: &'tcx [P<hir::Ty>],
if let Some(&lifetime) = self.map.defs.get(&lifetime_ref.id) {
let scope = Scope::Elision {
elide: Elide::Exact(lifetime),
s: self.scope
s: self.scope,
};
self.with(scope, |_, this| this.visit_ty(output));
return;
@@ -1343,31 +1504,36 @@ fn visit_fn_like_elision(&mut self, inputs: &'tcx [P<hir::Ty>],
// have that lifetime.
let mut possible_implied_output_region = None;
let mut lifetime_count = 0;
let arg_lifetimes = inputs.iter().enumerate().skip(has_self as usize).map(|(i, input)| {
let mut gather = GatherLifetimes {
map: self.map,
binder_depth: 1,
have_bound_regions: false,
lifetimes: FxHashSet()
};
gather.visit_ty(input);
let arg_lifetimes = inputs
.iter()
.enumerate()
.skip(has_self as usize)
.map(|(i, input)| {
let mut gather = GatherLifetimes {
map: self.map,
binder_depth: 1,
have_bound_regions: false,
lifetimes: FxHashSet(),
};
gather.visit_ty(input);
lifetime_count += gather.lifetimes.len();
lifetime_count += gather.lifetimes.len();
if lifetime_count == 1 && gather.lifetimes.len() == 1 {
// there's a chance that the unique lifetime of this
// iteration will be the appropriate lifetime for output
// parameters, so lets store it.
possible_implied_output_region = gather.lifetimes.iter().cloned().next();
}
if lifetime_count == 1 && gather.lifetimes.len() == 1 {
// there's a chance that the unique lifetime of this
// iteration will be the appropriate lifetime for output
// parameters, so lets store it.
possible_implied_output_region = gather.lifetimes.iter().cloned().next();
}
ElisionFailureInfo {
parent: body,
index: i,
lifetime_count: gather.lifetimes.len(),
have_bound_regions: gather.have_bound_regions
}
}).collect();
ElisionFailureInfo {
parent: body,
index: i,
lifetime_count: gather.lifetimes.len(),
have_bound_regions: gather.have_bound_regions,
}
})
.collect();
let elide = if lifetime_count == 1 {
Elide::Exact(possible_implied_output_region.unwrap())
@@ -1377,7 +1543,7 @@ fn visit_fn_like_elision(&mut self, inputs: &'tcx [P<hir::Ty>],
let scope = Scope::Elision {
elide,
s: self.scope
s: self.scope,
};
self.with(scope, |_, this| this.visit_ty(output));
@@ -1415,34 +1581,38 @@ fn visit_ty(&mut self, ty: &hir::Ty) {
}
}
fn visit_poly_trait_ref(&mut self,
trait_ref: &hir::PolyTraitRef,
modifier: hir::TraitBoundModifier) {
fn visit_poly_trait_ref(
&mut self,
trait_ref: &hir::PolyTraitRef,
modifier: hir::TraitBoundModifier,
) {
self.binder_depth += 1;
intravisit::walk_poly_trait_ref(self, trait_ref, modifier);
self.binder_depth -= 1;
}
fn visit_lifetime_def(&mut self, lifetime_def: &hir::LifetimeDef) {
for l in &lifetime_def.bounds { self.visit_lifetime(l); }
for l in &lifetime_def.bounds {
self.visit_lifetime(l);
}
}
fn visit_lifetime(&mut self, lifetime_ref: &hir::Lifetime) {
if let Some(&lifetime) = self.map.defs.get(&lifetime_ref.id) {
match lifetime {
Region::LateBound(debruijn, _, _) |
Region::LateBoundAnon(debruijn, _)
if debruijn.depth < self.binder_depth => {
Region::LateBound(debruijn, _, _) | Region::LateBoundAnon(debruijn, _)
if debruijn.depth < self.binder_depth =>
{
self.have_bound_regions = true;
}
_ => {
self.lifetimes.insert(lifetime.from_depth(self.binder_depth));
self.lifetimes
.insert(lifetime.from_depth(self.binder_depth));
}
}
}
}
}
}
fn resolve_elided_lifetimes(&mut self, lifetime_refs: &[hir::Lifetime]) {
@@ -1475,7 +1645,7 @@ fn resolve_elided_lifetimes(&mut self, lifetime_refs: &[hir::Lifetime]) {
return;
}
Elide::Exact(l) => l.shifted(late_depth),
Elide::Error(ref e) => break Some(e)
Elide::Error(ref e) => break Some(e),
};
for lifetime_ref in lifetime_refs {
self.insert_lifetime(lifetime_ref, lifetime);
@@ -1489,9 +1659,13 @@ fn resolve_elided_lifetimes(&mut self, lifetime_refs: &[hir::Lifetime]) {
}
};
let mut err = struct_span_err!(self.sess, span, E0106,
let mut err = struct_span_err!(
self.sess,
span,
E0106,
"missing lifetime specifier{}",
if lifetime_refs.len() > 1 { "s" } else { "" });
if lifetime_refs.len() > 1 { "s" } else { "" }
);
let msg = if lifetime_refs.len() > 1 {
format!("expected {} lifetime parameters", lifetime_refs.len())
} else {
@@ -1507,21 +1681,28 @@ fn resolve_elided_lifetimes(&mut self, lifetime_refs: &[hir::Lifetime]) {
err.emit();
}
fn report_elision_failure(&mut self,
db: &mut DiagnosticBuilder,
params: &[ElisionFailureInfo]) {
fn report_elision_failure(
&mut self,
db: &mut DiagnosticBuilder,
params: &[ElisionFailureInfo],
) {
let mut m = String::new();
let len = params.len();
let elided_params: Vec<_> = params.iter().cloned()
.filter(|info| info.lifetime_count > 0)
.collect();
let elided_params: Vec<_> = params
.iter()
.cloned()
.filter(|info| info.lifetime_count > 0)
.collect();
let elided_len = elided_params.len();
for (i, info) in elided_params.into_iter().enumerate() {
let ElisionFailureInfo {
parent, index, lifetime_count: n, have_bound_regions
parent,
index,
lifetime_count: n,
have_bound_regions,
} = info;
let help_name = if let Some(body) = parent {
@@ -1531,12 +1712,18 @@ fn report_elision_failure(&mut self,
format!("argument {}", index + 1)
};
m.push_str(&(if n == 1 {
help_name
} else {
format!("one of {}'s {} {}lifetimes", help_name, n,
if have_bound_regions { "free " } else { "" } )
})[..]);
m.push_str(
&(if n == 1 {
help_name
} else {
format!(
"one of {}'s {} {}lifetimes",
help_name,
n,
if have_bound_regions { "free " } else { "" }
)
})[..],
);
if elided_len == 2 && i == 0 {
m.push_str(" or ");
@@ -1545,33 +1732,41 @@ fn report_elision_failure(&mut self,
} else if i != elided_len - 1 {
m.push_str(", ");
}
}
if len == 0 {
help!(db,
"this function's return type contains a borrowed value, but \
there is no value for it to be borrowed from");
help!(db,
"consider giving it a 'static lifetime");
help!(
db,
"this function's return type contains a borrowed value, but \
there is no value for it to be borrowed from"
);
help!(db, "consider giving it a 'static lifetime");
} else if elided_len == 0 {
help!(db,
"this function's return type contains a borrowed value with \
an elided lifetime, but the lifetime cannot be derived from \
the arguments");
help!(db,
"consider giving it an explicit bounded or 'static \
lifetime");
help!(
db,
"this function's return type contains a borrowed value with \
an elided lifetime, but the lifetime cannot be derived from \
the arguments"
);
help!(
db,
"consider giving it an explicit bounded or 'static \
lifetime"
);
} else if elided_len == 1 {
help!(db,
"this function's return type contains a borrowed value, but \
the signature does not say which {} it is borrowed from",
m);
help!(
db,
"this function's return type contains a borrowed value, but \
the signature does not say which {} it is borrowed from",
m
);
} else {
help!(db,
"this function's return type contains a borrowed value, but \
the signature does not say whether it is borrowed from {}",
m);
help!(
db,
"this function's return type contains a borrowed value, but \
the signature does not say whether it is borrowed from {}",
m
);
}
}
@@ -1585,13 +1780,13 @@ fn resolve_object_lifetime_default(&mut self, lifetime_ref: &hir::Lifetime) {
scope = s;
}
Scope::Root |
Scope::Elision { .. } => break Region::Static,
Scope::Root | Scope::Elision { .. } => break Region::Static,
Scope::Body { .. } |
Scope::ObjectLifetimeDefault { lifetime: None, .. } => return,
Scope::Body { .. } | Scope::ObjectLifetimeDefault { lifetime: None, .. } => return,
Scope::ObjectLifetimeDefault { lifetime: Some(l), .. } => break l
Scope::ObjectLifetimeDefault {
lifetime: Some(l), ..
} => break l,
}
};
self.insert_lifetime(lifetime_ref, lifetime.shifted(late_depth));
@@ -1606,10 +1801,17 @@ fn check_lifetime_defs(&mut self, old_scope: ScopeRef, lifetimes: &[hir::Lifetim
hir::LifetimeName::Static | hir::LifetimeName::Underscore => {
let lifetime = lifetime.lifetime;
let name = lifetime.name.name();
let mut err = struct_span_err!(self.sess, lifetime.span, E0262,
"invalid lifetime parameter name: `{}`", name);
err.span_label(lifetime.span,
format!("{} is a reserved lifetime name", name));
let mut err = struct_span_err!(
self.sess,
lifetime.span,
E0262,
"invalid lifetime parameter name: `{}`",
name
);
err.span_label(
lifetime.span,
format!("{} is a reserved lifetime name", name),
);
err.emit();
}
hir::LifetimeName::Implicit | hir::LifetimeName::Name(_) => {}
@@ -1621,13 +1823,14 @@ fn check_lifetime_defs(&mut self, old_scope: ScopeRef, lifetimes: &[hir::Lifetim
let lifetime_j = &lifetimes[j];
if lifetime_i.lifetime.name == lifetime_j.lifetime.name {
struct_span_err!(self.sess, lifetime_j.lifetime.span, E0263,
"lifetime name `{}` declared twice in the same scope",
lifetime_j.lifetime.name.name())
.span_label(lifetime_j.lifetime.span,
"declared twice")
.span_label(lifetime_i.lifetime.span,
"previous declaration here")
struct_span_err!(
self.sess,
lifetime_j.lifetime.span,
E0263,
"lifetime name `{}` declared twice in the same scope",
lifetime_j.lifetime.name.name()
).span_label(lifetime_j.lifetime.span, "declared twice")
.span_label(lifetime_i.lifetime.span, "previous declaration here")
.emit();
}
}
@@ -1638,23 +1841,33 @@ fn check_lifetime_defs(&mut self, old_scope: ScopeRef, lifetimes: &[hir::Lifetim
for bound in &lifetime_i.bounds {
match bound.name {
hir::LifetimeName::Underscore => {
let mut err = struct_span_err!(self.sess, bound.span, E0637,
"invalid lifetime bound name: `'_`");
let mut err = struct_span_err!(
self.sess,
bound.span,
E0637,
"invalid lifetime bound name: `'_`"
);
err.span_label(bound.span, "`'_` is a reserved lifetime name");
err.emit();
}
hir::LifetimeName::Static => {
self.insert_lifetime(bound, Region::Static);
self.sess.struct_span_warn(lifetime_i.lifetime.span.to(bound.span),
&format!("unnecessary lifetime parameter `{}`",
lifetime_i.lifetime.name.name()))
self.sess
.struct_span_warn(
lifetime_i.lifetime.span.to(bound.span),
&format!(
"unnecessary lifetime parameter `{}`",
lifetime_i.lifetime.name.name()
),
)
.help(&format!(
"you can use the `'static` lifetime directly, in place \
of `{}`", lifetime_i.lifetime.name.name()))
of `{}`",
lifetime_i.lifetime.name.name()
))
.emit();
}
hir::LifetimeName::Implicit |
hir::LifetimeName::Name(_) => {
hir::LifetimeName::Implicit | hir::LifetimeName::Name(_) => {
self.resolve_lifetime_ref(bound);
}
}
@@ -1662,26 +1875,25 @@ fn check_lifetime_defs(&mut self, old_scope: ScopeRef, lifetimes: &[hir::Lifetim
}
}
fn check_lifetime_def_for_shadowing(&self,
mut old_scope: ScopeRef,
lifetime: &hir::Lifetime)
{
fn check_lifetime_def_for_shadowing(&self, mut old_scope: ScopeRef, lifetime: &hir::Lifetime) {
for &(label, label_span) in &self.labels_in_fn {
// FIXME (#24278): non-hygienic comparison
if lifetime.name.name() == label {
signal_shadowing_problem(self.sess,
label,
original_label(label_span),
shadower_lifetime(&lifetime));
signal_shadowing_problem(
self.sess,
label,
original_label(label_span),
shadower_lifetime(&lifetime),
);
return;
}
}
loop {
match *old_scope {
Scope::Body { s, .. } |
Scope::Elision { s, .. } |
Scope::ObjectLifetimeDefault { s, .. } => {
Scope::Body { s, .. }
| Scope::Elision { s, .. }
| Scope::ObjectLifetimeDefault { s, .. } => {
old_scope = s;
}
@@ -1689,17 +1901,20 @@ fn check_lifetime_def_for_shadowing(&self,
return;
}
Scope::Binder { ref lifetimes, s, next_early_index: _ } => {
Scope::Binder {
ref lifetimes,
s,
next_early_index: _,
} => {
if let Some(&def) = lifetimes.get(&lifetime.name) {
let node_id = self.hir_map
.as_local_node_id(def.id().unwrap())
.unwrap();
let node_id = self.hir_map.as_local_node_id(def.id().unwrap()).unwrap();
signal_shadowing_problem(
self.sess,
lifetime.name.name(),
original_lifetime(self.hir_map.span(node_id)),
shadower_lifetime(&lifetime));
shadower_lifetime(&lifetime),
);
return;
}
@@ -1709,19 +1924,21 @@ fn check_lifetime_def_for_shadowing(&self,
}
}
fn insert_lifetime(&mut self,
lifetime_ref: &hir::Lifetime,
def: Region) {
fn insert_lifetime(&mut self, lifetime_ref: &hir::Lifetime, def: Region) {
if lifetime_ref.id == ast::DUMMY_NODE_ID {
span_bug!(lifetime_ref.span,
"lifetime reference not renumbered, \
probably a bug in syntax::fold");
span_bug!(
lifetime_ref.span,
"lifetime reference not renumbered, \
probably a bug in syntax::fold"
);
}
debug!("insert_lifetime: {} resolved to {:?} span={:?}",
self.hir_map.node_to_string(lifetime_ref.id),
def,
self.sess.codemap().span_to_string(lifetime_ref.span));
debug!(
"insert_lifetime: {} resolved to {:?} span={:?}",
self.hir_map.node_to_string(lifetime_ref.id),
def,
self.sess.codemap().span_to_string(lifetime_ref.span)
);
self.map.defs.insert(lifetime_ref.id, def);
}
}
@@ -1738,12 +1955,20 @@ fn insert_lifetime(&mut self,
/// "Constrained" basically means that it appears in any type but
/// not amongst the inputs to a projection. In other words, `<&'a
/// T as Trait<''b>>::Foo` does not constrain `'a` or `'b`.
fn insert_late_bound_lifetimes(map: &mut NamedRegionMap,
decl: &hir::FnDecl,
generics: &hir::Generics) {
debug!("insert_late_bound_lifetimes(decl={:?}, generics={:?})", decl, generics);
fn insert_late_bound_lifetimes(
map: &mut NamedRegionMap,
decl: &hir::FnDecl,
generics: &hir::Generics,
) {
debug!(
"insert_late_bound_lifetimes(decl={:?}, generics={:?})",
decl,
generics
);
let mut constrained_by_input = ConstrainedCollector { regions: FxHashSet() };
let mut constrained_by_input = ConstrainedCollector {
regions: FxHashSet(),
};
for arg_ty in &decl.inputs {
constrained_by_input.visit_ty(arg_ty);
}
@@ -1753,8 +1978,10 @@ fn insert_late_bound_lifetimes(map: &mut NamedRegionMap,
};
intravisit::walk_fn_ret_ty(&mut appears_in_output, &decl.output);
debug!("insert_late_bound_lifetimes: constrained_by_input={:?}",
constrained_by_input.regions);
debug!(
"insert_late_bound_lifetimes: constrained_by_input={:?}",
constrained_by_input.regions
);
// Walk the lifetimes that appear in where clauses.
//
@@ -1764,24 +1991,30 @@ fn insert_late_bound_lifetimes(map: &mut NamedRegionMap,
regions: FxHashSet(),
};
for ty_param in generics.ty_params.iter() {
walk_list!(&mut appears_in_where_clause,
visit_ty_param_bound,
&ty_param.bounds);
walk_list!(
&mut appears_in_where_clause,
visit_ty_param_bound,
&ty_param.bounds
);
}
walk_list!(&mut appears_in_where_clause,
visit_where_predicate,
&generics.where_clause.predicates);
walk_list!(
&mut appears_in_where_clause,
visit_where_predicate,
&generics.where_clause.predicates
);
// We need to collect argument impl Trait lifetimes as well,
// we do so here.
walk_list!(&mut appears_in_where_clause,
visit_ty,
decl.inputs.iter().filter(|ty| {
if let hir::TyImplTraitUniversal(..) = ty.node {
true
} else {
false
}
}));
walk_list!(
&mut appears_in_where_clause,
visit_ty,
decl.inputs.iter().filter(|ty| {
if let hir::TyImplTraitUniversal(..) = ty.node {
true
} else {
false
}
})
);
for lifetime_def in &generics.lifetimes {
if !lifetime_def.bounds.is_empty() {
// `'a: 'b` means both `'a` and `'b` are referenced
@@ -1789,8 +2022,10 @@ fn insert_late_bound_lifetimes(map: &mut NamedRegionMap,
}
}
debug!("insert_late_bound_lifetimes: appears_in_where_clause={:?}",
appears_in_where_clause.regions);
debug!(
"insert_late_bound_lifetimes: appears_in_where_clause={:?}",
appears_in_where_clause.regions
);
// Late bound regions are those that:
// - appear in the inputs
@@ -1800,20 +2035,30 @@ fn insert_late_bound_lifetimes(map: &mut NamedRegionMap,
let name = lifetime.lifetime.name;
// appears in the where clauses? early-bound.
if appears_in_where_clause.regions.contains(&name) { continue; }
// does not appear in the inputs, but appears in the return type? early-bound.
if !constrained_by_input.regions.contains(&name) &&
appears_in_output.regions.contains(&name) {
if appears_in_where_clause.regions.contains(&name) {
continue;
}
debug!("insert_late_bound_lifetimes: \
lifetime {:?} with id {:?} is late-bound",
lifetime.lifetime.name, lifetime.lifetime.id);
// does not appear in the inputs, but appears in the return type? early-bound.
if !constrained_by_input.regions.contains(&name)
&& appears_in_output.regions.contains(&name)
{
continue;
}
debug!(
"insert_late_bound_lifetimes: \
lifetime {:?} with id {:?} is late-bound",
lifetime.lifetime.name,
lifetime.lifetime.id
);
let inserted = map.late_bound.insert(lifetime.lifetime.id);
assert!(inserted, "visited lifetime {:?} twice", lifetime.lifetime.id);
assert!(
inserted,
"visited lifetime {:?} twice",
lifetime.lifetime.id
);
}
return;
@@ -1829,8 +2074,8 @@ fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'v> {
fn visit_ty(&mut self, ty: &'v hir::Ty) {
match ty.node {
hir::TyPath(hir::QPath::Resolved(Some(_), _)) |
hir::TyPath(hir::QPath::TypeRelative(..)) => {
hir::TyPath(hir::QPath::Resolved(Some(_), _))
| hir::TyPath(hir::QPath::TypeRelative(..)) => {
// ignore lifetimes appearing in associated type
// projections, as they are not *constrained*
// (defined above)