From d737ea7902fb10fd3161d8001ceaec70ebe074d2 Mon Sep 17 00:00:00 2001 From: Niko Matsakis Date: Mon, 11 Dec 2017 09:00:05 -0500 Subject: [PATCH 1/3] resolve_lifetime: rustfmt --- src/librustc/middle/resolve_lifetime.rs | 1197 ++++++++++++++--------- 1 file changed, 721 insertions(+), 476 deletions(-) diff --git a/src/librustc/middle/resolve_lifetime.rs b/src/librustc/middle/resolve_lifetime.rs index 3683425cee5b4..96e537eedacb4 100644 --- a/src/librustc/middle/resolve_lifetime.rs +++ b/src/librustc/middle/resolve_lifetime.rs @@ -30,11 +30,11 @@ use syntax::ptr::P; 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 @@ impl LifetimeDefOrigin { #[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 @@ impl Region { fn id(&self) -> Option { 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 @@ impl 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 { + fn subst(self, params: &[hir::Lifetime], map: &NamedRegionMap) -> Option { 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 @@ impl Region { pub enum Set1 { Empty, One(T), - Many + Many, } impl Set1 { @@ -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, - 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) + Error(Vec), } #[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 { +pub fn krate( + sess: &Session, + cstore: &CrateStore, + hir_map: &Map, +) -> Result { let krate = hir_map.krate(); let mut map = NamedRegionMap { defs: NodeMap(), @@ -330,9 +342,15 @@ impl<'a, 'tcx> Visitor<'tcx> for LifetimeContext<'a, 'tcx> { 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 @@ impl<'a, 'tcx> Visitor<'tcx> for LifetimeContext<'a, 'tcx> { 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 @@ impl<'a, 'tcx> Visitor<'tcx> for LifetimeContext<'a, 'tcx> { 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 @@ impl<'a, 'tcx> Visitor<'tcx> for LifetimeContext<'a, 'tcx> { 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 @@ impl<'a, 'tcx> Visitor<'tcx> for LifetimeContext<'a, 'tcx> { 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 @@ impl<'a, 'tcx> Visitor<'tcx> for LifetimeContext<'a, 'tcx> { // `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 @@ impl<'a, 'tcx> Visitor<'tcx> for LifetimeContext<'a, 'tcx> { } }); } - _ => { - intravisit::walk_ty(self, ty) - } + _ => intravisit::walk_ty(self, ty), } } @@ -510,8 +541,10 @@ impl<'a, 'tcx> Visitor<'tcx> for LifetimeContext<'a, 'tcx> { 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 @@ impl<'a, 'tcx> Visitor<'tcx> for LifetimeContext<'a, 'tcx> { 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 @@ impl<'a, 'tcx> Visitor<'tcx> for LifetimeContext<'a, 'tcx> { 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 @@ impl<'a, 'tcx> Visitor<'tcx> for LifetimeContext<'a, 'tcx> { } 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 @@ impl<'a, 'tcx> Visitor<'tcx> for LifetimeContext<'a, 'tcx> { 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 @@ impl<'a, 'tcx> Visitor<'tcx> for LifetimeContext<'a, 'tcx> { } } - 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 @@ impl<'a, 'tcx> Visitor<'tcx> for LifetimeContext<'a, 'tcx> { } #[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 @@ impl ShadowKind { } } -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 extract_labels(ctxt: &mut LifetimeContext, body: &hir::Body) { 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 extract_labels(ctxt: &mut LifetimeContext, body: &hir::Body) { 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 extract_labels(ctxt: &mut LifetimeContext, body: &hir::Body) { } } -fn compute_object_lifetime_defaults(sess: &Session, hir_map: &Map) - -> NodeMap> { +fn compute_object_lifetime_defaults( + sess: &Session, + hir_map: &Map, +) -> NodeMap> { 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::>().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::>() + .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 { +fn object_lifetime_defaults_for_item( + hir_map: &Map, + generics: &hir::Generics, +) -> Vec { fn add_bounds(set: &mut Set1, bounds: &[hir::TyParamBound]) { for bound in bounds { if let hir::RegionTyParamBound(ref lifetime) = *bound { @@ -845,67 +952,82 @@ fn object_lifetime_defaults_for_item(hir_map: &Map, generics: &hir::Generics) } } - 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, ¶m.bounds); + add_bounds(&mut set, ¶m.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); + 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)) - }) + 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, } - Set1::Many => Set1::Many - } - }).collect() + }) + .collect() } impl<'a, 'tcx> LifetimeContext<'a, 'tcx> { // FIXME(#37666) this works around a limitation in the region inferencer - fn hack(&mut self, f: F) where + fn hack(&mut self, f: F) + where F: for<'b> FnOnce(&mut LifetimeContext<'b, 'tcx>), { f(self) } - fn with(&mut self, wrap_scope: Scope, f: F) where + fn with(&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 @@ impl<'a, 'tcx> LifetimeContext<'a, 'tcx> { /// 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(&mut self, - parent_id: Option, - decl: &'tcx hir::FnDecl, - generics: &'tcx hir::Generics, - walk: F) where + fn visit_early_late( + &mut self, + parent_id: Option, + 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 @@ impl<'a, 'tcx> LifetimeContext<'a, 'tcx> { 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 @@ impl<'a, 'tcx> LifetimeContext<'a, 'tcx> { 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 @@ impl<'a, 'tcx> LifetimeContext<'a, 'tcx> { 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 @@ impl<'a, 'tcx> LifetimeContext<'a, 'tcx> { } } - Scope::Elision { s, .. } | - Scope::ObjectLifetimeDefault { s, .. } => { + Scope::Elision { s, .. } | Scope::ObjectLifetimeDefault { s, .. } => { scope = s; } } @@ -1055,13 +1185,16 @@ impl<'a, 'tcx> LifetimeContext<'a, 'tcx> { 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 @@ impl<'a, 'tcx> LifetimeContext<'a, 'tcx> { // 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 @@ impl<'a, 'tcx> LifetimeContext<'a, 'tcx> { if params.lifetimes.iter().all(|l| l.is_elided()) { self.resolve_elided_lifetimes(¶ms.lifetimes); } else { - for l in ¶ms.lifetimes { self.visit_lifetime(l); } + for l in ¶ms.lifetimes { + self.visit_lifetime(l); + } } // Figure out if this is a type/trait segment, @@ -1129,22 +1271,21 @@ impl<'a, 'tcx> LifetimeContext<'a, 'tcx> { }; 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::Variant(def_id) if depth == 0 => { - 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::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 @@ impl<'a, 'tcx> LifetimeContext<'a, 'tcx> { 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 @@ impl<'a, 'tcx> LifetimeContext<'a, 'tcx> { } 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 @@ impl<'a, 'tcx> LifetimeContext<'a, 'tcx> { } } Set1::One(r) => r.subst(¶ms.lifetimes, map), - Set1::Many => None - } - }).collect() + Set1::Many => None, + }) + .collect() }); for (i, ty) in params.types.iter().enumerate() { if let Some(<) = 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 @@ impl<'a, 'tcx> LifetimeContext<'a, 'tcx> { } } - for b in ¶ms.bindings { self.visit_assoc_type_binding(b); } + for b in ¶ms.bindings { + self.visit_assoc_type_binding(b); + } } - fn visit_fn_like_elision(&mut self, inputs: &'tcx [P], - output: Option<&'tcx P>) { + fn visit_fn_like_elision( + &mut self, + inputs: &'tcx [P], + output: Option<&'tcx P>, + ) { 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 @@ impl<'a, 'tcx> LifetimeContext<'a, 'tcx> { 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 @@ impl<'a, 'tcx> LifetimeContext<'a, 'tcx> { 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 @@ impl<'a, 'tcx> LifetimeContext<'a, 'tcx> { } 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 @@ impl<'a, 'tcx> LifetimeContext<'a, 'tcx> { 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 @@ impl<'a, 'tcx> LifetimeContext<'a, 'tcx> { // 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 @@ impl<'a, 'tcx> LifetimeContext<'a, 'tcx> { 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 @@ impl<'a, 'tcx> LifetimeContext<'a, 'tcx> { // 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 @@ impl<'a, 'tcx> LifetimeContext<'a, 'tcx> { let scope = Scope::Elision { elide, - s: self.scope + s: self.scope, }; self.with(scope, |_, this| this.visit_ty(output)); @@ -1415,34 +1581,38 @@ impl<'a, 'tcx> LifetimeContext<'a, 'tcx> { } } - 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 @@ impl<'a, 'tcx> LifetimeContext<'a, 'tcx> { 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 @@ impl<'a, 'tcx> LifetimeContext<'a, 'tcx> { } }; - 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 @@ impl<'a, 'tcx> LifetimeContext<'a, 'tcx> { 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 @@ impl<'a, 'tcx> LifetimeContext<'a, 'tcx> { 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 @@ impl<'a, 'tcx> LifetimeContext<'a, 'tcx> { } 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 @@ impl<'a, 'tcx> LifetimeContext<'a, 'tcx> { 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 @@ impl<'a, 'tcx> LifetimeContext<'a, 'tcx> { 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 @@ impl<'a, 'tcx> LifetimeContext<'a, 'tcx> { 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 @@ impl<'a, 'tcx> LifetimeContext<'a, 'tcx> { 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 @@ impl<'a, 'tcx> LifetimeContext<'a, 'tcx> { } } - 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 @@ impl<'a, 'tcx> LifetimeContext<'a, 'tcx> { 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 @@ impl<'a, 'tcx> LifetimeContext<'a, 'tcx> { } } - 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 @@ impl<'a, 'tcx> LifetimeContext<'a, 'tcx> { /// "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; } + 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 !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); + 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 insert_late_bound_lifetimes(map: &mut NamedRegionMap, 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) From b7794c0d3f539ffe9f1bf735ad05b6da6324236e Mon Sep 17 00:00:00 2001 From: Niko Matsakis Date: Thu, 23 Nov 2017 08:05:58 -0500 Subject: [PATCH 2/3] move `resolve_lifetimes` into a proper query Now that we made `resolve_lifetimes` into a query, elision errors no longer abort compilation, which affects some tests. Also, remove `dep_graph_crosscontaminate_tables` -- there is no a path in the dep-graph, though red-green handles it. The same scenario is (correctly) tested by issue-42602.rs in any case. --- src/librustc/dep_graph/dep_node.rs | 7 +- src/librustc/hir/mod.rs | 12 +- src/librustc/middle/resolve_lifetime.rs | 336 +++++++++++------- src/librustc/ty/context.rs | 44 --- src/librustc/ty/maps/config.rs | 6 + src/librustc/ty/maps/mod.rs | 4 +- src/librustc/ty/maps/plumbing.rs | 1 + src/librustc_driver/driver.rs | 8 +- src/librustc_driver/test.rs | 3 - src/librustc_typeck/astconv.rs | 13 +- .../dep_graph_crosscontaminate_tables.rs | 40 --- .../compile-fail/where-lifetime-resolution.rs | 4 +- src/test/incremental/issue-42602.rs | 15 +- src/test/ui/print_type_sizes/anonymous.stderr | 0 src/test/ui/print_type_sizes/anonymous.stdout | 0 .../ui/print_type_sizes/multiple_types.stderr | 0 src/test/ui/print_type_sizes/packed.stderr | 0 .../ui/print_type_sizes/repr-align.stderr | 0 .../construct_with_other_type.rs | 1 + .../construct_with_other_type.stderr | 8 +- .../generic-associated-types-where.stderr | 2 +- .../iterable.rs | 2 + .../iterable.stderr | 14 +- 23 files changed, 283 insertions(+), 237 deletions(-) delete mode 100644 src/test/compile-fail/dep_graph_crosscontaminate_tables.rs create mode 100644 src/test/ui/print_type_sizes/anonymous.stderr create mode 100644 src/test/ui/print_type_sizes/anonymous.stdout create mode 100644 src/test/ui/print_type_sizes/multiple_types.stderr create mode 100644 src/test/ui/print_type_sizes/packed.stderr create mode 100644 src/test/ui/print_type_sizes/repr-align.stderr diff --git a/src/librustc/dep_graph/dep_node.rs b/src/librustc/dep_graph/dep_node.rs index 1fc3b04adb86d..06b745dbaaf1c 100644 --- a/src/librustc/dep_graph/dep_node.rs +++ b/src/librustc/dep_graph/dep_node.rs @@ -588,9 +588,10 @@ define_dep_nodes!( <'tcx> [] NativeLibraryKind(DefId), [input] LinkArgs, - [input] NamedRegion(DefIndex), - [input] IsLateBound(DefIndex), - [input] ObjectLifetimeDefaults(DefIndex), + [] ResolveLifetimes(CrateNum), + [] NamedRegion(DefIndex), + [] IsLateBound(DefIndex), + [] ObjectLifetimeDefaults(DefIndex), [] Visibility(DefId), [] DepKind(CrateNum), diff --git a/src/librustc/hir/mod.rs b/src/librustc/hir/mod.rs index 39ec33eef1fec..d6107a8f55197 100644 --- a/src/librustc/hir/mod.rs +++ b/src/librustc/hir/mod.rs @@ -28,7 +28,7 @@ pub use self::UnsafeSource::*; pub use self::Visibility::{Public, Inherited}; use hir::def::Def; -use hir::def_id::{DefId, DefIndex, CRATE_DEF_INDEX}; +use hir::def_id::{DefId, DefIndex, LocalDefId, CRATE_DEF_INDEX}; use util::nodemap::{NodeMap, FxHashSet}; use syntax_pos::{Span, DUMMY_SP}; @@ -92,6 +92,16 @@ pub struct HirId { pub local_id: ItemLocalId, } +impl HirId { + pub fn owner_def_id(self) -> DefId { + DefId::local(self.owner) + } + + pub fn owner_local_def_id(self) -> LocalDefId { + LocalDefId::from_def_id(DefId::local(self.owner)) + } +} + impl serialize::UseSpecializedEncodable for HirId { fn default_encode(&self, s: &mut S) -> Result<(), S::Error> { let HirId { diff --git a/src/librustc/middle/resolve_lifetime.rs b/src/librustc/middle/resolve_lifetime.rs index 96e537eedacb4..89df212938a42 100644 --- a/src/librustc/middle/resolve_lifetime.rs +++ b/src/librustc/middle/resolve_lifetime.rs @@ -17,13 +17,13 @@ use hir::map::Map; use hir::def::Def; -use hir::def_id::DefId; -use middle::cstore::CrateStore; -use session::Session; -use ty; +use hir::def_id::{CrateNum, DefId, LocalDefId, LOCAL_CRATE}; +use hir::ItemLocalId; +use ty::{self, TyCtxt}; use std::cell::Cell; use std::mem::replace; +use std::rc::Rc; use syntax::ast; use syntax::attr; use syntax::ptr::P; @@ -181,9 +181,14 @@ impl Set1 { pub type ObjectLifetimeDefault = Set1; -// Maps the id of each lifetime reference to the lifetime decl -// that it corresponds to. -pub struct NamedRegionMap { +/// Maps the id of each lifetime reference to the lifetime decl +/// that it corresponds to. +/// +/// FIXME. This struct gets converted to a `ResolveLifetimes` for +/// actual use. It has the same data, but indexed by `DefIndex`. This +/// is silly. +#[derive(Default)] +struct NamedRegionMap { // maps from every use of a named (not anonymous) lifetime to a // `Region` describing how that region is bound pub defs: NodeMap, @@ -198,10 +203,22 @@ pub struct NamedRegionMap { pub object_lifetime_defaults: NodeMap>, } +/// See `NamedRegionMap`. +pub struct ResolveLifetimes { + defs: FxHashMap>>, + late_bound: FxHashMap>>, + object_lifetime_defaults: + FxHashMap>>>>, +} + +impl_stable_hash_for!(struct ::middle::resolve_lifetime::ResolveLifetimes { + defs, + late_bound, + object_lifetime_defaults +}); + struct LifetimeContext<'a, 'tcx: 'a> { - sess: &'a Session, - cstore: &'a CrateStore, - hir_map: &'a Map<'tcx>, + tcx: TyCtxt<'a, 'tcx, 'tcx>, map: &'a mut NamedRegionMap, scope: ScopeRef<'a>, // Deep breath. Our representation for poly trait refs contains a single @@ -299,22 +316,92 @@ type ScopeRef<'a> = &'a Scope<'a>; const ROOT_SCOPE: ScopeRef<'static> = &Scope::Root; -pub fn krate( - sess: &Session, - cstore: &CrateStore, - hir_map: &Map, -) -> Result { - let krate = hir_map.krate(); +pub fn provide(providers: &mut ty::maps::Providers) { + *providers = ty::maps::Providers { + resolve_lifetimes, + + named_region_map: |tcx, id| { + let id = LocalDefId::from_def_id(DefId::local(id)); // (*) + tcx.resolve_lifetimes(LOCAL_CRATE).defs.get(&id).cloned() + }, + + is_late_bound_map: |tcx, id| { + let id = LocalDefId::from_def_id(DefId::local(id)); // (*) + tcx.resolve_lifetimes(LOCAL_CRATE) + .late_bound + .get(&id) + .cloned() + }, + + object_lifetime_defaults_map: |tcx, id| { + let id = LocalDefId::from_def_id(DefId::local(id)); // (*) + tcx.resolve_lifetimes(LOCAL_CRATE) + .object_lifetime_defaults + .get(&id) + .cloned() + }, + + ..*providers + }; + + // (*) FIXME the query should be defined to take a LocalDefId +} + +/// Computes the `ResolveLifetimes` map that contains data for the +/// entire crate. You should not read the result of this query +/// directly, but rather use `named_region_map`, `is_late_bound_map`, +/// etc. +fn resolve_lifetimes<'tcx>( + tcx: TyCtxt<'_, 'tcx, 'tcx>, + for_krate: CrateNum, +) -> Rc { + assert_eq!(for_krate, LOCAL_CRATE); + + let named_region_map = krate(tcx).unwrap_or_default(); + + let mut defs = FxHashMap(); + for (k, v) in named_region_map.defs { + let hir_id = tcx.hir.node_to_hir_id(k); + let map = defs.entry(hir_id.owner_local_def_id()) + .or_insert_with(|| Rc::new(FxHashMap())); + Rc::get_mut(map).unwrap().insert(hir_id.local_id, v); + } + let mut late_bound = FxHashMap(); + for k in named_region_map.late_bound { + let hir_id = tcx.hir.node_to_hir_id(k); + let map = late_bound + .entry(hir_id.owner_local_def_id()) + .or_insert_with(|| Rc::new(FxHashSet())); + Rc::get_mut(map).unwrap().insert(hir_id.local_id); + } + let mut object_lifetime_defaults = FxHashMap(); + for (k, v) in named_region_map.object_lifetime_defaults { + let hir_id = tcx.hir.node_to_hir_id(k); + let map = object_lifetime_defaults + .entry(hir_id.owner_local_def_id()) + .or_insert_with(|| Rc::new(FxHashMap())); + Rc::get_mut(map) + .unwrap() + .insert(hir_id.local_id, Rc::new(v)); + } + + Rc::new(ResolveLifetimes { + defs, + late_bound, + object_lifetime_defaults, + }) +} + +fn krate<'tcx>(tcx: TyCtxt<'_, 'tcx, 'tcx>) -> Result { + let krate = tcx.hir.krate(); let mut map = NamedRegionMap { defs: NodeMap(), late_bound: NodeSet(), - object_lifetime_defaults: compute_object_lifetime_defaults(sess, hir_map), + object_lifetime_defaults: compute_object_lifetime_defaults(tcx), }; - sess.track_errors(|| { + { let mut visitor = LifetimeContext { - sess, - cstore, - hir_map, + tcx, map: &mut map, scope: ROOT_SCOPE, trait_ref_hack: false, @@ -325,13 +412,13 @@ pub fn krate( for (_, item) in &krate.items { visitor.visit_item(item); } - })?; + } Ok(map) } impl<'a, 'tcx> Visitor<'tcx> for LifetimeContext<'a, 'tcx> { fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> { - NestedVisitorMap::All(self.hir_map) + NestedVisitorMap::All(&self.tcx.hir) } // We want to nest trait/impl items in their parent, but nothing else. @@ -340,7 +427,7 @@ impl<'a, 'tcx> Visitor<'tcx> for LifetimeContext<'a, 'tcx> { fn visit_nested_body(&mut self, body: hir::BodyId) { // Each body has their own set of labels, save labels. let saved = replace(&mut self.labels_in_fn, vec![]); - let body = self.hir_map.body(body); + let body = self.tcx.hir.body(body); extract_labels(self, body); self.with( Scope::Body { @@ -393,7 +480,7 @@ impl<'a, 'tcx> Visitor<'tcx> for LifetimeContext<'a, 'tcx> { let lifetimes = generics .lifetimes .iter() - .map(|def| Region::early(self.hir_map, &mut index, def)) + .map(|def| Region::early(&self.tcx.hir, &mut index, def)) .collect(); let next_early_index = index + generics.ty_params.len() as u32; let scope = Scope::Binder { @@ -435,10 +522,10 @@ impl<'a, 'tcx> Visitor<'tcx> for LifetimeContext<'a, 'tcx> { let scope = Scope::Binder { lifetimes: c.lifetimes .iter() - .map(|def| Region::late(self.hir_map, def)) + .map(|def| Region::late(&self.tcx.hir, def)) .collect(), - next_early_index, s: self.scope, + next_early_index, }; self.with(scope, |old_scope, this| { // a bare fn has no bounds, so everything @@ -481,18 +568,18 @@ impl<'a, 'tcx> Visitor<'tcx> for LifetimeContext<'a, 'tcx> { // In the future, this should be fixed and this error should be removed. let def = self.map.defs.get(&lifetime.id); if let Some(&Region::LateBound(_, def_id, _)) = def { - if let Some(node_id) = self.hir_map.as_local_node_id(def_id) { + if let Some(node_id) = self.tcx.hir.as_local_node_id(def_id) { // Ensure that the parent of the def is an item, not HRTB - let parent_id = self.hir_map.get_parent_node(node_id); + let parent_id = self.tcx.hir.get_parent_node(node_id); 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(); + let krate = self.tcx.hir.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)) { span_err!( - self.sess, + self.tcx.sess, lifetime.span, E0657, "`impl Trait` can only capture lifetimes \ @@ -517,7 +604,7 @@ impl<'a, 'tcx> Visitor<'tcx> for LifetimeContext<'a, 'tcx> { let lifetimes = generics .lifetimes .iter() - .map(|lt_def| Region::early(self.hir_map, &mut index, lt_def)) + .map(|lt_def| Region::early(&self.tcx.hir, &mut index, lt_def)) .collect(); let next_early_index = index + generics.ty_params.len() as u32; @@ -538,9 +625,10 @@ impl<'a, 'tcx> Visitor<'tcx> for LifetimeContext<'a, 'tcx> { } fn visit_trait_item(&mut self, trait_item: &'tcx hir::TraitItem) { + let tcx = self.tcx; if let hir::TraitItemKind::Method(ref sig, _) = trait_item.node { self.visit_early_late( - Some(self.hir_map.get_parent(trait_item.id)), + Some(tcx.hir.get_parent(trait_item.id)), &sig.decl, &trait_item.generics, |this| intravisit::walk_trait_item(this, trait_item), @@ -551,9 +639,10 @@ impl<'a, 'tcx> Visitor<'tcx> for LifetimeContext<'a, 'tcx> { } fn visit_impl_item(&mut self, impl_item: &'tcx hir::ImplItem) { + let tcx = self.tcx; if let hir::ImplItemKind::Method(ref sig, _) = impl_item.node { self.visit_early_late( - Some(self.hir_map.get_parent(impl_item.id)), + Some(tcx.hir.get_parent(impl_item.id)), &sig.decl, &impl_item.generics, |this| intravisit::walk_impl_item(this, impl_item), @@ -593,7 +682,7 @@ impl<'a, 'tcx> Visitor<'tcx> for LifetimeContext<'a, 'tcx> { } fn visit_generics(&mut self, generics: &'tcx hir::Generics) { - check_mixed_explicit_and_in_band_defs(&self.sess, &generics.lifetimes); + check_mixed_explicit_and_in_band_defs(self.tcx, &generics.lifetimes); for ty_param in generics.ty_params.iter() { walk_list!(self, visit_ty_param_bound, &ty_param.bounds); if let Some(ref ty) = ty_param.default { @@ -614,10 +703,10 @@ impl<'a, 'tcx> Visitor<'tcx> for LifetimeContext<'a, 'tcx> { let scope = Scope::Binder { lifetimes: bound_lifetimes .iter() - .map(|def| Region::late(self.hir_map, def)) + .map(|def| Region::late(&self.tcx.hir, def)) .collect(), - next_early_index, s: self.scope, + next_early_index, }; let result = self.with(scope, |old_scope, this| { this.check_lifetime_defs(old_scope, bound_lifetimes); @@ -663,7 +752,7 @@ impl<'a, 'tcx> Visitor<'tcx> for LifetimeContext<'a, 'tcx> { if !self.trait_ref_hack || !trait_ref.bound_lifetimes.is_empty() { if self.trait_ref_hack { span_err!( - self.sess, + self.tcx.sess, trait_ref.span, E0316, "nested quantification of lifetimes" @@ -674,10 +763,10 @@ impl<'a, 'tcx> Visitor<'tcx> for LifetimeContext<'a, 'tcx> { lifetimes: trait_ref .bound_lifetimes .iter() - .map(|def| Region::late(self.hir_map, def)) + .map(|def| Region::late(&self.tcx.hir, def)) .collect(), - next_early_index, s: self.scope, + next_early_index, }; self.with(scope, |old_scope, this| { this.check_lifetime_defs(old_scope, &trait_ref.bound_lifetimes); @@ -740,13 +829,16 @@ impl ShadowKind { } } -fn check_mixed_explicit_and_in_band_defs(sess: &Session, lifetime_defs: &[hir::LifetimeDef]) { +fn check_mixed_explicit_and_in_band_defs( + tcx: TyCtxt<'_, '_, '_>, + 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, + tcx.sess, in_band_def.lifetime.span, E0688, "cannot mix in-band and explicit lifetime definitions" @@ -759,11 +851,16 @@ fn check_mixed_explicit_and_in_band_defs(sess: &Session, lifetime_defs: &[hir::L } } -fn signal_shadowing_problem(sess: &Session, name: ast::Name, orig: Original, shadower: Shadower) { +fn signal_shadowing_problem( + tcx: TyCtxt<'_, '_, '_>, + 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, + tcx.sess, shadower.span, E0496, "{} name `{}` shadows a \ @@ -775,7 +872,7 @@ fn signal_shadowing_problem(sess: &Session, name: ast::Name, orig: Original, sha } else { // shadowing involving a label is only a warning, due to issues with // labels and lifetimes not being macro-hygienic. - sess.struct_span_warn( + tcx.sess.struct_span_warn( shadower.span, &format!( "{} name `{}` shadows a \ @@ -793,17 +890,15 @@ fn signal_shadowing_problem(sess: &Session, name: ast::Name, orig: Original, sha // Adds all labels in `b` to `ctxt.labels_in_fn`, signalling a warning // if one of the label shadows a lifetime or another label. -fn extract_labels(ctxt: &mut LifetimeContext, body: &hir::Body) { +fn extract_labels(ctxt: &mut LifetimeContext<'_, '_>, body: &hir::Body) { struct GatherLabels<'a, 'tcx: 'a> { - sess: &'a Session, - hir_map: &'a Map<'tcx>, + tcx: TyCtxt<'a, 'tcx, 'tcx>, scope: ScopeRef<'a>, labels_in_fn: &'a mut Vec<(ast::Name, Span)>, } let mut gather = GatherLabels { - sess: ctxt.sess, - hir_map: ctxt.hir_map, + tcx: ctxt.tcx, scope: ctxt.scope, labels_in_fn: &mut ctxt.labels_in_fn, }; @@ -820,7 +915,7 @@ fn extract_labels(ctxt: &mut LifetimeContext, body: &hir::Body) { // FIXME (#24278): non-hygienic comparison if label == prior { signal_shadowing_problem( - self.sess, + self.tcx, label, original_label(prior_span), shadower_label(label_span), @@ -828,13 +923,7 @@ fn extract_labels(ctxt: &mut LifetimeContext, body: &hir::Body) { } } - check_if_label_shadows_lifetime( - self.sess, - self.hir_map, - self.scope, - label, - label_span, - ); + check_if_label_shadows_lifetime(self.tcx, self.scope, label, label_span); self.labels_in_fn.push((label, label_span)); } @@ -851,10 +940,9 @@ fn extract_labels(ctxt: &mut LifetimeContext, body: &hir::Body) { } } - fn check_if_label_shadows_lifetime<'a>( - sess: &'a Session, - hir_map: &Map, - mut scope: ScopeRef<'a>, + fn check_if_label_shadows_lifetime( + tcx: TyCtxt<'_, '_, '_>, + mut scope: ScopeRef<'_>, label: ast::Name, label_span: Span, ) { @@ -877,12 +965,12 @@ fn extract_labels(ctxt: &mut LifetimeContext, body: &hir::Body) { } => { // 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 = tcx.hir.as_local_node_id(def.id().unwrap()).unwrap(); signal_shadowing_problem( - sess, + tcx, label, - original_lifetime(hir_map.span(node_id)), + original_lifetime(tcx.hir.span(node_id)), shadower_label(label_span), ); return; @@ -895,18 +983,17 @@ fn extract_labels(ctxt: &mut LifetimeContext, body: &hir::Body) { } fn compute_object_lifetime_defaults( - sess: &Session, - hir_map: &Map, + tcx: TyCtxt<'_, '_, '_>, ) -> NodeMap> { let mut map = NodeMap(); - for item in hir_map.krate().items.values() { + for item in tcx.hir.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, ..) => { - let result = object_lifetime_defaults_for_item(hir_map, generics); + let result = object_lifetime_defaults_for_item(tcx, generics); // Debugging aid. if attr::contains_name(&item.attrs, "rustc_object_lifetime_default") { @@ -926,7 +1013,7 @@ fn compute_object_lifetime_defaults( }) .collect::>() .join(","); - sess.span_err(item.span, &object_lifetime_default_reprs); + tcx.sess.span_err(item.span, &object_lifetime_default_reprs); } map.insert(item.id, result); @@ -941,7 +1028,7 @@ fn compute_object_lifetime_defaults( /// of the form `T:'a` so as to determine the `ObjectLifetimeDefault` /// for each type parameter. fn object_lifetime_defaults_for_item( - hir_map: &Map, + tcx: TyCtxt<'_, '_, '_>, generics: &hir::Generics, ) -> Vec { fn add_bounds(set: &mut Set1, bounds: &[hir::TyParamBound]) { @@ -960,7 +1047,7 @@ fn object_lifetime_defaults_for_item( add_bounds(&mut set, ¶m.bounds); - let param_def_id = hir_map.local_def_id(param.id); + let param_def_id = tcx.hir.local_def_id(param.id); for predicate in &generics.where_clause.predicates { // Look for `type: ...` where clauses. let data = match *predicate { @@ -996,7 +1083,7 @@ fn object_lifetime_defaults_for_item( .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 def_id = tcx.hir.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)) }) @@ -1022,19 +1109,13 @@ impl<'a, 'tcx> LifetimeContext<'a, 'tcx> { F: for<'b> FnOnce(ScopeRef, &mut LifetimeContext<'b, 'tcx>), { let LifetimeContext { - sess, - cstore, - hir_map, - ref mut map, - .. + tcx, 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()); let mut this = LifetimeContext { - sess, - cstore, - hir_map, + tcx, map: *map, scope: &wrap_scope, trait_ref_hack: self.trait_ref_hack, @@ -1081,7 +1162,7 @@ impl<'a, 'tcx> LifetimeContext<'a, 'tcx> { // Find the start of nested early scopes, e.g. in methods. let mut index = 0; if let Some(parent_id) = parent_id { - let parent = self.hir_map.expect_item(parent_id); + let parent = self.tcx.hir.expect_item(parent_id); if let hir::ItemTrait(..) = parent.node { index += 1; // Self comes first. } @@ -1099,9 +1180,9 @@ impl<'a, 'tcx> LifetimeContext<'a, 'tcx> { .iter() .map(|def| { if self.map.late_bound.contains(&def.lifetime.id) { - Region::late(self.hir_map, def) + Region::late(&self.tcx.hir, def) } else { - Region::early(self.hir_map, &mut index, def) + Region::early(&self.tcx.hir, &mut index, def) } }) .collect(); @@ -1182,8 +1263,8 @@ impl<'a, 'tcx> LifetimeContext<'a, 'tcx> { if let Region::EarlyBound(..) = def { // Do not free early-bound regions, only late-bound ones. } else if let Some(body_id) = outermost_body { - let fn_id = self.hir_map.body_owner(body_id); - match self.hir_map.get(fn_id) { + let fn_id = self.tcx.hir.body_owner(body_id); + match self.tcx.hir.get(fn_id) { hir::map::NodeItem(&hir::Item { node: hir::ItemFn(..), .. @@ -1196,7 +1277,7 @@ impl<'a, 'tcx> LifetimeContext<'a, 'tcx> { node: hir::ImplItemKind::Method(..), .. }) => { - let scope = self.hir_map.local_def_id(fn_id); + let scope = self.tcx.hir.local_def_id(fn_id); def = Region::Free(scope, def.id().unwrap()); } _ => {} @@ -1209,7 +1290,7 @@ impl<'a, 'tcx> LifetimeContext<'a, 'tcx> { Region::EarlyBound(_, _, LifetimeDefOrigin::InBand) | Region::LateBound(_, _, LifetimeDefOrigin::InBand) => { struct_span_err!( - self.sess, + self.tcx.sess, lifetime_ref.span, E0687, "lifetimes used in `fn` or `Fn` syntax must be \ @@ -1229,7 +1310,7 @@ impl<'a, 'tcx> LifetimeContext<'a, 'tcx> { self.insert_lifetime(lifetime_ref, def); } else { struct_span_err!( - self.sess, + self.tcx.sess, lifetime_ref.span, E0261, "use of undeclared lifetime name `{}`", @@ -1264,11 +1345,7 @@ impl<'a, 'tcx> LifetimeContext<'a, 'tcx> { // Figure out if this is a type/trait segment, // which requires object lifetime defaults. let parent_def_id = |this: &mut Self, def_id: DefId| { - let def_key = if def_id.is_local() { - this.hir_map.def_key(def_id) - } else { - this.cstore.def_key(def_id) - }; + let def_key = this.tcx.def_key(def_id); DefId { krate: def_id.krate, index: def_key.parent.expect("missing parent"), @@ -1307,18 +1384,16 @@ impl<'a, 'tcx> LifetimeContext<'a, 'tcx> { }; let map = &self.map; - let unsubst = if let Some(id) = self.hir_map.as_local_node_id(def_id) { + let unsubst = if let Some(id) = self.tcx.hir.as_local_node_id(def_id) { &map.object_lifetime_defaults[&id] } else { - let cstore = self.cstore; - let sess = self.sess; + let tcx = self.tcx; self.xcrate_object_lifetime_defaults .entry(def_id) .or_insert_with(|| { - cstore - .item_generics_cloned_untracked(def_id, sess) + tcx.generics_of(def_id) .types - .into_iter() + .iter() .map(|def| def.object_lifetime_default) .collect() }) @@ -1326,13 +1401,11 @@ impl<'a, 'tcx> LifetimeContext<'a, 'tcx> { unsubst .iter() .map(|set| match *set { - Set1::Empty => { - if in_body { - None - } else { - Some(Region::Static) - } - } + Set1::Empty => if in_body { + None + } else { + Some(Region::Static) + }, Set1::One(r) => r.subst(¶ms.lifetimes, map), Set1::Many => None, }) @@ -1387,8 +1460,8 @@ impl<'a, 'tcx> LifetimeContext<'a, 'tcx> { // and whether there's a `self` argument (treated specially). let mut assoc_item_kind = None; let mut impl_self = None; - let parent = self.hir_map.get_parent_node(output.id); - let body = match self.hir_map.get(parent) { + let parent = self.tcx.hir.get_parent_node(output.id); + let body = match self.tcx.hir.get(parent) { // `fn` definitions and methods. hir::map::NodeItem(&hir::Item { node: hir::ItemFn(.., body), @@ -1399,8 +1472,9 @@ impl<'a, 'tcx> LifetimeContext<'a, 'tcx> { node: hir::TraitItemKind::Method(_, ref m), .. }) => { - match self.hir_map - .expect_item(self.hir_map.get_parent(parent)) + match self.tcx + .hir + .expect_item(self.tcx.hir.get_parent(parent)) .node { hir::ItemTrait(.., ref trait_items) => { @@ -1421,8 +1495,9 @@ impl<'a, 'tcx> LifetimeContext<'a, 'tcx> { node: hir::ImplItemKind::Method(_, body), .. }) => { - match self.hir_map - .expect_item(self.hir_map.get_parent(parent)) + match self.tcx + .hir + .expect_item(self.tcx.hir.get_parent(parent)) .node { hir::ItemImpl(.., ref self_ty, ref impl_items) => { @@ -1660,7 +1735,7 @@ impl<'a, 'tcx> LifetimeContext<'a, 'tcx> { }; let mut err = struct_span_err!( - self.sess, + self.tcx.sess, span, E0106, "missing lifetime specifier{}", @@ -1706,8 +1781,8 @@ impl<'a, 'tcx> LifetimeContext<'a, 'tcx> { } = info; let help_name = if let Some(body) = parent { - let arg = &self.hir_map.body(body).arguments[index]; - format!("`{}`", self.hir_map.node_to_pretty_string(arg.pat.id)) + let arg = &self.tcx.hir.body(body).arguments[index]; + format!("`{}`", self.tcx.hir.node_to_pretty_string(arg.pat.id)) } else { format!("argument {}", index + 1) }; @@ -1802,7 +1877,7 @@ impl<'a, 'tcx> LifetimeContext<'a, 'tcx> { let lifetime = lifetime.lifetime; let name = lifetime.name.name(); let mut err = struct_span_err!( - self.sess, + self.tcx.sess, lifetime.span, E0262, "invalid lifetime parameter name: `{}`", @@ -1824,7 +1899,7 @@ impl<'a, 'tcx> LifetimeContext<'a, 'tcx> { if lifetime_i.lifetime.name == lifetime_j.lifetime.name { struct_span_err!( - self.sess, + self.tcx.sess, lifetime_j.lifetime.span, E0263, "lifetime name `{}` declared twice in the same scope", @@ -1842,7 +1917,7 @@ impl<'a, 'tcx> LifetimeContext<'a, 'tcx> { match bound.name { hir::LifetimeName::Underscore => { let mut err = struct_span_err!( - self.sess, + self.tcx.sess, bound.span, E0637, "invalid lifetime bound name: `'_`" @@ -1852,7 +1927,8 @@ impl<'a, 'tcx> LifetimeContext<'a, 'tcx> { } hir::LifetimeName::Static => { self.insert_lifetime(bound, Region::Static); - self.sess + self.tcx + .sess .struct_span_warn( lifetime_i.lifetime.span.to(bound.span), &format!( @@ -1880,7 +1956,7 @@ impl<'a, 'tcx> LifetimeContext<'a, 'tcx> { // FIXME (#24278): non-hygienic comparison if lifetime.name.name() == label { signal_shadowing_problem( - self.sess, + self.tcx, label, original_label(label_span), shadower_lifetime(&lifetime), @@ -1907,12 +1983,12 @@ impl<'a, 'tcx> LifetimeContext<'a, 'tcx> { 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.tcx.hir.as_local_node_id(def.id().unwrap()).unwrap(); signal_shadowing_problem( - self.sess, + self.tcx, lifetime.name.name(), - original_lifetime(self.hir_map.span(node_id)), + original_lifetime(self.tcx.hir.span(node_id)), shadower_lifetime(&lifetime), ); return; @@ -1935,9 +2011,9 @@ impl<'a, 'tcx> LifetimeContext<'a, 'tcx> { debug!( "insert_lifetime: {} resolved to {:?} span={:?}", - self.hir_map.node_to_string(lifetime_ref.id), + self.tcx.hir.node_to_string(lifetime_ref.id), def, - self.sess.codemap().span_to_string(lifetime_ref.span) + self.tcx.sess.codemap().span_to_string(lifetime_ref.span) ); self.map.defs.insert(lifetime_ref.id, def); } @@ -2007,13 +2083,13 @@ fn insert_late_bound_lifetimes( walk_list!( &mut appears_in_where_clause, visit_ty, - decl.inputs.iter().filter(|ty| { - if let hir::TyImplTraitUniversal(..) = ty.node { + 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() { diff --git a/src/librustc/ty/context.rs b/src/librustc/ty/context.rs index ce05acb01b001..4315d59f77165 100644 --- a/src/librustc/ty/context.rs +++ b/src/librustc/ty/context.rs @@ -802,8 +802,6 @@ pub struct GlobalCtxt<'tcx> { /// Export map produced by name resolution. export_map: FxHashMap>>, - named_region_map: NamedRegionMap, - pub hir: hir_map::Map<'tcx>, /// A map from DefPathHash -> DefId. Includes DefIds from the local crate @@ -986,7 +984,6 @@ impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'tcx> { arenas: &'tcx GlobalArenas<'tcx>, arena: &'tcx DroplessArena, resolutions: ty::Resolutions, - named_region_map: resolve_lifetime::NamedRegionMap, hir: hir_map::Map<'tcx>, on_disk_query_result_cache: maps::OnDiskCache<'tcx>, crate_name: &str, @@ -1044,27 +1041,6 @@ impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'tcx> { .insert(hir_id.local_id, Rc::new(StableVec::new(v))); } - let mut defs = FxHashMap(); - for (k, v) in named_region_map.defs { - let hir_id = hir.node_to_hir_id(k); - let map = defs.entry(hir_id.owner) - .or_insert_with(|| Rc::new(FxHashMap())); - Rc::get_mut(map).unwrap().insert(hir_id.local_id, v); - } - let mut late_bound = FxHashMap(); - for k in named_region_map.late_bound { - let hir_id = hir.node_to_hir_id(k); - let map = late_bound.entry(hir_id.owner) - .or_insert_with(|| Rc::new(FxHashSet())); - Rc::get_mut(map).unwrap().insert(hir_id.local_id); - } - let mut object_lifetime_defaults = FxHashMap(); - for (k, v) in named_region_map.object_lifetime_defaults { - let hir_id = hir.node_to_hir_id(k); - let map = object_lifetime_defaults.entry(hir_id.owner) - .or_insert_with(|| Rc::new(FxHashMap())); - Rc::get_mut(map).unwrap().insert(hir_id.local_id, Rc::new(v)); - } tls::enter_global(GlobalCtxt { sess: s, @@ -1074,11 +1050,6 @@ impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'tcx> { dep_graph: dep_graph.clone(), on_disk_query_result_cache, types: common_types, - named_region_map: NamedRegionMap { - defs, - late_bound, - object_lifetime_defaults, - }, trait_map, export_map: resolutions.export_map.into_iter().map(|(k, v)| { (k, Rc::new(v)) @@ -2176,27 +2147,12 @@ impl InternIteratorElement for Result { } } -struct NamedRegionMap { - defs: FxHashMap>>, - late_bound: FxHashMap>>, - object_lifetime_defaults: - FxHashMap< - DefIndex, - Rc>>>, - >, -} - pub fn provide(providers: &mut ty::maps::Providers) { // FIXME(#44234) - almost all of these queries have no sub-queries and // therefore no actual inputs, they're just reading tables calculated in // resolve! Does this work? Unsure! That's what the issue is about providers.in_scope_traits_map = |tcx, id| tcx.gcx.trait_map.get(&id).cloned(); providers.module_exports = |tcx, id| tcx.gcx.export_map.get(&id).cloned(); - providers.named_region_map = |tcx, id| tcx.gcx.named_region_map.defs.get(&id).cloned(); - providers.is_late_bound_map = |tcx, id| tcx.gcx.named_region_map.late_bound.get(&id).cloned(); - providers.object_lifetime_defaults_map = |tcx, id| { - tcx.gcx.named_region_map.object_lifetime_defaults.get(&id).cloned() - }; providers.crate_name = |tcx, id| { assert_eq!(id, LOCAL_CRATE); tcx.crate_name diff --git a/src/librustc/ty/maps/config.rs b/src/librustc/ty/maps/config.rs index 2d0a3799178a5..a556861147e39 100644 --- a/src/librustc/ty/maps/config.rs +++ b/src/librustc/ty/maps/config.rs @@ -443,6 +443,12 @@ impl<'tcx> QueryDescription<'tcx> for queries::link_args<'tcx> { } } +impl<'tcx> QueryDescription<'tcx> for queries::resolve_lifetimes<'tcx> { + fn describe(_tcx: TyCtxt, _: CrateNum) -> String { + format!("resolving lifetimes") + } +} + impl<'tcx> QueryDescription<'tcx> for queries::named_region_map<'tcx> { fn describe(_tcx: TyCtxt, _: DefIndex) -> String { format!("looking up a named region") diff --git a/src/librustc/ty/maps/mod.rs b/src/librustc/ty/maps/mod.rs index 848d2a0a7def7..7ba063adff4c2 100644 --- a/src/librustc/ty/maps/mod.rs +++ b/src/librustc/ty/maps/mod.rs @@ -23,7 +23,7 @@ use middle::cstore::{NativeLibraryKind, DepKind, CrateSource, ExternConstBody}; use middle::privacy::AccessLevels; use middle::reachable::ReachableSet; use middle::region; -use middle::resolve_lifetime::{Region, ObjectLifetimeDefault}; +use middle::resolve_lifetime::{ResolveLifetimes, Region, ObjectLifetimeDefault}; use middle::stability::{self, DeprecationEntry}; use middle::lang_items::{LanguageItems, LangItem}; use middle::exported_symbols::SymbolExportLevel; @@ -306,6 +306,8 @@ define_maps! { <'tcx> -> Option, [] fn link_args: link_args_node(CrateNum) -> Rc>, + // Lifetime resolution. See `middle::resolve_lifetimes`. + [] fn resolve_lifetimes: ResolveLifetimes(CrateNum) -> Rc, [] fn named_region_map: NamedRegion(DefIndex) -> Option>>, [] fn is_late_bound_map: IsLateBound(DefIndex) -> diff --git a/src/librustc/ty/maps/plumbing.rs b/src/librustc/ty/maps/plumbing.rs index ec6d190b8bde9..8875439be6b3d 100644 --- a/src/librustc/ty/maps/plumbing.rs +++ b/src/librustc/ty/maps/plumbing.rs @@ -875,6 +875,7 @@ pub fn force_from_dep_node<'a, 'gcx, 'lcx>(tcx: TyCtxt<'a, 'gcx, 'lcx>, DepKind::NativeLibraryKind => { force!(native_library_kind, def_id!()); } DepKind::LinkArgs => { force!(link_args, LOCAL_CRATE); } + DepKind::ResolveLifetimes => { force!(resolve_lifetimes, krate!()); } DepKind::NamedRegion => { force!(named_region_map, def_id!().index); } DepKind::IsLateBound => { force!(is_late_bound_map, def_id!().index); } DepKind::ObjectLifetimeDefaults => { diff --git a/src/librustc_driver/driver.rs b/src/librustc_driver/driver.rs index b0f61e9a19177..86b05955f1972 100644 --- a/src/librustc_driver/driver.rs +++ b/src/librustc_driver/driver.rs @@ -19,7 +19,7 @@ use rustc::session::CompileIncomplete; use rustc::session::config::{self, Input, OutputFilenames, OutputType}; use rustc::session::search_paths::PathKind; use rustc::lint; -use rustc::middle::{self, stability, reachable}; +use rustc::middle::{self, stability, reachable, resolve_lifetime}; use rustc::middle::cstore::CrateStore; use rustc::middle::privacy::AccessLevels; use rustc::ty::{self, TyCtxt, Resolutions, GlobalArenas}; @@ -928,6 +928,7 @@ pub fn default_provide(providers: &mut ty::maps::Providers) { borrowck::provide(providers); mir::provide(providers); reachable::provide(providers); + resolve_lifetime::provide(providers); rustc_privacy::provide(providers); DefaultTransCrate::provide(providers); typeck::provide(providers); @@ -984,10 +985,6 @@ pub fn phase_3_run_analysis_passes<'tcx, F, R>(control: &CompileController, "load query result cache", || rustc_incremental::load_query_result_cache(sess)); - let named_region_map = time(time_passes, - "lifetime resolution", - || middle::resolve_lifetime::krate(sess, cstore, &hir_map))?; - time(time_passes, "looking for entry point", || middle::entry::find_entry_point(sess, &hir_map)); @@ -1022,7 +1019,6 @@ pub fn phase_3_run_analysis_passes<'tcx, F, R>(control: &CompileController, arenas, arena, resolutions, - named_region_map, hir_map, query_result_on_disk_cache, name, diff --git a/src/librustc_driver/test.rs b/src/librustc_driver/test.rs index 0818b929ee7ad..2f55bee210838 100644 --- a/src/librustc_driver/test.rs +++ b/src/librustc_driver/test.rs @@ -18,7 +18,6 @@ use rustc_lint; use rustc_resolve::MakeGlobMap; use rustc_trans; use rustc::middle::region; -use rustc::middle::resolve_lifetime; use rustc::ty::subst::{Kind, Subst}; use rustc::traits::{ObligationCause, Reveal}; use rustc::ty::{self, Ty, TyCtxt, TypeFoldable}; @@ -137,7 +136,6 @@ fn test_env(source_string: &str, let hir_map = hir_map::map_crate(&sess, &*cstore, &mut hir_forest, &defs); // run just enough stuff to build a tcx: - let named_region_map = resolve_lifetime::krate(&sess, &*cstore, &hir_map); let (tx, _rx) = mpsc::channel(); let outputs = OutputFilenames { out_directory: PathBuf::new(), @@ -153,7 +151,6 @@ fn test_env(source_string: &str, &arenas, &arena, resolutions, - named_region_map.unwrap(), hir_map, OnDiskCache::new_empty(sess.codemap()), "test_crate", diff --git a/src/librustc_typeck/astconv.rs b/src/librustc_typeck/astconv.rs index e20706a0d5abb..83aec27c15315 100644 --- a/src/librustc_typeck/astconv.rs +++ b/src/librustc_typeck/astconv.rs @@ -140,7 +140,18 @@ impl<'o, 'gcx: 'tcx, 'tcx> AstConv<'gcx, 'tcx>+'o { } None => { - self.re_infer(lifetime.span, def).expect("unelided lifetime in signature") + self.re_infer(lifetime.span, def) + .unwrap_or_else(|| { + // This indicates an illegal lifetime + // elision. `resolve_lifetime` should have + // reported an error in this case -- but if + // not, let's error out. + tcx.sess.delay_span_bug(lifetime.span, "unelided lifetime in signature"); + + // Supply some dummy value. We don't have an + // `re_error`, annoyingly, so use `'static`. + tcx.types.re_static + }) } }; diff --git a/src/test/compile-fail/dep_graph_crosscontaminate_tables.rs b/src/test/compile-fail/dep_graph_crosscontaminate_tables.rs deleted file mode 100644 index 2520e3a095e1d..0000000000000 --- a/src/test/compile-fail/dep_graph_crosscontaminate_tables.rs +++ /dev/null @@ -1,40 +0,0 @@ -// Copyright 2016 The Rust Project Developers. See the COPYRIGHT -// file at the top-level directory of this distribution and at -// http://rust-lang.org/COPYRIGHT. -// -// Licensed under the Apache License, Version 2.0 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -// Test that the `TypeckTables` nodes for impl items are independent from -// one another. - -// compile-flags: -Z query-dep-graph - -#![feature(rustc_attrs)] - -struct Foo { - x: u8 -} - -impl Foo { - // Changing the item `new`... - #[rustc_if_this_changed(HirBody)] - fn new() -> Foo { - Foo { x: 0 } - } - - // ...should not cause us to recompute the tables for `with`! - #[rustc_then_this_would_need(TypeckTables)] //~ ERROR no path - fn with(x: u8) -> Foo { - Foo { x: x } - } -} - -fn main() { - let f = Foo::new(); - let g = Foo::with(22); - assert_eq!(f.x, g.x - 22); -} diff --git a/src/test/compile-fail/where-lifetime-resolution.rs b/src/test/compile-fail/where-lifetime-resolution.rs index f4c6842206db1..1204cc0df47b1 100644 --- a/src/test/compile-fail/where-lifetime-resolution.rs +++ b/src/test/compile-fail/where-lifetime-resolution.rs @@ -8,8 +8,8 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -trait Trait1 {} -trait Trait2 {} +trait Trait1<'a> {} +trait Trait2<'a, 'b> {} fn f() where for<'a> Trait1<'a>: Trait1<'a>, // OK diff --git a/src/test/incremental/issue-42602.rs b/src/test/incremental/issue-42602.rs index cb2236d375032..6afd794de8484 100644 --- a/src/test/incremental/issue-42602.rs +++ b/src/test/incremental/issue-42602.rs @@ -16,8 +16,9 @@ // This was fixed by improving the resolution of the `FnOnce` trait // selection node. -// revisions:cfail1 +// revisions:cfail1 cfail2 cfail3 // compile-flags:-Zquery-dep-graph +// must-compile-successfully #![feature(rustc_attrs)] @@ -27,16 +28,24 @@ fn main() { } mod a { - #[rustc_if_this_changed(HirBody)] + #[cfg(cfail1)] pub fn foo() { let x = vec![1, 2, 3]; let v = || ::std::mem::drop(x); v(); } + + #[cfg(not(cfail1))] + pub fn foo() { + let x = vec![1, 2, 3, 4]; + let v = || ::std::mem::drop(x); + v(); + } } mod b { - #[rustc_then_this_would_need(TypeckTables)] //[cfail1]~ ERROR no path + #[rustc_clean(cfg="cfail2")] + #[rustc_clean(cfg="cfail3")] pub fn bar() { let x = vec![1, 2, 3]; let v = || ::std::mem::drop(x); diff --git a/src/test/ui/print_type_sizes/anonymous.stderr b/src/test/ui/print_type_sizes/anonymous.stderr new file mode 100644 index 0000000000000..e69de29bb2d1d diff --git a/src/test/ui/print_type_sizes/anonymous.stdout b/src/test/ui/print_type_sizes/anonymous.stdout new file mode 100644 index 0000000000000..e69de29bb2d1d diff --git a/src/test/ui/print_type_sizes/multiple_types.stderr b/src/test/ui/print_type_sizes/multiple_types.stderr new file mode 100644 index 0000000000000..e69de29bb2d1d diff --git a/src/test/ui/print_type_sizes/packed.stderr b/src/test/ui/print_type_sizes/packed.stderr new file mode 100644 index 0000000000000..e69de29bb2d1d diff --git a/src/test/ui/print_type_sizes/repr-align.stderr b/src/test/ui/print_type_sizes/repr-align.stderr new file mode 100644 index 0000000000000..e69de29bb2d1d diff --git a/src/test/ui/rfc1598-generic-associated-types/construct_with_other_type.rs b/src/test/ui/rfc1598-generic-associated-types/construct_with_other_type.rs index 87a0b33e63b5e..208fc2ea08957 100644 --- a/src/test/ui/rfc1598-generic-associated-types/construct_with_other_type.rs +++ b/src/test/ui/rfc1598-generic-associated-types/construct_with_other_type.rs @@ -23,6 +23,7 @@ trait Baz { impl Baz for T where T: Foo { type Quux<'a> = ::Bar<'a, 'static>; //~^ ERROR undeclared lifetime + //~| ERROR lifetime parameters are not allowed on this type [E0110] } fn main() {} diff --git a/src/test/ui/rfc1598-generic-associated-types/construct_with_other_type.stderr b/src/test/ui/rfc1598-generic-associated-types/construct_with_other_type.stderr index 3c3c5d1262781..6a2047d10e6a5 100644 --- a/src/test/ui/rfc1598-generic-associated-types/construct_with_other_type.stderr +++ b/src/test/ui/rfc1598-generic-associated-types/construct_with_other_type.stderr @@ -4,5 +4,11 @@ error[E0261]: use of undeclared lifetime name `'a` 24 | type Quux<'a> = ::Bar<'a, 'static>; | ^^ undeclared lifetime -error: aborting due to previous error +error[E0110]: lifetime parameters are not allowed on this type + --> $DIR/construct_with_other_type.rs:24:37 + | +24 | type Quux<'a> = ::Bar<'a, 'static>; + | ^^ lifetime parameter not allowed on this type + +error: aborting due to 2 previous errors diff --git a/src/test/ui/rfc1598-generic-associated-types/generic-associated-types-where.stderr b/src/test/ui/rfc1598-generic-associated-types/generic-associated-types-where.stderr index e65da028b23b5..b99cb2a18309e 100644 --- a/src/test/ui/rfc1598-generic-associated-types/generic-associated-types-where.stderr +++ b/src/test/ui/rfc1598-generic-associated-types/generic-associated-types-where.stderr @@ -4,5 +4,5 @@ error[E0261]: use of undeclared lifetime name `'a` 34 | type WithDefault<'a, T> = &'a Iterator; | ^^ undeclared lifetime -error: aborting due to previous error +error: cannot continue compilation due to previous error diff --git a/src/test/ui/rfc1598-generic-associated-types/iterable.rs b/src/test/ui/rfc1598-generic-associated-types/iterable.rs index 0019c4be5e8e0..219554b587a9e 100644 --- a/src/test/ui/rfc1598-generic-associated-types/iterable.rs +++ b/src/test/ui/rfc1598-generic-associated-types/iterable.rs @@ -16,8 +16,10 @@ trait Iterable { type Item<'a>; type Iter<'a>: Iterator>; //~^ ERROR undeclared lifetime + //~| ERROR lifetime parameters are not allowed on this type [E0110] fn iter<'a>(&'a self) -> Self::Iter<'a>; + //~^ ERROR lifetime parameters are not allowed on this type [E0110] } fn main() {} diff --git a/src/test/ui/rfc1598-generic-associated-types/iterable.stderr b/src/test/ui/rfc1598-generic-associated-types/iterable.stderr index 0e565047afe63..fb91d38ba7a14 100644 --- a/src/test/ui/rfc1598-generic-associated-types/iterable.stderr +++ b/src/test/ui/rfc1598-generic-associated-types/iterable.stderr @@ -4,5 +4,17 @@ error[E0261]: use of undeclared lifetime name `'a` 17 | type Iter<'a>: Iterator>; | ^^ undeclared lifetime -error: aborting due to previous error +error[E0110]: lifetime parameters are not allowed on this type + --> $DIR/iterable.rs:17:47 + | +17 | type Iter<'a>: Iterator>; + | ^^ lifetime parameter not allowed on this type + +error[E0110]: lifetime parameters are not allowed on this type + --> $DIR/iterable.rs:21:41 + | +21 | fn iter<'a>(&'a self) -> Self::Iter<'a>; + | ^^ lifetime parameter not allowed on this type + +error: aborting due to 3 previous errors From fdbd9b0dd5cd6cec755bb7bfe688d78cab3d3e83 Mon Sep 17 00:00:00 2001 From: Niko Matsakis Date: Mon, 11 Dec 2017 15:52:46 -0500 Subject: [PATCH 3/3] make `krate` infallible --- src/librustc/middle/resolve_lifetime.rs | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/src/librustc/middle/resolve_lifetime.rs b/src/librustc/middle/resolve_lifetime.rs index 89df212938a42..bafd1e8e6cc5d 100644 --- a/src/librustc/middle/resolve_lifetime.rs +++ b/src/librustc/middle/resolve_lifetime.rs @@ -29,7 +29,6 @@ use syntax::attr; use syntax::ptr::P; use syntax_pos::Span; use errors::DiagnosticBuilder; -use util::common::ErrorReported; use util::nodemap::{DefIdMap, FxHashMap, FxHashSet, NodeMap, NodeSet}; use std::slice; @@ -357,7 +356,7 @@ fn resolve_lifetimes<'tcx>( ) -> Rc { assert_eq!(for_krate, LOCAL_CRATE); - let named_region_map = krate(tcx).unwrap_or_default(); + let named_region_map = krate(tcx); let mut defs = FxHashMap(); for (k, v) in named_region_map.defs { @@ -392,7 +391,7 @@ fn resolve_lifetimes<'tcx>( }) } -fn krate<'tcx>(tcx: TyCtxt<'_, 'tcx, 'tcx>) -> Result { +fn krate<'tcx>(tcx: TyCtxt<'_, 'tcx, 'tcx>) -> NamedRegionMap { let krate = tcx.hir.krate(); let mut map = NamedRegionMap { defs: NodeMap(), @@ -413,7 +412,7 @@ fn krate<'tcx>(tcx: TyCtxt<'_, 'tcx, 'tcx>) -> Result Visitor<'tcx> for LifetimeContext<'a, 'tcx> {