From 588e6e969eeb61460fdd6132f9f50295ec246b44 Mon Sep 17 00:00:00 2001 From: JoshBrudnak Date: Sun, 19 Aug 2018 12:34:21 -0400 Subject: [PATCH 1/3] Formatted collect.rs with rustfmt --- src/librustc_typeck/collect.rs | 1412 ++++++++++++++++++-------------- 1 file changed, 799 insertions(+), 613 deletions(-) diff --git a/src/librustc_typeck/collect.rs b/src/librustc_typeck/collect.rs index 956d542ab7d..44a1960ea18 100644 --- a/src/librustc_typeck/collect.rs +++ b/src/librustc_typeck/collect.rs @@ -25,17 +25,17 @@ //! crate as a kind of pass. This should eventually be factored away. use astconv::{AstConv, Bounds}; -use lint; use constrained_type_params as ctp; +use lint; use middle::lang_items::SizedTraitLangItem; use middle::resolve_lifetime as rl; use rustc::mir::mono::Linkage; -use rustc::ty::subst::Substs; -use rustc::ty::{ToPredicate, ReprOptions}; -use rustc::ty::{self, AdtKind, ToPolyTraitRef, Ty, TyCtxt}; use rustc::ty::query::Providers; -use rustc::ty::util::IntTypeExt; +use rustc::ty::subst::Substs; use rustc::ty::util::Discr; +use rustc::ty::util::IntTypeExt; +use rustc::ty::{self, AdtKind, ToPolyTraitRef, Ty, TyCtxt}; +use rustc::ty::{ReprOptions, ToPredicate}; use rustc::util::captures::Captures; use rustc::util::nodemap::FxHashMap; use rustc_target::spec::abi; @@ -44,22 +44,24 @@ use syntax::ast; use syntax::ast::MetaItemKind; use syntax::attr::{InlineAttr, list_contains_name, mark_used}; use syntax::source_map::Spanned; -use syntax::symbol::{Symbol, keywords}; use syntax::feature_gate; +use syntax::symbol::{keywords, Symbol}; use syntax_pos::{Span, DUMMY_SP}; -use rustc::hir::{self, map as hir_map, CodegenFnAttrs, CodegenFnAttrFlags, Unsafety}; -use rustc::hir::GenericParamKind; -use rustc::hir::intravisit::{self, Visitor, NestedVisitorMap}; -use rustc::hir::def::{Def, CtorKind}; +use rustc::hir::def::{CtorKind, Def}; use rustc::hir::def_id::{DefId, LOCAL_CRATE}; +use rustc::hir::intravisit::{self, NestedVisitorMap, Visitor}; +use rustc::hir::GenericParamKind; +use rustc::hir::{self, map as hir_map, CodegenFnAttrFlags, CodegenFnAttrs, Unsafety}; /////////////////////////////////////////////////////////////////////////// // Main entry point pub fn collect_item_types<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>) { let mut visitor = CollectItemTypesVisitor { tcx: tcx }; - tcx.hir.krate().visit_all_item_likes(&mut visitor.as_deep_visitor()); + tcx.hir + .krate() + .visit_all_item_likes(&mut visitor.as_deep_visitor()); } pub fn provide(providers: &mut Providers) { @@ -93,7 +95,7 @@ pub fn provide(providers: &mut Providers) { /// `ItemCtxt` is parameterized by a `DefId` that it uses to satisfy /// `get_type_parameter_bounds` requests, drawing the information from /// the AST (`hir::Generics`), recursively. -pub struct ItemCtxt<'a,'tcx:'a> { +pub struct ItemCtxt<'a, 'tcx: 'a> { tcx: TyCtxt<'a, 'tcx, 'tcx>, item_def_id: DefId, } @@ -101,7 +103,7 @@ pub struct ItemCtxt<'a,'tcx:'a> { /////////////////////////////////////////////////////////////////////////// struct CollectItemTypesVisitor<'a, 'tcx: 'a> { - tcx: TyCtxt<'a, 'tcx, 'tcx> + tcx: TyCtxt<'a, 'tcx, 'tcx>, } impl<'a, 'tcx> Visitor<'tcx> for CollectItemTypesVisitor<'a, 'tcx> { @@ -118,7 +120,9 @@ impl<'a, 'tcx> Visitor<'tcx> for CollectItemTypesVisitor<'a, 'tcx> { for param in &generics.params { match param.kind { hir::GenericParamKind::Lifetime { .. } => {} - hir::GenericParamKind::Type { default: Some(_), .. } => { + hir::GenericParamKind::Type { + default: Some(_), .. + } => { let def_id = self.tcx.hir.local_def_id(param.id); self.tcx.type_of(def_id); } @@ -152,34 +156,33 @@ impl<'a, 'tcx> Visitor<'tcx> for CollectItemTypesVisitor<'a, 'tcx> { // Utility types and common code for the above passes. impl<'a, 'tcx> ItemCtxt<'a, 'tcx> { - pub fn new(tcx: TyCtxt<'a, 'tcx, 'tcx>, item_def_id: DefId) - -> ItemCtxt<'a,'tcx> { - ItemCtxt { - tcx, - item_def_id, - } + pub fn new(tcx: TyCtxt<'a, 'tcx, 'tcx>, item_def_id: DefId) -> ItemCtxt<'a, 'tcx> { + ItemCtxt { tcx, item_def_id } } } -impl<'a,'tcx> ItemCtxt<'a,'tcx> { +impl<'a, 'tcx> ItemCtxt<'a, 'tcx> { pub fn to_ty(&self, ast_ty: &hir::Ty) -> Ty<'tcx> { AstConv::ast_ty_to_ty(self, ast_ty) } } impl<'a, 'tcx> AstConv<'tcx, 'tcx> for ItemCtxt<'a, 'tcx> { - fn tcx<'b>(&'b self) -> TyCtxt<'b, 'tcx, 'tcx> { self.tcx } - - fn get_type_parameter_bounds(&self, - span: Span, - def_id: DefId) - -> ty::GenericPredicates<'tcx> - { - self.tcx.at(span).type_param_predicates((self.item_def_id, def_id)) + fn tcx<'b>(&'b self) -> TyCtxt<'b, 'tcx, 'tcx> { + self.tcx } - fn re_infer(&self, _span: Span, _def: Option<&ty::GenericParamDef>) - -> Option> { + fn get_type_parameter_bounds(&self, span: Span, def_id: DefId) -> ty::GenericPredicates<'tcx> { + self.tcx + .at(span) + .type_param_predicates((self.item_def_id, def_id)) + } + + fn re_infer( + &self, + _span: Span, + _def: Option<&ty::GenericParamDef>, + ) -> Option> { None } @@ -190,23 +193,27 @@ impl<'a, 'tcx> AstConv<'tcx, 'tcx> for ItemCtxt<'a, 'tcx> { E0121, "the type placeholder `_` is not allowed within types on item signatures" ).span_label(span, "not allowed in type signatures") - .emit(); + .emit(); self.tcx().types.err } - fn projected_ty_from_poly_trait_ref(&self, - span: Span, - item_def_id: DefId, - poly_trait_ref: ty::PolyTraitRef<'tcx>) - -> Ty<'tcx> - { + fn projected_ty_from_poly_trait_ref( + &self, + span: Span, + item_def_id: DefId, + poly_trait_ref: ty::PolyTraitRef<'tcx>, + ) -> Ty<'tcx> { if let Some(trait_ref) = poly_trait_ref.no_late_bound_regions() { self.tcx().mk_projection(item_def_id, trait_ref.substs) } else { // no late-bound regions, we can just ignore the binder - span_err!(self.tcx().sess, span, E0212, + span_err!( + self.tcx().sess, + span, + E0212, "cannot extract an associated type from a higher-ranked trait bound \ - in this context"); + in this context" + ); self.tcx().types.err } } @@ -226,9 +233,10 @@ impl<'a, 'tcx> AstConv<'tcx, 'tcx> for ItemCtxt<'a, 'tcx> { } } -fn type_param_predicates<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, - (item_def_id, def_id): (DefId, DefId)) - -> ty::GenericPredicates<'tcx> { +fn type_param_predicates<'a, 'tcx>( + tcx: TyCtxt<'a, 'tcx, 'tcx>, + (item_def_id, def_id): (DefId, DefId), +) -> ty::GenericPredicates<'tcx> { use rustc::hir::map::*; use rustc::hir::*; @@ -250,13 +258,16 @@ fn type_param_predicates<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, tcx.generics_of(item_def_id).parent }; - let mut result = parent.map_or(ty::GenericPredicates { - parent: None, - predicates: vec![] - }, |parent| { - let icx = ItemCtxt::new(tcx, parent); - icx.get_type_parameter_bounds(DUMMY_SP, def_id) - }); + let mut result = parent.map_or( + ty::GenericPredicates { + parent: None, + predicates: vec![], + }, + |parent| { + let icx = ItemCtxt::new(tcx, parent); + icx.get_type_parameter_bounds(DUMMY_SP, def_id) + }, + ); let item_node_id = tcx.hir.as_local_node_id(item_def_id).unwrap(); let ast_generics = match tcx.hir.get(item_node_id) { @@ -266,39 +277,42 @@ fn type_param_predicates<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, NodeItem(item) => { match item.node { - ItemKind::Fn(.., ref generics, _) | - ItemKind::Impl(_, _, _, ref generics, ..) | - ItemKind::Ty(_, ref generics) | - ItemKind::Existential(ExistTy { ref generics, impl_trait_fn: None, ..}) | - ItemKind::Enum(_, ref generics) | - ItemKind::Struct(_, ref generics) | - ItemKind::Union(_, ref generics) => generics, + ItemKind::Fn(.., ref generics, _) + | ItemKind::Impl(_, _, _, ref generics, ..) + | ItemKind::Ty(_, ref generics) + | ItemKind::Existential(ExistTy { + ref generics, + impl_trait_fn: None, + .. + }) + | ItemKind::Enum(_, ref generics) + | ItemKind::Struct(_, ref generics) + | ItemKind::Union(_, ref generics) => generics, ItemKind::Trait(_, _, ref generics, ..) => { // Implied `Self: Trait` and supertrait bounds. if param_id == item_node_id { - result.predicates.push( - ty::TraitRef::identity(tcx, item_def_id).to_predicate() - ); + result + .predicates + .push(ty::TraitRef::identity(tcx, item_def_id).to_predicate()); } generics } - _ => return result + _ => return result, } } - NodeForeignItem(item) => { - match item.node { - ForeignItemKind::Fn(_, _, ref generics) => generics, - _ => return result - } - } + NodeForeignItem(item) => match item.node { + ForeignItemKind::Fn(_, _, ref generics) => generics, + _ => return result, + }, - _ => return result + _ => return result, }; let icx = ItemCtxt::new(tcx, item_def_id); - result.predicates.extend( - icx.type_parameter_bounds_in_generics(ast_generics, param_id, ty)); + result + .predicates + .extend(icx.type_parameter_bounds_in_generics(ast_generics, param_id, ty)); result } @@ -307,32 +321,33 @@ impl<'a, 'tcx> ItemCtxt<'a, 'tcx> { /// AST. We do this to avoid having to convert *all* the bounds, which /// would create artificial cycles. Instead we can only convert the /// bounds for a type parameter `X` if `X::Foo` is used. - fn type_parameter_bounds_in_generics(&self, - ast_generics: &hir::Generics, - param_id: ast::NodeId, - ty: Ty<'tcx>) - -> Vec> - { - let from_ty_params = - ast_generics.params.iter() - .filter_map(|param| match param.kind { - GenericParamKind::Type { .. } if param.id == param_id => Some(¶m.bounds), - _ => None - }) - .flat_map(|bounds| bounds.iter()) - .flat_map(|b| predicates_from_bound(self, ty, b)); + fn type_parameter_bounds_in_generics( + &self, + ast_generics: &hir::Generics, + param_id: ast::NodeId, + ty: Ty<'tcx>, + ) -> Vec> { + let from_ty_params = ast_generics + .params + .iter() + .filter_map(|param| match param.kind { + GenericParamKind::Type { .. } if param.id == param_id => Some(¶m.bounds), + _ => None, + }) + .flat_map(|bounds| bounds.iter()) + .flat_map(|b| predicates_from_bound(self, ty, b)); - let from_where_clauses = - ast_generics.where_clause - .predicates - .iter() - .filter_map(|wp| match *wp { - hir::WherePredicate::BoundPredicate(ref bp) => Some(bp), - _ => None - }) - .filter(|bp| is_param(self.tcx, &bp.bounded_ty, param_id)) - .flat_map(|bp| bp.bounds.iter()) - .flat_map(|b| predicates_from_bound(self, ty, b)); + let from_where_clauses = ast_generics + .where_clause + .predicates + .iter() + .filter_map(|wp| match *wp { + hir::WherePredicate::BoundPredicate(ref bp) => Some(bp), + _ => None, + }) + .filter(|bp| is_param(self.tcx, &bp.bounded_ty, param_id)) + .flat_map(|bp| bp.bounds.iter()) + .flat_map(|b| predicates_from_bound(self, ty, b)); from_ty_params.chain(from_where_clauses).collect() } @@ -342,18 +357,17 @@ impl<'a, 'tcx> ItemCtxt<'a, 'tcx> { /// parameter with id `param_id`. We use this so as to avoid running /// `ast_ty_to_ty`, because we want to avoid triggering an all-out /// conversion of the type to avoid inducing unnecessary cycles. -fn is_param<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, - ast_ty: &hir::Ty, - param_id: ast::NodeId) - -> bool -{ +fn is_param<'a, 'tcx>( + tcx: TyCtxt<'a, 'tcx, 'tcx>, + ast_ty: &hir::Ty, + param_id: ast::NodeId, +) -> bool { if let hir::TyKind::Path(hir::QPath::Resolved(None, ref path)) = ast_ty.node { match path.def { - Def::SelfTy(Some(def_id), None) | - Def::TyParam(def_id) => { + Def::SelfTy(Some(def_id), None) | Def::TyParam(def_id) => { def_id == tcx.hir.local_def_id(param_id) } - _ => false + _ => false, } } else { false @@ -366,10 +380,10 @@ fn convert_item<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, item_id: ast::NodeId) { let def_id = tcx.hir.local_def_id(item_id); match it.node { // These don't define types. - hir::ItemKind::ExternCrate(_) | - hir::ItemKind::Use(..) | - hir::ItemKind::Mod(_) | - hir::ItemKind::GlobalAsm(_) => {} + hir::ItemKind::ExternCrate(_) + | hir::ItemKind::Use(..) + | hir::ItemKind::Mod(_) + | hir::ItemKind::GlobalAsm(_) => {} hir::ItemKind::ForeignMod(ref foreign_mod) => { for item in &foreign_mod.items { let def_id = tcx.hir.local_def_id(item.id); @@ -386,25 +400,28 @@ fn convert_item<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, item_id: ast::NodeId) { tcx.type_of(def_id); tcx.predicates_of(def_id); convert_enum_variant_types(tcx, def_id, &enum_definition.variants); - }, + } hir::ItemKind::Impl(..) => { tcx.generics_of(def_id); tcx.type_of(def_id); tcx.impl_trait_ref(def_id); tcx.predicates_of(def_id); - }, + } hir::ItemKind::Trait(..) => { tcx.generics_of(def_id); tcx.trait_def(def_id); tcx.at(it.span).super_predicates_of(def_id); tcx.predicates_of(def_id); - }, + } hir::ItemKind::TraitAlias(..) => { - span_err!(tcx.sess, it.span, E0645, - "trait aliases are not yet implemented (see issue #41517)"); - }, - hir::ItemKind::Struct(ref struct_def, _) | - hir::ItemKind::Union(ref struct_def, _) => { + span_err!( + tcx.sess, + it.span, + E0645, + "trait aliases are not yet implemented (see issue #41517)" + ); + } + hir::ItemKind::Struct(ref struct_def, _) | hir::ItemKind::Union(ref struct_def, _) => { tcx.generics_of(def_id); tcx.type_of(def_id); tcx.predicates_of(def_id); @@ -419,16 +436,19 @@ fn convert_item<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, item_id: ast::NodeId) { if !struct_def.is_struct() { convert_variant_ctor(tcx, struct_def.id()); } - }, + } // Desugared from `impl Trait` -> visited by the function's return type - hir::ItemKind::Existential(hir::ExistTy { impl_trait_fn: Some(_), .. }) => {} + hir::ItemKind::Existential(hir::ExistTy { + impl_trait_fn: Some(_), + .. + }) => {} - hir::ItemKind::Existential(..) | - hir::ItemKind::Ty(..) | - hir::ItemKind::Static(..) | - hir::ItemKind::Const(..) | - hir::ItemKind::Fn(..) => { + hir::ItemKind::Existential(..) + | hir::ItemKind::Ty(..) + | hir::ItemKind::Static(..) + | hir::ItemKind::Const(..) + | hir::ItemKind::Fn(..) => { tcx.generics_of(def_id); tcx.type_of(def_id); tcx.predicates_of(def_id); @@ -445,9 +465,9 @@ fn convert_trait_item<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, trait_item_id: ast: tcx.generics_of(def_id); match trait_item.node { - hir::TraitItemKind::Const(..) | - hir::TraitItemKind::Type(_, Some(_)) | - hir::TraitItemKind::Method(..) => { + hir::TraitItemKind::Const(..) + | hir::TraitItemKind::Type(_, Some(_)) + | hir::TraitItemKind::Method(..) => { tcx.type_of(def_id); if let hir::TraitItemKind::Method(..) = trait_item.node { tcx.fn_sig(def_id); @@ -470,17 +490,18 @@ fn convert_impl_item<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, impl_item_id: ast::N } } -fn convert_variant_ctor<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, - ctor_id: ast::NodeId) { +fn convert_variant_ctor<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, ctor_id: ast::NodeId) { let def_id = tcx.hir.local_def_id(ctor_id); tcx.generics_of(def_id); tcx.type_of(def_id); tcx.predicates_of(def_id); } -fn convert_enum_variant_types<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, - def_id: DefId, - variants: &[hir::Variant]) { +fn convert_enum_variant_types<'a, 'tcx>( + tcx: TyCtxt<'a, 'tcx, 'tcx>, + def_id: DefId, + variants: &[hir::Variant], +) { let def = tcx.adt_def(def_id); let repr_type = def.repr.discr_type(); let initial = repr_type.initial_discriminant(tcx); @@ -489,21 +510,30 @@ fn convert_enum_variant_types<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, // fill the discriminant values and field types for variant in variants { let wrapped_discr = prev_discr.map_or(initial, |d| d.wrap_incr(tcx)); - prev_discr = Some(if let Some(ref e) = variant.node.disr_expr { - let expr_did = tcx.hir.local_def_id(e.id); - def.eval_explicit_discr(tcx, expr_did) - } else if let Some(discr) = repr_type.disr_incr(tcx, prev_discr) { - Some(discr) - } else { - struct_span_err!(tcx.sess, variant.span, E0370, - "enum discriminant overflowed") - .span_label(variant.span, format!("overflowed on value after {}", - prev_discr.unwrap())) - .note(&format!("explicitly set `{} = {}` if that is desired outcome", - variant.node.name, wrapped_discr)) - .emit(); - None - }.unwrap_or(wrapped_discr)); + prev_discr = Some( + if let Some(ref e) = variant.node.disr_expr { + let expr_did = tcx.hir.local_def_id(e.id); + def.eval_explicit_discr(tcx, expr_did) + } else if let Some(discr) = repr_type.disr_incr(tcx, prev_discr) { + Some(discr) + } else { + struct_span_err!( + tcx.sess, + variant.span, + E0370, + "enum discriminant overflowed" + ).span_label( + variant.span, + format!("overflowed on value after {}", prev_discr.unwrap()), + ) + .note(&format!( + "explicitly set `{} = {}` if that is desired outcome", + variant.node.name, wrapped_discr + )) + .emit(); + None + }.unwrap_or(wrapped_discr), + ); for f in variant.node.data.fields() { let def_id = tcx.hir.local_def_id(f.id); @@ -518,34 +548,42 @@ fn convert_enum_variant_types<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, } } -fn convert_struct_variant<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, - did: DefId, - name: ast::Name, - discr: ty::VariantDiscr, - def: &hir::VariantData) - -> ty::VariantDef { +fn convert_struct_variant<'a, 'tcx>( + tcx: TyCtxt<'a, 'tcx, 'tcx>, + did: DefId, + name: ast::Name, + discr: ty::VariantDiscr, + def: &hir::VariantData, +) -> ty::VariantDef { let mut seen_fields: FxHashMap = FxHashMap(); let node_id = tcx.hir.as_local_node_id(did).unwrap(); - let fields = def.fields().iter().map(|f| { - let fid = tcx.hir.local_def_id(f.id); - let dup_span = seen_fields.get(&f.ident.modern()).cloned(); - if let Some(prev_span) = dup_span { - struct_span_err!(tcx.sess, f.span, E0124, - "field `{}` is already declared", - f.ident) - .span_label(f.span, "field already declared") - .span_label(prev_span, format!("`{}` first declared here", f.ident)) - .emit(); - } else { - seen_fields.insert(f.ident.modern(), f.span); - } + let fields = def + .fields() + .iter() + .map(|f| { + let fid = tcx.hir.local_def_id(f.id); + let dup_span = seen_fields.get(&f.ident.modern()).cloned(); + if let Some(prev_span) = dup_span { + struct_span_err!( + tcx.sess, + f.span, + E0124, + "field `{}` is already declared", + f.ident + ).span_label(f.span, "field already declared") + .span_label(prev_span, format!("`{}` first declared here", f.ident)) + .emit(); + } else { + seen_fields.insert(f.ident.modern(), f.span); + } - ty::FieldDef { - did: fid, - ident: f.ident, - vis: ty::Visibility::from_hir(&f.vis, node_id, tcx) - } - }).collect(); + ty::FieldDef { + did: fid, + ident: f.ident, + vis: ty::Visibility::from_hir(&f.vis, node_id, tcx), + } + }) + .collect(); ty::VariantDef { did, name, @@ -555,34 +593,38 @@ fn convert_struct_variant<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, } } -fn adt_def<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, - def_id: DefId) - -> &'tcx ty::AdtDef { +fn adt_def<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId) -> &'tcx ty::AdtDef { use rustc::hir::map::*; use rustc::hir::*; let node_id = tcx.hir.as_local_node_id(def_id).unwrap(); let item = match tcx.hir.get(node_id) { NodeItem(item) => item, - _ => bug!() + _ => bug!(), }; let repr = ReprOptions::new(tcx, def_id); let (kind, variants) = match item.node { ItemKind::Enum(ref def, _) => { let mut distance_from_explicit = 0; - (AdtKind::Enum, def.variants.iter().map(|v| { - let did = tcx.hir.local_def_id(v.node.data.id()); - let discr = if let Some(ref e) = v.node.disr_expr { - distance_from_explicit = 0; - ty::VariantDiscr::Explicit(tcx.hir.local_def_id(e.id)) - } else { - ty::VariantDiscr::Relative(distance_from_explicit) - }; - distance_from_explicit += 1; + ( + AdtKind::Enum, + def.variants + .iter() + .map(|v| { + let did = tcx.hir.local_def_id(v.node.data.id()); + let discr = if let Some(ref e) = v.node.disr_expr { + distance_from_explicit = 0; + ty::VariantDiscr::Explicit(tcx.hir.local_def_id(e.id)) + } else { + ty::VariantDiscr::Relative(distance_from_explicit) + }; + distance_from_explicit += 1; - convert_struct_variant(tcx, did, v.node.name, discr, &v.node.data) - }).collect()) + convert_struct_variant(tcx, did, v.node.name, discr, &v.node.data) + }) + .collect(), + ) } ItemKind::Struct(ref def, _) => { // Use separate constructor id for unit/tuple structs and reuse did for braced structs. @@ -591,18 +633,28 @@ fn adt_def<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, } else { None }; - (AdtKind::Struct, vec![ - convert_struct_variant(tcx, ctor_id.unwrap_or(def_id), item.name, - ty::VariantDiscr::Relative(0), def) - ]) + ( + AdtKind::Struct, + vec![convert_struct_variant( + tcx, + ctor_id.unwrap_or(def_id), + item.name, + ty::VariantDiscr::Relative(0), + def, + )], + ) } - ItemKind::Union(ref def, _) => { - (AdtKind::Union, vec![ - convert_struct_variant(tcx, def_id, item.name, - ty::VariantDiscr::Relative(0), def) - ]) - } - _ => bug!() + ItemKind::Union(ref def, _) => ( + AdtKind::Union, + vec![convert_struct_variant( + tcx, + def_id, + item.name, + ty::VariantDiscr::Relative(0), + def, + )], + ), + _ => bug!(), }; tcx.alloc_adt_def(def_id, kind, variants, repr) } @@ -610,33 +662,29 @@ fn adt_def<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, /// Ensures that the super-predicates of the trait with def-id /// trait_def_id are converted and stored. This also ensures that /// the transitive super-predicates are converted; -fn super_predicates_of<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, - trait_def_id: DefId) - -> ty::GenericPredicates<'tcx> { +fn super_predicates_of<'a, 'tcx>( + tcx: TyCtxt<'a, 'tcx, 'tcx>, + trait_def_id: DefId, +) -> ty::GenericPredicates<'tcx> { debug!("super_predicates(trait_def_id={:?})", trait_def_id); let trait_node_id = tcx.hir.as_local_node_id(trait_def_id).unwrap(); let item = match tcx.hir.get(trait_node_id) { hir_map::NodeItem(item) => item, - _ => bug!("trait_node_id {} is not an item", trait_node_id) + _ => bug!("trait_node_id {} is not an item", trait_node_id), }; let (generics, bounds) = match item.node { hir::ItemKind::Trait(.., ref generics, ref supertraits, _) => (generics, supertraits), hir::ItemKind::TraitAlias(ref generics, ref supertraits) => (generics, supertraits), - _ => span_bug!(item.span, - "super_predicates invoked on non-trait"), + _ => span_bug!(item.span, "super_predicates invoked on non-trait"), }; let icx = ItemCtxt::new(tcx, trait_def_id); // Convert the bounds that follow the colon, e.g. `Bar+Zed` in `trait Foo : Bar+Zed`. let self_param_ty = tcx.mk_self_type(); - let superbounds1 = compute_bounds(&icx, - self_param_ty, - bounds, - SizedByDefault::No, - item.span); + let superbounds1 = compute_bounds(&icx, self_param_ty, bounds, SizedByDefault::No, item.span); let superbounds1 = superbounds1.predicates(tcx, self_param_ty); @@ -655,13 +703,11 @@ fn super_predicates_of<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, ty::GenericPredicates { parent: None, - predicates: superbounds + predicates: superbounds, } } -fn trait_def<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, - def_id: DefId) - -> &'tcx ty::TraitDef { +fn trait_def<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId) -> &'tcx ty::TraitDef { let node_id = tcx.hir.as_local_node_id(def_id).unwrap(); let item = tcx.hir.expect_item(node_id); @@ -676,25 +722,25 @@ fn trait_def<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, let mut err = tcx.sess.struct_span_err( item.span, "the `#[rustc_paren_sugar]` attribute is a temporary means of controlling \ - which traits can use parenthetical notation"); - help!(&mut err, + which traits can use parenthetical notation", + ); + help!( + &mut err, "add `#![feature(unboxed_closures)]` to \ - the crate attributes to use it"); + the crate attributes to use it" + ); err.emit(); } let def_path_hash = tcx.def_path_hash(def_id); - let def = ty::TraitDef::new(def_id, - unsafety, - paren_sugar, - is_auto, - def_path_hash); + let def = ty::TraitDef::new(def_id, unsafety, paren_sugar, is_auto, def_path_hash); tcx.alloc_trait_def(def) } -fn has_late_bound_regions<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, - node: hir_map::Node<'tcx>) - -> Option { +fn has_late_bound_regions<'a, 'tcx>( + tcx: TyCtxt<'a, 'tcx, 'tcx>, + node: hir_map::Node<'tcx>, +) -> Option { struct LateBoundRegionsDetector<'a, 'tcx: 'a> { tcx: TyCtxt<'a, 'tcx, 'tcx>, outer_index: ty::DebruijnIndex, @@ -707,49 +753,57 @@ fn has_late_bound_regions<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, } fn visit_ty(&mut self, ty: &'tcx hir::Ty) { - if self.has_late_bound_regions.is_some() { return } + if self.has_late_bound_regions.is_some() { + return; + } match ty.node { hir::TyKind::BareFn(..) => { self.outer_index.shift_in(1); intravisit::walk_ty(self, ty); self.outer_index.shift_out(1); } - _ => intravisit::walk_ty(self, ty) + _ => intravisit::walk_ty(self, ty), } } - fn visit_poly_trait_ref(&mut self, - tr: &'tcx hir::PolyTraitRef, - m: hir::TraitBoundModifier) { - if self.has_late_bound_regions.is_some() { return } + fn visit_poly_trait_ref( + &mut self, + tr: &'tcx hir::PolyTraitRef, + m: hir::TraitBoundModifier, + ) { + if self.has_late_bound_regions.is_some() { + return; + } self.outer_index.shift_in(1); intravisit::walk_poly_trait_ref(self, tr, m); self.outer_index.shift_out(1); } fn visit_lifetime(&mut self, lt: &'tcx hir::Lifetime) { - if self.has_late_bound_regions.is_some() { return } + if self.has_late_bound_regions.is_some() { + return; + } let hir_id = self.tcx.hir.node_to_hir_id(lt.id); match self.tcx.named_region(hir_id) { Some(rl::Region::Static) | Some(rl::Region::EarlyBound(..)) => {} - Some(rl::Region::LateBound(debruijn, _, _)) | - Some(rl::Region::LateBoundAnon(debruijn, _)) - if debruijn < self.outer_index => {} - Some(rl::Region::LateBound(..)) | - Some(rl::Region::LateBoundAnon(..)) | - Some(rl::Region::Free(..)) | - None => { + Some(rl::Region::LateBound(debruijn, _, _)) + | Some(rl::Region::LateBoundAnon(debruijn, _)) if debruijn < self.outer_index => {} + Some(rl::Region::LateBound(..)) + | Some(rl::Region::LateBoundAnon(..)) + | Some(rl::Region::Free(..)) + | None => { self.has_late_bound_regions = Some(lt.span); } } } } - fn has_late_bound_regions<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, - generics: &'tcx hir::Generics, - decl: &'tcx hir::FnDecl) - -> Option { + fn has_late_bound_regions<'a, 'tcx>( + tcx: TyCtxt<'a, 'tcx, 'tcx>, + generics: &'tcx hir::Generics, + decl: &'tcx hir::FnDecl, + ) -> Option { let mut visitor = LateBoundRegionsDetector { tcx, outer_index: ty::INNERMOST, @@ -763,7 +817,7 @@ fn has_late_bound_regions<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, return Some(param.span); } } - _ => {}, + _ => {} } } visitor.visit_fn_decl(decl); @@ -772,32 +826,34 @@ fn has_late_bound_regions<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, match node { hir_map::NodeTraitItem(item) => match item.node { - hir::TraitItemKind::Method(ref sig, _) => - has_late_bound_regions(tcx, &item.generics, &sig.decl), + hir::TraitItemKind::Method(ref sig, _) => { + has_late_bound_regions(tcx, &item.generics, &sig.decl) + } _ => None, }, hir_map::NodeImplItem(item) => match item.node { - hir::ImplItemKind::Method(ref sig, _) => - has_late_bound_regions(tcx, &item.generics, &sig.decl), + hir::ImplItemKind::Method(ref sig, _) => { + has_late_bound_regions(tcx, &item.generics, &sig.decl) + } _ => None, }, hir_map::NodeForeignItem(item) => match item.node { - hir::ForeignItemKind::Fn(ref fn_decl, _, ref generics) => - has_late_bound_regions(tcx, generics, fn_decl), + hir::ForeignItemKind::Fn(ref fn_decl, _, ref generics) => { + has_late_bound_regions(tcx, generics, fn_decl) + } _ => None, }, hir_map::NodeItem(item) => match item.node { - hir::ItemKind::Fn(ref fn_decl, .., ref generics, _) => - has_late_bound_regions(tcx, generics, fn_decl), + hir::ItemKind::Fn(ref fn_decl, .., ref generics, _) => { + has_late_bound_regions(tcx, generics, fn_decl) + } _ => None, }, - _ => None + _ => None, } } -fn generics_of<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, - def_id: DefId) - -> &'tcx ty::Generics { +fn generics_of<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId) -> &'tcx ty::Generics { use rustc::hir::map::*; use rustc::hir::*; @@ -805,24 +861,19 @@ fn generics_of<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, let node = tcx.hir.get(node_id); let parent_def_id = match node { - NodeImplItem(_) | - NodeTraitItem(_) | - NodeVariant(_) | - NodeStructCtor(_) | - NodeField(_) => { + NodeImplItem(_) | NodeTraitItem(_) | NodeVariant(_) | NodeStructCtor(_) | NodeField(_) => { let parent_id = tcx.hir.get_parent(node_id); Some(tcx.hir.local_def_id(parent_id)) } - NodeExpr(&hir::Expr { node: hir::ExprKind::Closure(..), .. }) => { - Some(tcx.closure_base_def_id(def_id)) - } - NodeItem(item) => { - match item.node { - ItemKind::Existential(hir::ExistTy { impl_trait_fn, .. }) => impl_trait_fn, - _ => None, - } + NodeExpr(&hir::Expr { + node: hir::ExprKind::Closure(..), + .. + }) => Some(tcx.closure_base_def_id(def_id)), + NodeItem(item) => match item.node { + ItemKind::Existential(hir::ExistTy { impl_trait_fn, .. }) => impl_trait_fn, + _ => None, }, - _ => None + _ => None, }; let mut opt_self = None; @@ -836,20 +887,21 @@ fn generics_of<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, NodeItem(item) => { match item.node { - ItemKind::Fn(.., ref generics, _) | - ItemKind::Impl(_, _, _, ref generics, ..) => generics, + ItemKind::Fn(.., ref generics, _) | ItemKind::Impl(_, _, _, ref generics, ..) => { + generics + } - ItemKind::Ty(_, ref generics) | - ItemKind::Enum(_, ref generics) | - ItemKind::Struct(_, ref generics) | - ItemKind::Existential(hir::ExistTy { ref generics, .. }) | - ItemKind::Union(_, ref generics) => { + ItemKind::Ty(_, ref generics) + | ItemKind::Enum(_, ref generics) + | ItemKind::Struct(_, ref generics) + | ItemKind::Existential(hir::ExistTy { ref generics, .. }) + | ItemKind::Union(_, ref generics) => { allow_defaults = true; generics } - ItemKind::Trait(_, _, ref generics, ..) | - ItemKind::TraitAlias(ref generics, ..) => { + ItemKind::Trait(_, _, ref generics, ..) + | ItemKind::TraitAlias(ref generics, ..) => { // Add in the self type parameter. // // Something of a hack: use the node id for the trait, also as @@ -876,13 +928,11 @@ fn generics_of<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, } } - NodeForeignItem(item) => { - match item.node { - ForeignItemKind::Static(..) => &no_generics, - ForeignItemKind::Fn(_, _, ref generics) => generics, - ForeignItemKind::Type => &no_generics, - } - } + NodeForeignItem(item) => match item.node { + ForeignItemKind::Static(..) => &no_generics, + ForeignItemKind::Fn(_, _, ref generics) => generics, + ForeignItemKind::Type => &no_generics, + }, _ => &no_generics, }; @@ -901,15 +951,17 @@ fn generics_of<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, let mut params: Vec<_> = opt_self.into_iter().collect(); let early_lifetimes = early_bound_lifetimes_from_generics(tcx, ast_generics); - params.extend(early_lifetimes.enumerate().map(|(i, param)| { - ty::GenericParamDef { - name: param.name.ident().as_interned_str(), - index: own_start + i as u32, - def_id: tcx.hir.local_def_id(param.id), - pure_wrt_drop: param.pure_wrt_drop, - kind: ty::GenericParamDefKind::Lifetime, - } - })); + params.extend( + early_lifetimes + .enumerate() + .map(|(i, param)| ty::GenericParamDef { + name: param.name.ident().as_interned_str(), + index: own_start + i as u32, + def_id: tcx.hir.local_def_id(param.id), + pure_wrt_drop: param.pure_wrt_drop, + kind: ty::GenericParamDefKind::Lifetime, + }), + ); let hir_id = tcx.hir.node_to_hir_id(node_id); let object_lifetime_defaults = tcx.object_lifetime_defaults(hir_id); @@ -917,45 +969,65 @@ fn generics_of<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, // Now create the real type parameters. let type_start = own_start - has_self as u32 + params.len() as u32; let mut i = 0; - params.extend(ast_generics.params.iter().filter_map(|param| match param.kind { - GenericParamKind::Type { ref default, synthetic, .. } => { - if param.name.ident().name == keywords::SelfType.name() { - span_bug!(param.span, "`Self` should not be the name of a regular parameter"); - } - - if !allow_defaults && default.is_some() { - if !tcx.features().default_type_parameter_fallback { - tcx.lint_node( - lint::builtin::INVALID_TYPE_PARAM_DEFAULT, - param.id, - param.span, - &format!("defaults for type parameters are only allowed in \ - `struct`, `enum`, `type`, or `trait` definitions.")); - } - } - - let ty_param = ty::GenericParamDef { - index: type_start + i as u32, - name: param.name.ident().as_interned_str(), - def_id: tcx.hir.local_def_id(param.id), - pure_wrt_drop: param.pure_wrt_drop, - kind: ty::GenericParamDefKind::Type { - has_default: default.is_some(), - object_lifetime_default: - object_lifetime_defaults.as_ref().map_or(rl::Set1::Empty, |o| o[i]), + params.extend( + ast_generics + .params + .iter() + .filter_map(|param| match param.kind { + GenericParamKind::Type { + ref default, synthetic, - }, - }; - i += 1; - Some(ty_param) - } - _ => None, - })); + .. + } => { + if param.name.ident().name == keywords::SelfType.name() { + span_bug!( + param.span, + "`Self` should not be the name of a regular parameter" + ); + } + + if !allow_defaults && default.is_some() { + if !tcx.features().default_type_parameter_fallback { + tcx.lint_node( + lint::builtin::INVALID_TYPE_PARAM_DEFAULT, + param.id, + param.span, + &format!( + "defaults for type parameters are only allowed in \ + `struct`, `enum`, `type`, or `trait` definitions." + ), + ); + } + } + + let ty_param = ty::GenericParamDef { + index: type_start + i as u32, + name: param.name.ident().as_interned_str(), + def_id: tcx.hir.local_def_id(param.id), + pure_wrt_drop: param.pure_wrt_drop, + kind: ty::GenericParamDefKind::Type { + has_default: default.is_some(), + object_lifetime_default: object_lifetime_defaults + .as_ref() + .map_or(rl::Set1::Empty, |o| o[i]), + synthetic, + }, + }; + i += 1; + Some(ty_param) + } + _ => None, + }), + ); // provide junk type parameter defs - the only place that // cares about anything but the length is instantiation, // and we don't do that for closures. - if let NodeExpr(&hir::Expr { node: hir::ExprKind::Closure(.., gen), .. }) = node { + if let NodeExpr(&hir::Expr { + node: hir::ExprKind::Closure(.., gen), + .. + }) = node + { let dummy_args = if gen.is_some() { &["", "", ""][..] } else { @@ -963,8 +1035,10 @@ fn generics_of<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, }; params.extend( - dummy_args.iter().enumerate().map(|(i, &arg)| - ty::GenericParamDef { + dummy_args + .iter() + .enumerate() + .map(|(i, &arg)| ty::GenericParamDef { index: type_start + i as u32, name: Symbol::intern(arg).as_interned_str(), def_id, @@ -974,8 +1048,7 @@ fn generics_of<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, object_lifetime_default: rl::Set1::Empty, synthetic: None, }, - } - ) + }), ); tcx.with_freevars(node_id, |fv| { @@ -995,9 +1068,10 @@ fn generics_of<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, }); } - let param_def_id_to_index = params.iter() - .map(|param| (param.def_id, param.index)) - .collect(); + let param_def_id_to_index = params + .iter() + .map(|param| (param.def_id, param.index)) + .collect(); tcx.alloc_generics(ty::Generics { parent: parent_def_id, @@ -1009,16 +1083,16 @@ fn generics_of<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, }) } -fn report_assoc_ty_on_inherent_impl<'a, 'tcx>( - tcx: TyCtxt<'a, 'tcx, 'tcx>, - span: Span, -) { - span_err!(tcx.sess, span, E0202, "associated types are not allowed in inherent impls"); +fn report_assoc_ty_on_inherent_impl<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, span: Span) { + span_err!( + tcx.sess, + span, + E0202, + "associated types are not allowed in inherent impls" + ); } -fn type_of<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, - def_id: DefId) - -> Ty<'tcx> { +fn type_of<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId) -> Ty<'tcx> { use rustc::hir::map::*; use rustc::hir::*; @@ -1027,109 +1101,114 @@ fn type_of<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, let icx = ItemCtxt::new(tcx, def_id); match tcx.hir.get(node_id) { - NodeTraitItem(item) => { - match item.node { - TraitItemKind::Method(..) => { - let substs = Substs::identity_for_item(tcx, def_id); - tcx.mk_fn_def(def_id, substs) - } - TraitItemKind::Const(ref ty, _) | - TraitItemKind::Type(_, Some(ref ty)) => icx.to_ty(ty), - TraitItemKind::Type(_, None) => { - span_bug!(item.span, "associated type missing default"); - } + NodeTraitItem(item) => match item.node { + TraitItemKind::Method(..) => { + let substs = Substs::identity_for_item(tcx, def_id); + tcx.mk_fn_def(def_id, substs) } - } - - NodeImplItem(item) => { - match item.node { - ImplItemKind::Method(..) => { - let substs = Substs::identity_for_item(tcx, def_id); - tcx.mk_fn_def(def_id, substs) - } - ImplItemKind::Const(ref ty, _) => icx.to_ty(ty), - ImplItemKind::Existential(_) => { - if tcx.impl_trait_ref(tcx.hir.get_parent_did(node_id)).is_none() { - report_assoc_ty_on_inherent_impl(tcx, item.span); - } - - find_existential_constraints(tcx, def_id) - } - ImplItemKind::Type(ref ty) => { - if tcx.impl_trait_ref(tcx.hir.get_parent_did(node_id)).is_none() { - report_assoc_ty_on_inherent_impl(tcx, item.span); - } - - icx.to_ty(ty) - } + TraitItemKind::Const(ref ty, _) | TraitItemKind::Type(_, Some(ref ty)) => icx.to_ty(ty), + TraitItemKind::Type(_, None) => { + span_bug!(item.span, "associated type missing default"); } - } + }, + + NodeImplItem(item) => match item.node { + ImplItemKind::Method(..) => { + let substs = Substs::identity_for_item(tcx, def_id); + tcx.mk_fn_def(def_id, substs) + } + ImplItemKind::Const(ref ty, _) => icx.to_ty(ty), + ImplItemKind::Existential(_) => { + if tcx + .impl_trait_ref(tcx.hir.get_parent_did(node_id)) + .is_none() + { + report_assoc_ty_on_inherent_impl(tcx, item.span); + } + + find_existential_constraints(tcx, def_id) + } + ImplItemKind::Type(ref ty) => { + if tcx + .impl_trait_ref(tcx.hir.get_parent_did(node_id)) + .is_none() + { + report_assoc_ty_on_inherent_impl(tcx, item.span); + } + + icx.to_ty(ty) + } + }, NodeItem(item) => { match item.node { - ItemKind::Static(ref t, ..) | ItemKind::Const(ref t, _) | - ItemKind::Ty(ref t, _) | ItemKind::Impl(.., ref t, _) => { - icx.to_ty(t) - } + ItemKind::Static(ref t, ..) + | ItemKind::Const(ref t, _) + | ItemKind::Ty(ref t, _) + | ItemKind::Impl(.., ref t, _) => icx.to_ty(t), ItemKind::Fn(..) => { let substs = Substs::identity_for_item(tcx, def_id); tcx.mk_fn_def(def_id, substs) } - ItemKind::Enum(..) | - ItemKind::Struct(..) | - ItemKind::Union(..) => { + ItemKind::Enum(..) | ItemKind::Struct(..) | ItemKind::Union(..) => { let def = tcx.adt_def(def_id); let substs = Substs::identity_for_item(tcx, def_id); tcx.mk_adt(def, substs) } - ItemKind::Existential(hir::ExistTy { impl_trait_fn: None, .. }) => { - find_existential_constraints(tcx, def_id) - }, + ItemKind::Existential(hir::ExistTy { + impl_trait_fn: None, + .. + }) => find_existential_constraints(tcx, def_id), // existential types desugared from impl Trait - ItemKind::Existential(hir::ExistTy { impl_trait_fn: Some(owner), .. }) => { - tcx.typeck_tables_of(owner).concrete_existential_types[&def_id] - }, - ItemKind::Trait(..) | ItemKind::TraitAlias(..) | - ItemKind::Mod(..) | - ItemKind::ForeignMod(..) | - ItemKind::GlobalAsm(..) | - ItemKind::ExternCrate(..) | - ItemKind::Use(..) => { + ItemKind::Existential(hir::ExistTy { + impl_trait_fn: Some(owner), + .. + }) => tcx.typeck_tables_of(owner).concrete_existential_types[&def_id], + ItemKind::Trait(..) + | ItemKind::TraitAlias(..) + | ItemKind::Mod(..) + | ItemKind::ForeignMod(..) + | ItemKind::GlobalAsm(..) + | ItemKind::ExternCrate(..) + | ItemKind::Use(..) => { span_bug!( item.span, "compute_type_of_item: unexpected item type: {:?}", - item.node); + item.node + ); } } } - NodeForeignItem(foreign_item) => { - match foreign_item.node { - ForeignItemKind::Fn(..) => { - let substs = Substs::identity_for_item(tcx, def_id); - tcx.mk_fn_def(def_id, substs) - } - ForeignItemKind::Static(ref t, _) => icx.to_ty(t), - ForeignItemKind::Type => tcx.mk_foreign(def_id), + NodeForeignItem(foreign_item) => match foreign_item.node { + ForeignItemKind::Fn(..) => { + let substs = Substs::identity_for_item(tcx, def_id); + tcx.mk_fn_def(def_id, substs) } - } + ForeignItemKind::Static(ref t, _) => icx.to_ty(t), + ForeignItemKind::Type => tcx.mk_foreign(def_id), + }, - NodeStructCtor(&ref def) | - NodeVariant(&Spanned { node: hir::VariantKind { data: ref def, .. }, .. }) => { - match *def { - VariantData::Unit(..) | VariantData::Struct(..) => { - tcx.type_of(tcx.hir.get_parent_did(node_id)) - } - VariantData::Tuple(..) => { - let substs = Substs::identity_for_item(tcx, def_id); - tcx.mk_fn_def(def_id, substs) - } + NodeStructCtor(&ref def) + | NodeVariant(&Spanned { + node: hir::VariantKind { data: ref def, .. }, + .. + }) => match *def { + VariantData::Unit(..) | VariantData::Struct(..) => { + tcx.type_of(tcx.hir.get_parent_did(node_id)) } - } + VariantData::Tuple(..) => { + let substs = Substs::identity_for_item(tcx, def_id); + tcx.mk_fn_def(def_id, substs) + } + }, NodeField(field) => icx.to_ty(&field.ty), - NodeExpr(&hir::Expr { node: hir::ExprKind::Closure(.., gen), .. }) => { + NodeExpr(&hir::Expr { + node: hir::ExprKind::Closure(.., gen), + .. + }) => { if gen.is_some() { let hir_id = tcx.hir.node_to_hir_id(node_id); return tcx.typeck_tables_of(def_id).node_id_to_type(hir_id); @@ -1143,30 +1222,49 @@ fn type_of<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, } NodeAnonConst(_) => match tcx.hir.get(tcx.hir.get_parent_node(node_id)) { - NodeTy(&hir::Ty { node: hir::TyKind::Array(_, ref constant), .. }) | - NodeTy(&hir::Ty { node: hir::TyKind::Typeof(ref constant), .. }) | - NodeExpr(&hir::Expr { node: ExprKind::Repeat(_, ref constant), .. }) - if constant.id == node_id => tcx.types.usize, + NodeTy(&hir::Ty { + node: hir::TyKind::Array(_, ref constant), + .. + }) + | NodeTy(&hir::Ty { + node: hir::TyKind::Typeof(ref constant), + .. + }) + | NodeExpr(&hir::Expr { + node: ExprKind::Repeat(_, ref constant), + .. + }) if constant.id == node_id => + { + tcx.types.usize + } - NodeVariant(&Spanned { node: VariantKind { disr_expr: Some(ref e), .. }, .. }) - if e.id == node_id => { - tcx.adt_def(tcx.hir.get_parent_did(node_id)) - .repr.discr_type().to_ty(tcx) - } + NodeVariant(&Spanned { + node: + VariantKind { + disr_expr: Some(ref e), + .. + }, + .. + }) if e.id == node_id => + { + tcx.adt_def(tcx.hir.get_parent_did(node_id)) + .repr + .discr_type() + .to_ty(tcx) + } x => { bug!("unexpected const parent in type_of_def_id(): {:?}", x); } }, - NodeGenericParam(param) => { - match param.kind { - hir::GenericParamKind::Type { default: Some(ref ty), .. } => { - icx.to_ty(ty) - } - _ => bug!("unexpected non-type NodeGenericParam"), - } - } + NodeGenericParam(param) => match param.kind { + hir::GenericParamKind::Type { + default: Some(ref ty), + .. + } => icx.to_ty(ty), + _ => bug!("unexpected non-type NodeGenericParam"), + }, x => { bug!("unexpected sort of node in type_of_def_id(): {:?}", x); @@ -1245,7 +1343,11 @@ fn find_existential_constraints<'a, 'tcx>( intravisit::walk_trait_item(self, it); } } - let mut locator = ConstraintLocator { def_id, tcx, found: None }; + let mut locator = ConstraintLocator { + def_id, + tcx, + found: None, + }; let node_id = tcx.hir.as_local_node_id(def_id).unwrap(); let parent = tcx.hir.get_parent(node_id); trace!("parent_id: {:?}", parent); @@ -1257,7 +1359,10 @@ fn find_existential_constraints<'a, 'tcx>( NodeItem(ref it) => intravisit::walk_item(&mut locator, it), NodeImplItem(ref it) => intravisit::walk_impl_item(&mut locator, it), NodeTraitItem(ref it) => intravisit::walk_trait_item(&mut locator, it), - other => bug!("{:?} is not a valid parent of an existential type item", other), + other => bug!( + "{:?} is not a valid parent of an existential type item", + other + ), } } match locator.found { @@ -1270,9 +1375,7 @@ fn find_existential_constraints<'a, 'tcx>( } } -fn fn_sig<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, - def_id: DefId) - -> ty::PolyFnSig<'tcx> { +fn fn_sig<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId) -> ty::PolyFnSig<'tcx> { use rustc::hir::map::*; use rustc::hir::*; @@ -1281,38 +1384,54 @@ fn fn_sig<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, let icx = ItemCtxt::new(tcx, def_id); match tcx.hir.get(node_id) { - NodeTraitItem(hir::TraitItem { node: TraitItemKind::Method(sig, _), .. }) | - NodeImplItem(hir::ImplItem { node: ImplItemKind::Method(sig, _), .. }) => { - AstConv::ty_of_fn(&icx, sig.header.unsafety, sig.header.abi, &sig.decl) - } + NodeTraitItem(hir::TraitItem { + node: TraitItemKind::Method(sig, _), + .. + }) + | NodeImplItem(hir::ImplItem { + node: ImplItemKind::Method(sig, _), + .. + }) => AstConv::ty_of_fn(&icx, sig.header.unsafety, sig.header.abi, &sig.decl), - NodeItem(hir::Item { node: ItemKind::Fn(decl, header, _, _), .. }) => { - AstConv::ty_of_fn(&icx, header.unsafety, header.abi, decl) - } + NodeItem(hir::Item { + node: ItemKind::Fn(decl, header, _, _), + .. + }) => AstConv::ty_of_fn(&icx, header.unsafety, header.abi, decl), - NodeForeignItem(&hir::ForeignItem { node: ForeignItemKind::Fn(ref fn_decl, _, _), .. }) => { + NodeForeignItem(&hir::ForeignItem { + node: ForeignItemKind::Fn(ref fn_decl, _, _), + .. + }) => { let abi = tcx.hir.get_foreign_abi(node_id); compute_sig_of_foreign_fn_decl(tcx, def_id, fn_decl, abi) } - NodeStructCtor(&VariantData::Tuple(ref fields, _)) | - NodeVariant(&Spanned { node: hir::VariantKind { - data: VariantData::Tuple(ref fields, _), .. - }, .. }) => { + NodeStructCtor(&VariantData::Tuple(ref fields, _)) + | NodeVariant(&Spanned { + node: + hir::VariantKind { + data: VariantData::Tuple(ref fields, _), + .. + }, + .. + }) => { let ty = tcx.type_of(tcx.hir.get_parent_did(node_id)); - let inputs = fields.iter().map(|f| { - tcx.type_of(tcx.hir.local_def_id(f.id)) - }); + let inputs = fields + .iter() + .map(|f| tcx.type_of(tcx.hir.local_def_id(f.id))); ty::Binder::bind(tcx.mk_fn_sig( inputs, ty, false, hir::Unsafety::Normal, - abi::Abi::Rust + abi::Abi::Rust, )) } - NodeExpr(&hir::Expr { node: hir::ExprKind::Closure(..), .. }) => { + NodeExpr(&hir::Expr { + node: hir::ExprKind::Closure(..), + .. + }) => { // Closure signatures are not like other function // signatures and cannot be accessed through `fn_sig`. For // example, a closure signature excludes the `self` @@ -1337,9 +1456,10 @@ fn fn_sig<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, } } -fn impl_trait_ref<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, - def_id: DefId) - -> Option> { +fn impl_trait_ref<'a, 'tcx>( + tcx: TyCtxt<'a, 'tcx, 'tcx>, + def_id: DefId, +) -> Option> { let icx = ItemCtxt::new(tcx, def_id); let node_id = tcx.hir.as_local_node_id(def_id).unwrap(); @@ -1350,37 +1470,40 @@ fn impl_trait_ref<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, AstConv::instantiate_mono_trait_ref(&icx, ast_trait_ref, selfty) }) } - _ => bug!() + _ => bug!(), } } -fn impl_polarity<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, - def_id: DefId) - -> hir::ImplPolarity { +fn impl_polarity<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId) -> hir::ImplPolarity { let node_id = tcx.hir.as_local_node_id(def_id).unwrap(); match tcx.hir.expect_item(node_id).node { hir::ItemKind::Impl(_, polarity, ..) => polarity, - ref item => bug!("impl_polarity: {:?} not an impl", item) + ref item => bug!("impl_polarity: {:?} not an impl", item), } } // Is it marked with ?Sized -fn is_unsized<'gcx: 'tcx, 'tcx>(astconv: &dyn AstConv<'gcx, 'tcx>, - ast_bounds: &[hir::GenericBound], - span: Span) -> bool -{ +fn is_unsized<'gcx: 'tcx, 'tcx>( + astconv: &dyn AstConv<'gcx, 'tcx>, + ast_bounds: &[hir::GenericBound], + span: Span, +) -> bool { let tcx = astconv.tcx(); // Try to find an unbound in bounds. let mut unbound = None; for ab in ast_bounds { - if let &hir::GenericBound::Trait(ref ptr, hir::TraitBoundModifier::Maybe) = ab { + if let &hir::GenericBound::Trait(ref ptr, hir::TraitBoundModifier::Maybe) = ab { if unbound.is_none() { unbound = Some(ptr.trait_ref.clone()); } else { - span_err!(tcx.sess, span, E0203, - "type parameter has more than one relaxed default \ - bound, only one is supported"); + span_err!( + tcx.sess, + span, + E0203, + "type parameter has more than one relaxed default \ + bound, only one is supported" + ); } } } @@ -1391,10 +1514,12 @@ fn is_unsized<'gcx: 'tcx, 'tcx>(astconv: &dyn AstConv<'gcx, 'tcx>, // FIXME(#8559) currently requires the unbound to be built-in. if let Ok(kind_id) = kind_id { if tpb.path.def != Def::Trait(kind_id) { - tcx.sess.span_warn(span, - "default bound relaxed for a type parameter, but \ - this does nothing because the given bound is not \ - a default. Only `?Sized` is supported"); + tcx.sess.span_warn( + span, + "default bound relaxed for a type parameter, but \ + this does nothing because the given bound is not \ + a default. Only `?Sized` is supported", + ); } } } @@ -1415,25 +1540,33 @@ fn is_unsized<'gcx: 'tcx, 'tcx>(astconv: &dyn AstConv<'gcx, 'tcx>, /// `resolve_lifetime::early_bound_lifetimes`. fn early_bound_lifetimes_from_generics<'a, 'tcx>( tcx: TyCtxt<'a, 'tcx, 'tcx>, - generics: &'a hir::Generics) - -> impl Iterator + Captures<'tcx> -{ - generics.params.iter().filter(move |param| match param.kind { - GenericParamKind::Lifetime { .. } => { - let hir_id = tcx.hir.node_to_hir_id(param.id); - !tcx.is_late_bound(hir_id) - } - _ => false, - }) + generics: &'a hir::Generics, +) -> impl Iterator + Captures<'tcx> { + generics + .params + .iter() + .filter(move |param| match param.kind { + GenericParamKind::Lifetime { .. } => { + let hir_id = tcx.hir.node_to_hir_id(param.id); + !tcx.is_late_bound(hir_id) + } + _ => false, + }) } -fn predicates_defined_on<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, - def_id: DefId) - -> ty::GenericPredicates<'tcx> { +fn predicates_defined_on<'a, 'tcx>( + tcx: TyCtxt<'a, 'tcx, 'tcx>, + def_id: DefId, +) -> ty::GenericPredicates<'tcx> { let explicit = tcx.explicit_predicates_of(def_id); let predicates = if tcx.sess.features_untracked().infer_outlives_requirements { - [&explicit.predicates[..], &tcx.inferred_outlives_of(def_id)[..]].concat() - } else { explicit.predicates }; + [ + &explicit.predicates[..], + &tcx.inferred_outlives_of(def_id)[..], + ].concat() + } else { + explicit.predicates + }; ty::GenericPredicates { parent: explicit.parent, @@ -1441,11 +1574,14 @@ fn predicates_defined_on<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, } } -fn predicates_of<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, - def_id: DefId) - -> ty::GenericPredicates<'tcx> { - let ty::GenericPredicates { parent, mut predicates } = - tcx.predicates_defined_on(def_id); +fn predicates_of<'a, 'tcx>( + tcx: TyCtxt<'a, 'tcx, 'tcx>, + def_id: DefId, +) -> ty::GenericPredicates<'tcx> { + let ty::GenericPredicates { + parent, + mut predicates, + } = tcx.predicates_defined_on(def_id); if tcx.is_trait(def_id) { // For traits, add `Self: Trait` predicate. This is @@ -1487,9 +1623,7 @@ fn explicit_predicates_of<'a, 'tcx>( let mut predicates = vec![]; let ast_generics = match node { - NodeTraitItem(item) => { - &item.generics - } + NodeTraitItem(item) => &item.generics, NodeImplItem(item) => match item.node { ImplItemKind::Existential(ref bounds) => { @@ -1497,17 +1631,19 @@ fn explicit_predicates_of<'a, 'tcx>( let anon_ty = tcx.mk_anon(def_id, substs); // Collect the bounds, i.e. the `A+B+'c` in `impl A+B+'c`. - let bounds = compute_bounds(&icx, - anon_ty, - bounds, - SizedByDefault::Yes, - tcx.def_span(def_id)); + let bounds = compute_bounds( + &icx, + anon_ty, + bounds, + SizedByDefault::Yes, + tcx.def_span(def_id), + ); predicates.extend(bounds.predicates(tcx, anon_ty)); &item.generics - }, + } _ => &item.generics, - } + }, NodeItem(item) => { match item.node { @@ -1517,26 +1653,32 @@ fn explicit_predicates_of<'a, 'tcx>( } generics } - ItemKind::Fn(.., ref generics, _) | - ItemKind::Ty(_, ref generics) | - ItemKind::Enum(_, ref generics) | - ItemKind::Struct(_, ref generics) | - ItemKind::Union(_, ref generics) => generics, + ItemKind::Fn(.., ref generics, _) + | ItemKind::Ty(_, ref generics) + | ItemKind::Enum(_, ref generics) + | ItemKind::Struct(_, ref generics) + | ItemKind::Union(_, ref generics) => generics, ItemKind::Trait(_, _, ref generics, .., ref items) => { is_trait = Some((ty::TraitRef::identity(tcx, def_id), items)); generics } - ItemKind::Existential(ExistTy { ref bounds, impl_trait_fn, ref generics }) => { + ItemKind::Existential(ExistTy { + ref bounds, + impl_trait_fn, + ref generics, + }) => { let substs = Substs::identity_for_item(tcx, def_id); let anon_ty = tcx.mk_anon(def_id, substs); // Collect the bounds, i.e. the `A+B+'c` in `impl A+B+'c`. - let bounds = compute_bounds(&icx, - anon_ty, - bounds, - SizedByDefault::Yes, - tcx.def_span(def_id)); + let bounds = compute_bounds( + &icx, + anon_ty, + bounds, + SizedByDefault::Yes, + tcx.def_span(def_id), + ); if impl_trait_fn.is_some() { // impl Trait @@ -1555,13 +1697,11 @@ fn explicit_predicates_of<'a, 'tcx>( } } - NodeForeignItem(item) => { - match item.node { - ForeignItemKind::Static(..) => &no_generics, - ForeignItemKind::Fn(_, _, ref generics) => generics, - ForeignItemKind::Type => &no_generics, - } - } + NodeForeignItem(item) => match item.node { + ForeignItemKind::Static(..) => &no_generics, + ForeignItemKind::Fn(_, _, ref generics) => generics, + ForeignItemKind::Type => &no_generics, + }, _ => &no_generics, }; @@ -1612,7 +1752,7 @@ fn explicit_predicates_of<'a, 'tcx>( } _ => bug!(), }); - }, + } _ => bug!(), } } @@ -1646,20 +1786,19 @@ fn explicit_predicates_of<'a, 'tcx>( &hir::GenericBound::Trait(ref poly_trait_ref, _) => { let mut projections = Vec::new(); - let trait_ref = - AstConv::instantiate_poly_trait_ref(&icx, - poly_trait_ref, - ty, - &mut projections); + let trait_ref = AstConv::instantiate_poly_trait_ref( + &icx, + poly_trait_ref, + ty, + &mut projections, + ); predicates.push(trait_ref.to_predicate()); predicates.extend(projections.iter().map(|p| p.to_predicate())); } &hir::GenericBound::Outlives(ref lifetime) => { - let region = AstConv::ast_region_to_region(&icx, - lifetime, - None); + let region = AstConv::ast_region_to_region(&icx, lifetime, None); let pred = ty::Binder::bind(ty::OutlivesPredicate(ty, region)); predicates.push(ty::Predicate::TypeOutlives(pred)) } @@ -1698,16 +1837,16 @@ fn explicit_predicates_of<'a, 'tcx>( } }; - let assoc_ty = tcx.mk_projection( - tcx.hir.local_def_id(trait_item.id), - self_trait_ref.substs, - ); + let assoc_ty = + tcx.mk_projection(tcx.hir.local_def_id(trait_item.id), self_trait_ref.substs); - let bounds = compute_bounds(&ItemCtxt::new(tcx, def_id), - assoc_ty, - bounds, - SizedByDefault::Yes, - trait_item.span); + let bounds = compute_bounds( + &ItemCtxt::new(tcx, def_id), + assoc_ty, + bounds, + SizedByDefault::Yes, + trait_item.span, + ); bounds.predicates(tcx, assoc_ty).into_iter() })) @@ -1718,13 +1857,19 @@ fn explicit_predicates_of<'a, 'tcx>( // before uses of `U`. This avoids false ambiguity errors // in trait checking. See `setup_constraining_predicates` // for details. - if let NodeItem(&Item { node: ItemKind::Impl(..), .. }) = node { + if let NodeItem(&Item { + node: ItemKind::Impl(..), + .. + }) = node + { let self_ty = tcx.type_of(def_id); let trait_ref = tcx.impl_trait_ref(def_id); - ctp::setup_constraining_predicates(tcx, - &mut predicates, - trait_ref, - &mut ctp::parameters_for_impl(self_ty, trait_ref)); + ctp::setup_constraining_predicates( + tcx, + &mut predicates, + trait_ref, + &mut ctp::parameters_for_impl(self_ty, trait_ref), + ); } ty::GenericPredicates { @@ -1733,18 +1878,21 @@ fn explicit_predicates_of<'a, 'tcx>( } } -pub enum SizedByDefault { Yes, No, } +pub enum SizedByDefault { + Yes, + No, +} /// Translate the AST's notion of ty param bounds (which are an enum consisting of a newtyped Ty or /// a region) to ty's notion of ty param bounds, which can either be user-defined traits, or the /// built-in trait (formerly known as kind): Send. -pub fn compute_bounds<'gcx: 'tcx, 'tcx>(astconv: &dyn AstConv<'gcx, 'tcx>, - param_ty: Ty<'tcx>, - ast_bounds: &[hir::GenericBound], - sized_by_default: SizedByDefault, - span: Span) - -> Bounds<'tcx> -{ +pub fn compute_bounds<'gcx: 'tcx, 'tcx>( + astconv: &dyn AstConv<'gcx, 'tcx>, + param_ty: Ty<'tcx>, + ast_bounds: &[hir::GenericBound], + sized_by_default: SizedByDefault, + span: Span, +) -> Bounds<'tcx> { let mut region_bounds = vec![]; let mut trait_bounds = vec![]; for ast_bound in ast_bounds { @@ -1757,13 +1905,15 @@ pub fn compute_bounds<'gcx: 'tcx, 'tcx>(astconv: &dyn AstConv<'gcx, 'tcx>, let mut projection_bounds = vec![]; - let mut trait_bounds: Vec<_> = trait_bounds.iter().map(|&bound| { - astconv.instantiate_poly_trait_ref(bound, param_ty, &mut projection_bounds) - }).collect(); + let mut trait_bounds: Vec<_> = trait_bounds + .iter() + .map(|&bound| astconv.instantiate_poly_trait_ref(bound, param_ty, &mut projection_bounds)) + .collect(); - let region_bounds = region_bounds.into_iter().map(|r| { - astconv.ast_region_to_region(r, None) - }).collect(); + let region_bounds = region_bounds + .into_iter() + .map(|r| astconv.ast_region_to_region(r, None)) + .collect(); trait_bounds.sort_by_key(|t| t.def_id()); @@ -1786,21 +1936,20 @@ pub fn compute_bounds<'gcx: 'tcx, 'tcx>(astconv: &dyn AstConv<'gcx, 'tcx>, /// because this can be anywhere from 0 predicates (`T:?Sized` adds no /// predicates) to 1 (`T:Foo`) to many (`T:Bar` adds `T:Bar` /// and `::X == i32`). -fn predicates_from_bound<'tcx>(astconv: &dyn AstConv<'tcx, 'tcx>, - param_ty: Ty<'tcx>, - bound: &hir::GenericBound) - -> Vec> -{ +fn predicates_from_bound<'tcx>( + astconv: &dyn AstConv<'tcx, 'tcx>, + param_ty: Ty<'tcx>, + bound: &hir::GenericBound, +) -> Vec> { match *bound { hir::GenericBound::Trait(ref tr, hir::TraitBoundModifier::None) => { let mut projections = Vec::new(); - let pred = astconv.instantiate_poly_trait_ref(tr, - param_ty, - &mut projections); - projections.into_iter() - .map(|p| p.to_predicate()) - .chain(Some(pred.to_predicate())) - .collect() + let pred = astconv.instantiate_poly_trait_ref(tr, param_ty, &mut projections); + projections + .into_iter() + .map(|p| p.to_predicate()) + .chain(Some(pred.to_predicate())) + .collect() } hir::GenericBound::Outlives(ref lifetime) => { let region = astconv.ast_region_to_region(lifetime, None); @@ -1815,21 +1964,32 @@ fn compute_sig_of_foreign_fn_decl<'a, 'tcx>( tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId, decl: &hir::FnDecl, - abi: abi::Abi) - -> ty::PolyFnSig<'tcx> -{ - let fty = AstConv::ty_of_fn(&ItemCtxt::new(tcx, def_id), hir::Unsafety::Unsafe, abi, decl); + abi: abi::Abi, +) -> ty::PolyFnSig<'tcx> { + let fty = AstConv::ty_of_fn( + &ItemCtxt::new(tcx, def_id), + hir::Unsafety::Unsafe, + abi, + decl, + ); // feature gate SIMD types in FFI, since I (huonw) am not sure the // ABIs are handled at all correctly. - if abi != abi::Abi::RustIntrinsic && abi != abi::Abi::PlatformIntrinsic - && !tcx.features().simd_ffi { + if abi != abi::Abi::RustIntrinsic + && abi != abi::Abi::PlatformIntrinsic + && !tcx.features().simd_ffi + { let check = |ast_ty: &hir::Ty, ty: Ty| { if ty.is_simd() { - tcx.sess.struct_span_err(ast_ty.span, - &format!("use of SIMD type `{}` in FFI is highly experimental and \ - may result in invalid code", - tcx.hir.node_to_pretty_string(ast_ty.id))) + tcx.sess + .struct_span_err( + ast_ty.span, + &format!( + "use of SIMD type `{}` in FFI is highly experimental and \ + may result in invalid code", + tcx.hir.node_to_pretty_string(ast_ty.id) + ), + ) .help("add #![feature(simd_ffi)] to the crate attributes to enable") .emit(); } @@ -1845,13 +2005,11 @@ fn compute_sig_of_foreign_fn_decl<'a, 'tcx>( fty } -fn is_foreign_item<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, - def_id: DefId) - -> bool { +fn is_foreign_item<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId) -> bool { match tcx.hir.get_if_local(def_id) { Some(hir_map::NodeForeignItem(..)) => true, Some(_) => false, - _ => bug!("is_foreign_item applied to non-local def-id {:?}", def_id) + _ => bug!("is_foreign_item applied to non-local def-id {:?}", def_id), } } @@ -1868,7 +2026,7 @@ fn from_target_feature( let msg = "#[target_feature] attribute must be of the form \ #[target_feature(..)]"; tcx.sess.span_err(attr.span, &msg); - return + return; } }; let rust_features = tcx.features(); @@ -1878,7 +2036,7 @@ fn from_target_feature( let msg = "#[target_feature(..)] only accepts sub-keys of `enable` \ currently"; tcx.sess.span_err(item.span, &msg); - continue + continue; } // Must be of the form `enable = "..."` ( a string) @@ -1888,19 +2046,21 @@ fn from_target_feature( let msg = "#[target_feature] attribute must be of the form \ #[target_feature(enable = \"..\")]"; tcx.sess.span_err(item.span, &msg); - continue + continue; } }; // We allow comma separation to enable multiple features for feature in value.as_str().split(',') { - // Only allow whitelisted features per platform let feature_gate = match whitelist.get(feature) { Some(g) => g, None => { - let msg = format!("the feature named `{}` is not valid for \ - this target", feature); + let msg = format!( + "the feature named `{}` is not valid for \ + this target", + feature + ); let mut err = tcx.sess.struct_span_err(item.span, &msg); if feature.starts_with("+") { @@ -1910,7 +2070,7 @@ fn from_target_feature( } } err.emit(); - continue + continue; } }; @@ -1935,10 +2095,9 @@ fn from_target_feature( feature_gate.as_ref().unwrap(), item.span, feature_gate::GateIssue::Language, - &format!("the target feature `{}` is currently unstable", - feature), + &format!("the target feature `{}` is currently unstable", feature), ); - continue + continue; } target_features.push(Symbol::intern(feature)); } @@ -1973,7 +2132,8 @@ fn linkage_by_name<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId, name: & if let Some(span) = span { tcx.sess.span_fatal(span, "invalid linkage specified") } else { - tcx.sess.fatal(&format!("invalid linkage specified: {}", name)) + tcx.sess + .fatal(&format!("invalid linkage specified: {}", name)) } } } @@ -2026,16 +2186,24 @@ fn codegen_fn_attrs<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, id: DefId) -> Codegen mark_used(attr); inline_span = Some(attr.span); if items.len() != 1 { - span_err!(tcx.sess.diagnostic(), attr.span, E0534, - "expected one argument"); + span_err!( + tcx.sess.diagnostic(), + attr.span, + E0534, + "expected one argument" + ); InlineAttr::None } else if list_contains_name(&items[..], "always") { InlineAttr::Always } else if list_contains_name(&items[..], "never") { InlineAttr::Never } else { - span_err!(tcx.sess.diagnostic(), items[0].span, E0535, - "invalid argument"); + span_err!( + tcx.sess.diagnostic(), + items[0].span, + E0535, + "invalid argument" + ); InlineAttr::None } @@ -2048,15 +2216,21 @@ fn codegen_fn_attrs<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, id: DefId) -> Codegen if s.as_str().contains("\0") { // `#[export_name = ...]` will be converted to a null-terminated string, // so it may not contain any null characters. - struct_span_err!(tcx.sess, attr.span, E0648, - "`export_name` may not contain null characters") - .emit(); + struct_span_err!( + tcx.sess, + attr.span, + E0648, + "`export_name` may not contain null characters" + ).emit(); } codegen_fn_attrs.export_name = Some(s); } else { - struct_span_err!(tcx.sess, attr.span, E0558, - "`export_name` attribute has invalid format") - .span_label(attr.span, "did you mean #[export_name=\"*\"]?") + struct_span_err!( + tcx.sess, + attr.span, + E0558, + "`export_name` attribute has invalid format" + ).span_label(attr.span, "did you mean #[export_name=\"*\"]?") .emit(); } } else if attr.check_name("target_feature") { @@ -2065,7 +2239,13 @@ fn codegen_fn_attrs<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, id: DefId) -> Codegen `unsafe` function"; tcx.sess.span_err(attr.span, msg); } - from_target_feature(tcx, id, attr, &whitelist, &mut codegen_fn_attrs.target_features); + from_target_feature( + tcx, + id, + attr, + &whitelist, + &mut codegen_fn_attrs.target_features, + ); } else if attr.check_name("linkage") { if let Some(val) = attr.value_str() { codegen_fn_attrs.linkage = Some(linkage_by_name(tcx, id, &val.as_str())); @@ -2073,8 +2253,11 @@ fn codegen_fn_attrs<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, id: DefId) -> Codegen } else if attr.check_name("link_section") { if let Some(val) = attr.value_str() { if val.as_str().bytes().any(|b| b == 0) { - let msg = format!("illegal null byte in link_section \ - value: `{}`", &val); + let msg = format!( + "illegal null byte in link_section \ + value: `{}`", + &val + ); tcx.sess.span_err(attr.span, &msg); } else { codegen_fn_attrs.link_section = Some(val); @@ -2090,8 +2273,11 @@ fn codegen_fn_attrs<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, id: DefId) -> Codegen if codegen_fn_attrs.target_features.len() > 0 { if codegen_fn_attrs.inline == InlineAttr::Always { if let Some(span) = inline_span { - tcx.sess.span_err(span, "cannot use #[inline(always)] with \ - #[target_feature]"); + tcx.sess.span_err( + span, + "cannot use #[inline(always)] with \ + #[target_feature]", + ); } } } From ec47293998c32aab48bd85a418298a868b1e360a Mon Sep 17 00:00:00 2001 From: JoshBrudnak Date: Sun, 19 Aug 2018 12:40:30 -0400 Subject: [PATCH 2/3] Fix compile panic on non existant type return #53300 --- src/librustc_typeck/collect.rs | 20 +++++++++++++++++++- src/test/compile-fail/issue-53300.rs | 22 ++++++++++++++++++++++ 2 files changed, 41 insertions(+), 1 deletion(-) create mode 100644 src/test/compile-fail/issue-53300.rs diff --git a/src/librustc_typeck/collect.rs b/src/librustc_typeck/collect.rs index 44a1960ea18..e404eb4ecca 100644 --- a/src/librustc_typeck/collect.rs +++ b/src/librustc_typeck/collect.rs @@ -1163,7 +1163,25 @@ fn type_of<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId) -> Ty<'tcx> { ItemKind::Existential(hir::ExistTy { impl_trait_fn: Some(owner), .. - }) => tcx.typeck_tables_of(owner).concrete_existential_types[&def_id], + }) => { + tcx.typeck_tables_of(owner) + .concrete_existential_types + .get(&def_id) + .cloned() + .unwrap_or_else(|| { + // This can occur if some error in the + // owner fn prevented us from populating + // the `concrete_existential_types` table. + tcx.sess.delay_span_bug( + DUMMY_SP, + &format!( + "owner {:?} has no existential type for {:?} in its tables", + owner, def_id, + ), + ); + tcx.types.err + }) + } ItemKind::Trait(..) | ItemKind::TraitAlias(..) | ItemKind::Mod(..) diff --git a/src/test/compile-fail/issue-53300.rs b/src/test/compile-fail/issue-53300.rs new file mode 100644 index 00000000000..d055a6f12c1 --- /dev/null +++ b/src/test/compile-fail/issue-53300.rs @@ -0,0 +1,22 @@ +// Copyright 2012-2014 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. + +// issue 53300 + +pub trait A { + fn add(&self, b: i32) -> i32; +} + +fn addition() -> Wrapper {} +//~^ ERROR cannot find type `Wrapper` in this scope [E0412] + +fn main() { + let res = addition(); +} From 264d0a2e5c7291dc2dd2701b8e990c6fb58b54ed Mon Sep 17 00:00:00 2001 From: JoshBrudnak Date: Sun, 19 Aug 2018 19:16:48 -0400 Subject: [PATCH 3/3] Move non-existant type return test to the ui suite --- src/test/{compile-fail => ui}/issue-53300.rs | 0 src/test/ui/issue-53300.stderr | 9 +++++++++ 2 files changed, 9 insertions(+) rename src/test/{compile-fail => ui}/issue-53300.rs (100%) create mode 100644 src/test/ui/issue-53300.stderr diff --git a/src/test/compile-fail/issue-53300.rs b/src/test/ui/issue-53300.rs similarity index 100% rename from src/test/compile-fail/issue-53300.rs rename to src/test/ui/issue-53300.rs diff --git a/src/test/ui/issue-53300.stderr b/src/test/ui/issue-53300.stderr new file mode 100644 index 00000000000..920287a32d6 --- /dev/null +++ b/src/test/ui/issue-53300.stderr @@ -0,0 +1,9 @@ +error[E0412]: cannot find type `Wrapper` in this scope + --> $DIR/issue-53300.rs:17:18 + | +LL | fn addition() -> Wrapper {} + | ^^^^^^^ not found in this scope + +error: aborting due to previous error + +For more information about this error, try `rustc --explain E0412`.