From 494859e8dde5080534e94aba6d98affb921552f8 Mon Sep 17 00:00:00 2001 From: varkor Date: Thu, 8 Feb 2018 08:58:13 +0000 Subject: [PATCH 01/41] Consolidate PathParameters and AngleBracketedParameterData --- src/librustc/hir/intravisit.rs | 4 +- src/librustc/hir/lowering.rs | 59 ++++++------- src/librustc/hir/mod.rs | 40 +++++++-- src/librustc/hir/print.rs | 44 ++++++---- src/librustc/ich/impls_hir.rs | 8 +- src/librustc/middle/resolve_lifetime.rs | 18 ++-- src/librustc/ty/mod.rs | 95 +++++++++++++++++++++ src/librustc_driver/pretty.rs | 2 +- src/librustc_save_analysis/dump_visitor.rs | 4 +- src/librustc_typeck/astconv.rs | 42 ++++----- src/librustc_typeck/check/method/confirm.rs | 5 +- src/librustc_typeck/check/mod.rs | 14 +-- src/librustc_typeck/collect.rs | 7 ++ src/libsyntax/ast.rs | 34 +++++++- src/libsyntax/ext/build.rs | 33 +++---- src/libsyntax/fold.rs | 22 ++++- src/libsyntax/parse/parser.rs | 20 +++-- src/libsyntax/print/pprust.rs | 29 +++---- src/libsyntax/visit.rs | 4 +- src/libsyntax_ext/deriving/clone.rs | 3 +- src/libsyntax_ext/deriving/cmp/eq.rs | 4 +- src/libsyntax_ext/deriving/generic/mod.rs | 17 ++-- src/libsyntax_ext/deriving/generic/ty.rs | 26 ++++-- src/libsyntax_ext/env.rs | 5 +- 24 files changed, 364 insertions(+), 175 deletions(-) diff --git a/src/librustc/hir/intravisit.rs b/src/librustc/hir/intravisit.rs index 12ccb329e06ff..79b433e3cb2c3 100644 --- a/src/librustc/hir/intravisit.rs +++ b/src/librustc/hir/intravisit.rs @@ -650,8 +650,8 @@ pub fn walk_path_segment<'v, V: Visitor<'v>>(visitor: &mut V, pub fn walk_path_parameters<'v, V: Visitor<'v>>(visitor: &mut V, _path_span: Span, path_parameters: &'v PathParameters) { - walk_list!(visitor, visit_lifetime, &path_parameters.lifetimes); - walk_list!(visitor, visit_ty, &path_parameters.types); + walk_list!(visitor, visit_lifetime, path_parameters.lifetimes()); + walk_list!(visitor, visit_ty, path_parameters.types()); walk_list!(visitor, visit_assoc_type_binding, &path_parameters.bindings); } diff --git a/src/librustc/hir/lowering.rs b/src/librustc/hir/lowering.rs index dd12edb73027a..8e66ce3fd1825 100644 --- a/src/librustc/hir/lowering.rs +++ b/src/librustc/hir/lowering.rs @@ -46,6 +46,7 @@ use hir::HirVec; use hir::map::{DefKey, DefPathData, Definitions}; use hir::def_id::{DefId, DefIndex, DefIndexAddressSpace, CRATE_DEF_INDEX}; use hir::def::{Def, PathResolution, PerNS}; +use hir::GenericPathParam; use lint::builtin::{self, PARENTHESIZED_PARAMS_IN_TYPES_AND_MODULES}; use middle::cstore::CrateStore; use rustc_data_structures::indexed_vec::IndexVec; @@ -1037,6 +1038,20 @@ impl<'a> LoweringContext<'a> { } } + fn lower_param(&mut self, + p: &GenericAngleBracketedParam, + itctx: ImplTraitContext) + -> GenericPathParam { + match p { + GenericAngleBracketedParam::Lifetime(lt) => { + GenericPathParam::Lifetime(self.lower_lifetime(<)) + } + GenericAngleBracketedParam::Type(ty) => { + GenericPathParam::Type(self.lower_ty(&ty, itctx)) + } + } + } + fn lower_ty(&mut self, t: &Ty, itctx: ImplTraitContext) -> P { let kind = match t.node { TyKind::Infer => hir::TyInfer, @@ -1552,7 +1567,7 @@ impl<'a> LoweringContext<'a> { assert!(!def_id.is_local()); let item_generics = self.cstore.item_generics_cloned_untracked(def_id, self.sess); - let n = item_generics.own_counts().lifetimes; + let n = item_generics.own_counts().lifetimes(); self.type_def_lifetime_params.insert(def_id, n); n }); @@ -1671,7 +1686,7 @@ impl<'a> LoweringContext<'a> { ) -> hir::PathSegment { let (mut parameters, infer_types) = if let Some(ref parameters) = segment.parameters { let msg = "parenthesized parameters may only be used with a trait"; - match **parameters { + match **path_params { PathParameters::AngleBracketed(ref data) => { self.lower_angle_bracketed_parameter_data(data, param_mode, itctx) } @@ -1699,12 +1714,14 @@ impl<'a> LoweringContext<'a> { }; if !parameters.parenthesized && parameters.lifetimes.is_empty() { - parameters.lifetimes = self.elided_path_lifetimes(path_span, expected_lifetimes); + path_params.parameters = (0..expected_lifetimes).map(|_| { + GenericPathParam::Lifetime(self.elided_lifetime(path_span)) + }).chain(path_params.parameters.into_iter()).collect(); } hir::PathSegment::new( self.lower_ident(segment.ident), - parameters, + path_params, infer_types, ) } @@ -1715,24 +1732,13 @@ impl<'a> LoweringContext<'a> { param_mode: ParamMode, itctx: ImplTraitContext, ) -> (hir::PathParameters, bool) { - let &AngleBracketedParameterData { - ref lifetimes, - ref types, - ref bindings, - .. - } = data; - ( - hir::PathParameters { - lifetimes: self.lower_lifetimes(lifetimes), - types: types.iter().map(|ty| self.lower_ty(ty, itctx)).collect(), - bindings: bindings - .iter() - .map(|b| self.lower_ty_binding(b, itctx)) - .collect(), - parenthesized: false, - }, - types.is_empty() && param_mode == ParamMode::Optional, - ) + let &AngleBracketedParameterData { ref parameters, ref bindings, .. } = data; + (hir::PathParameters { + parameters: parameters.iter().map(|p| self.lower_param(p, itctx)).collect(), + bindings: bindings.iter().map(|b| self.lower_ty_binding(b, itctx)).collect(), + parenthesized: false, + }, + types.is_empty() && param_mode == ParamMode::Optional) } fn lower_parenthesized_parameter_data( @@ -1769,8 +1775,7 @@ impl<'a> LoweringContext<'a> { ( hir::PathParameters { - lifetimes: hir::HirVec::new(), - types: hir_vec![mk_tup(this, inputs, span)], + parameters: hir_vec![GenericPathParam::Type(mk_tup(this, inputs, span))], bindings: hir_vec![ hir::TypeBinding { id: this.next_id().node_id, @@ -1971,7 +1976,7 @@ impl<'a> LoweringContext<'a> { let def = hir::LifetimeDef { lifetime: self.lower_lifetime(&l.lifetime), - bounds: self.lower_lifetimes(&l.bounds), + bounds: l.bounds.iter().map(|l| self.lower_lifetime(l)).collect(), pure_wrt_drop: attr::contains_name(&l.attrs, "may_dangle"), in_band: false, }; @@ -1981,10 +1986,6 @@ impl<'a> LoweringContext<'a> { def } - fn lower_lifetimes(&mut self, lts: &Vec) -> hir::HirVec { - lts.iter().map(|l| self.lower_lifetime(l)).collect() - } - fn lower_generic_params( &mut self, params: &Vec, diff --git a/src/librustc/hir/mod.rs b/src/librustc/hir/mod.rs index 833090c3ee092..e69b824e77909 100644 --- a/src/librustc/hir/mod.rs +++ b/src/librustc/hir/mod.rs @@ -372,12 +372,16 @@ impl PathSegment { } } +#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)] +pub enum GenericPathParam { + Lifetime(Lifetime), + Type(P), +} + #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)] pub struct PathParameters { - /// The lifetime parameters for this path segment. - pub lifetimes: HirVec, - /// The type parameters for this path segment, if present. - pub types: HirVec>, + /// The generic parameters for this path segment. + pub parameters: HirVec, /// Bindings (equality constraints) on associated types, if present. /// E.g., `Foo`. pub bindings: HirVec, @@ -390,21 +394,19 @@ pub struct PathParameters { impl PathParameters { pub fn none() -> Self { Self { - lifetimes: HirVec::new(), - types: HirVec::new(), + parameters: HirVec::new(), bindings: HirVec::new(), parenthesized: false, } } pub fn is_empty(&self) -> bool { - self.lifetimes.is_empty() && self.types.is_empty() && - self.bindings.is_empty() && !self.parenthesized + self.parameters.is_empty() && self.bindings.is_empty() && !self.parenthesized } pub fn inputs(&self) -> &[P] { if self.parenthesized { - if let Some(ref ty) = self.types.get(0) { + if let Some(ref ty) = self.types().get(0) { if let TyTup(ref tys) = ty.node { return tys; } @@ -412,6 +414,26 @@ impl PathParameters { } bug!("PathParameters::inputs: not a `Fn(T) -> U`"); } + + pub fn lifetimes(&self) -> Vec<&Lifetime> { + self.parameters.iter().filter_map(|p| { + if let GenericPathParam::Lifetime(lt) = p { + Some(lt) + } else { + None + } + }).collect() + } + + pub fn types(&self) -> Vec<&P> { + self.parameters.iter().filter_map(|p| { + if let GenericPathParam::Type(ty) = p { + Some(ty) + } else { + None + } + }).collect() + } } /// The AST represents all type param bounds as types. diff --git a/src/librustc/hir/print.rs b/src/librustc/hir/print.rs index 1beef3f715e22..9e3c103b97812 100644 --- a/src/librustc/hir/print.rs +++ b/src/librustc/hir/print.rs @@ -25,6 +25,7 @@ use syntax_pos::{self, BytePos, FileName}; use hir; use hir::{PatKind, RegionTyParamBound, TraitTyParamBound, TraitBoundModifier, RangeEnd}; +use hir::GenericPathParam; use std::cell::Cell; use std::io::{self, Write, Read}; @@ -1269,8 +1270,7 @@ impl<'a> State<'a> { self.print_name(segment.name)?; segment.with_parameters(|parameters| { - if !parameters.lifetimes.is_empty() || - !parameters.types.is_empty() || + if !parameters.parameters.is_empty() || !parameters.bindings.is_empty() { self.print_path_parameters(¶meters, segment.infer_types, true) @@ -1707,18 +1707,18 @@ impl<'a> State<'a> { } fn print_path_parameters(&mut self, - parameters: &hir::PathParameters, + path_params: &hir::PathParameters, infer_types: bool, colons_before_params: bool) -> io::Result<()> { - if parameters.parenthesized { + if path_params.parenthesized { self.s.word("(")?; - self.commasep(Inconsistent, parameters.inputs(), |s, ty| s.print_type(&ty))?; + self.commasep(Inconsistent, path_params.inputs(), |s, ty| s.print_type(&ty))?; self.s.word(")")?; self.space_if_not_bol()?; self.word_space("->")?; - self.print_type(¶meters.bindings[0].ty)?; + self.print_type(&path_params.bindings[0].ty)?; } else { let start = if colons_before_params { "::<" } else { "<" }; let empty = Cell::new(true); @@ -1731,17 +1731,27 @@ impl<'a> State<'a> { } }; - if !parameters.lifetimes.iter().all(|lt| lt.is_elided()) { - for lifetime in ¶meters.lifetimes { - start_or_comma(self)?; - self.print_lifetime(lifetime)?; + let elide_lifetimes = path_params.parameters.iter().all(|p| { + if let GenericPathParam::Lifetime(lt) = p { + if !lt.is_elided() { + return false; + } } - } - - if !parameters.types.is_empty() { - start_or_comma(self)?; - self.commasep(Inconsistent, ¶meters.types, |s, ty| s.print_type(&ty))?; - } + true + }); + + self.commasep(Inconsistent, &path_params.parameters, |s, p| { + match p { + GenericPathParam::Lifetime(lt) => { + if !elide_lifetimes { + s.print_lifetime(lt) + } else { + Ok(()) + } + } + GenericPathParam::Type(ty) => s.print_type(ty), + } + })?; // FIXME(eddyb) This would leak into error messages, e.g.: // "non-exhaustive patterns: `Some::<..>(_)` not covered". @@ -1750,7 +1760,7 @@ impl<'a> State<'a> { self.s.word("..")?; } - for binding in parameters.bindings.iter() { + for binding in path_params.bindings.iter() { start_or_comma(self)?; self.print_name(binding.name)?; self.s.space()?; diff --git a/src/librustc/ich/impls_hir.rs b/src/librustc/ich/impls_hir.rs index ed259b2854511..54e6989d55a24 100644 --- a/src/librustc/ich/impls_hir.rs +++ b/src/librustc/ich/impls_hir.rs @@ -180,9 +180,13 @@ impl_stable_hash_for!(struct hir::PathSegment { parameters }); +impl_stable_hash_for!(enum hir::GenericPathParam { + Lifetime(lt), + Type(ty) +}); + impl_stable_hash_for!(struct hir::PathParameters { - lifetimes, - types, + parameters, bindings, parenthesized }); diff --git a/src/librustc/middle/resolve_lifetime.rs b/src/librustc/middle/resolve_lifetime.rs index f251a3d5f3838..477c4c213ce40 100644 --- a/src/librustc/middle/resolve_lifetime.rs +++ b/src/librustc/middle/resolve_lifetime.rs @@ -155,7 +155,7 @@ impl Region { } } - fn subst(self, params: &[hir::Lifetime], map: &NamedRegionMap) -> Option { + fn subst(self, params: Vec<&hir::Lifetime>, map: &NamedRegionMap) -> Option { if let Region::EarlyBound(index, _, _) = self { params .get(index as usize) @@ -820,7 +820,7 @@ impl<'a, 'tcx> Visitor<'tcx> for LifetimeContext<'a, 'tcx> { fn visit_lifetime(&mut self, lifetime_ref: &'tcx hir::Lifetime) { if lifetime_ref.is_elided() { - self.resolve_elided_lifetimes(slice::from_ref(lifetime_ref), false); + self.resolve_elided_lifetimes(vec![lifetime_ref], false); return; } if lifetime_ref.is_static() { @@ -1613,10 +1613,10 @@ impl<'a, 'tcx> LifetimeContext<'a, 'tcx> { return; } - if params.lifetimes.iter().all(|l| l.is_elided()) { - self.resolve_elided_lifetimes(¶ms.lifetimes, true); + if params.lifetimes().iter().all(|l| l.is_elided()) { + self.resolve_elided_lifetimes(params.lifetimes(), true); } else { - for l in ¶ms.lifetimes { + for l in ¶ms.lifetimes() { self.visit_lifetime(l); } } @@ -1688,13 +1688,13 @@ impl<'a, 'tcx> LifetimeContext<'a, 'tcx> { } else { Some(Region::Static) }, - Set1::One(r) => r.subst(¶ms.lifetimes, map), + Set1::One(r) => r.subst(params.lifetimes(), map), Set1::Many => None, }) .collect() }); - for (i, ty) in params.types.iter().enumerate() { + for (i, ty) in params.types().iter().enumerate() { if let Some(<) = object_lifetime_defaults.get(i) { let scope = Scope::ObjectLifetimeDefault { lifetime: lt, @@ -1981,7 +1981,9 @@ impl<'a, 'tcx> LifetimeContext<'a, 'tcx> { } } - fn resolve_elided_lifetimes(&mut self, lifetime_refs: &'tcx [hir::Lifetime], deprecated: bool) { + fn resolve_elided_lifetimes(&mut self, + lifetime_refs: Vec<&'tcx hir::Lifetime>, + deprecated: bool) { if lifetime_refs.is_empty() { return; } diff --git a/src/librustc/ty/mod.rs b/src/librustc/ty/mod.rs index 4f5f0c9d740cc..d09be8e5c4505 100644 --- a/src/librustc/ty/mod.rs +++ b/src/librustc/ty/mod.rs @@ -885,6 +885,73 @@ pub struct GenericParamCount { pub types: usize, } +#[derive(Clone, Debug, RustcEncodable, RustcDecodable)] +pub enum GenericParameterDef { + Lifetime(RegionParameterDef), + Type(TypeParameterDef), +} + +impl GenericParameterDef { + pub fn index(&self) -> u32 { + match self { + GenericParameterDef::Lifetime(lt) => lt.index, + GenericParameterDef::Type(ty) => ty.index, + } + } +} + +#[derive(Clone, Debug, RustcEncodable, RustcDecodable)] +pub enum KindIndex { + Lifetime, + Type, +} + +#[derive(Clone, Debug, RustcEncodable, RustcDecodable)] +pub struct KindIndexed { + pub lt: L, + pub ty: T, +} + +impl KindIndexed { + pub fn get(&self, idx: KindIndex) -> &T { + match idx { + KindIndex::Lifetime => &self.lt, + KindIndex::Type => &self.ty, + } + } + + pub fn iter(&self) -> KindIndexIterator { + KindIndexIterator { + index: self, + next: Some(KindIndex::Lifetime), + } + } +} + +#[derive(Clone, Debug)] +pub struct KindIndexIterator<'a, T: 'a> { + pub index: &'a KindIndexed, + pub next: Option, +} + +impl<'a, T> Iterator for KindIndexIterator<'a, T> { + type Item = &'a T; + + fn next(&mut self) -> Option { + match self.next { + Some(KindIndex::Lifetime) => { + self.next = Some(KindIndex::Type); + Some(&self.index.lt) + } + Some(KindIndex::Type) => { + self.next = None; + Some(&self.index.ty) + }, + None => None, + } + } +} + /// Information about the formal type/lifetime parameters associated /// with an item or method. Analogous to hir::Generics. /// @@ -942,6 +1009,34 @@ impl<'a, 'gcx, 'tcx> Generics { } } + pub fn lifetimes(&self) -> Vec<&RegionParameterDef> { + self.parameters.iter().filter_map(|p| { + if let GenericParameterDef::Lifetime(lt) = p { + Some(lt) + } else { + None + } + }).collect() + } + + pub fn types(&self) -> Vec<&TypeParameterDef> { + self.parameters.iter().filter_map(|p| { + if let GenericParameterDef::Type(ty) = p { + Some(ty) + } else { + None + } + }).collect() + } + + pub fn parent_lifetimes(&self) -> u32 { + *self.parent_parameters.get(KindIndex::Lifetime) + } + + pub fn parent_types(&self) -> u32 { + *self.parent_parameters.get(KindIndex::Type) + } + pub fn region_param(&'tcx self, param: &EarlyBoundRegion, tcx: TyCtxt<'a, 'gcx, 'tcx>) diff --git a/src/librustc_driver/pretty.rs b/src/librustc_driver/pretty.rs index f1ad14237eec2..71ecc89380646 100644 --- a/src/librustc_driver/pretty.rs +++ b/src/librustc_driver/pretty.rs @@ -680,7 +680,7 @@ impl<'a> ReplaceBodyWithLoop<'a> { match seg.parameters.as_ref().map(|p| &**p) { None => false, Some(&ast::PathParameters::AngleBracketed(ref data)) => - any_involves_impl_trait(data.types.iter()) || + any_involves_impl_trait(data.types().into_iter()) || any_involves_impl_trait(data.bindings.iter().map(|b| &b.ty)), Some(&ast::PathParameters::Parenthesized(ref data)) => any_involves_impl_trait(data.inputs.iter()) || diff --git a/src/librustc_save_analysis/dump_visitor.rs b/src/librustc_save_analysis/dump_visitor.rs index 279ee403cc625..81a3617f0aabb 100644 --- a/src/librustc_save_analysis/dump_visitor.rs +++ b/src/librustc_save_analysis/dump_visitor.rs @@ -822,7 +822,7 @@ impl<'l, 'tcx: 'l, 'll, O: DumpOutput + 'll> DumpVisitor<'l, 'tcx, 'll, O> { for seg in &path.segments { if let Some(ref params) = seg.parameters { match **params { - ast::PathParameters::AngleBracketed(ref data) => for t in &data.types { + ast::PathParameters::AngleBracketed(ref data) => for t in data.types() { self.visit_ty(t); }, ast::PathParameters::Parenthesized(ref data) => { @@ -907,7 +907,7 @@ impl<'l, 'tcx: 'l, 'll, O: DumpOutput + 'll> DumpVisitor<'l, 'tcx, 'll, O> { // Explicit types in the turbo-fish. if let Some(ref params) = seg.parameters { if let ast::PathParameters::AngleBracketed(ref data) = **params { - for t in &data.types { + for t in data.types() { self.visit_ty(t); } } diff --git a/src/librustc_typeck/astconv.rs b/src/librustc_typeck/astconv.rs index 18911b47ed1d0..005d088c4786f 100644 --- a/src/librustc_typeck/astconv.rs +++ b/src/librustc_typeck/astconv.rs @@ -214,8 +214,8 @@ impl<'o, 'gcx: 'tcx, 'tcx> AstConv<'gcx, 'tcx>+'o { // region with the current anon region binding (in other words, // whatever & would get replaced with). let decl_generics = tcx.generics_of(def_id); - let ty_provided = parameters.types.len(); - let lt_provided = parameters.lifetimes.len(); + let ty_provided = parameters.types().len(); + let lt_provided = parameters.lifetimes().len(); let mut lt_accepted = 0; let mut ty_params = ParamRange { required: 0, accepted: 0 }; @@ -269,7 +269,7 @@ impl<'o, 'gcx: 'tcx, 'tcx> AstConv<'gcx, 'tcx>+'o { match param.kind { GenericParamDefKind::Lifetime => { let i = param.index as usize - own_self; - if let Some(lifetime) = parameters.lifetimes.get(i) { + if let Some(lifetime) = parameters.lifetimes().get(i) { self.ast_region_to_region(lifetime, Some(param)).into() } else { tcx.types.re_static.into() @@ -286,7 +286,7 @@ impl<'o, 'gcx: 'tcx, 'tcx> AstConv<'gcx, 'tcx>+'o { let i = i - (lt_accepted + own_self); if i < ty_provided { // A provided type parameter. - self.ast_ty_to_ty(¶meters.types[i]).into() + self.ast_ty_to_ty(¶meters.types()[i]).into() } else if infer_types { // No type parameters were provided, we can infer all. if !default_needs_object_self(param) { @@ -970,23 +970,27 @@ impl<'o, 'gcx: 'tcx, 'tcx> AstConv<'gcx, 'tcx>+'o { pub fn prohibit_type_params(&self, segments: &[hir::PathSegment]) { for segment in segments { - segment.with_parameters(|parameters| { - for typ in ¶meters.types { - struct_span_err!(self.tcx().sess, typ.span, E0109, - "type parameters are not allowed on this type") - .span_label(typ.span, "type parameter not allowed") - .emit(); - break; - } - for lifetime in ¶meters.lifetimes { - struct_span_err!(self.tcx().sess, lifetime.span, E0110, - "lifetime parameters are not allowed on this type") - .span_label(lifetime.span, - "lifetime parameter not allowed on this type") - .emit(); + segment.with_parameters(|params| { + for p in ¶ms.parameters { + let (mut span_err, span, kind) = match p { + hir::GenericPathParam::Lifetime(lt) => { + (struct_span_err!(self.tcx().sess, lt.span, E0110, + "lifetime parameters are not allowed on this type"), + lt.span, + "lifetime") + } + hir::GenericPathParam::Type(ty) => { + (struct_span_err!(self.tcx().sess, ty.span, E0109, + "type parameters are not allowed on this type"), + ty.span, + "type") + } + }; + span_err.span_label(span, format!("{} parameter not allowed", kind)) + .emit(); break; } - for binding in ¶meters.bindings { + for binding in ¶ms.bindings { self.prohibit_projection(binding.span); break; } diff --git a/src/librustc_typeck/check/method/confirm.rs b/src/librustc_typeck/check/method/confirm.rs index f3a3c30fe5ad9..33102757925df 100644 --- a/src/librustc_typeck/check/method/confirm.rs +++ b/src/librustc_typeck/check/method/confirm.rs @@ -331,7 +331,7 @@ impl<'a, 'gcx, 'tcx> ConfirmContext<'a, 'gcx, 'tcx> { match param.kind { GenericParamDefKind::Lifetime => { if let Some(lifetime) = provided.as_ref().and_then(|p| { - p.lifetimes.get(i - parent_substs.len()) + p.lifetimes().get(i - parent_substs.len()) }) { return AstConv::ast_region_to_region( self.fcx, lifetime, Some(param)).into(); @@ -339,7 +339,7 @@ impl<'a, 'gcx, 'tcx> ConfirmContext<'a, 'gcx, 'tcx> { } GenericParamDefKind::Type {..} => { if let Some(ast_ty) = provided.as_ref().and_then(|p| { - p.types.get(i - parent_substs.len() - own_counts.lifetimes) + p.types().get(i - parent_substs.len() - own_counts.lifetimes) }) { return self.to_ty(ast_ty).into(); } @@ -347,6 +347,7 @@ impl<'a, 'gcx, 'tcx> ConfirmContext<'a, 'gcx, 'tcx> { } self.var_for_def(self.span, param) } + self.type_var_for_def(self.span, def, cur_substs) }) } diff --git a/src/librustc_typeck/check/mod.rs b/src/librustc_typeck/check/mod.rs index b70b61d191594..0f1b739cddf0a 100644 --- a/src/librustc_typeck/check/mod.rs +++ b/src/librustc_typeck/check/mod.rs @@ -4833,8 +4833,8 @@ impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> { match param.kind { GenericParamDefKind::Lifetime => { - let lifetimes = segment.map_or(&[][..], |(s, _)| { - s.parameters.as_ref().map_or(&[][..], |p| &p.lifetimes[..]) + let lifetimes = segment.map_or(vec![], |(s, _)| { + s.parameters.as_ref().map_or(vec![], |p| p.lifetimes()) }); if let Some(lifetime) = lifetimes.get(i) { @@ -4844,8 +4844,8 @@ impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> { } } GenericParamDefKind::Type {..} => { - let (types, infer_types) = segment.map_or((&[][..], true), |(s, _)| { - (s.parameters.as_ref().map_or(&[][..], |p| &p.types[..]), s.infer_types) + let (types, infer_types) = segment.map_or((vec![], true), |(s, _)| { + (s.parameters.as_ref().map_or(vec![], |p| |p| p.types()), s.infer_types) }); // Skip over the lifetimes in the same segment. @@ -4961,10 +4961,10 @@ impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> { is_method_call: bool, supress_mismatch_error: bool) { let (lifetimes, types, infer_types, bindings) = segment.map_or( - (&[][..], &[][..], true, &[][..]), + (vec![], vec![], true, &[][..]), |(s, _)| s.parameters.as_ref().map_or( - (&[][..], &[][..], s.infer_types, &[][..]), - |p| (&p.lifetimes[..], &p.types[..], + (vec![], vec![], s.infer_types, &[][..]), + |p| (p.lifetimes(), p.types(), s.infer_types, &p.bindings[..]))); let infer_lifetimes = lifetimes.len() == 0; diff --git a/src/librustc_typeck/collect.rs b/src/librustc_typeck/collect.rs index 58e804fc13f2d..6e323e5913aa1 100644 --- a/src/librustc_typeck/collect.rs +++ b/src/librustc_typeck/collect.rs @@ -973,6 +973,13 @@ fn generics_of<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, .map(|param| (param.def_id, param.index)) .collect(); + let parent_parameters = ty::KindIndexed { lt: parent_regions, ty: parent_types }; + let lifetimes: Vec = + regions.into_iter().map(|lt| ty::GenericParameterDef::Lifetime(lt)).collect(); + let types: Vec = + types.into_iter().map(|ty| ty::GenericParameterDef::Type(ty)).collect(); + let parameters = lifetimes.into_iter().chain(types.into_iter()).collect(); + tcx.alloc_generics(ty::Generics { parent: parent_def_id, parent_count, diff --git a/src/libsyntax/ast.rs b/src/libsyntax/ast.rs index 76fa463a63134..1af4743cfe4cb 100644 --- a/src/libsyntax/ast.rs +++ b/src/libsyntax/ast.rs @@ -167,21 +167,47 @@ impl PathParameters { } } +#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)] +pub enum GenericAngleBracketedParam { + Lifetime(Lifetime), + Type(P), +} + /// A path like `Foo<'a, T>` #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Default)] pub struct AngleBracketedParameterData { /// Overall span pub span: Span, - /// The lifetime parameters for this path segment. - pub lifetimes: Vec, - /// The type parameters for this path segment, if present. - pub types: Vec>, + /// The parameters for this path segment. + pub parameters: Vec, /// Bindings (equality constraints) on associated types, if present. /// /// E.g., `Foo`. pub bindings: Vec, } +impl AngleBracketedParameterData { + pub fn lifetimes(&self) -> Vec<&Lifetime> { + self.parameters.iter().filter_map(|p| { + if let GenericAngleBracketedParam::Lifetime(lt) = p { + Some(lt) + } else { + None + } + }).collect() + } + + pub fn types(&self) -> Vec<&P> { + self.parameters.iter().filter_map(|p| { + if let GenericAngleBracketedParam::Type(ty) = p { + Some(ty) + } else { + None + } + }).collect() + } +} + impl Into>> for AngleBracketedParameterData { fn into(self) -> Option> { Some(P(PathParameters::AngleBracketed(self))) diff --git a/src/libsyntax/ext/build.rs b/src/libsyntax/ext/build.rs index 4a6f06dcc17ba..02112517827a5 100644 --- a/src/libsyntax/ext/build.rs +++ b/src/libsyntax/ext/build.rs @@ -30,10 +30,9 @@ pub trait AstBuilder { fn path_global(&self, span: Span, strs: Vec ) -> ast::Path; fn path_all(&self, sp: Span, global: bool, - idents: Vec , - lifetimes: Vec, - types: Vec>, - bindings: Vec ) + idents: Vec, + parameters: Vec, + bindings: Vec) -> ast::Path; fn qpath(&self, self_type: P, @@ -43,8 +42,7 @@ pub trait AstBuilder { fn qpath_all(&self, self_type: P, trait_path: ast::Path, ident: ast::Ident, - lifetimes: Vec, - types: Vec>, + parameters: Vec, bindings: Vec) -> (ast::QSelf, ast::Path); @@ -304,20 +302,19 @@ pub trait AstBuilder { impl<'a> AstBuilder for ExtCtxt<'a> { fn path(&self, span: Span, strs: Vec ) -> ast::Path { - self.path_all(span, false, strs, Vec::new(), Vec::new(), Vec::new()) + self.path_all(span, false, strs, Vec::new(), Vec::new()) } fn path_ident(&self, span: Span, id: ast::Ident) -> ast::Path { self.path(span, vec![id]) } fn path_global(&self, span: Span, strs: Vec ) -> ast::Path { - self.path_all(span, true, strs, Vec::new(), Vec::new(), Vec::new()) + self.path_all(span, true, strs, Vec::new(), Vec::new()) } fn path_all(&self, span: Span, global: bool, mut idents: Vec , - lifetimes: Vec, - types: Vec>, + parameters: Vec, bindings: Vec ) -> ast::Path { let last_ident = idents.pop().unwrap(); @@ -326,8 +323,8 @@ impl<'a> AstBuilder for ExtCtxt<'a> { segments.extend(idents.into_iter().map(|ident| { ast::PathSegment::from_ident(ident.with_span_pos(span)) })); - let parameters = if !lifetimes.is_empty() || !types.is_empty() || !bindings.is_empty() { - ast::AngleBracketedParameterData { lifetimes, types, bindings, span }.into() + let parameters = if !parameters.is_empty() !bindings.is_empty() { + ast::AngleBracketedParameterData { parameters, bindings, span }.into() } else { None }; @@ -349,7 +346,7 @@ impl<'a> AstBuilder for ExtCtxt<'a> { trait_path: ast::Path, ident: ast::Ident) -> (ast::QSelf, ast::Path) { - self.qpath_all(self_type, trait_path, ident, vec![], vec![], vec![]) + self.qpath_all(self_type, trait_path, ident, vec![], vec![]) } /// Constructs a qualified path. @@ -359,13 +356,12 @@ impl<'a> AstBuilder for ExtCtxt<'a> { self_type: P, trait_path: ast::Path, ident: ast::Ident, - lifetimes: Vec, - types: Vec>, + parameters: Vec, bindings: Vec) -> (ast::QSelf, ast::Path) { let mut path = trait_path; - let parameters = if !lifetimes.is_empty() || !types.is_empty() || !bindings.is_empty() { - ast::AngleBracketedParameterData { lifetimes, types, bindings, span: ident.span }.into() + let parameters = if !parameters.is_empty() || !bindings.is_empty() { + ast::AngleBracketedParameterData { parameters, bindings, span: ident.span }.into() } else { None }; @@ -428,8 +424,7 @@ impl<'a> AstBuilder for ExtCtxt<'a> { self.path_all(DUMMY_SP, true, self.std_path(&["option", "Option"]), - Vec::new(), - vec![ ty ], + vec![ ast::GenericAngleBracketedParam::Type(ty) ], Vec::new())) } diff --git a/src/libsyntax/fold.rs b/src/libsyntax/fold.rs index 8544ef330dc33..b935425cdd400 100644 --- a/src/libsyntax/fold.rs +++ b/src/libsyntax/fold.rs @@ -132,6 +132,10 @@ pub trait Folder : Sized { noop_fold_exprs(es, self) } + fn fold_param(&mut self, p: GenericAngleBracketedParam) -> GenericAngleBracketedParam { + noop_fold_param(p, self) + } + fn fold_ty(&mut self, t: P) -> P { noop_fold_ty(t, self) } @@ -353,6 +357,19 @@ pub fn noop_fold_ty_binding(b: TypeBinding, fld: &mut T) -> TypeBindi } } +pub fn noop_fold_param(p: GenericAngleBracketedParam, + fld: &mut T) + -> GenericAngleBracketedParam { + match p { + GenericAngleBracketedParam::Lifetime(lt) => { + GenericAngleBracketedParam::Lifetime(noop_fold_lifetime(lt, fld)) + } + GenericAngleBracketedParam::Type(ty) => { + GenericAngleBracketedParam::Type(noop_fold_ty(ty, fld)) + } + } +} + pub fn noop_fold_ty(t: P, fld: &mut T) -> P { t.map(|Ty {id, node, span}| Ty { id: fld.new_id(id), @@ -469,9 +486,8 @@ pub fn noop_fold_angle_bracketed_parameter_data(data: AngleBracketedP fld: &mut T) -> AngleBracketedParameterData { - let AngleBracketedParameterData { lifetimes, types, bindings, span } = data; - AngleBracketedParameterData { lifetimes: lifetimes.move_map(|l| noop_fold_lifetime(l, fld)), - types: types.move_map(|ty| fld.fold_ty(ty)), + let AngleBracketedParameterData { parameters, bindings, span } = data; + AngleBracketedParameterData { parameters: parameters.move_map(|p| fld.fold_param(p)), bindings: bindings.move_map(|b| fld.fold_ty_binding(b)), span: fld.new_span(span) } } diff --git a/src/libsyntax/parse/parser.rs b/src/libsyntax/parse/parser.rs index 1735951da2f34..c205e93761105 100644 --- a/src/libsyntax/parse/parser.rs +++ b/src/libsyntax/parse/parser.rs @@ -22,6 +22,7 @@ use ast::{Expr, ExprKind, RangeLimits}; use ast::{Field, FnDecl}; use ast::{ForeignItem, ForeignItemKind, FunctionRetTy}; use ast::GenericParam; +use ast::GenericAngleBracketedParam; use ast::{Ident, ImplItem, IsAuto, Item, ItemKind}; use ast::{Label, Lifetime, LifetimeDef, Lit, LitKind}; use ast::Local; @@ -1971,10 +1972,10 @@ impl<'a> Parser<'a> { let parameters = if self.eat_lt() { // `<'a, T, A = U>` - let (lifetimes, types, bindings) = self.parse_generic_args()?; + let (parameters, bindings) = self.parse_generic_args()?; self.expect_gt()?; let span = lo.to(self.prev_span); - AngleBracketedParameterData { lifetimes, types, bindings, span }.into() + AngleBracketedParameterData { parameters, bindings, span }.into() } else { // `(T, U) -> R` self.bump(); // `(` @@ -4936,16 +4937,16 @@ impl<'a> Parser<'a> { /// Parses (possibly empty) list of lifetime and type arguments and associated type bindings, /// possibly including trailing comma. - fn parse_generic_args(&mut self) -> PResult<'a, (Vec, Vec>, Vec)> { - let mut lifetimes = Vec::new(); - let mut types = Vec::new(); + fn parse_generic_args(&mut self) + -> PResult<'a, (Vec, Vec)> { + let mut parameters = Vec::new(); let mut bindings = Vec::new(); let mut seen_type = false; let mut seen_binding = false; loop { if self.check_lifetime() && self.look_ahead(1, |t| !t.is_like_plus()) { // Parse lifetime argument. - lifetimes.push(self.expect_lifetime()); + parameters.push(GenericAngleBracketedParam::Lifetime(self.expect_lifetime())); if seen_type || seen_binding { self.span_err(self.prev_span, "lifetime parameters must be declared prior to type parameters"); @@ -4965,11 +4966,12 @@ impl<'a> Parser<'a> { seen_binding = true; } else if self.check_type() { // Parse type argument. - types.push(self.parse_ty()?); + let ty_param = self.parse_ty()?; if seen_binding { - self.span_err(types[types.len() - 1].span, + self.span_err(ty_param.span, "type parameters must be declared prior to associated type bindings"); } + parameters.push(GenericAngleBracketedParam::Type(ty_param)); seen_type = true; } else { break @@ -4979,7 +4981,7 @@ impl<'a> Parser<'a> { break } } - Ok((lifetimes, types, bindings)) + Ok((parameters, bindings)) } /// Parses an optional `where` clause and places it in `generics`. diff --git a/src/libsyntax/print/pprust.rs b/src/libsyntax/print/pprust.rs index 87edfd69e2bd6..dc204e3d0ef6c 100644 --- a/src/libsyntax/print/pprust.rs +++ b/src/libsyntax/print/pprust.rs @@ -13,7 +13,7 @@ pub use self::AnnNode::*; use rustc_target::spec::abi::{self, Abi}; use ast::{self, BlockCheckMode, PatKind, RangeEnd, RangeSyntax}; use ast::{SelfKind, RegionTyParamBound, TraitTyParamBound, TraitBoundModifier}; -use ast::{Attribute, MacDelimiter}; +use ast::{Attribute, MacDelimiter, GenericAngleBracketedParam}; use util::parser::{self, AssocOp, Fixity}; use attr; use codemap::{self, CodeMap}; @@ -1017,6 +1017,13 @@ impl<'a> State<'a> { Ok(()) } + pub fn print_param(&mut self, param: &GenericAngleBracketedParam) -> io::Result<()> { + match param { + GenericAngleBracketedParam::Lifetime(lt) => self.print_lifetime(lt), + GenericAngleBracketedParam::Type(ty) => self.print_type(ty), + } + } + pub fn print_type(&mut self, ty: &ast::Ty) -> io::Result<()> { self.maybe_print_comment(ty.span.lo())?; self.ibox(0)?; @@ -2474,25 +2481,9 @@ impl<'a> State<'a> { ast::PathParameters::AngleBracketed(ref data) => { self.s.word("<")?; - let mut comma = false; - for lifetime in &data.lifetimes { - if comma { - self.word_space(",")? - } - self.print_lifetime(lifetime)?; - comma = true; - } + self.commasep(Inconsistent, &data.parameters, |s, p| s.print_param(p))?; - if !data.types.is_empty() { - if comma { - self.word_space(",")? - } - self.commasep( - Inconsistent, - &data.types, - |s, ty| s.print_type(ty))?; - comma = true; - } + let mut comma = data.parameters.len() != 0; for binding in data.bindings.iter() { if comma { diff --git a/src/libsyntax/visit.rs b/src/libsyntax/visit.rs index adda39c62ed0e..a4b9e3d7d4519 100644 --- a/src/libsyntax/visit.rs +++ b/src/libsyntax/visit.rs @@ -387,8 +387,8 @@ pub fn walk_path_parameters<'a, V>(visitor: &mut V, { match *path_parameters { PathParameters::AngleBracketed(ref data) => { - walk_list!(visitor, visit_ty, &data.types); - walk_list!(visitor, visit_lifetime, &data.lifetimes); + walk_list!(visitor, visit_lifetime, data.lifetimes()); + walk_list!(visitor, visit_ty, data.types()); walk_list!(visitor, visit_assoc_type_binding, &data.bindings); } PathParameters::Parenthesized(ref data) => { diff --git a/src/libsyntax_ext/deriving/clone.rs b/src/libsyntax_ext/deriving/clone.rs index dec24d13c9b49..3a83922bc90c1 100644 --- a/src/libsyntax_ext/deriving/clone.rs +++ b/src/libsyntax_ext/deriving/clone.rs @@ -13,6 +13,7 @@ use deriving::generic::*; use deriving::generic::ty::*; use syntax::ast::{self, Expr, Generics, ItemKind, MetaItem, VariantData}; +use syntax::ast::GenericAngleBracketedParam; use syntax::attr; use syntax::ext::base::{Annotatable, ExtCtxt}; use syntax::ext::build::AstBuilder; @@ -123,7 +124,7 @@ fn cs_clone_shallow(name: &str, let span = span.with_ctxt(cx.backtrace()); let assert_path = cx.path_all(span, true, cx.std_path(&["clone", helper_name]), - vec![], vec![ty], vec![]); + vec![GenericAngleBracketedParam::Type(ty)], vec![]); stmts.push(cx.stmt_let_type_only(span, cx.ty_path(assert_path))); } fn process_variant(cx: &mut ExtCtxt, stmts: &mut Vec, variant: &VariantData) { diff --git a/src/libsyntax_ext/deriving/cmp/eq.rs b/src/libsyntax_ext/deriving/cmp/eq.rs index 237c8654edf6e..61b7e5b482d76 100644 --- a/src/libsyntax_ext/deriving/cmp/eq.rs +++ b/src/libsyntax_ext/deriving/cmp/eq.rs @@ -12,7 +12,7 @@ use deriving::path_std; use deriving::generic::*; use deriving::generic::ty::*; -use syntax::ast::{self, Expr, MetaItem}; +use syntax::ast::{self, Expr, MetaItem, GenericAngleBracketedParam}; use syntax::ext::base::{Annotatable, ExtCtxt}; use syntax::ext::build::AstBuilder; use syntax::ptr::P; @@ -62,7 +62,7 @@ fn cs_total_eq_assert(cx: &mut ExtCtxt, trait_span: Span, substr: &Substructure) let span = span.with_ctxt(cx.backtrace()); let assert_path = cx.path_all(span, true, cx.std_path(&["cmp", helper_name]), - vec![], vec![ty], vec![]); + vec![GenericAngleBracketedParam::Type(ty)], vec![]); stmts.push(cx.stmt_let_type_only(span, cx.ty_path(assert_path))); } fn process_variant(cx: &mut ExtCtxt, stmts: &mut Vec, variant: &ast::VariantData) { diff --git a/src/libsyntax_ext/deriving/generic/mod.rs b/src/libsyntax_ext/deriving/generic/mod.rs index 80f65957c39a2..7ab0acda4080a 100644 --- a/src/libsyntax_ext/deriving/generic/mod.rs +++ b/src/libsyntax_ext/deriving/generic/mod.rs @@ -192,10 +192,8 @@ use std::collections::HashSet; use std::vec; use rustc_target::spec::abi::Abi; -use syntax::ast::{ - self, BinOpKind, EnumDef, Expr, GenericParam, Generics, Ident, PatKind, VariantData -}; - +use syntax::ast::{self, BinOpKind, EnumDef, Expr, GenericParam, Generics, Ident, PatKind}; +use syntax::ast::{VariantData, GenericAngleBracketedParam}; use syntax::attr; use syntax::ext::base::{Annotatable, ExtCtxt}; use syntax::ext::build::AstBuilder; @@ -667,7 +665,7 @@ impl<'a> TraitDef<'a> { let trait_ref = cx.trait_ref(trait_path); // Create the type parameters on the `self` path. - let self_ty_params = generics.params + let self_ty_params: Vec> = generics.params .iter() .filter_map(|param| match *param { GenericParam::Type(ref ty_param) @@ -684,12 +682,17 @@ impl<'a> TraitDef<'a> { }) .collect(); + let self_params = self_lifetimes.into_iter() + .map(|lt| GenericAngleBracketedParam::Lifetime(lt)) + .chain(self_ty_params.into_iter().map(|ty| + GenericAngleBracketedParam::Type(ty))) + .collect(); + // Create the type of `self`. let self_type = cx.ty_path(cx.path_all(self.span, false, vec![type_ident], - self_lifetimes, - self_ty_params, + self_params, Vec::new())); let attr = cx.attribute(self.span, diff --git a/src/libsyntax_ext/deriving/generic/ty.rs b/src/libsyntax_ext/deriving/generic/ty.rs index 25a2969448835..6387f2d8d98f0 100644 --- a/src/libsyntax_ext/deriving/generic/ty.rs +++ b/src/libsyntax_ext/deriving/generic/ty.rs @@ -15,7 +15,7 @@ pub use self::PtrTy::*; pub use self::Ty::*; use syntax::ast; -use syntax::ast::{Expr, GenericParam, Generics, Ident, SelfKind}; +use syntax::ast::{Expr, GenericParam, Generics, Ident, SelfKind, GenericAngleBracketedParam}; use syntax::ext::base::ExtCtxt; use syntax::ext::build::AstBuilder; use syntax::codemap::{respan, DUMMY_SP}; @@ -86,15 +86,20 @@ impl<'a> Path<'a> { -> ast::Path { let mut idents = self.path.iter().map(|s| cx.ident_of(*s)).collect(); let lt = mk_lifetimes(cx, span, &self.lifetime); - let tys = self.params.iter().map(|t| t.to_ty(cx, span, self_ty, self_generics)).collect(); + let tys: Vec> = + self.params.iter().map(|t| t.to_ty(cx, span, self_ty, self_generics)).collect(); + let params = lt.into_iter() + .map(|lt| GenericAngleBracketedParam::Lifetime(lt)) + .chain(tys.into_iter().map(|ty| GenericAngleBracketedParam::Type(ty))) + .collect(); match self.kind { - PathKind::Global => cx.path_all(span, true, idents, lt, tys, Vec::new()), - PathKind::Local => cx.path_all(span, false, idents, lt, tys, Vec::new()), + PathKind::Global => cx.path_all(span, true, idents, params, Vec::new()), + PathKind::Local => cx.path_all(span, false, idents, params, Vec::new()), PathKind::Std => { let def_site = DUMMY_SP.apply_mark(cx.current_expansion.mark); idents.insert(0, Ident::new(keywords::DollarCrate.name(), def_site)); - cx.path_all(span, false, idents, lt, tys, Vec::new()) + cx.path_all(span, false, idents, params, Vec::new()) } } @@ -184,7 +189,7 @@ impl<'a> Ty<'a> { -> ast::Path { match *self { Self_ => { - let self_params = self_generics.params + let ty_params: Vec> = self_generics.params .iter() .filter_map(|param| match *param { GenericParam::Type(ref ty_param) => Some(cx.ty_ident(span, ty_param.ident)), @@ -200,11 +205,16 @@ impl<'a> Ty<'a> { }) .collect(); + let params = lifetimes.into_iter() + .map(|lt| GenericAngleBracketedParam::Lifetime(lt)) + .chain(ty_params.into_iter().map(|ty| + GenericAngleBracketedParam::Type(ty))) + .collect(); + cx.path_all(span, false, vec![self_ty], - lifetimes, - self_params, + params, Vec::new()) } Literal(ref p) => p.to_path(cx, span, self_ty, self_generics), diff --git a/src/libsyntax_ext/env.rs b/src/libsyntax_ext/env.rs index 4e1af108ab4fa..c904cfcfdbff4 100644 --- a/src/libsyntax_ext/env.rs +++ b/src/libsyntax_ext/env.rs @@ -13,7 +13,7 @@ // interface. // -use syntax::ast::{self, Ident}; +use syntax::ast::{self, Ident, GenericAngleBracketedParam}; use syntax::ext::base::*; use syntax::ext::base; use syntax::ext::build::AstBuilder; @@ -39,8 +39,7 @@ pub fn expand_option_env<'cx>(cx: &'cx mut ExtCtxt, cx.expr_path(cx.path_all(sp, true, cx.std_path(&["option", "Option", "None"]), - Vec::new(), - vec![cx.ty_rptr(sp, + vec![GenericAngleBracketedParam::Type(cx.ty_rptr(sp, cx.ty_ident(sp, Ident::from_str("str")), Some(lt), ast::Mutability::Immutable)], From 1ed60a9173ab5b757adf239269e3aa91d30abf54 Mon Sep 17 00:00:00 2001 From: varkor Date: Mon, 12 Feb 2018 21:44:05 +0000 Subject: [PATCH 02/41] Rename *Parameter to *Param --- src/librustc/hir/lowering.rs | 24 +++++++++++------------ src/librustc/hir/mod.rs | 8 ++++---- src/librustc/hir/print.rs | 12 ++++++++---- src/librustc/ich/impls_hir.rs | 2 +- src/librustc/ty/mod.rs | 16 +++++++-------- src/librustc_typeck/astconv.rs | 4 ++-- src/librustc_typeck/collect.rs | 10 +++++----- src/librustdoc/clean/mod.rs | 6 +++--- src/libsyntax/ast.rs | 8 ++++---- src/libsyntax/ext/build.rs | 10 +++++----- src/libsyntax/fold.rs | 14 ++++++------- src/libsyntax/parse/parser.rs | 8 ++++---- src/libsyntax/print/pprust.rs | 8 ++++---- src/libsyntax_ext/deriving/clone.rs | 4 ++-- src/libsyntax_ext/deriving/cmp/eq.rs | 4 ++-- src/libsyntax_ext/deriving/generic/mod.rs | 6 +++--- src/libsyntax_ext/deriving/generic/ty.rs | 10 +++++----- src/libsyntax_ext/env.rs | 4 ++-- 18 files changed, 81 insertions(+), 77 deletions(-) diff --git a/src/librustc/hir/lowering.rs b/src/librustc/hir/lowering.rs index 8e66ce3fd1825..fd914f9f62bb1 100644 --- a/src/librustc/hir/lowering.rs +++ b/src/librustc/hir/lowering.rs @@ -46,7 +46,7 @@ use hir::HirVec; use hir::map::{DefKey, DefPathData, Definitions}; use hir::def_id::{DefId, DefIndex, DefIndexAddressSpace, CRATE_DEF_INDEX}; use hir::def::{Def, PathResolution, PerNS}; -use hir::GenericPathParam; +use hir::PathParam; use lint::builtin::{self, PARENTHESIZED_PARAMS_IN_TYPES_AND_MODULES}; use middle::cstore::CrateStore; use rustc_data_structures::indexed_vec::IndexVec; @@ -1038,16 +1038,16 @@ impl<'a> LoweringContext<'a> { } } - fn lower_param(&mut self, - p: &GenericAngleBracketedParam, - itctx: ImplTraitContext) - -> GenericPathParam { + fn lower_path_param(&mut self, + p: &AngleBracketedParam, + itctx: ImplTraitContext) + -> PathParam { match p { - GenericAngleBracketedParam::Lifetime(lt) => { - GenericPathParam::Lifetime(self.lower_lifetime(<)) + AngleBracketedParam::Lifetime(lt) => { + PathParam::Lifetime(self.lower_lifetime(<)) } - GenericAngleBracketedParam::Type(ty) => { - GenericPathParam::Type(self.lower_ty(&ty, itctx)) + AngleBracketedParam::Type(ty) => { + PathParam::Type(self.lower_ty(&ty, itctx)) } } } @@ -1715,7 +1715,7 @@ impl<'a> LoweringContext<'a> { if !parameters.parenthesized && parameters.lifetimes.is_empty() { path_params.parameters = (0..expected_lifetimes).map(|_| { - GenericPathParam::Lifetime(self.elided_lifetime(path_span)) + PathParam::Lifetime(self.elided_lifetime(path_span)) }).chain(path_params.parameters.into_iter()).collect(); } @@ -1734,7 +1734,7 @@ impl<'a> LoweringContext<'a> { ) -> (hir::PathParameters, bool) { let &AngleBracketedParameterData { ref parameters, ref bindings, .. } = data; (hir::PathParameters { - parameters: parameters.iter().map(|p| self.lower_param(p, itctx)).collect(), + parameters: parameters.iter().map(|p| self.lower_path_param(p, itctx)).collect(), bindings: bindings.iter().map(|b| self.lower_ty_binding(b, itctx)).collect(), parenthesized: false, }, @@ -1775,7 +1775,7 @@ impl<'a> LoweringContext<'a> { ( hir::PathParameters { - parameters: hir_vec![GenericPathParam::Type(mk_tup(this, inputs, span))], + parameters: hir_vec![PathParam::Type(mk_tup(this, inputs, span))], bindings: hir_vec![ hir::TypeBinding { id: this.next_id().node_id, diff --git a/src/librustc/hir/mod.rs b/src/librustc/hir/mod.rs index e69b824e77909..455e64351e186 100644 --- a/src/librustc/hir/mod.rs +++ b/src/librustc/hir/mod.rs @@ -373,7 +373,7 @@ impl PathSegment { } #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)] -pub enum GenericPathParam { +pub enum PathParam { Lifetime(Lifetime), Type(P), } @@ -381,7 +381,7 @@ pub enum GenericPathParam { #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)] pub struct PathParameters { /// The generic parameters for this path segment. - pub parameters: HirVec, + pub parameters: HirVec, /// Bindings (equality constraints) on associated types, if present. /// E.g., `Foo`. pub bindings: HirVec, @@ -417,7 +417,7 @@ impl PathParameters { pub fn lifetimes(&self) -> Vec<&Lifetime> { self.parameters.iter().filter_map(|p| { - if let GenericPathParam::Lifetime(lt) = p { + if let PathParam::Lifetime(lt) = p { Some(lt) } else { None @@ -427,7 +427,7 @@ impl PathParameters { pub fn types(&self) -> Vec<&P> { self.parameters.iter().filter_map(|p| { - if let GenericPathParam::Type(ty) = p { + if let PathParam::Type(ty) = p { Some(ty) } else { None diff --git a/src/librustc/hir/print.rs b/src/librustc/hir/print.rs index 9e3c103b97812..6f4a9dd59296e 100644 --- a/src/librustc/hir/print.rs +++ b/src/librustc/hir/print.rs @@ -25,7 +25,7 @@ use syntax_pos::{self, BytePos, FileName}; use hir; use hir::{PatKind, RegionTyParamBound, TraitTyParamBound, TraitBoundModifier, RangeEnd}; -use hir::GenericPathParam; +use hir::PathParam; use std::cell::Cell; use std::io::{self, Write, Read}; @@ -1732,7 +1732,7 @@ impl<'a> State<'a> { }; let elide_lifetimes = path_params.parameters.iter().all(|p| { - if let GenericPathParam::Lifetime(lt) = p { + if let PathParam::Lifetime(lt) = p { if !lt.is_elided() { return false; } @@ -1742,17 +1742,21 @@ impl<'a> State<'a> { self.commasep(Inconsistent, &path_params.parameters, |s, p| { match p { - GenericPathParam::Lifetime(lt) => { + PathParam::Lifetime(lt) => { if !elide_lifetimes { s.print_lifetime(lt) } else { Ok(()) } } - GenericPathParam::Type(ty) => s.print_type(ty), + PathParam::Type(ty) => s.print_type(ty), } })?; + if !path_params.parameters.is_empty() { + empty.set(false); + } + // FIXME(eddyb) This would leak into error messages, e.g.: // "non-exhaustive patterns: `Some::<..>(_)` not covered". if infer_types && false { diff --git a/src/librustc/ich/impls_hir.rs b/src/librustc/ich/impls_hir.rs index 54e6989d55a24..ee139412853b1 100644 --- a/src/librustc/ich/impls_hir.rs +++ b/src/librustc/ich/impls_hir.rs @@ -180,7 +180,7 @@ impl_stable_hash_for!(struct hir::PathSegment { parameters }); -impl_stable_hash_for!(enum hir::GenericPathParam { +impl_stable_hash_for!(enum hir::PathParam { Lifetime(lt), Type(ty) }); diff --git a/src/librustc/ty/mod.rs b/src/librustc/ty/mod.rs index d09be8e5c4505..9e0f98772bf14 100644 --- a/src/librustc/ty/mod.rs +++ b/src/librustc/ty/mod.rs @@ -886,16 +886,16 @@ pub struct GenericParamCount { } #[derive(Clone, Debug, RustcEncodable, RustcDecodable)] -pub enum GenericParameterDef { +pub enum GenericParam { Lifetime(RegionParameterDef), Type(TypeParameterDef), } -impl GenericParameterDef { +impl GenericParam { pub fn index(&self) -> u32 { match self { - GenericParameterDef::Lifetime(lt) => lt.index, - GenericParameterDef::Type(ty) => ty.index, + GenericParam::Lifetime(lt) => lt.index, + GenericParam::Type(ty) => ty.index, } } } @@ -1011,7 +1011,7 @@ impl<'a, 'gcx, 'tcx> Generics { pub fn lifetimes(&self) -> Vec<&RegionParameterDef> { self.parameters.iter().filter_map(|p| { - if let GenericParameterDef::Lifetime(lt) = p { + if let GenericParam::Lifetime(lt) = p { Some(lt) } else { None @@ -1021,7 +1021,7 @@ impl<'a, 'gcx, 'tcx> Generics { pub fn types(&self) -> Vec<&TypeParameterDef> { self.parameters.iter().filter_map(|p| { - if let GenericParameterDef::Type(ty) = p { + if let GenericParam::Type(ty) = p { Some(ty) } else { None @@ -1030,11 +1030,11 @@ impl<'a, 'gcx, 'tcx> Generics { } pub fn parent_lifetimes(&self) -> u32 { - *self.parent_parameters.get(KindIndex::Lifetime) + *self.parent_params.get(KindIndex::Lifetime) } pub fn parent_types(&self) -> u32 { - *self.parent_parameters.get(KindIndex::Type) + *self.parent_params.get(KindIndex::Type) } pub fn region_param(&'tcx self, diff --git a/src/librustc_typeck/astconv.rs b/src/librustc_typeck/astconv.rs index 005d088c4786f..a9d97df46134c 100644 --- a/src/librustc_typeck/astconv.rs +++ b/src/librustc_typeck/astconv.rs @@ -973,13 +973,13 @@ impl<'o, 'gcx: 'tcx, 'tcx> AstConv<'gcx, 'tcx>+'o { segment.with_parameters(|params| { for p in ¶ms.parameters { let (mut span_err, span, kind) = match p { - hir::GenericPathParam::Lifetime(lt) => { + hir::PathParam::Lifetime(lt) => { (struct_span_err!(self.tcx().sess, lt.span, E0110, "lifetime parameters are not allowed on this type"), lt.span, "lifetime") } - hir::GenericPathParam::Type(ty) => { + hir::PathParam::Type(ty) => { (struct_span_err!(self.tcx().sess, ty.span, E0109, "type parameters are not allowed on this type"), ty.span, diff --git a/src/librustc_typeck/collect.rs b/src/librustc_typeck/collect.rs index 6e323e5913aa1..70367dd2461d2 100644 --- a/src/librustc_typeck/collect.rs +++ b/src/librustc_typeck/collect.rs @@ -973,11 +973,11 @@ fn generics_of<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, .map(|param| (param.def_id, param.index)) .collect(); - let parent_parameters = ty::KindIndexed { lt: parent_regions, ty: parent_types }; - let lifetimes: Vec = - regions.into_iter().map(|lt| ty::GenericParameterDef::Lifetime(lt)).collect(); - let types: Vec = - types.into_iter().map(|ty| ty::GenericParameterDef::Type(ty)).collect(); + let parent_params = ty::KindIndexed { lt: parent_regions, ty: parent_types }; + let lifetimes: Vec = + regions.into_iter().map(|lt| ty::GenericParam::Lifetime(lt)).collect(); + let types: Vec = + types.into_iter().map(|ty| ty::GenericParam::Type(ty)).collect(); let parameters = lifetimes.into_iter().chain(types.into_iter()).collect(); tcx.alloc_generics(ty::Generics { diff --git a/src/librustdoc/clean/mod.rs b/src/librustdoc/clean/mod.rs index 852a4479199df..b886b31a08b78 100644 --- a/src/librustdoc/clean/mod.rs +++ b/src/librustdoc/clean/mod.rs @@ -3494,12 +3494,12 @@ impl Clean for hir::PathParameters { } } else { PathParameters::AngleBracketed { - lifetimes: if self.lifetimes.iter().all(|lt| lt.is_elided()) { + lifetimes: if self.lifetimes().iter().all(|lt| lt.is_elided()) { vec![] } else { - self.lifetimes.clean(cx) + self.lifetimes().iter().map(|lp| lp.clean(cx)).collect() }, - types: self.types.clean(cx), + types: self.types().iter().map(|tp| tp.clean(cx)).collect(), bindings: self.bindings.clean(cx), } } diff --git a/src/libsyntax/ast.rs b/src/libsyntax/ast.rs index 1af4743cfe4cb..9a05c5c063a20 100644 --- a/src/libsyntax/ast.rs +++ b/src/libsyntax/ast.rs @@ -168,7 +168,7 @@ impl PathParameters { } #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)] -pub enum GenericAngleBracketedParam { +pub enum AngleBracketedParam { Lifetime(Lifetime), Type(P), } @@ -179,7 +179,7 @@ pub struct AngleBracketedParameterData { /// Overall span pub span: Span, /// The parameters for this path segment. - pub parameters: Vec, + pub parameters: Vec, /// Bindings (equality constraints) on associated types, if present. /// /// E.g., `Foo`. @@ -189,7 +189,7 @@ pub struct AngleBracketedParameterData { impl AngleBracketedParameterData { pub fn lifetimes(&self) -> Vec<&Lifetime> { self.parameters.iter().filter_map(|p| { - if let GenericAngleBracketedParam::Lifetime(lt) = p { + if let AngleBracketedParam::Lifetime(lt) = p { Some(lt) } else { None @@ -199,7 +199,7 @@ impl AngleBracketedParameterData { pub fn types(&self) -> Vec<&P> { self.parameters.iter().filter_map(|p| { - if let GenericAngleBracketedParam::Type(ty) = p { + if let AngleBracketedParam::Type(ty) = p { Some(ty) } else { None diff --git a/src/libsyntax/ext/build.rs b/src/libsyntax/ext/build.rs index 02112517827a5..a59e34580c045 100644 --- a/src/libsyntax/ext/build.rs +++ b/src/libsyntax/ext/build.rs @@ -31,7 +31,7 @@ pub trait AstBuilder { fn path_all(&self, sp: Span, global: bool, idents: Vec, - parameters: Vec, + parameters: Vec, bindings: Vec) -> ast::Path; @@ -42,7 +42,7 @@ pub trait AstBuilder { fn qpath_all(&self, self_type: P, trait_path: ast::Path, ident: ast::Ident, - parameters: Vec, + parameters: Vec, bindings: Vec) -> (ast::QSelf, ast::Path); @@ -314,7 +314,7 @@ impl<'a> AstBuilder for ExtCtxt<'a> { span: Span, global: bool, mut idents: Vec , - parameters: Vec, + parameters: Vec, bindings: Vec ) -> ast::Path { let last_ident = idents.pop().unwrap(); @@ -356,7 +356,7 @@ impl<'a> AstBuilder for ExtCtxt<'a> { self_type: P, trait_path: ast::Path, ident: ast::Ident, - parameters: Vec, + parameters: Vec, bindings: Vec) -> (ast::QSelf, ast::Path) { let mut path = trait_path; @@ -424,7 +424,7 @@ impl<'a> AstBuilder for ExtCtxt<'a> { self.path_all(DUMMY_SP, true, self.std_path(&["option", "Option"]), - vec![ ast::GenericAngleBracketedParam::Type(ty) ], + vec![ ast::AngleBracketedParam::Type(ty) ], Vec::new())) } diff --git a/src/libsyntax/fold.rs b/src/libsyntax/fold.rs index b935425cdd400..fc70ee9c38f4b 100644 --- a/src/libsyntax/fold.rs +++ b/src/libsyntax/fold.rs @@ -132,7 +132,7 @@ pub trait Folder : Sized { noop_fold_exprs(es, self) } - fn fold_param(&mut self, p: GenericAngleBracketedParam) -> GenericAngleBracketedParam { + fn fold_param(&mut self, p: AngleBracketedParam) -> AngleBracketedParam { noop_fold_param(p, self) } @@ -357,15 +357,15 @@ pub fn noop_fold_ty_binding(b: TypeBinding, fld: &mut T) -> TypeBindi } } -pub fn noop_fold_param(p: GenericAngleBracketedParam, +pub fn noop_fold_param(p: AngleBracketedParam, fld: &mut T) - -> GenericAngleBracketedParam { + -> AngleBracketedParam { match p { - GenericAngleBracketedParam::Lifetime(lt) => { - GenericAngleBracketedParam::Lifetime(noop_fold_lifetime(lt, fld)) + AngleBracketedParam::Lifetime(lt) => { + AngleBracketedParam::Lifetime(noop_fold_lifetime(lt, fld)) } - GenericAngleBracketedParam::Type(ty) => { - GenericAngleBracketedParam::Type(noop_fold_ty(ty, fld)) + AngleBracketedParam::Type(ty) => { + AngleBracketedParam::Type(noop_fold_ty(ty, fld)) } } } diff --git a/src/libsyntax/parse/parser.rs b/src/libsyntax/parse/parser.rs index c205e93761105..e54c5445fa2f8 100644 --- a/src/libsyntax/parse/parser.rs +++ b/src/libsyntax/parse/parser.rs @@ -22,7 +22,7 @@ use ast::{Expr, ExprKind, RangeLimits}; use ast::{Field, FnDecl}; use ast::{ForeignItem, ForeignItemKind, FunctionRetTy}; use ast::GenericParam; -use ast::GenericAngleBracketedParam; +use ast::AngleBracketedParam; use ast::{Ident, ImplItem, IsAuto, Item, ItemKind}; use ast::{Label, Lifetime, LifetimeDef, Lit, LitKind}; use ast::Local; @@ -4938,7 +4938,7 @@ impl<'a> Parser<'a> { /// Parses (possibly empty) list of lifetime and type arguments and associated type bindings, /// possibly including trailing comma. fn parse_generic_args(&mut self) - -> PResult<'a, (Vec, Vec)> { + -> PResult<'a, (Vec, Vec)> { let mut parameters = Vec::new(); let mut bindings = Vec::new(); let mut seen_type = false; @@ -4946,7 +4946,7 @@ impl<'a> Parser<'a> { loop { if self.check_lifetime() && self.look_ahead(1, |t| !t.is_like_plus()) { // Parse lifetime argument. - parameters.push(GenericAngleBracketedParam::Lifetime(self.expect_lifetime())); + parameters.push(AngleBracketedParam::Lifetime(self.expect_lifetime())); if seen_type || seen_binding { self.span_err(self.prev_span, "lifetime parameters must be declared prior to type parameters"); @@ -4971,7 +4971,7 @@ impl<'a> Parser<'a> { self.span_err(ty_param.span, "type parameters must be declared prior to associated type bindings"); } - parameters.push(GenericAngleBracketedParam::Type(ty_param)); + parameters.push(AngleBracketedParam::Type(ty_param)); seen_type = true; } else { break diff --git a/src/libsyntax/print/pprust.rs b/src/libsyntax/print/pprust.rs index dc204e3d0ef6c..282b5dd545a1d 100644 --- a/src/libsyntax/print/pprust.rs +++ b/src/libsyntax/print/pprust.rs @@ -13,7 +13,7 @@ pub use self::AnnNode::*; use rustc_target::spec::abi::{self, Abi}; use ast::{self, BlockCheckMode, PatKind, RangeEnd, RangeSyntax}; use ast::{SelfKind, RegionTyParamBound, TraitTyParamBound, TraitBoundModifier}; -use ast::{Attribute, MacDelimiter, GenericAngleBracketedParam}; +use ast::{Attribute, MacDelimiter, AngleBracketedParam}; use util::parser::{self, AssocOp, Fixity}; use attr; use codemap::{self, CodeMap}; @@ -1017,10 +1017,10 @@ impl<'a> State<'a> { Ok(()) } - pub fn print_param(&mut self, param: &GenericAngleBracketedParam) -> io::Result<()> { + pub fn print_param(&mut self, param: &AngleBracketedParam) -> io::Result<()> { match param { - GenericAngleBracketedParam::Lifetime(lt) => self.print_lifetime(lt), - GenericAngleBracketedParam::Type(ty) => self.print_type(ty), + AngleBracketedParam::Lifetime(lt) => self.print_lifetime(lt), + AngleBracketedParam::Type(ty) => self.print_type(ty), } } diff --git a/src/libsyntax_ext/deriving/clone.rs b/src/libsyntax_ext/deriving/clone.rs index 3a83922bc90c1..2e0551b32f73c 100644 --- a/src/libsyntax_ext/deriving/clone.rs +++ b/src/libsyntax_ext/deriving/clone.rs @@ -13,7 +13,7 @@ use deriving::generic::*; use deriving::generic::ty::*; use syntax::ast::{self, Expr, Generics, ItemKind, MetaItem, VariantData}; -use syntax::ast::GenericAngleBracketedParam; +use syntax::ast::AngleBracketedParam; use syntax::attr; use syntax::ext::base::{Annotatable, ExtCtxt}; use syntax::ext::build::AstBuilder; @@ -124,7 +124,7 @@ fn cs_clone_shallow(name: &str, let span = span.with_ctxt(cx.backtrace()); let assert_path = cx.path_all(span, true, cx.std_path(&["clone", helper_name]), - vec![GenericAngleBracketedParam::Type(ty)], vec![]); + vec![AngleBracketedParam::Type(ty)], vec![]); stmts.push(cx.stmt_let_type_only(span, cx.ty_path(assert_path))); } fn process_variant(cx: &mut ExtCtxt, stmts: &mut Vec, variant: &VariantData) { diff --git a/src/libsyntax_ext/deriving/cmp/eq.rs b/src/libsyntax_ext/deriving/cmp/eq.rs index 61b7e5b482d76..51ab9975ed986 100644 --- a/src/libsyntax_ext/deriving/cmp/eq.rs +++ b/src/libsyntax_ext/deriving/cmp/eq.rs @@ -12,7 +12,7 @@ use deriving::path_std; use deriving::generic::*; use deriving::generic::ty::*; -use syntax::ast::{self, Expr, MetaItem, GenericAngleBracketedParam}; +use syntax::ast::{self, Expr, MetaItem, AngleBracketedParam}; use syntax::ext::base::{Annotatable, ExtCtxt}; use syntax::ext::build::AstBuilder; use syntax::ptr::P; @@ -62,7 +62,7 @@ fn cs_total_eq_assert(cx: &mut ExtCtxt, trait_span: Span, substr: &Substructure) let span = span.with_ctxt(cx.backtrace()); let assert_path = cx.path_all(span, true, cx.std_path(&["cmp", helper_name]), - vec![GenericAngleBracketedParam::Type(ty)], vec![]); + vec![AngleBracketedParam::Type(ty)], vec![]); stmts.push(cx.stmt_let_type_only(span, cx.ty_path(assert_path))); } fn process_variant(cx: &mut ExtCtxt, stmts: &mut Vec, variant: &ast::VariantData) { diff --git a/src/libsyntax_ext/deriving/generic/mod.rs b/src/libsyntax_ext/deriving/generic/mod.rs index 7ab0acda4080a..a7bb7ba025f71 100644 --- a/src/libsyntax_ext/deriving/generic/mod.rs +++ b/src/libsyntax_ext/deriving/generic/mod.rs @@ -193,7 +193,7 @@ use std::vec; use rustc_target::spec::abi::Abi; use syntax::ast::{self, BinOpKind, EnumDef, Expr, GenericParam, Generics, Ident, PatKind}; -use syntax::ast::{VariantData, GenericAngleBracketedParam}; +use syntax::ast::{VariantData, AngleBracketedParam}; use syntax::attr; use syntax::ext::base::{Annotatable, ExtCtxt}; use syntax::ext::build::AstBuilder; @@ -683,9 +683,9 @@ impl<'a> TraitDef<'a> { .collect(); let self_params = self_lifetimes.into_iter() - .map(|lt| GenericAngleBracketedParam::Lifetime(lt)) + .map(|lt| AngleBracketedParam::Lifetime(lt)) .chain(self_ty_params.into_iter().map(|ty| - GenericAngleBracketedParam::Type(ty))) + AngleBracketedParam::Type(ty))) .collect(); // Create the type of `self`. diff --git a/src/libsyntax_ext/deriving/generic/ty.rs b/src/libsyntax_ext/deriving/generic/ty.rs index 6387f2d8d98f0..d6ee7759ae63e 100644 --- a/src/libsyntax_ext/deriving/generic/ty.rs +++ b/src/libsyntax_ext/deriving/generic/ty.rs @@ -15,7 +15,7 @@ pub use self::PtrTy::*; pub use self::Ty::*; use syntax::ast; -use syntax::ast::{Expr, GenericParam, Generics, Ident, SelfKind, GenericAngleBracketedParam}; +use syntax::ast::{Expr, GenericParam, Generics, Ident, SelfKind, AngleBracketedParam}; use syntax::ext::base::ExtCtxt; use syntax::ext::build::AstBuilder; use syntax::codemap::{respan, DUMMY_SP}; @@ -89,8 +89,8 @@ impl<'a> Path<'a> { let tys: Vec> = self.params.iter().map(|t| t.to_ty(cx, span, self_ty, self_generics)).collect(); let params = lt.into_iter() - .map(|lt| GenericAngleBracketedParam::Lifetime(lt)) - .chain(tys.into_iter().map(|ty| GenericAngleBracketedParam::Type(ty))) + .map(|lt| AngleBracketedParam::Lifetime(lt)) + .chain(tys.into_iter().map(|ty| AngleBracketedParam::Type(ty))) .collect(); match self.kind { @@ -206,9 +206,9 @@ impl<'a> Ty<'a> { .collect(); let params = lifetimes.into_iter() - .map(|lt| GenericAngleBracketedParam::Lifetime(lt)) + .map(|lt| AngleBracketedParam::Lifetime(lt)) .chain(ty_params.into_iter().map(|ty| - GenericAngleBracketedParam::Type(ty))) + AngleBracketedParam::Type(ty))) .collect(); cx.path_all(span, diff --git a/src/libsyntax_ext/env.rs b/src/libsyntax_ext/env.rs index c904cfcfdbff4..78721d880fce7 100644 --- a/src/libsyntax_ext/env.rs +++ b/src/libsyntax_ext/env.rs @@ -13,7 +13,7 @@ // interface. // -use syntax::ast::{self, Ident, GenericAngleBracketedParam}; +use syntax::ast::{self, Ident, AngleBracketedParam}; use syntax::ext::base::*; use syntax::ext::base; use syntax::ext::build::AstBuilder; @@ -39,7 +39,7 @@ pub fn expand_option_env<'cx>(cx: &'cx mut ExtCtxt, cx.expr_path(cx.path_all(sp, true, cx.std_path(&["option", "Option", "None"]), - vec![GenericAngleBracketedParam::Type(cx.ty_rptr(sp, + vec![AngleBracketedParam::Type(cx.ty_rptr(sp, cx.ty_ident(sp, Ident::from_str("str")), Some(lt), ast::Mutability::Immutable)], From e05ad4f31a6440d78588912ef76c4ba454b1b539 Mon Sep 17 00:00:00 2001 From: varkor Date: Sun, 25 Feb 2018 13:46:45 +0000 Subject: [PATCH 03/41] Abstract walk_path_parameters --- src/librustc/hir/intravisit.rs | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/src/librustc/hir/intravisit.rs b/src/librustc/hir/intravisit.rs index 79b433e3cb2c3..1965488171e00 100644 --- a/src/librustc/hir/intravisit.rs +++ b/src/librustc/hir/intravisit.rs @@ -344,6 +344,12 @@ pub trait Visitor<'v> : Sized { fn visit_label(&mut self, label: &'v Label) { walk_label(self, label) } + fn visit_path_param(&mut self, path_param: &'v PathParam) { + match path_param { + PathParam::Lifetime(lt) => self.visit_lifetime(lt), + PathParam::Type(ty) => self.visit_ty(ty), + } + } fn visit_lifetime(&mut self, lifetime: &'v Lifetime) { walk_lifetime(self, lifetime) } @@ -650,8 +656,7 @@ pub fn walk_path_segment<'v, V: Visitor<'v>>(visitor: &mut V, pub fn walk_path_parameters<'v, V: Visitor<'v>>(visitor: &mut V, _path_span: Span, path_parameters: &'v PathParameters) { - walk_list!(visitor, visit_lifetime, path_parameters.lifetimes()); - walk_list!(visitor, visit_ty, path_parameters.types()); + walk_list!(visitor, visit_path_param, &path_parameters.parameters); walk_list!(visitor, visit_assoc_type_binding, &path_parameters.bindings); } From 3e89753283a3d08704ab293b337d255e5d5e5210 Mon Sep 17 00:00:00 2001 From: varkor Date: Tue, 13 Feb 2018 11:32:37 +0000 Subject: [PATCH 04/41] Rename PathParameter(s) to GenericArg(s) --- src/librustc/hir/intravisit.rs | 22 +++---- src/librustc/hir/lowering.rs | 57 +++++++++--------- src/librustc/hir/mod.rs | 38 ++++++------ src/librustc/hir/print.rs | 60 ++++++++----------- src/librustc/ich/impls_hir.rs | 4 +- src/librustc/middle/resolve_lifetime.rs | 12 ++-- src/librustc/ty/mod.rs | 8 +-- src/librustc/ty/subst.rs | 4 ++ src/librustc_driver/pretty.rs | 4 +- src/librustc_save_analysis/dump_visitor.rs | 6 +- src/librustc_save_analysis/lib.rs | 2 +- src/librustc_typeck/astconv.rs | 6 +- src/librustc_typeck/check/method/confirm.rs | 2 +- src/librustc_typeck/check/mod.rs | 8 +-- src/librustdoc/clean/mod.rs | 36 +++++------ src/librustdoc/clean/simplify.rs | 2 +- src/librustdoc/html/format.rs | 6 +- src/libsyntax/ast.rs | 28 ++++----- src/libsyntax/fold.rs | 41 +++++-------- src/libsyntax/print/pprust.rs | 14 ++--- src/libsyntax/util/node_count.rs | 4 +- src/libsyntax/visit.rs | 27 +++++---- src/test/run-pass/issue-22777.rs | 4 +- .../streaming_iterator.rs | 2 +- 24 files changed, 194 insertions(+), 203 deletions(-) diff --git a/src/librustc/hir/intravisit.rs b/src/librustc/hir/intravisit.rs index 1965488171e00..9b5b53e891baf 100644 --- a/src/librustc/hir/intravisit.rs +++ b/src/librustc/hir/intravisit.rs @@ -344,10 +344,10 @@ pub trait Visitor<'v> : Sized { fn visit_label(&mut self, label: &'v Label) { walk_label(self, label) } - fn visit_path_param(&mut self, path_param: &'v PathParam) { - match path_param { - PathParam::Lifetime(lt) => self.visit_lifetime(lt), - PathParam::Type(ty) => self.visit_ty(ty), + fn visit_generic_arg(&mut self, generic_arg: &'v GenericArg) { + match generic_arg { + GenericArg::Lifetime(lt) => self.visit_lifetime(lt), + GenericArg::Type(ty) => self.visit_ty(ty), } } fn visit_lifetime(&mut self, lifetime: &'v Lifetime) { @@ -362,8 +362,8 @@ pub trait Visitor<'v> : Sized { fn visit_path_segment(&mut self, path_span: Span, path_segment: &'v PathSegment) { walk_path_segment(self, path_span, path_segment) } - fn visit_path_parameters(&mut self, path_span: Span, path_parameters: &'v PathParameters) { - walk_path_parameters(self, path_span, path_parameters) + fn visit_generic_args(&mut self, path_span: Span, generic_args: &'v GenericArgs) { + walk_generic_args(self, path_span, generic_args) } fn visit_assoc_type_binding(&mut self, type_binding: &'v TypeBinding) { walk_assoc_type_binding(self, type_binding) @@ -649,15 +649,15 @@ pub fn walk_path_segment<'v, V: Visitor<'v>>(visitor: &mut V, segment: &'v PathSegment) { visitor.visit_name(path_span, segment.name); if let Some(ref parameters) = segment.parameters { - visitor.visit_path_parameters(path_span, parameters); + visitor.visit_generic_args(path_span, parameters); } } -pub fn walk_path_parameters<'v, V: Visitor<'v>>(visitor: &mut V, +pub fn walk_generic_args<'v, V: Visitor<'v>>(visitor: &mut V, _path_span: Span, - path_parameters: &'v PathParameters) { - walk_list!(visitor, visit_path_param, &path_parameters.parameters); - walk_list!(visitor, visit_assoc_type_binding, &path_parameters.bindings); + generic_args: &'v GenericArgs) { + walk_list!(visitor, visit_generic_arg, &generic_args.parameters); + walk_list!(visitor, visit_assoc_type_binding, &generic_args.bindings); } pub fn walk_assoc_type_binding<'v, V: Visitor<'v>>(visitor: &mut V, diff --git a/src/librustc/hir/lowering.rs b/src/librustc/hir/lowering.rs index fd914f9f62bb1..4b090e88c4046 100644 --- a/src/librustc/hir/lowering.rs +++ b/src/librustc/hir/lowering.rs @@ -46,7 +46,7 @@ use hir::HirVec; use hir::map::{DefKey, DefPathData, Definitions}; use hir::def_id::{DefId, DefIndex, DefIndexAddressSpace, CRATE_DEF_INDEX}; use hir::def::{Def, PathResolution, PerNS}; -use hir::PathParam; +use hir::GenericArg; use lint::builtin::{self, PARENTHESIZED_PARAMS_IN_TYPES_AND_MODULES}; use middle::cstore::CrateStore; use rustc_data_structures::indexed_vec::IndexVec; @@ -1038,16 +1038,16 @@ impl<'a> LoweringContext<'a> { } } - fn lower_path_param(&mut self, + fn lower_generic_arg(&mut self, p: &AngleBracketedParam, itctx: ImplTraitContext) - -> PathParam { + -> GenericArg { match p { AngleBracketedParam::Lifetime(lt) => { - PathParam::Lifetime(self.lower_lifetime(<)) + GenericArg::Lifetime(self.lower_lifetime(<)) } AngleBracketedParam::Type(ty) => { - PathParam::Type(self.lower_ty(&ty, itctx)) + GenericArg::Type(self.lower_ty(&ty, itctx)) } } } @@ -1322,15 +1322,15 @@ impl<'a> LoweringContext<'a> { hir::intravisit::NestedVisitorMap::None } - fn visit_path_parameters(&mut self, span: Span, parameters: &'v hir::PathParameters) { + fn visit_generic_args(&mut self, span: Span, parameters: &'v hir::GenericArgs) { // Don't collect elided lifetimes used inside of `Fn()` syntax. if parameters.parenthesized { let old_collect_elided_lifetimes = self.collect_elided_lifetimes; self.collect_elided_lifetimes = false; - hir::intravisit::walk_path_parameters(self, span, parameters); + hir::intravisit::walk_generic_args(self, span, parameters); self.collect_elided_lifetimes = old_collect_elided_lifetimes; } else { - hir::intravisit::walk_path_parameters(self, span, parameters); + hir::intravisit::walk_generic_args(self, span, parameters); } } @@ -1567,7 +1567,7 @@ impl<'a> LoweringContext<'a> { assert!(!def_id.is_local()); let item_generics = self.cstore.item_generics_cloned_untracked(def_id, self.sess); - let n = item_generics.own_counts().lifetimes(); + let n = item_generics.own_counts().lifetimes; self.type_def_lifetime_params.insert(def_id, n); n }); @@ -1684,13 +1684,14 @@ impl<'a> LoweringContext<'a> { parenthesized_generic_args: ParenthesizedGenericArgs, itctx: ImplTraitContext, ) -> hir::PathSegment { - let (mut parameters, infer_types) = if let Some(ref parameters) = segment.parameters { + let (mut generic_args, infer_types) = + if let Some(ref generic_args) = segment.parameters { let msg = "parenthesized parameters may only be used with a trait"; - match **path_params { - PathParameters::AngleBracketed(ref data) => { + match **generic_args { + GenericArgs::AngleBracketed(ref data) => { self.lower_angle_bracketed_parameter_data(data, param_mode, itctx) } - PathParameters::Parenthesized(ref data) => match parenthesized_generic_args { + GenericArgs::Parenthesized(ref data) => match parenthesized_generic_args { ParenthesizedGenericArgs::Ok => self.lower_parenthesized_parameter_data(data), ParenthesizedGenericArgs::Warn => { self.sess.buffer_lint( @@ -1699,13 +1700,13 @@ impl<'a> LoweringContext<'a> { data.span, msg.into(), ); - (hir::PathParameters::none(), true) + (hir::GenericArgs::none(), true) } ParenthesizedGenericArgs::Err => { struct_span_err!(self.sess, data.span, E0214, "{}", msg) .span_label(data.span, "only traits may use parentheses") .emit(); - (hir::PathParameters::none(), true) + (hir::GenericArgs::none(), true) } }, } @@ -1713,16 +1714,16 @@ impl<'a> LoweringContext<'a> { self.lower_angle_bracketed_parameter_data(&Default::default(), param_mode, itctx) }; - if !parameters.parenthesized && parameters.lifetimes.is_empty() { - path_params.parameters = (0..expected_lifetimes).map(|_| { - PathParam::Lifetime(self.elided_lifetime(path_span)) - }).chain(path_params.parameters.into_iter()).collect(); + if !generic_args.parenthesized && generic_args.lifetimes().count() == 0 { + generic_args.parameters = (0..expected_lifetimes).map(|_| { + GenericArg::Lifetime(self.elided_lifetime(path_span)) + }).chain(generic_args.parameters.into_iter()).collect(); } hir::PathSegment::new( - self.lower_ident(segment.ident), - path_params, - infer_types, + self.lower_ident(segment.identifier), + generic_args, + infer_types ) } @@ -1731,14 +1732,14 @@ impl<'a> LoweringContext<'a> { data: &AngleBracketedParameterData, param_mode: ParamMode, itctx: ImplTraitContext, - ) -> (hir::PathParameters, bool) { + ) -> (hir::GenericArgs, bool) { let &AngleBracketedParameterData { ref parameters, ref bindings, .. } = data; - (hir::PathParameters { - parameters: parameters.iter().map(|p| self.lower_path_param(p, itctx)).collect(), + (hir::GenericArgs { + parameters: parameters.iter().map(|p| self.lower_generic_arg(p, itctx)).collect(), bindings: bindings.iter().map(|b| self.lower_ty_binding(b, itctx)).collect(), parenthesized: false, }, - types.is_empty() && param_mode == ParamMode::Optional) + data.types().count() == 0 && param_mode == ParamMode::Optional) } fn lower_parenthesized_parameter_data( @@ -1774,8 +1775,8 @@ impl<'a> LoweringContext<'a> { }; ( - hir::PathParameters { - parameters: hir_vec![PathParam::Type(mk_tup(this, inputs, span))], + hir::GenericArgs { + parameters: hir_vec![GenericArg::Type(mk_tup(this, inputs, span))], bindings: hir_vec![ hir::TypeBinding { id: this.next_id().node_id, diff --git a/src/librustc/hir/mod.rs b/src/librustc/hir/mod.rs index 455e64351e186..38a894df3cd5a 100644 --- a/src/librustc/hir/mod.rs +++ b/src/librustc/hir/mod.rs @@ -327,7 +327,7 @@ pub struct PathSegment { /// this is more than just simple syntactic sugar; the use of /// parens affects the region binding rules, so we preserve the /// distinction. - pub parameters: Option>, + pub parameters: Option>, /// Whether to infer remaining type parameters, if any. /// This only applies to expression and pattern paths, and @@ -346,7 +346,7 @@ impl PathSegment { } } - pub fn new(name: Name, parameters: PathParameters, infer_types: bool) -> Self { + pub fn new(name: Name, parameters: GenericArgs, infer_types: bool) -> Self { PathSegment { name, infer_types, @@ -359,11 +359,11 @@ impl PathSegment { } // FIXME: hack required because you can't create a static - // PathParameters, so you can't just return a &PathParameters. + // GenericArgs, so you can't just return a &GenericArgs. pub fn with_parameters(&self, f: F) -> R - where F: FnOnce(&PathParameters) -> R + where F: FnOnce(&GenericArgs) -> R { - let dummy = PathParameters::none(); + let dummy = GenericArgs::none(); f(if let Some(ref params) = self.parameters { ¶ms } else { @@ -373,15 +373,15 @@ impl PathSegment { } #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)] -pub enum PathParam { +pub enum GenericArg { Lifetime(Lifetime), Type(P), } #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)] -pub struct PathParameters { +pub struct GenericArgs { /// The generic parameters for this path segment. - pub parameters: HirVec, + pub parameters: HirVec, /// Bindings (equality constraints) on associated types, if present. /// E.g., `Foo`. pub bindings: HirVec, @@ -391,7 +391,7 @@ pub struct PathParameters { pub parenthesized: bool, } -impl PathParameters { +impl GenericArgs { pub fn none() -> Self { Self { parameters: HirVec::new(), @@ -406,33 +406,33 @@ impl PathParameters { pub fn inputs(&self) -> &[P] { if self.parenthesized { - if let Some(ref ty) = self.types().get(0) { + if let Some(ref ty) = self.types().next() { if let TyTup(ref tys) = ty.node { return tys; } } } - bug!("PathParameters::inputs: not a `Fn(T) -> U`"); + bug!("GenericArgs::inputs: not a `Fn(T) -> U`"); } - pub fn lifetimes(&self) -> Vec<&Lifetime> { + pub fn lifetimes(&self) -> impl DoubleEndedIterator { self.parameters.iter().filter_map(|p| { - if let PathParam::Lifetime(lt) = p { + if let GenericArg::Lifetime(lt) = p { Some(lt) } else { None } - }).collect() + }) } - pub fn types(&self) -> Vec<&P> { + pub fn types(&self) -> impl DoubleEndedIterator> { self.parameters.iter().filter_map(|p| { - if let PathParam::Type(ty) = p { + if let GenericArg::Type(ty) = p { Some(ty) } else { None } - }).collect() + }) } } @@ -562,11 +562,11 @@ impl Generics { self.params.iter().any(|param| param.is_type_param()) } - pub fn lifetimes<'a>(&'a self) -> impl Iterator { + pub fn lifetimes<'a>(&'a self) -> impl DoubleEndedIterator { self.params.lifetimes() } - pub fn ty_params<'a>(&'a self) -> impl Iterator { + pub fn ty_params<'a>(&'a self) -> impl DoubleEndedIterator { self.params.ty_params() } } diff --git a/src/librustc/hir/print.rs b/src/librustc/hir/print.rs index 6f4a9dd59296e..f7e98591c112b 100644 --- a/src/librustc/hir/print.rs +++ b/src/librustc/hir/print.rs @@ -25,7 +25,7 @@ use syntax_pos::{self, BytePos, FileName}; use hir; use hir::{PatKind, RegionTyParamBound, TraitTyParamBound, TraitBoundModifier, RangeEnd}; -use hir::PathParam; +use hir::GenericArg; use std::cell::Cell; use std::io::{self, Write, Read}; @@ -1273,7 +1273,7 @@ impl<'a> State<'a> { if !parameters.parameters.is_empty() || !parameters.bindings.is_empty() { - self.print_path_parameters(¶meters, segment.infer_types, true) + self.print_generic_args(¶meters, segment.infer_types, true) } else { Ok(()) } @@ -1642,7 +1642,7 @@ impl<'a> State<'a> { segment.name != keywords::DollarCrate.name() { self.print_name(segment.name)?; segment.with_parameters(|parameters| { - self.print_path_parameters(parameters, + self.print_generic_args(parameters, segment.infer_types, colons_before_params) })?; @@ -1674,7 +1674,7 @@ impl<'a> State<'a> { segment.name != keywords::DollarCrate.name() { self.print_name(segment.name)?; segment.with_parameters(|parameters| { - self.print_path_parameters(parameters, + self.print_generic_args(parameters, segment.infer_types, colons_before_params) })?; @@ -1686,7 +1686,7 @@ impl<'a> State<'a> { let item_segment = path.segments.last().unwrap(); self.print_name(item_segment.name)?; item_segment.with_parameters(|parameters| { - self.print_path_parameters(parameters, + self.print_generic_args(parameters, item_segment.infer_types, colons_before_params) }) @@ -1698,7 +1698,7 @@ impl<'a> State<'a> { self.s.word("::")?; self.print_name(item_segment.name)?; item_segment.with_parameters(|parameters| { - self.print_path_parameters(parameters, + self.print_generic_args(parameters, item_segment.infer_types, colons_before_params) }) @@ -1706,19 +1706,19 @@ impl<'a> State<'a> { } } - fn print_path_parameters(&mut self, - path_params: &hir::PathParameters, + fn print_generic_args(&mut self, + generic_args: &hir::GenericArgs, infer_types: bool, colons_before_params: bool) -> io::Result<()> { - if path_params.parenthesized { + if generic_args.parenthesized { self.s.word("(")?; - self.commasep(Inconsistent, path_params.inputs(), |s, ty| s.print_type(&ty))?; + self.commasep(Inconsistent, generic_args.inputs(), |s, ty| s.print_type(&ty))?; self.s.word(")")?; self.space_if_not_bol()?; self.word_space("->")?; - self.print_type(&path_params.bindings[0].ty)?; + self.print_type(&generic_args.bindings[0].ty)?; } else { let start = if colons_before_params { "::<" } else { "<" }; let empty = Cell::new(true); @@ -1731,30 +1731,20 @@ impl<'a> State<'a> { } }; - let elide_lifetimes = path_params.parameters.iter().all(|p| { - if let PathParam::Lifetime(lt) = p { - if !lt.is_elided() { - return false; - } - } - true - }); - - self.commasep(Inconsistent, &path_params.parameters, |s, p| { - match p { - PathParam::Lifetime(lt) => { - if !elide_lifetimes { - s.print_lifetime(lt) - } else { - Ok(()) - } + let elide_lifetimes = generic_args.lifetimes().all(|lt| lt.is_elided()); + if !elide_lifetimes { + start_or_comma(self)?; + self.commasep(Inconsistent, &generic_args.parameters, |s, p| { + match p { + GenericArg::Lifetime(lt) => s.print_lifetime(lt), + GenericArg::Type(ty) => s.print_type(ty), } - PathParam::Type(ty) => s.print_type(ty), - } - })?; - - if !path_params.parameters.is_empty() { - empty.set(false); + })?; + } else if generic_args.types().count() != 0 { + start_or_comma(self)?; + self.commasep(Inconsistent, + &generic_args.types().collect::>(), + |s, ty| s.print_type(&ty))?; } // FIXME(eddyb) This would leak into error messages, e.g.: @@ -1764,7 +1754,7 @@ impl<'a> State<'a> { self.s.word("..")?; } - for binding in path_params.bindings.iter() { + for binding in generic_args.bindings.iter() { start_or_comma(self)?; self.print_name(binding.name)?; self.s.space()?; diff --git a/src/librustc/ich/impls_hir.rs b/src/librustc/ich/impls_hir.rs index ee139412853b1..6f65562867804 100644 --- a/src/librustc/ich/impls_hir.rs +++ b/src/librustc/ich/impls_hir.rs @@ -180,12 +180,12 @@ impl_stable_hash_for!(struct hir::PathSegment { parameters }); -impl_stable_hash_for!(enum hir::PathParam { +impl_stable_hash_for!(enum hir::GenericArg { Lifetime(lt), Type(ty) }); -impl_stable_hash_for!(struct hir::PathParameters { +impl_stable_hash_for!(struct hir::GenericArgs { parameters, bindings, parenthesized diff --git a/src/librustc/middle/resolve_lifetime.rs b/src/librustc/middle/resolve_lifetime.rs index 477c4c213ce40..69818068e9c92 100644 --- a/src/librustc/middle/resolve_lifetime.rs +++ b/src/librustc/middle/resolve_lifetime.rs @@ -1603,7 +1603,7 @@ impl<'a, 'tcx> LifetimeContext<'a, 'tcx> { &mut self, def: Def, depth: usize, - params: &'tcx hir::PathParameters, + params: &'tcx hir::GenericArgs, ) { if params.parenthesized { let was_in_fn_syntax = self.is_in_fn_syntax; @@ -1613,10 +1613,10 @@ impl<'a, 'tcx> LifetimeContext<'a, 'tcx> { return; } - if params.lifetimes().iter().all(|l| l.is_elided()) { - self.resolve_elided_lifetimes(params.lifetimes(), true); + if params.lifetimes().all(|l| l.is_elided()) { + self.resolve_elided_lifetimes(params.lifetimes().collect(), true); } else { - for l in ¶ms.lifetimes() { + for l in params.lifetimes() { self.visit_lifetime(l); } } @@ -1688,13 +1688,13 @@ impl<'a, 'tcx> LifetimeContext<'a, 'tcx> { } else { Some(Region::Static) }, - Set1::One(r) => r.subst(params.lifetimes(), map), + Set1::One(r) => r.subst(params.lifetimes().collect(), map), Set1::Many => None, }) .collect() }); - for (i, ty) in params.types().iter().enumerate() { + for (i, ty) in params.types().enumerate() { if let Some(<) = object_lifetime_defaults.get(i) { let scope = Scope::ObjectLifetimeDefault { lifetime: lt, diff --git a/src/librustc/ty/mod.rs b/src/librustc/ty/mod.rs index 9e0f98772bf14..447267adfcdd0 100644 --- a/src/librustc/ty/mod.rs +++ b/src/librustc/ty/mod.rs @@ -1009,24 +1009,24 @@ impl<'a, 'gcx, 'tcx> Generics { } } - pub fn lifetimes(&self) -> Vec<&RegionParameterDef> { + pub fn lifetimes(&self) -> impl DoubleEndedIterator { self.parameters.iter().filter_map(|p| { if let GenericParam::Lifetime(lt) = p { Some(lt) } else { None } - }).collect() + }) } - pub fn types(&self) -> Vec<&TypeParameterDef> { + pub fn types(&self) -> impl DoubleEndedIterator { self.parameters.iter().filter_map(|p| { if let GenericParam::Type(ty) = p { Some(ty) } else { None } - }).collect() + }) } pub fn parent_lifetimes(&self) -> u32 { diff --git a/src/librustc/ty/subst.rs b/src/librustc/ty/subst.rs index 2e3c6df9754df..932f082c87cb0 100644 --- a/src/librustc/ty/subst.rs +++ b/src/librustc/ty/subst.rs @@ -105,6 +105,10 @@ impl<'tcx> From> for Kind<'tcx> { } } +impl<'tcx> Into> for ty::Region<'tcx> {} + +impl<'tcx> Into> for Ty<'tcx> {} + impl<'tcx> Kind<'tcx> { #[inline] pub fn unpack(self) -> UnpackedKind<'tcx> { diff --git a/src/librustc_driver/pretty.rs b/src/librustc_driver/pretty.rs index 71ecc89380646..834bd0c32ed8f 100644 --- a/src/librustc_driver/pretty.rs +++ b/src/librustc_driver/pretty.rs @@ -679,10 +679,10 @@ impl<'a> ReplaceBodyWithLoop<'a> { ast::TyKind::Path(_, ref path) => path.segments.iter().any(|seg| { match seg.parameters.as_ref().map(|p| &**p) { None => false, - Some(&ast::PathParameters::AngleBracketed(ref data)) => + Some(&ast::GenericArgs::AngleBracketed(ref data)) => any_involves_impl_trait(data.types().into_iter()) || any_involves_impl_trait(data.bindings.iter().map(|b| &b.ty)), - Some(&ast::PathParameters::Parenthesized(ref data)) => + Some(&ast::GenericArgs::Parenthesized(ref data)) => any_involves_impl_trait(data.inputs.iter()) || any_involves_impl_trait(data.output.iter()), } diff --git a/src/librustc_save_analysis/dump_visitor.rs b/src/librustc_save_analysis/dump_visitor.rs index 81a3617f0aabb..6d13548b9adff 100644 --- a/src/librustc_save_analysis/dump_visitor.rs +++ b/src/librustc_save_analysis/dump_visitor.rs @@ -822,10 +822,10 @@ impl<'l, 'tcx: 'l, 'll, O: DumpOutput + 'll> DumpVisitor<'l, 'tcx, 'll, O> { for seg in &path.segments { if let Some(ref params) = seg.parameters { match **params { - ast::PathParameters::AngleBracketed(ref data) => for t in data.types() { + ast::GenericArgs::AngleBracketed(ref data) => for t in data.types() { self.visit_ty(t); }, - ast::PathParameters::Parenthesized(ref data) => { + ast::GenericArgs::Parenthesized(ref data) => { for t in &data.inputs { self.visit_ty(t); } @@ -906,7 +906,7 @@ impl<'l, 'tcx: 'l, 'll, O: DumpOutput + 'll> DumpVisitor<'l, 'tcx, 'll, O> { // Explicit types in the turbo-fish. if let Some(ref params) = seg.parameters { - if let ast::PathParameters::AngleBracketed(ref data) = **params { + if let ast::GenericArgs::AngleBracketed(ref data) = **params { for t in data.types() { self.visit_ty(t); } diff --git a/src/librustc_save_analysis/lib.rs b/src/librustc_save_analysis/lib.rs index f9510970e43d4..c1022c09de35a 100644 --- a/src/librustc_save_analysis/lib.rs +++ b/src/librustc_save_analysis/lib.rs @@ -693,7 +693,7 @@ impl<'l, 'tcx: 'l> SaveContext<'l, 'tcx> { return false; } if let Some(ref params) = path.segments[0].parameters { - if let ast::PathParameters::Parenthesized(_) = **params { + if let ast::GenericArgs::Parenthesized(_) = **params { return true; } } diff --git a/src/librustc_typeck/astconv.rs b/src/librustc_typeck/astconv.rs index a9d97df46134c..656045c970f9c 100644 --- a/src/librustc_typeck/astconv.rs +++ b/src/librustc_typeck/astconv.rs @@ -199,7 +199,7 @@ impl<'o, 'gcx: 'tcx, 'tcx> AstConv<'gcx, 'tcx>+'o { fn create_substs_for_ast_path(&self, span: Span, def_id: DefId, - parameters: &hir::PathParameters, + parameters: &hir::GenericArgs, infer_types: bool, self_ty: Option>) -> (&'tcx Substs<'tcx>, Vec>) @@ -973,13 +973,13 @@ impl<'o, 'gcx: 'tcx, 'tcx> AstConv<'gcx, 'tcx>+'o { segment.with_parameters(|params| { for p in ¶ms.parameters { let (mut span_err, span, kind) = match p { - hir::PathParam::Lifetime(lt) => { + hir::GenericArg::Lifetime(lt) => { (struct_span_err!(self.tcx().sess, lt.span, E0110, "lifetime parameters are not allowed on this type"), lt.span, "lifetime") } - hir::PathParam::Type(ty) => { + hir::GenericArg::Type(ty) => { (struct_span_err!(self.tcx().sess, ty.span, E0109, "type parameters are not allowed on this type"), ty.span, diff --git a/src/librustc_typeck/check/method/confirm.rs b/src/librustc_typeck/check/method/confirm.rs index 33102757925df..3274c449daa4a 100644 --- a/src/librustc_typeck/check/method/confirm.rs +++ b/src/librustc_typeck/check/method/confirm.rs @@ -316,7 +316,7 @@ impl<'a, 'gcx, 'tcx> ConfirmContext<'a, 'gcx, 'tcx> { let method_generics = self.tcx.generics_of(pick.item.def_id); let mut fn_segment = Some((segment, method_generics)); let supress_mismatch = self.fcx.check_impl_trait(self.span, fn_segment); - self.fcx.check_path_parameter_count(self.span, &mut fn_segment, true, supress_mismatch); + self.fcx.check_generic_arg_count(self.span, &mut fn_segment, true, supress_mismatch); // Create subst for early-bound lifetime parameters, combining // parameters from the type and those from the method. diff --git a/src/librustc_typeck/check/mod.rs b/src/librustc_typeck/check/mod.rs index 0f1b739cddf0a..ef61c99ae01cf 100644 --- a/src/librustc_typeck/check/mod.rs +++ b/src/librustc_typeck/check/mod.rs @@ -4800,8 +4800,8 @@ impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> { // to add defaults. If the user provided *too many* types, that's // a problem. let supress_mismatch = self.check_impl_trait(span, fn_segment); - self.check_path_parameter_count(span, &mut type_segment, false, supress_mismatch); - self.check_path_parameter_count(span, &mut fn_segment, false, supress_mismatch); + self.check_generic_arg_count(span, &mut type_segment, false, supress_mismatch); + self.check_generic_arg_count(span, &mut fn_segment, false, supress_mismatch); let (fn_start, has_self) = match (type_segment, fn_segment) { (_, Some((_, generics))) => { @@ -4955,7 +4955,7 @@ impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> { } /// Report errors if the provided parameters are too few or too many. - fn check_path_parameter_count(&self, + fn check_generic_arg_count(&self, span: Span, segment: &mut Option<(&hir::PathSegment, &ty::Generics)>, is_method_call: bool, @@ -4964,7 +4964,7 @@ impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> { (vec![], vec![], true, &[][..]), |(s, _)| s.parameters.as_ref().map_or( (vec![], vec![], s.infer_types, &[][..]), - |p| (p.lifetimes(), p.types(), + |p| (p.lifetimes().collect(), p.types().collect(), s.infer_types, &p.bindings[..]))); let infer_lifetimes = lifetimes.len() == 0; diff --git a/src/librustdoc/clean/mod.rs b/src/librustdoc/clean/mod.rs index b886b31a08b78..f454136026f43 100644 --- a/src/librustdoc/clean/mod.rs +++ b/src/librustdoc/clean/mod.rs @@ -1558,8 +1558,8 @@ impl Clean for hir::TyParamBound { } } -fn external_path_params(cx: &DocContext, trait_did: Option, has_self: bool, - bindings: Vec, substs: &Substs) -> PathParameters { +fn external_generic_args(cx: &DocContext, trait_did: Option, has_self: bool, + bindings: Vec, substs: &Substs) -> GenericArgs { let lifetimes = substs.regions().filter_map(|v| v.clean(cx)).collect(); let types = substs.types().skip(has_self as usize).collect::>(); @@ -1570,7 +1570,7 @@ fn external_path_params(cx: &DocContext, trait_did: Option, has_self: boo let inputs = match types[0].sty { ty::TyTuple(ref tys) => tys.iter().map(|t| t.clean(cx)).collect(), _ => { - return PathParameters::AngleBracketed { + return GenericArgs::AngleBracketed { lifetimes, types: types.clean(cx), bindings, @@ -1583,13 +1583,13 @@ fn external_path_params(cx: &DocContext, trait_did: Option, has_self: boo // ty::TyTuple(ref v) if v.is_empty() => None, // -> () // _ => Some(types[1].clean(cx)) // }; - PathParameters::Parenthesized { + GenericArgs::Parenthesized { inputs, output, } }, _ => { - PathParameters::AngleBracketed { + GenericArgs::AngleBracketed { lifetimes, types: types.clean(cx), bindings, @@ -1607,7 +1607,7 @@ fn external_path(cx: &DocContext, name: &str, trait_did: Option, has_self def: Def::Err, segments: vec![PathSegment { name: name.to_string(), - params: external_path_params(cx, trait_did, has_self, bindings, substs) + params: external_generic_args(cx, trait_did, has_self, bindings, substs) }], } } @@ -2656,7 +2656,7 @@ impl Type { match *self { ResolvedPath { ref path, .. } => { path.segments.last().and_then(|seg| { - if let PathParameters::AngleBracketed { ref types, .. } = seg.params { + if let GenericArgs::AngleBracketed { ref types, .. } = seg.params { Some(&**types) } else { None @@ -3447,7 +3447,7 @@ impl Path { def: Def::Err, segments: vec![PathSegment { name, - params: PathParameters::AngleBracketed { + params: GenericArgs::AngleBracketed { lifetimes: Vec::new(), types: Vec::new(), bindings: Vec::new(), @@ -3471,8 +3471,8 @@ impl Clean for hir::Path { } } -#[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Eq, Debug, Hash)] -pub enum PathParameters { +#[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Eg, Debug, Hash)] +pub enum GenericArgs { AngleBracketed { lifetimes: Vec, types: Vec, @@ -3484,22 +3484,22 @@ pub enum PathParameters { } } -impl Clean for hir::PathParameters { - fn clean(&self, cx: &DocContext) -> PathParameters { +impl Clean for hir::GenericArgs { + fn clean(&self, cx: &DocContext) -> GenericArgs { if self.parenthesized { let output = self.bindings[0].ty.clean(cx); - PathParameters::Parenthesized { + GenericArgs::Parenthesized { inputs: self.inputs().clean(cx), output: if output != Type::Tuple(Vec::new()) { Some(output) } else { None } } } else { - PathParameters::AngleBracketed { - lifetimes: if self.lifetimes().iter().all(|lt| lt.is_elided()) { + GenericArgs::AngleBracketed { + lifetimes: if self.lifetimes().all(|lt| lt.is_elided()) { vec![] } else { - self.lifetimes().iter().map(|lp| lp.clean(cx)).collect() + self.lifetimes().map(|lp| lp.clean(cx)).collect() }, - types: self.types().iter().map(|tp| tp.clean(cx)).collect(), + types: self.types().map(|tp| tp.clean(cx)).collect(), bindings: self.bindings.clean(cx), } } @@ -3509,7 +3509,7 @@ impl Clean for hir::PathParameters { #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Eq, Debug, Hash)] pub struct PathSegment { pub name: String, - pub params: PathParameters, + pub params: GenericArgs, } impl Clean for hir::PathSegment { diff --git a/src/librustdoc/clean/simplify.rs b/src/librustdoc/clean/simplify.rs index b7767606a6aa4..1dd5746599667 100644 --- a/src/librustdoc/clean/simplify.rs +++ b/src/librustdoc/clean/simplify.rs @@ -27,7 +27,7 @@ use std::collections::BTreeMap; use rustc::hir::def_id::DefId; use rustc::ty; -use clean::PathParameters as PP; +use clean::GenericArgs as PP; use clean::WherePredicate as WP; use clean; use core::DocContext; diff --git a/src/librustdoc/html/format.rs b/src/librustdoc/html/format.rs index 40dcd6e891fe8..de5c0eeffc98c 100644 --- a/src/librustdoc/html/format.rs +++ b/src/librustdoc/html/format.rs @@ -288,10 +288,10 @@ impl fmt::Display for clean::TyParamBound { } } -impl fmt::Display for clean::PathParameters { +impl fmt::Display for clean::GenericArgs { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { - clean::PathParameters::AngleBracketed { + clean::GenericArgs::AngleBracketed { ref lifetimes, ref types, ref bindings } => { if !lifetimes.is_empty() || !types.is_empty() || !bindings.is_empty() { @@ -337,7 +337,7 @@ impl fmt::Display for clean::PathParameters { } } } - clean::PathParameters::Parenthesized { ref inputs, ref output } => { + clean::GenericArgs::Parenthesized { ref inputs, ref output } => { f.write_str("(")?; let mut comma = false; for ty in inputs { diff --git a/src/libsyntax/ast.rs b/src/libsyntax/ast.rs index 9a05c5c063a20..7bcaf9bbd5246 100644 --- a/src/libsyntax/ast.rs +++ b/src/libsyntax/ast.rs @@ -12,7 +12,7 @@ pub use self::TyParamBound::*; pub use self::UnsafeSource::*; -pub use self::PathParameters::*; +pub use self::GenericArgs::*; pub use symbol::{Ident, Symbol as Name}; pub use util::ThinVec; pub use util::parser::ExprPrecedence; @@ -135,7 +135,7 @@ pub struct PathSegment { /// `Some` means that parameter list is supplied (`Path`) /// but it can be empty (`Path<>`). /// `P` is used as a size optimization for the common case with no parameters. - pub parameters: Option>, + pub parameters: Option>, } impl PathSegment { @@ -151,14 +151,14 @@ impl PathSegment { /// /// E.g. `` as in `Foo` or `(A, B)` as in `Foo(A, B)` #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)] -pub enum PathParameters { +pub enum GenericArgs { /// The `<'a, A,B,C>` in `foo::bar::baz::<'a, A,B,C>` AngleBracketed(AngleBracketedParameterData), /// The `(A,B)` and `C` in `Foo(A,B) -> C` Parenthesized(ParenthesizedParameterData), } -impl PathParameters { +impl GenericArgs { pub fn span(&self) -> Span { match *self { AngleBracketed(ref data) => data.span, @@ -187,36 +187,36 @@ pub struct AngleBracketedParameterData { } impl AngleBracketedParameterData { - pub fn lifetimes(&self) -> Vec<&Lifetime> { + pub fn lifetimes(&self) -> impl DoubleEndedIterator { self.parameters.iter().filter_map(|p| { if let AngleBracketedParam::Lifetime(lt) = p { Some(lt) } else { None } - }).collect() + }) } - pub fn types(&self) -> Vec<&P> { + pub fn types(&self) -> impl DoubleEndedIterator> { self.parameters.iter().filter_map(|p| { if let AngleBracketedParam::Type(ty) = p { Some(ty) } else { None } - }).collect() + }) } } -impl Into>> for AngleBracketedParameterData { - fn into(self) -> Option> { - Some(P(PathParameters::AngleBracketed(self))) +impl Into>> for AngleBracketedParameterData { + fn into(self) -> Option> { + Some(P(GenericArgs::AngleBracketed(self))) } } -impl Into>> for ParenthesizedParameterData { - fn into(self) -> Option> { - Some(P(PathParameters::Parenthesized(self))) +impl Into>> for ParenthesizedParameterData { + fn into(self) -> Option> { + Some(P(GenericArgs::Parenthesized(self))) } } diff --git a/src/libsyntax/fold.rs b/src/libsyntax/fold.rs index fc70ee9c38f4b..decb7e56132f1 100644 --- a/src/libsyntax/fold.rs +++ b/src/libsyntax/fold.rs @@ -133,7 +133,11 @@ pub trait Folder : Sized { } fn fold_param(&mut self, p: AngleBracketedParam) -> AngleBracketedParam { - noop_fold_param(p, self) + match p { + AngleBracketedParam::Lifetime(lt) => + AngleBracketedParam::Lifetime(self.fold_lifetime(lt)), + AngleBracketedParam::Type(ty) => AngleBracketedParam::Type(self.fold_ty(ty)), + } } fn fold_ty(&mut self, t: P) -> P { @@ -176,8 +180,8 @@ pub trait Folder : Sized { noop_fold_qpath(qs, p, self) } - fn fold_path_parameters(&mut self, p: PathParameters) -> PathParameters { - noop_fold_path_parameters(p, self) + fn fold_generic_args(&mut self, p: GenericArgs) -> GenericArgs { + noop_fold_generic_args(p, self) } fn fold_angle_bracketed_parameter_data(&mut self, p: AngleBracketedParameterData) @@ -357,19 +361,6 @@ pub fn noop_fold_ty_binding(b: TypeBinding, fld: &mut T) -> TypeBindi } } -pub fn noop_fold_param(p: AngleBracketedParam, - fld: &mut T) - -> AngleBracketedParam { - match p { - AngleBracketedParam::Lifetime(lt) => { - AngleBracketedParam::Lifetime(noop_fold_lifetime(lt, fld)) - } - AngleBracketedParam::Type(ty) => { - AngleBracketedParam::Type(noop_fold_ty(ty, fld)) - } - } -} - pub fn noop_fold_ty(t: P, fld: &mut T) -> P { t.map(|Ty {id, node, span}| Ty { id: fld.new_id(id), @@ -452,7 +443,7 @@ pub fn noop_fold_path(Path { segments, span }: Path, fld: &mut T) -> Path { segments: segments.move_map(|PathSegment {ident, parameters}| PathSegment { ident: fld.fold_ident(ident), - parameters: parameters.map(|ps| ps.map(|ps| fld.fold_path_parameters(ps))), + parameters: parameters.map(|ps| ps.map(|ps| fld.fold_generic_args(ps))), }), span: fld.new_span(span) } @@ -471,14 +462,14 @@ pub fn noop_fold_qpath(qself: Option, (qself, fld.fold_path(path)) } -pub fn noop_fold_path_parameters(path_parameters: PathParameters, fld: &mut T) - -> PathParameters +pub fn noop_fold_generic_args(generic_args: GenericArgs, fld: &mut T) + -> GenericArgs { - match path_parameters { - PathParameters::AngleBracketed(data) => - PathParameters::AngleBracketed(fld.fold_angle_bracketed_parameter_data(data)), - PathParameters::Parenthesized(data) => - PathParameters::Parenthesized(fld.fold_parenthesized_parameter_data(data)), + match generic_args { + GenericArgs::AngleBracketed(data) => + GenericArgs::AngleBracketed(fld.fold_angle_bracketed_parameter_data(data)), + GenericArgs::Parenthesized(data) => + GenericArgs::Parenthesized(fld.fold_parenthesized_parameter_data(data)), } } @@ -1201,7 +1192,7 @@ pub fn noop_fold_expr(Expr {id, node, span, attrs}: Expr, folder: &mu PathSegment { ident: folder.fold_ident(seg.ident), parameters: seg.parameters.map(|ps| { - ps.map(|ps| folder.fold_path_parameters(ps)) + ps.map(|ps| folder.fold_generic_args(ps)) }), }, folder.fold_exprs(args)) diff --git a/src/libsyntax/print/pprust.rs b/src/libsyntax/print/pprust.rs index 282b5dd545a1d..287fe0b636f1c 100644 --- a/src/libsyntax/print/pprust.rs +++ b/src/libsyntax/print/pprust.rs @@ -1992,7 +1992,7 @@ impl<'a> State<'a> { self.s.word(".")?; self.print_ident(segment.ident)?; if let Some(ref parameters) = segment.parameters { - self.print_path_parameters(parameters, true)?; + self.print_generic_args(parameters, true)?; } self.print_call_post(base_args) } @@ -2436,7 +2436,7 @@ impl<'a> State<'a> { segment.ident.name != keywords::DollarCrate.name() { self.print_ident(segment.ident)?; if let Some(ref parameters) = segment.parameters { - self.print_path_parameters(parameters, colons_before_params)?; + self.print_generic_args(parameters, colons_before_params)?; } } else if segment.ident.name == keywords::DollarCrate.name() { self.print_dollar_crate(segment.ident.span.ctxt())?; @@ -2463,13 +2463,13 @@ impl<'a> State<'a> { let item_segment = path.segments.last().unwrap(); self.print_ident(item_segment.ident)?; match item_segment.parameters { - Some(ref parameters) => self.print_path_parameters(parameters, colons_before_params), + Some(ref parameters) => self.print_generic_args(parameters, colons_before_params), None => Ok(()), } } - fn print_path_parameters(&mut self, - parameters: &ast::PathParameters, + fn print_generic_args(&mut self, + parameters: &ast::GenericArgs, colons_before_params: bool) -> io::Result<()> { @@ -2478,7 +2478,7 @@ impl<'a> State<'a> { } match *parameters { - ast::PathParameters::AngleBracketed(ref data) => { + ast::GenericArgs::AngleBracketed(ref data) => { self.s.word("<")?; self.commasep(Inconsistent, &data.parameters, |s, p| s.print_param(p))?; @@ -2499,7 +2499,7 @@ impl<'a> State<'a> { self.s.word(">")? } - ast::PathParameters::Parenthesized(ref data) => { + ast::GenericArgs::Parenthesized(ref data) => { self.s.word("(")?; self.commasep( Inconsistent, diff --git a/src/libsyntax/util/node_count.rs b/src/libsyntax/util/node_count.rs index d4c6b4b158b25..95ae9f9bcf802 100644 --- a/src/libsyntax/util/node_count.rs +++ b/src/libsyntax/util/node_count.rs @@ -137,9 +137,9 @@ impl<'ast> Visitor<'ast> for NodeCounter { self.count += 1; walk_use_tree(self, use_tree, id) } - fn visit_path_parameters(&mut self, path_span: Span, path_parameters: &PathParameters) { + fn visit_generic_args(&mut self, path_span: Span, generic_args: &GenericArgs) { self.count += 1; - walk_path_parameters(self, path_span, path_parameters) + walk_generic_args(self, path_span, generic_args) } fn visit_assoc_type_binding(&mut self, type_binding: &TypeBinding) { self.count += 1; diff --git a/src/libsyntax/visit.rs b/src/libsyntax/visit.rs index a4b9e3d7d4519..6dc61f3058a5c 100644 --- a/src/libsyntax/visit.rs +++ b/src/libsyntax/visit.rs @@ -128,8 +128,14 @@ pub trait Visitor<'ast>: Sized { fn visit_path_segment(&mut self, path_span: Span, path_segment: &'ast PathSegment) { walk_path_segment(self, path_span, path_segment) } - fn visit_path_parameters(&mut self, path_span: Span, path_parameters: &'ast PathParameters) { - walk_path_parameters(self, path_span, path_parameters) + fn visit_generic_args(&mut self, path_span: Span, generic_args: &'ast GenericArgs) { + walk_generic_args(self, path_span, generic_args) + } + fn visit_angle_bracketed_param(&mut self, param: &'ast AngleBracketedParam) { + match param { + AngleBracketedParam::Lifetime(lt) => self.visit_lifetime(lt), + AngleBracketedParam::Type(ty) => self.visit_ty(ty), + } } fn visit_assoc_type_binding(&mut self, type_binding: &'ast TypeBinding) { walk_assoc_type_binding(self, type_binding) @@ -376,22 +382,21 @@ pub fn walk_path_segment<'a, V: Visitor<'a>>(visitor: &mut V, segment: &'a PathSegment) { visitor.visit_ident(segment.ident); if let Some(ref parameters) = segment.parameters { - visitor.visit_path_parameters(path_span, parameters); + visitor.visit_generic_args(path_span, parameters); } } -pub fn walk_path_parameters<'a, V>(visitor: &mut V, - _path_span: Span, - path_parameters: &'a PathParameters) +pub fn walk_generic_args<'a, V>(visitor: &mut V, + _path_span: Span, + generic_args: &'a GenericArgs) where V: Visitor<'a>, { - match *path_parameters { - PathParameters::AngleBracketed(ref data) => { - walk_list!(visitor, visit_lifetime, data.lifetimes()); - walk_list!(visitor, visit_ty, data.types()); + match *generic_args { + GenericArgs::AngleBracketed(ref data) => { + walk_list!(visitor, visit_angle_bracketed_param, &data.parameters); walk_list!(visitor, visit_assoc_type_binding, &data.bindings); } - PathParameters::Parenthesized(ref data) => { + GenericArgs::Parenthesized(ref data) => { walk_list!(visitor, visit_ty, &data.inputs); walk_list!(visitor, visit_ty, &data.output); } diff --git a/src/test/run-pass/issue-22777.rs b/src/test/run-pass/issue-22777.rs index 2dc4d775a9c45..4df46c0e2e1e7 100644 --- a/src/test/run-pass/issue-22777.rs +++ b/src/test/run-pass/issue-22777.rs @@ -32,8 +32,8 @@ struct S04_TyParamBound(S05_PolyTraitRef); struct S05_PolyTraitRef(S06_TraitRef); struct S06_TraitRef(S07_Path); struct S07_Path(Vec); -struct S08_PathSegment(S09_PathParameters); -struct S09_PathParameters(P); +struct S08_PathSegment(S09_GenericArgs); +struct S09_GenericArgs(P); struct S10_ParenthesizedParameterData(Option>); struct S11_Ty(P); struct S12_Expr(P); diff --git a/src/test/ui/rfc1598-generic-associated-types/streaming_iterator.rs b/src/test/ui/rfc1598-generic-associated-types/streaming_iterator.rs index 522ddb5dc135e..3f69de3de834f 100644 --- a/src/test/ui/rfc1598-generic-associated-types/streaming_iterator.rs +++ b/src/test/ui/rfc1598-generic-associated-types/streaming_iterator.rs @@ -10,7 +10,7 @@ #![feature(generic_associated_types)] -//FIXME(#44265): "lifetime parameter not allowed on this type" errors will be addressed in a +//FIXME(#44265): "lifetime parameter not allowed" errors will be addressed in a // follow-up PR use std::fmt::Display; From 76c0d687453cb1da2e76a1c8e007ac080f8aa0d7 Mon Sep 17 00:00:00 2001 From: varkor Date: Fri, 23 Feb 2018 17:48:54 +0000 Subject: [PATCH 05/41] Rename "parameter" to "arg" --- src/librustc/hir/intravisit.rs | 6 +- src/librustc/hir/lowering.rs | 47 ++++------ src/librustc/hir/mod.rs | 30 +++---- src/librustc/hir/print.rs | 18 ++-- src/librustc/ich/impls_hir.rs | 4 +- src/librustc/middle/resolve_lifetime.rs | 34 ++++--- src/librustc/ty/instance.rs | 1 + src/librustc/ty/mod.rs | 95 -------------------- src/librustc_codegen_llvm/base.rs | 1 + src/librustc_driver/pretty.rs | 2 +- src/librustc_mir/hair/pattern/check_match.rs | 2 +- src/librustc_mir/monomorphize/mod.rs | 1 + src/librustc_passes/ast_validation.rs | 20 ++--- src/librustc_resolve/macros.rs | 4 +- src/librustc_save_analysis/dump_visitor.rs | 10 +-- src/librustc_save_analysis/lib.rs | 4 +- src/librustc_typeck/astconv.rs | 28 +++--- src/librustc_typeck/check/method/confirm.rs | 9 +- src/librustc_typeck/check/mod.rs | 6 +- src/librustc_typeck/collect.rs | 7 -- src/librustdoc/clean/auto_trait.rs | 36 ++++---- src/librustdoc/clean/mod.rs | 26 +++--- src/librustdoc/clean/simplify.rs | 2 +- src/librustdoc/html/format.rs | 10 +-- src/libsyntax/ast.rs | 34 +++---- src/libsyntax/ext/build.rs | 22 ++--- src/libsyntax/fold.rs | 38 ++++---- src/libsyntax/parse/parser.rs | 30 +++---- src/libsyntax/print/pprust.rs | 28 +++--- src/libsyntax/visit.rs | 12 +-- src/libsyntax_ext/deriving/clone.rs | 4 +- src/libsyntax_ext/deriving/cmp/eq.rs | 4 +- src/libsyntax_ext/deriving/generic/mod.rs | 6 +- src/libsyntax_ext/deriving/generic/ty.rs | 10 +-- src/libsyntax_ext/env.rs | 6 +- 35 files changed, 242 insertions(+), 355 deletions(-) diff --git a/src/librustc/hir/intravisit.rs b/src/librustc/hir/intravisit.rs index 9b5b53e891baf..fef33939fac6a 100644 --- a/src/librustc/hir/intravisit.rs +++ b/src/librustc/hir/intravisit.rs @@ -648,15 +648,15 @@ pub fn walk_path_segment<'v, V: Visitor<'v>>(visitor: &mut V, path_span: Span, segment: &'v PathSegment) { visitor.visit_name(path_span, segment.name); - if let Some(ref parameters) = segment.parameters { - visitor.visit_generic_args(path_span, parameters); + if let Some(ref args) = segment.args { + visitor.visit_generic_args(path_span, args); } } pub fn walk_generic_args<'v, V: Visitor<'v>>(visitor: &mut V, _path_span: Span, generic_args: &'v GenericArgs) { - walk_list!(visitor, visit_generic_arg, &generic_args.parameters); + walk_list!(visitor, visit_generic_arg, &generic_args.args); walk_list!(visitor, visit_assoc_type_binding, &generic_args.bindings); } diff --git a/src/librustc/hir/lowering.rs b/src/librustc/hir/lowering.rs index 4b090e88c4046..831a689a34997 100644 --- a/src/librustc/hir/lowering.rs +++ b/src/librustc/hir/lowering.rs @@ -59,6 +59,7 @@ use std::fmt::Debug; use std::iter; use std::mem; use syntax::attr; +use syntax::ast; use syntax::ast::*; use syntax::errors; use syntax::ext::hygiene::{Mark, SyntaxContext}; @@ -1039,14 +1040,14 @@ impl<'a> LoweringContext<'a> { } fn lower_generic_arg(&mut self, - p: &AngleBracketedParam, + p: &ast::GenericArg, itctx: ImplTraitContext) - -> GenericArg { + -> hir::GenericArg { match p { - AngleBracketedParam::Lifetime(lt) => { + ast::GenericArg::Lifetime(lt) => { GenericArg::Lifetime(self.lower_lifetime(<)) } - AngleBracketedParam::Type(ty) => { + ast::GenericArg::Type(ty) => { GenericArg::Type(self.lower_ty(&ty, itctx)) } } @@ -1684,8 +1685,7 @@ impl<'a> LoweringContext<'a> { parenthesized_generic_args: ParenthesizedGenericArgs, itctx: ImplTraitContext, ) -> hir::PathSegment { - let (mut generic_args, infer_types) = - if let Some(ref generic_args) = segment.parameters { + let (mut generic_args, infer_types) = if let Some(ref generic_args) = segment.args { let msg = "parenthesized parameters may only be used with a trait"; match **generic_args { GenericArgs::AngleBracketed(ref data) => { @@ -1715,13 +1715,16 @@ impl<'a> LoweringContext<'a> { }; if !generic_args.parenthesized && generic_args.lifetimes().count() == 0 { - generic_args.parameters = (0..expected_lifetimes).map(|_| { - GenericArg::Lifetime(self.elided_lifetime(path_span)) - }).chain(generic_args.parameters.into_iter()).collect(); + generic_args.args = + self.elided_path_lifetimes(path_span, expected_lifetimes) + .into_iter() + .map(|lt| GenericArg::Lifetime(lt)) + .chain(generic_args.args.into_iter()) + .collect(); } hir::PathSegment::new( - self.lower_ident(segment.identifier), + self.lower_ident(segment.ident), generic_args, infer_types ) @@ -1729,13 +1732,13 @@ impl<'a> LoweringContext<'a> { fn lower_angle_bracketed_parameter_data( &mut self, - data: &AngleBracketedParameterData, + data: &AngleBracketedArgs, param_mode: ParamMode, itctx: ImplTraitContext, ) -> (hir::GenericArgs, bool) { - let &AngleBracketedParameterData { ref parameters, ref bindings, .. } = data; + let &AngleBracketedArgs { ref args, ref bindings, .. } = data; (hir::GenericArgs { - parameters: parameters.iter().map(|p| self.lower_generic_arg(p, itctx)).collect(), + args: args.iter().map(|p| self.lower_generic_arg(p, itctx)).collect(), bindings: bindings.iter().map(|b| self.lower_ty_binding(b, itctx)).collect(), parenthesized: false, }, @@ -1755,23 +1758,11 @@ impl<'a> LoweringContext<'a> { AnonymousLifetimeMode::PassThrough, |this| { const DISALLOWED: ImplTraitContext = ImplTraitContext::Disallowed; - let &ParenthesizedParameterData { - ref inputs, - ref output, - span, - } = data; - let inputs = inputs - .iter() - .map(|ty| this.lower_ty(ty, DISALLOWED)) - .collect(); + let &ParenthesizedParameterData { ref inputs, ref output, span } = data; + let inputs = inputs.iter().map(|ty| this.lower_ty(ty, DISALLOWED)).collect(); let mk_tup = |this: &mut Self, tys, span| { let LoweredNodeId { node_id, hir_id } = this.next_id(); - P(hir::Ty { - node: hir::TyTup(tys), - id: node_id, - hir_id, - span, - }) + P(hir::Ty { node: hir::TyTup(tys), id: node_id, hir_id, span }) }; ( diff --git a/src/librustc/hir/mod.rs b/src/librustc/hir/mod.rs index 38a894df3cd5a..729ac17ae0991 100644 --- a/src/librustc/hir/mod.rs +++ b/src/librustc/hir/mod.rs @@ -327,7 +327,7 @@ pub struct PathSegment { /// this is more than just simple syntactic sugar; the use of /// parens affects the region binding rules, so we preserve the /// distinction. - pub parameters: Option>, + pub args: Option>, /// Whether to infer remaining type parameters, if any. /// This only applies to expression and pattern paths, and @@ -342,30 +342,30 @@ impl PathSegment { PathSegment { name, infer_types: true, - parameters: None + args: None, } } - pub fn new(name: Name, parameters: GenericArgs, infer_types: bool) -> Self { + pub fn new(name: Name, args: GenericArgs, infer_types: bool) -> Self { PathSegment { name, infer_types, - parameters: if parameters.is_empty() { + args: if args.is_empty() { None } else { - Some(P(parameters)) + Some(P(args)) } } } // FIXME: hack required because you can't create a static // GenericArgs, so you can't just return a &GenericArgs. - pub fn with_parameters(&self, f: F) -> R + pub fn with_args(&self, f: F) -> R where F: FnOnce(&GenericArgs) -> R { let dummy = GenericArgs::none(); - f(if let Some(ref params) = self.parameters { - ¶ms + f(if let Some(ref args) = self.args { + &args } else { &dummy }) @@ -380,12 +380,12 @@ pub enum GenericArg { #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)] pub struct GenericArgs { - /// The generic parameters for this path segment. - pub parameters: HirVec, + /// The generic arguments for this path segment. + pub args: HirVec, /// Bindings (equality constraints) on associated types, if present. /// E.g., `Foo`. pub bindings: HirVec, - /// Were parameters written in parenthesized form `Fn(T) -> U`? + /// Were arguments written in parenthesized form `Fn(T) -> U`? /// This is required mostly for pretty-printing and diagnostics, /// but also for changing lifetime elision rules to be "function-like". pub parenthesized: bool, @@ -394,14 +394,14 @@ pub struct GenericArgs { impl GenericArgs { pub fn none() -> Self { Self { - parameters: HirVec::new(), + args: HirVec::new(), bindings: HirVec::new(), parenthesized: false, } } pub fn is_empty(&self) -> bool { - self.parameters.is_empty() && self.bindings.is_empty() && !self.parenthesized + self.args.is_empty() && self.bindings.is_empty() && !self.parenthesized } pub fn inputs(&self) -> &[P] { @@ -416,7 +416,7 @@ impl GenericArgs { } pub fn lifetimes(&self) -> impl DoubleEndedIterator { - self.parameters.iter().filter_map(|p| { + self.args.iter().filter_map(|p| { if let GenericArg::Lifetime(lt) = p { Some(lt) } else { @@ -426,7 +426,7 @@ impl GenericArgs { } pub fn types(&self) -> impl DoubleEndedIterator> { - self.parameters.iter().filter_map(|p| { + self.args.iter().filter_map(|p| { if let GenericArg::Type(ty) = p { Some(ty) } else { diff --git a/src/librustc/hir/print.rs b/src/librustc/hir/print.rs index f7e98591c112b..c12d258b6c7c9 100644 --- a/src/librustc/hir/print.rs +++ b/src/librustc/hir/print.rs @@ -1269,11 +1269,11 @@ impl<'a> State<'a> { self.s.word(".")?; self.print_name(segment.name)?; - segment.with_parameters(|parameters| { - if !parameters.parameters.is_empty() || - !parameters.bindings.is_empty() + segment.with_args(|args| { + if !args.args.is_empty() || + !args.bindings.is_empty() { - self.print_generic_args(¶meters, segment.infer_types, true) + self.print_generic_args(&args, segment.infer_types, true) } else { Ok(()) } @@ -1641,7 +1641,7 @@ impl<'a> State<'a> { if segment.name != keywords::CrateRoot.name() && segment.name != keywords::DollarCrate.name() { self.print_name(segment.name)?; - segment.with_parameters(|parameters| { + segment.with_args(|parameters| { self.print_generic_args(parameters, segment.infer_types, colons_before_params) @@ -1673,7 +1673,7 @@ impl<'a> State<'a> { if segment.name != keywords::CrateRoot.name() && segment.name != keywords::DollarCrate.name() { self.print_name(segment.name)?; - segment.with_parameters(|parameters| { + segment.with_args(|parameters| { self.print_generic_args(parameters, segment.infer_types, colons_before_params) @@ -1685,7 +1685,7 @@ impl<'a> State<'a> { self.s.word("::")?; let item_segment = path.segments.last().unwrap(); self.print_name(item_segment.name)?; - item_segment.with_parameters(|parameters| { + item_segment.with_args(|parameters| { self.print_generic_args(parameters, item_segment.infer_types, colons_before_params) @@ -1697,7 +1697,7 @@ impl<'a> State<'a> { self.s.word(">")?; self.s.word("::")?; self.print_name(item_segment.name)?; - item_segment.with_parameters(|parameters| { + item_segment.with_args(|parameters| { self.print_generic_args(parameters, item_segment.infer_types, colons_before_params) @@ -1734,7 +1734,7 @@ impl<'a> State<'a> { let elide_lifetimes = generic_args.lifetimes().all(|lt| lt.is_elided()); if !elide_lifetimes { start_or_comma(self)?; - self.commasep(Inconsistent, &generic_args.parameters, |s, p| { + self.commasep(Inconsistent, &generic_args.args, |s, p| { match p { GenericArg::Lifetime(lt) => s.print_lifetime(lt), GenericArg::Type(ty) => s.print_type(ty), diff --git a/src/librustc/ich/impls_hir.rs b/src/librustc/ich/impls_hir.rs index 6f65562867804..871e399b4f259 100644 --- a/src/librustc/ich/impls_hir.rs +++ b/src/librustc/ich/impls_hir.rs @@ -177,7 +177,7 @@ impl_stable_hash_for!(struct hir::Path { impl_stable_hash_for!(struct hir::PathSegment { name, infer_types, - parameters + args }); impl_stable_hash_for!(enum hir::GenericArg { @@ -186,7 +186,7 @@ impl_stable_hash_for!(enum hir::GenericArg { }); impl_stable_hash_for!(struct hir::GenericArgs { - parameters, + args, bindings, parenthesized }); diff --git a/src/librustc/middle/resolve_lifetime.rs b/src/librustc/middle/resolve_lifetime.rs index 69818068e9c92..39dfa77ea677e 100644 --- a/src/librustc/middle/resolve_lifetime.rs +++ b/src/librustc/middle/resolve_lifetime.rs @@ -28,7 +28,6 @@ use rustc_data_structures::sync::Lrc; use session::Session; use std::cell::Cell; use std::mem::replace; -use std::slice; use syntax::ast; use syntax::attr; use syntax::ptr::P; @@ -155,11 +154,10 @@ impl Region { } } - fn subst(self, params: Vec<&hir::Lifetime>, map: &NamedRegionMap) -> Option { + fn subst<'a, L>(self, mut params: L, map: &NamedRegionMap) -> Option + where L: Iterator { if let Region::EarlyBound(index, _, _) = self { - params - .get(index as usize) - .and_then(|lifetime| map.defs.get(&lifetime.id).cloned()) + params.nth(index as usize).and_then(|lifetime| map.defs.get(&lifetime.id).cloned()) } else { Some(self) } @@ -603,7 +601,7 @@ impl<'a, 'tcx> Visitor<'tcx> for LifetimeContext<'a, 'tcx> { // resolved the same as the `'_` in `&'_ Foo`. // // cc #48468 - self.resolve_elided_lifetimes(slice::from_ref(lifetime), false) + self.resolve_elided_lifetimes(vec![lifetime], false) } LifetimeName::Fresh(_) | LifetimeName::Static | LifetimeName::Name(_) => { // If the user wrote an explicit name, use that. @@ -833,8 +831,8 @@ impl<'a, 'tcx> Visitor<'tcx> for LifetimeContext<'a, 'tcx> { fn visit_path(&mut self, path: &'tcx hir::Path, _: ast::NodeId) { for (i, segment) in path.segments.iter().enumerate() { let depth = path.segments.len() - i - 1; - if let Some(ref parameters) = segment.parameters { - self.visit_segment_parameters(path.def, depth, parameters); + if let Some(ref args) = segment.args { + self.visit_segment_args(path.def, depth, args); } } } @@ -1599,24 +1597,24 @@ impl<'a, 'tcx> LifetimeContext<'a, 'tcx> { } } - fn visit_segment_parameters( + fn visit_segment_args( &mut self, def: Def, depth: usize, - params: &'tcx hir::GenericArgs, + args: &'tcx hir::GenericArgs, ) { - if params.parenthesized { + if args.parenthesized { let was_in_fn_syntax = self.is_in_fn_syntax; self.is_in_fn_syntax = true; - self.visit_fn_like_elision(params.inputs(), Some(¶ms.bindings[0].ty)); + self.visit_fn_like_elision(args.inputs(), Some(&args.bindings[0].ty)); self.is_in_fn_syntax = was_in_fn_syntax; return; } - if params.lifetimes().all(|l| l.is_elided()) { - self.resolve_elided_lifetimes(params.lifetimes().collect(), true); + if args.lifetimes().all(|l| l.is_elided()) { + self.resolve_elided_lifetimes(args.lifetimes().collect(), true); } else { - for l in params.lifetimes() { + for l in args.lifetimes() { self.visit_lifetime(l); } } @@ -1688,13 +1686,13 @@ impl<'a, 'tcx> LifetimeContext<'a, 'tcx> { } else { Some(Region::Static) }, - Set1::One(r) => r.subst(params.lifetimes().collect(), map), + Set1::One(r) => r.subst(args.lifetimes(), map), Set1::Many => None, }) .collect() }); - for (i, ty) in params.types().enumerate() { + for (i, ty) in args.types().enumerate() { if let Some(<) = object_lifetime_defaults.get(i) { let scope = Scope::ObjectLifetimeDefault { lifetime: lt, @@ -1706,7 +1704,7 @@ impl<'a, 'tcx> LifetimeContext<'a, 'tcx> { } } - for b in ¶ms.bindings { + for b in &args.bindings { self.visit_assoc_type_binding(b); } } diff --git a/src/librustc/ty/instance.rs b/src/librustc/ty/instance.rs index 66edbeff749f7..8b1c31deb1377 100644 --- a/src/librustc/ty/instance.rs +++ b/src/librustc/ty/instance.rs @@ -10,6 +10,7 @@ use hir::def_id::DefId; use ty::{self, Ty, TypeFoldable, Substs, TyCtxt}; +use ty::subst::Kind; use traits; use rustc_target::spec::abi::Abi; use util::ppaux; diff --git a/src/librustc/ty/mod.rs b/src/librustc/ty/mod.rs index 447267adfcdd0..4f5f0c9d740cc 100644 --- a/src/librustc/ty/mod.rs +++ b/src/librustc/ty/mod.rs @@ -885,73 +885,6 @@ pub struct GenericParamCount { pub types: usize, } -#[derive(Clone, Debug, RustcEncodable, RustcDecodable)] -pub enum GenericParam { - Lifetime(RegionParameterDef), - Type(TypeParameterDef), -} - -impl GenericParam { - pub fn index(&self) -> u32 { - match self { - GenericParam::Lifetime(lt) => lt.index, - GenericParam::Type(ty) => ty.index, - } - } -} - -#[derive(Clone, Debug, RustcEncodable, RustcDecodable)] -pub enum KindIndex { - Lifetime, - Type, -} - -#[derive(Clone, Debug, RustcEncodable, RustcDecodable)] -pub struct KindIndexed { - pub lt: L, - pub ty: T, -} - -impl KindIndexed { - pub fn get(&self, idx: KindIndex) -> &T { - match idx { - KindIndex::Lifetime => &self.lt, - KindIndex::Type => &self.ty, - } - } - - pub fn iter(&self) -> KindIndexIterator { - KindIndexIterator { - index: self, - next: Some(KindIndex::Lifetime), - } - } -} - -#[derive(Clone, Debug)] -pub struct KindIndexIterator<'a, T: 'a> { - pub index: &'a KindIndexed, - pub next: Option, -} - -impl<'a, T> Iterator for KindIndexIterator<'a, T> { - type Item = &'a T; - - fn next(&mut self) -> Option { - match self.next { - Some(KindIndex::Lifetime) => { - self.next = Some(KindIndex::Type); - Some(&self.index.lt) - } - Some(KindIndex::Type) => { - self.next = None; - Some(&self.index.ty) - }, - None => None, - } - } -} - /// Information about the formal type/lifetime parameters associated /// with an item or method. Analogous to hir::Generics. /// @@ -1009,34 +942,6 @@ impl<'a, 'gcx, 'tcx> Generics { } } - pub fn lifetimes(&self) -> impl DoubleEndedIterator { - self.parameters.iter().filter_map(|p| { - if let GenericParam::Lifetime(lt) = p { - Some(lt) - } else { - None - } - }) - } - - pub fn types(&self) -> impl DoubleEndedIterator { - self.parameters.iter().filter_map(|p| { - if let GenericParam::Type(ty) = p { - Some(ty) - } else { - None - } - }) - } - - pub fn parent_lifetimes(&self) -> u32 { - *self.parent_params.get(KindIndex::Lifetime) - } - - pub fn parent_types(&self) -> u32 { - *self.parent_params.get(KindIndex::Type) - } - pub fn region_param(&'tcx self, param: &EarlyBoundRegion, tcx: TyCtxt<'a, 'gcx, 'tcx>) diff --git a/src/librustc_codegen_llvm/base.rs b/src/librustc_codegen_llvm/base.rs index 322924535d1f7..7c8ba63c15eb9 100644 --- a/src/librustc_codegen_llvm/base.rs +++ b/src/librustc_codegen_llvm/base.rs @@ -40,6 +40,7 @@ use rustc::middle::weak_lang_items; use rustc::mir::mono::{Linkage, Visibility, Stats}; use rustc::middle::cstore::{EncodedMetadata}; use rustc::ty::{self, Ty, TyCtxt}; +use rustc::ty::subst::Kind; use rustc::ty::layout::{self, Align, TyLayout, LayoutOf}; use rustc::ty::query::Providers; use rustc::dep_graph::{DepNode, DepConstructor}; diff --git a/src/librustc_driver/pretty.rs b/src/librustc_driver/pretty.rs index 834bd0c32ed8f..7468f01de705f 100644 --- a/src/librustc_driver/pretty.rs +++ b/src/librustc_driver/pretty.rs @@ -677,7 +677,7 @@ impl<'a> ReplaceBodyWithLoop<'a> { ast::TyKind::Paren(ref subty) => involves_impl_trait(subty), ast::TyKind::Tup(ref tys) => any_involves_impl_trait(tys.iter()), ast::TyKind::Path(_, ref path) => path.segments.iter().any(|seg| { - match seg.parameters.as_ref().map(|p| &**p) { + match seg.args.as_ref().map(|p| &**p) { None => false, Some(&ast::GenericArgs::AngleBracketed(ref data)) => any_involves_impl_trait(data.types().into_iter()) || diff --git a/src/librustc_mir/hair/pattern/check_match.rs b/src/librustc_mir/hair/pattern/check_match.rs index 7cef8a75aa6ba..2c58bd8e79b08 100644 --- a/src/librustc_mir/hair/pattern/check_match.rs +++ b/src/librustc_mir/hair/pattern/check_match.rs @@ -295,7 +295,7 @@ impl<'a, 'tcx> MatchVisitor<'a, 'tcx> { ); let label_msg = match pat.node { PatKind::Path(hir::QPath::Resolved(None, ref path)) - if path.segments.len() == 1 && path.segments[0].parameters.is_none() => { + if path.segments.len() == 1 && path.segments[0].args.is_none() => { format!("interpreted as a {} pattern, not new variable", path.def.kind_name()) } _ => format!("pattern `{}` not covered", pattern_string), diff --git a/src/librustc_mir/monomorphize/mod.rs b/src/librustc_mir/monomorphize/mod.rs index bf544e5120cd8..3afe9991c68d0 100644 --- a/src/librustc_mir/monomorphize/mod.rs +++ b/src/librustc_mir/monomorphize/mod.rs @@ -13,6 +13,7 @@ use rustc::middle::lang_items::DropInPlaceFnLangItem; use rustc::traits; use rustc::ty::adjustment::CustomCoerceUnsized; use rustc::ty::{self, Ty, TyCtxt}; +use rustc::ty::subst::Kind; pub use rustc::ty::Instance; pub use self::item::{MonoItem, MonoItemExt}; diff --git a/src/librustc_passes/ast_validation.rs b/src/librustc_passes/ast_validation.rs index 39e0a5392580b..63c8bd3d1f77a 100644 --- a/src/librustc_passes/ast_validation.rs +++ b/src/librustc_passes/ast_validation.rs @@ -230,9 +230,9 @@ impl<'a> Visitor<'a> for AstValidator<'a> { // } // foo!(bar::baz); use_tree.prefix.segments.iter().find(|segment| { - segment.parameters.is_some() + segment.args.is_some() }).map(|segment| { - self.err_handler().span_err(segment.parameters.as_ref().unwrap().span(), + self.err_handler().span_err(segment.args.as_ref().unwrap().span(), "generic arguments in import path"); }); @@ -398,8 +398,8 @@ impl<'a> Visitor<'a> for AstValidator<'a> { fn visit_vis(&mut self, vis: &'a Visibility) { match vis.node { VisibilityKind::Restricted { ref path, .. } => { - path.segments.iter().find(|segment| segment.parameters.is_some()).map(|segment| { - self.err_handler().span_err(segment.parameters.as_ref().unwrap().span(), + path.segments.iter().find(|segment| segment.args.is_some()).map(|segment| { + self.err_handler().span_err(segment.args.as_ref().unwrap().span(), "generic arguments in visibility path"); }); } @@ -521,10 +521,10 @@ impl<'a> Visitor<'a> for NestedImplTraitVisitor<'a> { visit::walk_ty(self, t); } } - fn visit_path_parameters(&mut self, _: Span, path_parameters: &'a PathParameters) { - match *path_parameters { - PathParameters::AngleBracketed(ref params) => { - for type_ in ¶ms.types { + fn visit_generic_args(&mut self, _: Span, generic_args: &'a GenericArgs) { + match *generic_args { + GenericArgs::AngleBracketed(ref params) => { + for type_ in params.types() { self.visit_ty(type_); } for type_binding in ¶ms.bindings { @@ -533,7 +533,7 @@ impl<'a> Visitor<'a> for NestedImplTraitVisitor<'a> { self.with_impl_trait(None, |this| visit::walk_ty(this, &type_binding.ty)); } } - PathParameters::Parenthesized(ref params) => { + GenericArgs::Parenthesized(ref params) => { for type_ in ¶ms.inputs { self.visit_ty(type_); } @@ -590,7 +590,7 @@ impl<'a> Visitor<'a> for ImplTraitProjectionVisitor<'a> { // // To implement this, we disallow `impl Trait` from `qself` // (for cases like `::Foo>`) - // but we allow `impl Trait` in `PathParameters` + // but we allow `impl Trait` in `GenericArgs` // iff there are no more PathSegments. if let Some(ref qself) = *qself { // `impl Trait` in `qself` is always illegal diff --git a/src/librustc_resolve/macros.rs b/src/librustc_resolve/macros.rs index de7a3dc5ceeb2..649e8858b0971 100644 --- a/src/librustc_resolve/macros.rs +++ b/src/librustc_resolve/macros.rs @@ -437,8 +437,8 @@ impl<'a> Resolver<'a> { let def = self.resolve_macro_to_def_inner(scope, path, kind, force); if def != Err(Determinacy::Undetermined) { // Do not report duplicated errors on every undetermined resolution. - path.segments.iter().find(|segment| segment.parameters.is_some()).map(|segment| { - self.session.span_err(segment.parameters.as_ref().unwrap().span(), + path.segments.iter().find(|segment| segment.args.is_some()).map(|segment| { + self.session.span_err(segment.args.as_ref().unwrap().span(), "generic arguments in macro path"); }); } diff --git a/src/librustc_save_analysis/dump_visitor.rs b/src/librustc_save_analysis/dump_visitor.rs index 6d13548b9adff..fa055d246f30a 100644 --- a/src/librustc_save_analysis/dump_visitor.rs +++ b/src/librustc_save_analysis/dump_visitor.rs @@ -818,10 +818,10 @@ impl<'l, 'tcx: 'l, 'll, O: DumpOutput + 'll> DumpVisitor<'l, 'tcx, 'll, O> { } self.dump_path_ref(id, path); - // Type parameters + // Type arguments for seg in &path.segments { - if let Some(ref params) = seg.parameters { - match **params { + if let Some(ref args) = seg.args { + match **args { ast::GenericArgs::AngleBracketed(ref data) => for t in data.types() { self.visit_ty(t); }, @@ -905,8 +905,8 @@ impl<'l, 'tcx: 'l, 'll, O: DumpOutput + 'll> DumpVisitor<'l, 'tcx, 'll, O> { } // Explicit types in the turbo-fish. - if let Some(ref params) = seg.parameters { - if let ast::GenericArgs::AngleBracketed(ref data) = **params { + if let Some(ref args) = seg.args { + if let ast::GenericArgs::AngleBracketed(ref data) = **args { for t in data.types() { self.visit_ty(t); } diff --git a/src/librustc_save_analysis/lib.rs b/src/librustc_save_analysis/lib.rs index c1022c09de35a..4f03698d9b17c 100644 --- a/src/librustc_save_analysis/lib.rs +++ b/src/librustc_save_analysis/lib.rs @@ -692,8 +692,8 @@ impl<'l, 'tcx: 'l> SaveContext<'l, 'tcx> { if path.segments.len() != 1 { return false; } - if let Some(ref params) = path.segments[0].parameters { - if let ast::GenericArgs::Parenthesized(_) = **params { + if let Some(ref args) = path.segments[0].args { + if let ast::GenericArgs::Parenthesized(_) = **args { return true; } } diff --git a/src/librustc_typeck/astconv.rs b/src/librustc_typeck/astconv.rs index 656045c970f9c..be4c423e959bb 100644 --- a/src/librustc_typeck/astconv.rs +++ b/src/librustc_typeck/astconv.rs @@ -177,11 +177,11 @@ impl<'o, 'gcx: 'tcx, 'tcx> AstConv<'gcx, 'tcx>+'o { { let (substs, assoc_bindings) = - item_segment.with_parameters(|parameters| { + item_segment.with_args(|args| { self.create_substs_for_ast_path( span, def_id, - parameters, + args, item_segment.infer_types, None) }); @@ -199,7 +199,7 @@ impl<'o, 'gcx: 'tcx, 'tcx> AstConv<'gcx, 'tcx>+'o { fn create_substs_for_ast_path(&self, span: Span, def_id: DefId, - parameters: &hir::GenericArgs, + args: &hir::GenericArgs, infer_types: bool, self_ty: Option>) -> (&'tcx Substs<'tcx>, Vec>) @@ -207,15 +207,15 @@ impl<'o, 'gcx: 'tcx, 'tcx> AstConv<'gcx, 'tcx>+'o { let tcx = self.tcx(); debug!("create_substs_for_ast_path(def_id={:?}, self_ty={:?}, \ - parameters={:?})", - def_id, self_ty, parameters); + args={:?})", + def_id, self_ty, args); // If the type is parameterized by this region, then replace this // region with the current anon region binding (in other words, // whatever & would get replaced with). let decl_generics = tcx.generics_of(def_id); - let ty_provided = parameters.types().len(); - let lt_provided = parameters.lifetimes().len(); + let ty_provided = args.types().count(); + let lt_provided = args.lifetimes().count(); let mut lt_accepted = 0; let mut ty_params = ParamRange { required: 0, accepted: 0 }; @@ -269,7 +269,7 @@ impl<'o, 'gcx: 'tcx, 'tcx> AstConv<'gcx, 'tcx>+'o { match param.kind { GenericParamDefKind::Lifetime => { let i = param.index as usize - own_self; - if let Some(lifetime) = parameters.lifetimes().get(i) { + if let Some(lifetime) = args.lifetimes().nth(i) { self.ast_region_to_region(lifetime, Some(param)).into() } else { tcx.types.re_static.into() @@ -286,7 +286,7 @@ impl<'o, 'gcx: 'tcx, 'tcx> AstConv<'gcx, 'tcx>+'o { let i = i - (lt_accepted + own_self); if i < ty_provided { // A provided type parameter. - self.ast_ty_to_ty(¶meters.types()[i]).into() + self.ast_ty_to_ty(&args.types().nth(i).unwrap()).into() } else if infer_types { // No type parameters were provided, we can infer all. if !default_needs_object_self(param) { @@ -330,7 +330,7 @@ impl<'o, 'gcx: 'tcx, 'tcx> AstConv<'gcx, 'tcx>+'o { } }); - let assoc_bindings = parameters.bindings.iter().map(|binding| { + let assoc_bindings = args.bindings.iter().map(|binding| { ConvertedBinding { item_name: binding.name, ty: self.ast_ty_to_ty(&binding.ty), @@ -451,7 +451,7 @@ impl<'o, 'gcx: 'tcx, 'tcx> AstConv<'gcx, 'tcx>+'o { let trait_def = self.tcx().trait_def(trait_def_id); if !self.tcx().features().unboxed_closures && - trait_segment.with_parameters(|p| p.parenthesized) != trait_def.paren_sugar { + trait_segment.with_args(|p| p.parenthesized) != trait_def.paren_sugar { // For now, require that parenthetical notation be used only with `Fn()` etc. let msg = if trait_def.paren_sugar { "the precise format of `Fn`-family traits' type parameters is subject to change. \ @@ -463,7 +463,7 @@ impl<'o, 'gcx: 'tcx, 'tcx> AstConv<'gcx, 'tcx>+'o { span, GateIssue::Language, msg); } - trait_segment.with_parameters(|parameters| { + trait_segment.with_args(|parameters| { self.create_substs_for_ast_path(span, trait_def_id, parameters, @@ -970,8 +970,8 @@ impl<'o, 'gcx: 'tcx, 'tcx> AstConv<'gcx, 'tcx>+'o { pub fn prohibit_type_params(&self, segments: &[hir::PathSegment]) { for segment in segments { - segment.with_parameters(|params| { - for p in ¶ms.parameters { + segment.with_args(|params| { + for p in ¶ms.args { let (mut span_err, span, kind) = match p { hir::GenericArg::Lifetime(lt) => { (struct_span_err!(self.tcx().sess, lt.span, E0110, diff --git a/src/librustc_typeck/check/method/confirm.rs b/src/librustc_typeck/check/method/confirm.rs index 3274c449daa4a..bb5bdd4dc7791 100644 --- a/src/librustc_typeck/check/method/confirm.rs +++ b/src/librustc_typeck/check/method/confirm.rs @@ -59,7 +59,7 @@ impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> { "confirm(unadjusted_self_ty={:?}, pick={:?}, generic_args={:?})", unadjusted_self_ty, pick, - segment.parameters, + segment.args, ); let mut confirm_cx = ConfirmContext::new(self, span, self_expr, call_expr); @@ -321,7 +321,7 @@ impl<'a, 'gcx, 'tcx> ConfirmContext<'a, 'gcx, 'tcx> { // Create subst for early-bound lifetime parameters, combining // parameters from the type and those from the method. assert_eq!(method_generics.parent_count, parent_substs.len()); - let provided = &segment.parameters; + let provided = &segment.args; let own_counts = method_generics.own_counts(); Substs::for_item(self.tcx, pick.item.def_id, |param, _| { let i = param.index as usize; @@ -331,7 +331,7 @@ impl<'a, 'gcx, 'tcx> ConfirmContext<'a, 'gcx, 'tcx> { match param.kind { GenericParamDefKind::Lifetime => { if let Some(lifetime) = provided.as_ref().and_then(|p| { - p.lifetimes().get(i - parent_substs.len()) + p.lifetimes().nth(i - parent_substs.len()) }) { return AstConv::ast_region_to_region( self.fcx, lifetime, Some(param)).into(); @@ -339,7 +339,7 @@ impl<'a, 'gcx, 'tcx> ConfirmContext<'a, 'gcx, 'tcx> { } GenericParamDefKind::Type {..} => { if let Some(ast_ty) = provided.as_ref().and_then(|p| { - p.types().get(i - parent_substs.len() - own_counts.lifetimes) + p.types().nth(i - parent_substs.len() - own_counts.lifetimes) }) { return self.to_ty(ast_ty).into(); } @@ -347,7 +347,6 @@ impl<'a, 'gcx, 'tcx> ConfirmContext<'a, 'gcx, 'tcx> { } self.var_for_def(self.span, param) } - self.type_var_for_def(self.span, def, cur_substs) }) } diff --git a/src/librustc_typeck/check/mod.rs b/src/librustc_typeck/check/mod.rs index ef61c99ae01cf..5af3d2fc42c9e 100644 --- a/src/librustc_typeck/check/mod.rs +++ b/src/librustc_typeck/check/mod.rs @@ -4834,7 +4834,7 @@ impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> { match param.kind { GenericParamDefKind::Lifetime => { let lifetimes = segment.map_or(vec![], |(s, _)| { - s.parameters.as_ref().map_or(vec![], |p| p.lifetimes()) + s.args.as_ref().map_or(vec![], |p| p.lifetimes().collect()) }); if let Some(lifetime) = lifetimes.get(i) { @@ -4845,7 +4845,7 @@ impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> { } GenericParamDefKind::Type {..} => { let (types, infer_types) = segment.map_or((vec![], true), |(s, _)| { - (s.parameters.as_ref().map_or(vec![], |p| |p| p.types()), s.infer_types) + (s.args.as_ref().map_or(vec![], |p| p.types().collect()), s.infer_types) }); // Skip over the lifetimes in the same segment. @@ -4962,7 +4962,7 @@ impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> { supress_mismatch_error: bool) { let (lifetimes, types, infer_types, bindings) = segment.map_or( (vec![], vec![], true, &[][..]), - |(s, _)| s.parameters.as_ref().map_or( + |(s, _)| s.args.as_ref().map_or( (vec![], vec![], s.infer_types, &[][..]), |p| (p.lifetimes().collect(), p.types().collect(), s.infer_types, &p.bindings[..]))); diff --git a/src/librustc_typeck/collect.rs b/src/librustc_typeck/collect.rs index 70367dd2461d2..58e804fc13f2d 100644 --- a/src/librustc_typeck/collect.rs +++ b/src/librustc_typeck/collect.rs @@ -973,13 +973,6 @@ fn generics_of<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, .map(|param| (param.def_id, param.index)) .collect(); - let parent_params = ty::KindIndexed { lt: parent_regions, ty: parent_types }; - let lifetimes: Vec = - regions.into_iter().map(|lt| ty::GenericParam::Lifetime(lt)).collect(); - let types: Vec = - types.into_iter().map(|ty| ty::GenericParam::Type(ty)).collect(); - let parameters = lifetimes.into_iter().chain(types.into_iter()).collect(); - tcx.alloc_generics(ty::Generics { parent: parent_def_id, parent_count, diff --git a/src/librustdoc/clean/auto_trait.rs b/src/librustdoc/clean/auto_trait.rs index da749fca2a953..4418c10722308 100644 --- a/src/librustdoc/clean/auto_trait.rs +++ b/src/librustdoc/clean/auto_trait.rs @@ -244,9 +244,8 @@ impl<'a, 'tcx, 'rcx> AutoTraitFinder<'a, 'tcx, 'rcx> { None } - fn generics_to_path_params(&self, generics: ty::Generics) -> hir::PathParameters { - let mut lifetimes = vec![]; - let mut types = vec![]; + fn generics_to_path_params(&self, generics: ty::Generics) -> hir::GenericArgs { + let mut args = vec![]; for param in generics.params.iter() { match param.kind { @@ -257,21 +256,20 @@ impl<'a, 'tcx, 'rcx> AutoTraitFinder<'a, 'tcx, 'rcx> { hir::LifetimeName::Name(param.name.as_symbol()) }; - lifetimes.push(hir::Lifetime { + args.push(hir::GenericArg::Lifetime(hir::Lifetime { id: ast::DUMMY_NODE_ID, span: DUMMY_SP, name, - }); + })); } ty::GenericParamDefKind::Type {..} => { - types.push(P(self.ty_param_to_ty(param.clone()))); + args.push(hir::GenericArg::Type(P(self.ty_param_to_ty(param.clone())))); } } } - hir::PathParameters { - lifetimes: HirVec::from_vec(lifetimes), - types: HirVec::from_vec(types), + hir::GenericArgs { + args: HirVec::from_vec(args), bindings: HirVec::new(), parenthesized: false, } @@ -555,9 +553,9 @@ impl<'a, 'tcx, 'rcx> AutoTraitFinder<'a, 'tcx, 'rcx> { let mut new_path = path.clone(); let last_segment = new_path.segments.pop().unwrap(); - let (old_input, old_output) = match last_segment.params { - PathParameters::AngleBracketed { types, .. } => (types, None), - PathParameters::Parenthesized { inputs, output, .. } => { + let (old_input, old_output) = match last_segment.args { + GenericArgs::AngleBracketed { types, .. } => (types, None), + GenericArgs::Parenthesized { inputs, output, .. } => { (inputs, output) } }; @@ -569,14 +567,14 @@ impl<'a, 'tcx, 'rcx> AutoTraitFinder<'a, 'tcx, 'rcx> { ); } - let new_params = PathParameters::Parenthesized { + let new_params = GenericArgs::Parenthesized { inputs: old_input, output, }; new_path.segments.push(PathSegment { name: last_segment.name, - params: new_params, + args: new_params, }); Type::ResolvedPath { @@ -793,13 +791,13 @@ impl<'a, 'tcx, 'rcx> AutoTraitFinder<'a, 'tcx, 'rcx> { // FIXME: Remove this scope when NLL lands { - let params = - &mut new_trait_path.segments.last_mut().unwrap().params; + let args = + &mut new_trait_path.segments.last_mut().unwrap().args; - match params { + match args { // Convert somethiung like ' = u8' // to 'T: Iterator' - &mut PathParameters::AngleBracketed { + &mut GenericArgs::AngleBracketed { ref mut bindings, .. } => { @@ -808,7 +806,7 @@ impl<'a, 'tcx, 'rcx> AutoTraitFinder<'a, 'tcx, 'rcx> { ty: rhs, }); } - &mut PathParameters::Parenthesized { .. } => { + &mut GenericArgs::Parenthesized { .. } => { existing_predicates.push( WherePredicate::EqPredicate { lhs: lhs.clone(), diff --git a/src/librustdoc/clean/mod.rs b/src/librustdoc/clean/mod.rs index f454136026f43..793a8a7f11035 100644 --- a/src/librustdoc/clean/mod.rs +++ b/src/librustdoc/clean/mod.rs @@ -1607,7 +1607,7 @@ fn external_path(cx: &DocContext, name: &str, trait_did: Option, has_self def: Def::Err, segments: vec![PathSegment { name: name.to_string(), - params: external_generic_args(cx, trait_did, has_self, bindings, substs) + args: external_generic_args(cx, trait_did, has_self, bindings, substs) }], } } @@ -2656,7 +2656,7 @@ impl Type { match *self { ResolvedPath { ref path, .. } => { path.segments.last().and_then(|seg| { - if let GenericArgs::AngleBracketed { ref types, .. } = seg.params { + if let GenericArgs::AngleBracketed { ref types, .. } = seg.args { Some(&**types) } else { None @@ -2851,7 +2851,7 @@ impl Clean for hir::Ty { let provided_params = &path.segments.last().unwrap(); let mut ty_substs = FxHashMap(); let mut lt_substs = FxHashMap(); - provided_params.with_parameters(|provided_params| { + provided_params.with_args(|provided_params| { let mut indices = GenericParamCount { lifetimes: 0, types: 0 @@ -2859,8 +2859,8 @@ impl Clean for hir::Ty { for param in generics.params.iter() { match param { hir::GenericParam::Lifetime(lt_param) => { - if let Some(lt) = provided_params.lifetimes - .get(indices.lifetimes).cloned() { + if let Some(lt) = provided_params.lifetimes() + .nth(indices.lifetimes).cloned() { if !lt.is_elided() { let lt_def_id = cx.tcx.hir.local_def_id(lt_param.lifetime.id); @@ -2872,8 +2872,8 @@ impl Clean for hir::Ty { hir::GenericParam::Type(ty_param) => { let ty_param_def = Def::TyParam(cx.tcx.hir.local_def_id(ty_param.id)); - if let Some(ty) = provided_params.types - .get(indices.types).cloned() { + if let Some(ty) = provided_params.types() + .nth(indices.types).cloned() { ty_substs.insert(ty_param_def, ty.into_inner().clean(cx)); } else if let Some(default) = ty_param.default.clone() { ty_substs.insert(ty_param_def, @@ -3447,7 +3447,7 @@ impl Path { def: Def::Err, segments: vec![PathSegment { name, - params: GenericArgs::AngleBracketed { + args: GenericArgs::AngleBracketed { lifetimes: Vec::new(), types: Vec::new(), bindings: Vec::new(), @@ -3471,7 +3471,7 @@ impl Clean for hir::Path { } } -#[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Eg, Debug, Hash)] +#[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Eq, Debug, Hash)] pub enum GenericArgs { AngleBracketed { lifetimes: Vec, @@ -3509,14 +3509,14 @@ impl Clean for hir::GenericArgs { #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Eq, Debug, Hash)] pub struct PathSegment { pub name: String, - pub params: GenericArgs, + pub args: GenericArgs, } impl Clean for hir::PathSegment { fn clean(&self, cx: &DocContext) -> PathSegment { PathSegment { name: self.name.clean(cx), - params: self.with_parameters(|parameters| parameters.clean(cx)) + args: self.with_args(|args| args.clean(cx)) } } } @@ -3550,7 +3550,7 @@ fn strip_path(path: &Path) -> Path { let segments = path.segments.iter().map(|s| { PathSegment { name: s.name.clone(), - params: PathParameters::AngleBracketed { + args: GenericArgs::AngleBracketed { lifetimes: Vec::new(), types: Vec::new(), bindings: Vec::new(), @@ -4365,7 +4365,7 @@ where F: Fn(DefId) -> Def { def: def_ctor(def_id), segments: hir::HirVec::from_vec(apb.names.iter().map(|s| hir::PathSegment { name: ast::Name::intern(&s), - parameters: None, + args: None, infer_types: false, }).collect()) } diff --git a/src/librustdoc/clean/simplify.rs b/src/librustdoc/clean/simplify.rs index 1dd5746599667..ac1952a4babbf 100644 --- a/src/librustdoc/clean/simplify.rs +++ b/src/librustdoc/clean/simplify.rs @@ -97,7 +97,7 @@ pub fn where_clauses(cx: &DocContext, clauses: Vec) -> Vec { return false } let last = path.segments.last_mut().unwrap(); - match last.params { + match last.args { PP::AngleBracketed { ref mut bindings, .. } => { bindings.push(clean::TypeBinding { name: name.clone(), diff --git a/src/librustdoc/html/format.rs b/src/librustdoc/html/format.rs index de5c0eeffc98c..d2d068e520957 100644 --- a/src/librustdoc/html/format.rs +++ b/src/librustdoc/html/format.rs @@ -369,9 +369,9 @@ impl fmt::Display for clean::PathSegment { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { f.write_str(&self.name)?; if f.alternate() { - write!(f, "{:#}", self.params) + write!(f, "{:#}", self.args) } else { - write!(f, "{}", self.params) + write!(f, "{}", self.args) } } } @@ -447,7 +447,7 @@ fn resolved_path(w: &mut fmt::Formatter, did: DefId, path: &clean::Path, } } if w.alternate() { - write!(w, "{:#}{:#}", HRef::new(did, &last.name), last.params)?; + write!(w, "{:#}{:#}", HRef::new(did, &last.name), last.args)?; } else { let path = if use_absolute { match href(did) { @@ -461,7 +461,7 @@ fn resolved_path(w: &mut fmt::Formatter, did: DefId, path: &clean::Path, } else { format!("{}", HRef::new(did, &last.name)) }; - write!(w, "{}{}", path, last.params)?; + write!(w, "{}{}", path, last.args)?; } Ok(()) } @@ -757,7 +757,7 @@ fn fmt_impl(i: &clean::Impl, clean::ResolvedPath { typarams: None, ref path, is_generic: false, .. } => { let last = path.segments.last().unwrap(); fmt::Display::fmt(&last.name, f)?; - fmt::Display::fmt(&last.params, f)?; + fmt::Display::fmt(&last.args, f)?; } _ => unreachable!(), } diff --git a/src/libsyntax/ast.rs b/src/libsyntax/ast.rs index 7bcaf9bbd5246..7ff00123624f6 100644 --- a/src/libsyntax/ast.rs +++ b/src/libsyntax/ast.rs @@ -135,27 +135,27 @@ pub struct PathSegment { /// `Some` means that parameter list is supplied (`Path`) /// but it can be empty (`Path<>`). /// `P` is used as a size optimization for the common case with no parameters. - pub parameters: Option>, + pub args: Option>, } impl PathSegment { pub fn from_ident(ident: Ident) -> Self { - PathSegment { ident, parameters: None } + PathSegment { ident, args: None } } pub fn crate_root(span: Span) -> Self { PathSegment::from_ident(Ident::new(keywords::CrateRoot.name(), span)) } } -/// Parameters of a path segment. +/// Arguments of a path segment. /// /// E.g. `` as in `Foo` or `(A, B)` as in `Foo(A, B)` #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)] pub enum GenericArgs { /// The `<'a, A,B,C>` in `foo::bar::baz::<'a, A,B,C>` - AngleBracketed(AngleBracketedParameterData), + AngleBracketed(AngleBracketedArgs), /// The `(A,B)` and `C` in `Foo(A,B) -> C` - Parenthesized(ParenthesizedParameterData), + Parenthesized(ParenthesizedArgData), } impl GenericArgs { @@ -168,28 +168,28 @@ impl GenericArgs { } #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)] -pub enum AngleBracketedParam { +pub enum GenericArg { Lifetime(Lifetime), Type(P), } /// A path like `Foo<'a, T>` #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Default)] -pub struct AngleBracketedParameterData { +pub struct AngleBracketedArgs { /// Overall span pub span: Span, - /// The parameters for this path segment. - pub parameters: Vec, + /// The arguments for this path segment. + pub args: Vec, /// Bindings (equality constraints) on associated types, if present. /// /// E.g., `Foo`. pub bindings: Vec, } -impl AngleBracketedParameterData { +impl AngleBracketedArgs { pub fn lifetimes(&self) -> impl DoubleEndedIterator { - self.parameters.iter().filter_map(|p| { - if let AngleBracketedParam::Lifetime(lt) = p { + self.args.iter().filter_map(|p| { + if let GenericArg::Lifetime(lt) = p { Some(lt) } else { None @@ -198,8 +198,8 @@ impl AngleBracketedParameterData { } pub fn types(&self) -> impl DoubleEndedIterator> { - self.parameters.iter().filter_map(|p| { - if let AngleBracketedParam::Type(ty) = p { + self.args.iter().filter_map(|p| { + if let GenericArg::Type(ty) = p { Some(ty) } else { None @@ -208,13 +208,13 @@ impl AngleBracketedParameterData { } } -impl Into>> for AngleBracketedParameterData { +impl Into>> for AngleBracketedArgs { fn into(self) -> Option> { Some(P(GenericArgs::AngleBracketed(self))) } } -impl Into>> for ParenthesizedParameterData { +impl Into>> for ParenthesizedArgData { fn into(self) -> Option> { Some(P(GenericArgs::Parenthesized(self))) } @@ -222,7 +222,7 @@ impl Into>> for ParenthesizedParameterData { /// A path like `Foo(A,B) -> C` #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)] -pub struct ParenthesizedParameterData { +pub struct ParenthesizedArgData { /// Overall span pub span: Span, diff --git a/src/libsyntax/ext/build.rs b/src/libsyntax/ext/build.rs index a59e34580c045..05a345fb2a175 100644 --- a/src/libsyntax/ext/build.rs +++ b/src/libsyntax/ext/build.rs @@ -31,7 +31,7 @@ pub trait AstBuilder { fn path_all(&self, sp: Span, global: bool, idents: Vec, - parameters: Vec, + parameters: Vec, bindings: Vec) -> ast::Path; @@ -42,7 +42,7 @@ pub trait AstBuilder { fn qpath_all(&self, self_type: P, trait_path: ast::Path, ident: ast::Ident, - parameters: Vec, + parameters: Vec, bindings: Vec) -> (ast::QSelf, ast::Path); @@ -314,7 +314,7 @@ impl<'a> AstBuilder for ExtCtxt<'a> { span: Span, global: bool, mut idents: Vec , - parameters: Vec, + args: Vec, bindings: Vec ) -> ast::Path { let last_ident = idents.pop().unwrap(); @@ -323,12 +323,12 @@ impl<'a> AstBuilder for ExtCtxt<'a> { segments.extend(idents.into_iter().map(|ident| { ast::PathSegment::from_ident(ident.with_span_pos(span)) })); - let parameters = if !parameters.is_empty() !bindings.is_empty() { - ast::AngleBracketedParameterData { parameters, bindings, span }.into() + let args = if !args.is_empty() || !bindings.is_empty() { + ast::AngleBracketedArgs { args, bindings, span }.into() } else { None }; - segments.push(ast::PathSegment { ident: last_ident.with_span_pos(span), parameters }); + segments.push(ast::PathSegment { ident: last_ident.with_span_pos(span), args }); let mut path = ast::Path { span, segments }; if global { if let Some(seg) = path.make_root() { @@ -356,16 +356,16 @@ impl<'a> AstBuilder for ExtCtxt<'a> { self_type: P, trait_path: ast::Path, ident: ast::Ident, - parameters: Vec, + args: Vec, bindings: Vec) -> (ast::QSelf, ast::Path) { let mut path = trait_path; - let parameters = if !parameters.is_empty() || !bindings.is_empty() { - ast::AngleBracketedParameterData { parameters, bindings, span: ident.span }.into() + let args = if !args.is_empty() || !bindings.is_empty() { + ast::AngleBracketedArgs { args, bindings, span: ident.span }.into() } else { None }; - path.segments.push(ast::PathSegment { ident, parameters }); + path.segments.push(ast::PathSegment { ident, args }); (ast::QSelf { ty: self_type, @@ -424,7 +424,7 @@ impl<'a> AstBuilder for ExtCtxt<'a> { self.path_all(DUMMY_SP, true, self.std_path(&["option", "Option"]), - vec![ ast::AngleBracketedParam::Type(ty) ], + vec![ ast::GenericArg::Type(ty) ], Vec::new())) } diff --git a/src/libsyntax/fold.rs b/src/libsyntax/fold.rs index decb7e56132f1..dc23ed19d1bee 100644 --- a/src/libsyntax/fold.rs +++ b/src/libsyntax/fold.rs @@ -132,11 +132,11 @@ pub trait Folder : Sized { noop_fold_exprs(es, self) } - fn fold_param(&mut self, p: AngleBracketedParam) -> AngleBracketedParam { + fn fold_param(&mut self, p: GenericArg) -> GenericArg { match p { - AngleBracketedParam::Lifetime(lt) => - AngleBracketedParam::Lifetime(self.fold_lifetime(lt)), - AngleBracketedParam::Type(ty) => AngleBracketedParam::Type(self.fold_ty(ty)), + GenericArg::Lifetime(lt) => + GenericArg::Lifetime(self.fold_lifetime(lt)), + GenericArg::Type(ty) => GenericArg::Type(self.fold_ty(ty)), } } @@ -184,14 +184,14 @@ pub trait Folder : Sized { noop_fold_generic_args(p, self) } - fn fold_angle_bracketed_parameter_data(&mut self, p: AngleBracketedParameterData) - -> AngleBracketedParameterData + fn fold_angle_bracketed_parameter_data(&mut self, p: AngleBracketedArgs) + -> AngleBracketedArgs { noop_fold_angle_bracketed_parameter_data(p, self) } - fn fold_parenthesized_parameter_data(&mut self, p: ParenthesizedParameterData) - -> ParenthesizedParameterData + fn fold_parenthesized_parameter_data(&mut self, p: ParenthesizedArgData) + -> ParenthesizedArgData { noop_fold_parenthesized_parameter_data(p, self) } @@ -441,9 +441,9 @@ pub fn noop_fold_usize(i: usize, _: &mut T) -> usize { pub fn noop_fold_path(Path { segments, span }: Path, fld: &mut T) -> Path { Path { - segments: segments.move_map(|PathSegment {ident, parameters}| PathSegment { + segments: segments.move_map(|PathSegment {ident, args}| PathSegment { ident: fld.fold_ident(ident), - parameters: parameters.map(|ps| ps.map(|ps| fld.fold_generic_args(ps))), + args: args.map(|ps| ps.map(|ps| fld.fold_generic_args(ps))), }), span: fld.new_span(span) } @@ -473,22 +473,22 @@ pub fn noop_fold_generic_args(generic_args: GenericArgs, fld: &mut T) } } -pub fn noop_fold_angle_bracketed_parameter_data(data: AngleBracketedParameterData, +pub fn noop_fold_angle_bracketed_parameter_data(data: AngleBracketedArgs, fld: &mut T) - -> AngleBracketedParameterData + -> AngleBracketedArgs { - let AngleBracketedParameterData { parameters, bindings, span } = data; - AngleBracketedParameterData { parameters: parameters.move_map(|p| fld.fold_param(p)), + let AngleBracketedArgs { args, bindings, span } = data; + AngleBracketedArgs { args: args.move_map(|p| fld.fold_param(p)), bindings: bindings.move_map(|b| fld.fold_ty_binding(b)), span: fld.new_span(span) } } -pub fn noop_fold_parenthesized_parameter_data(data: ParenthesizedParameterData, +pub fn noop_fold_parenthesized_parameter_data(data: ParenthesizedArgData, fld: &mut T) - -> ParenthesizedParameterData + -> ParenthesizedArgData { - let ParenthesizedParameterData { inputs, output, span } = data; - ParenthesizedParameterData { inputs: inputs.move_map(|ty| fld.fold_ty(ty)), + let ParenthesizedArgData { inputs, output, span } = data; + ParenthesizedArgData { inputs: inputs.move_map(|ty| fld.fold_ty(ty)), output: output.map(|ty| fld.fold_ty(ty)), span: fld.new_span(span) } } @@ -1191,7 +1191,7 @@ pub fn noop_fold_expr(Expr {id, node, span, attrs}: Expr, folder: &mu ExprKind::MethodCall( PathSegment { ident: folder.fold_ident(seg.ident), - parameters: seg.parameters.map(|ps| { + args: seg.args.map(|ps| { ps.map(|ps| folder.fold_generic_args(ps)) }), }, diff --git a/src/libsyntax/parse/parser.rs b/src/libsyntax/parse/parser.rs index e54c5445fa2f8..a51b3bc0ae41c 100644 --- a/src/libsyntax/parse/parser.rs +++ b/src/libsyntax/parse/parser.rs @@ -9,7 +9,7 @@ // except according to those terms. use rustc_target::spec::abi::{self, Abi}; -use ast::{AngleBracketedParameterData, ParenthesizedParameterData, AttrStyle, BareFnTy}; +use ast::{AngleBracketedArgs, ParenthesizedArgData, AttrStyle, BareFnTy}; use ast::{RegionTyParamBound, TraitTyParamBound, TraitBoundModifier}; use ast::Unsafety; use ast::{Mod, AnonConst, Arg, Arm, Attribute, BindingMode, TraitItemKind}; @@ -22,7 +22,7 @@ use ast::{Expr, ExprKind, RangeLimits}; use ast::{Field, FnDecl}; use ast::{ForeignItem, ForeignItemKind, FunctionRetTy}; use ast::GenericParam; -use ast::AngleBracketedParam; +use ast::GenericArg; use ast::{Ident, ImplItem, IsAuto, Item, ItemKind}; use ast::{Label, Lifetime, LifetimeDef, Lit, LitKind}; use ast::Local; @@ -1895,7 +1895,7 @@ impl<'a> Parser<'a> { -> PResult<'a, ast::Path> { maybe_whole!(self, NtPath, |path| { if style == PathStyle::Mod && - path.segments.iter().any(|segment| segment.parameters.is_some()) { + path.segments.iter().any(|segment| segment.args.is_some()) { self.diagnostic().span_err(path.span, "unexpected generic arguments in path"); } path @@ -1970,12 +1970,12 @@ impl<'a> Parser<'a> { .span_label(self.prev_span, "try removing `::`").emit(); } - let parameters = if self.eat_lt() { + let args = if self.eat_lt() { // `<'a, T, A = U>` - let (parameters, bindings) = self.parse_generic_args()?; + let (args, bindings) = self.parse_generic_args()?; self.expect_gt()?; let span = lo.to(self.prev_span); - AngleBracketedParameterData { parameters, bindings, span }.into() + AngleBracketedArgs { args, bindings, span }.into() } else { // `(T, U) -> R` self.bump(); // `(` @@ -1991,10 +1991,10 @@ impl<'a> Parser<'a> { None }; let span = lo.to(self.prev_span); - ParenthesizedParameterData { inputs, output, span }.into() + ParenthesizedArgData { inputs, output, span }.into() }; - PathSegment { ident, parameters } + PathSegment { ident, args } } else { // Generic arguments are not found. PathSegment::from_ident(ident) @@ -2544,8 +2544,8 @@ impl<'a> Parser<'a> { } _ => { // Field access `expr.f` - if let Some(parameters) = segment.parameters { - self.span_err(parameters.span(), + if let Some(args) = segment.args { + self.span_err(args.span(), "field expressions may not have generic arguments"); } @@ -4938,15 +4938,15 @@ impl<'a> Parser<'a> { /// Parses (possibly empty) list of lifetime and type arguments and associated type bindings, /// possibly including trailing comma. fn parse_generic_args(&mut self) - -> PResult<'a, (Vec, Vec)> { - let mut parameters = Vec::new(); + -> PResult<'a, (Vec, Vec)> { + let mut args = Vec::new(); let mut bindings = Vec::new(); let mut seen_type = false; let mut seen_binding = false; loop { if self.check_lifetime() && self.look_ahead(1, |t| !t.is_like_plus()) { // Parse lifetime argument. - parameters.push(AngleBracketedParam::Lifetime(self.expect_lifetime())); + args.push(GenericArg::Lifetime(self.expect_lifetime())); if seen_type || seen_binding { self.span_err(self.prev_span, "lifetime parameters must be declared prior to type parameters"); @@ -4971,7 +4971,7 @@ impl<'a> Parser<'a> { self.span_err(ty_param.span, "type parameters must be declared prior to associated type bindings"); } - parameters.push(AngleBracketedParam::Type(ty_param)); + args.push(GenericArg::Type(ty_param)); seen_type = true; } else { break @@ -4981,7 +4981,7 @@ impl<'a> Parser<'a> { break } } - Ok((parameters, bindings)) + Ok((args, bindings)) } /// Parses an optional `where` clause and places it in `generics`. diff --git a/src/libsyntax/print/pprust.rs b/src/libsyntax/print/pprust.rs index 287fe0b636f1c..3b487430c52a5 100644 --- a/src/libsyntax/print/pprust.rs +++ b/src/libsyntax/print/pprust.rs @@ -13,7 +13,7 @@ pub use self::AnnNode::*; use rustc_target::spec::abi::{self, Abi}; use ast::{self, BlockCheckMode, PatKind, RangeEnd, RangeSyntax}; use ast::{SelfKind, RegionTyParamBound, TraitTyParamBound, TraitBoundModifier}; -use ast::{Attribute, MacDelimiter, AngleBracketedParam}; +use ast::{Attribute, MacDelimiter, GenericArg}; use util::parser::{self, AssocOp, Fixity}; use attr; use codemap::{self, CodeMap}; @@ -1017,10 +1017,10 @@ impl<'a> State<'a> { Ok(()) } - pub fn print_param(&mut self, param: &AngleBracketedParam) -> io::Result<()> { + pub fn print_param(&mut self, param: &GenericArg) -> io::Result<()> { match param { - AngleBracketedParam::Lifetime(lt) => self.print_lifetime(lt), - AngleBracketedParam::Type(ty) => self.print_type(ty), + GenericArg::Lifetime(lt) => self.print_lifetime(lt), + GenericArg::Type(ty) => self.print_type(ty), } } @@ -1991,8 +1991,8 @@ impl<'a> State<'a> { self.print_expr_maybe_paren(&args[0], parser::PREC_POSTFIX)?; self.s.word(".")?; self.print_ident(segment.ident)?; - if let Some(ref parameters) = segment.parameters { - self.print_generic_args(parameters, true)?; + if let Some(ref args) = segment.args { + self.print_generic_args(args, true)?; } self.print_call_post(base_args) } @@ -2435,8 +2435,8 @@ impl<'a> State<'a> { if segment.ident.name != keywords::CrateRoot.name() && segment.ident.name != keywords::DollarCrate.name() { self.print_ident(segment.ident)?; - if let Some(ref parameters) = segment.parameters { - self.print_generic_args(parameters, colons_before_params)?; + if let Some(ref args) = segment.args { + self.print_generic_args(args, colons_before_params)?; } } else if segment.ident.name == keywords::DollarCrate.name() { self.print_dollar_crate(segment.ident.span.ctxt())?; @@ -2462,14 +2462,14 @@ impl<'a> State<'a> { self.s.word("::")?; let item_segment = path.segments.last().unwrap(); self.print_ident(item_segment.ident)?; - match item_segment.parameters { - Some(ref parameters) => self.print_generic_args(parameters, colons_before_params), + match item_segment.args { + Some(ref args) => self.print_generic_args(args, colons_before_params), None => Ok(()), } } fn print_generic_args(&mut self, - parameters: &ast::GenericArgs, + args: &ast::GenericArgs, colons_before_params: bool) -> io::Result<()> { @@ -2477,13 +2477,13 @@ impl<'a> State<'a> { self.s.word("::")? } - match *parameters { + match *args { ast::GenericArgs::AngleBracketed(ref data) => { self.s.word("<")?; - self.commasep(Inconsistent, &data.parameters, |s, p| s.print_param(p))?; + self.commasep(Inconsistent, &data.args, |s, p| s.print_param(p))?; - let mut comma = data.parameters.len() != 0; + let mut comma = data.args.len() != 0; for binding in data.bindings.iter() { if comma { diff --git a/src/libsyntax/visit.rs b/src/libsyntax/visit.rs index 6dc61f3058a5c..906f1941cd6a7 100644 --- a/src/libsyntax/visit.rs +++ b/src/libsyntax/visit.rs @@ -131,10 +131,10 @@ pub trait Visitor<'ast>: Sized { fn visit_generic_args(&mut self, path_span: Span, generic_args: &'ast GenericArgs) { walk_generic_args(self, path_span, generic_args) } - fn visit_angle_bracketed_param(&mut self, param: &'ast AngleBracketedParam) { + fn visit_angle_bracketed_param(&mut self, param: &'ast GenericArg) { match param { - AngleBracketedParam::Lifetime(lt) => self.visit_lifetime(lt), - AngleBracketedParam::Type(ty) => self.visit_ty(ty), + GenericArg::Lifetime(lt) => self.visit_lifetime(lt), + GenericArg::Type(ty) => self.visit_ty(ty), } } fn visit_assoc_type_binding(&mut self, type_binding: &'ast TypeBinding) { @@ -381,8 +381,8 @@ pub fn walk_path_segment<'a, V: Visitor<'a>>(visitor: &mut V, path_span: Span, segment: &'a PathSegment) { visitor.visit_ident(segment.ident); - if let Some(ref parameters) = segment.parameters { - visitor.visit_generic_args(path_span, parameters); + if let Some(ref args) = segment.args { + visitor.visit_generic_args(path_span, args); } } @@ -393,7 +393,7 @@ pub fn walk_generic_args<'a, V>(visitor: &mut V, { match *generic_args { GenericArgs::AngleBracketed(ref data) => { - walk_list!(visitor, visit_angle_bracketed_param, &data.parameters); + walk_list!(visitor, visit_angle_bracketed_param, &data.args); walk_list!(visitor, visit_assoc_type_binding, &data.bindings); } GenericArgs::Parenthesized(ref data) => { diff --git a/src/libsyntax_ext/deriving/clone.rs b/src/libsyntax_ext/deriving/clone.rs index 2e0551b32f73c..504c3f8e91349 100644 --- a/src/libsyntax_ext/deriving/clone.rs +++ b/src/libsyntax_ext/deriving/clone.rs @@ -13,7 +13,7 @@ use deriving::generic::*; use deriving::generic::ty::*; use syntax::ast::{self, Expr, Generics, ItemKind, MetaItem, VariantData}; -use syntax::ast::AngleBracketedParam; +use syntax::ast::GenericArg; use syntax::attr; use syntax::ext::base::{Annotatable, ExtCtxt}; use syntax::ext::build::AstBuilder; @@ -124,7 +124,7 @@ fn cs_clone_shallow(name: &str, let span = span.with_ctxt(cx.backtrace()); let assert_path = cx.path_all(span, true, cx.std_path(&["clone", helper_name]), - vec![AngleBracketedParam::Type(ty)], vec![]); + vec![GenericArg::Type(ty)], vec![]); stmts.push(cx.stmt_let_type_only(span, cx.ty_path(assert_path))); } fn process_variant(cx: &mut ExtCtxt, stmts: &mut Vec, variant: &VariantData) { diff --git a/src/libsyntax_ext/deriving/cmp/eq.rs b/src/libsyntax_ext/deriving/cmp/eq.rs index 51ab9975ed986..00ab39032acbd 100644 --- a/src/libsyntax_ext/deriving/cmp/eq.rs +++ b/src/libsyntax_ext/deriving/cmp/eq.rs @@ -12,7 +12,7 @@ use deriving::path_std; use deriving::generic::*; use deriving::generic::ty::*; -use syntax::ast::{self, Expr, MetaItem, AngleBracketedParam}; +use syntax::ast::{self, Expr, MetaItem, GenericArg}; use syntax::ext::base::{Annotatable, ExtCtxt}; use syntax::ext::build::AstBuilder; use syntax::ptr::P; @@ -62,7 +62,7 @@ fn cs_total_eq_assert(cx: &mut ExtCtxt, trait_span: Span, substr: &Substructure) let span = span.with_ctxt(cx.backtrace()); let assert_path = cx.path_all(span, true, cx.std_path(&["cmp", helper_name]), - vec![AngleBracketedParam::Type(ty)], vec![]); + vec![GenericArg::Type(ty)], vec![]); stmts.push(cx.stmt_let_type_only(span, cx.ty_path(assert_path))); } fn process_variant(cx: &mut ExtCtxt, stmts: &mut Vec, variant: &ast::VariantData) { diff --git a/src/libsyntax_ext/deriving/generic/mod.rs b/src/libsyntax_ext/deriving/generic/mod.rs index a7bb7ba025f71..299c53f310114 100644 --- a/src/libsyntax_ext/deriving/generic/mod.rs +++ b/src/libsyntax_ext/deriving/generic/mod.rs @@ -193,7 +193,7 @@ use std::vec; use rustc_target::spec::abi::Abi; use syntax::ast::{self, BinOpKind, EnumDef, Expr, GenericParam, Generics, Ident, PatKind}; -use syntax::ast::{VariantData, AngleBracketedParam}; +use syntax::ast::{VariantData, GenericArg}; use syntax::attr; use syntax::ext::base::{Annotatable, ExtCtxt}; use syntax::ext::build::AstBuilder; @@ -683,9 +683,9 @@ impl<'a> TraitDef<'a> { .collect(); let self_params = self_lifetimes.into_iter() - .map(|lt| AngleBracketedParam::Lifetime(lt)) + .map(|lt| GenericArg::Lifetime(lt)) .chain(self_ty_params.into_iter().map(|ty| - AngleBracketedParam::Type(ty))) + GenericArg::Type(ty))) .collect(); // Create the type of `self`. diff --git a/src/libsyntax_ext/deriving/generic/ty.rs b/src/libsyntax_ext/deriving/generic/ty.rs index d6ee7759ae63e..7e6dd5fad2583 100644 --- a/src/libsyntax_ext/deriving/generic/ty.rs +++ b/src/libsyntax_ext/deriving/generic/ty.rs @@ -15,7 +15,7 @@ pub use self::PtrTy::*; pub use self::Ty::*; use syntax::ast; -use syntax::ast::{Expr, GenericParam, Generics, Ident, SelfKind, AngleBracketedParam}; +use syntax::ast::{Expr, GenericParam, Generics, Ident, SelfKind, GenericArg}; use syntax::ext::base::ExtCtxt; use syntax::ext::build::AstBuilder; use syntax::codemap::{respan, DUMMY_SP}; @@ -89,8 +89,8 @@ impl<'a> Path<'a> { let tys: Vec> = self.params.iter().map(|t| t.to_ty(cx, span, self_ty, self_generics)).collect(); let params = lt.into_iter() - .map(|lt| AngleBracketedParam::Lifetime(lt)) - .chain(tys.into_iter().map(|ty| AngleBracketedParam::Type(ty))) + .map(|lt| GenericArg::Lifetime(lt)) + .chain(tys.into_iter().map(|ty| GenericArg::Type(ty))) .collect(); match self.kind { @@ -206,9 +206,9 @@ impl<'a> Ty<'a> { .collect(); let params = lifetimes.into_iter() - .map(|lt| AngleBracketedParam::Lifetime(lt)) + .map(|lt| GenericArg::Lifetime(lt)) .chain(ty_params.into_iter().map(|ty| - AngleBracketedParam::Type(ty))) + GenericArg::Type(ty))) .collect(); cx.path_all(span, diff --git a/src/libsyntax_ext/env.rs b/src/libsyntax_ext/env.rs index 78721d880fce7..5c3080260ccd5 100644 --- a/src/libsyntax_ext/env.rs +++ b/src/libsyntax_ext/env.rs @@ -13,7 +13,7 @@ // interface. // -use syntax::ast::{self, Ident, AngleBracketedParam}; +use syntax::ast::{self, Ident, GenericArg}; use syntax::ext::base::*; use syntax::ext::base; use syntax::ext::build::AstBuilder; @@ -39,10 +39,10 @@ pub fn expand_option_env<'cx>(cx: &'cx mut ExtCtxt, cx.expr_path(cx.path_all(sp, true, cx.std_path(&["option", "Option", "None"]), - vec![AngleBracketedParam::Type(cx.ty_rptr(sp, + vec![GenericArg::Type(cx.ty_rptr(sp, cx.ty_ident(sp, Ident::from_str("str")), Some(lt), - ast::Mutability::Immutable)], + ast::Mutability::Immutable))], Vec::new())) } Ok(s) => { From f9d0968906aa6bc5ed0f82d74b5504b58afc9d3b Mon Sep 17 00:00:00 2001 From: varkor Date: Wed, 16 May 2018 12:57:45 +0100 Subject: [PATCH 06/41] Make method and variable names more consistent --- src/librustc/hir/lowering.rs | 4 +- src/librustc/hir/mod.rs | 2 +- src/librustc/hir/print.rs | 46 ++++++++--------- src/librustc/middle/resolve_lifetime.rs | 19 +++---- src/librustc/ty/instance.rs | 1 - src/librustc/ty/subst.rs | 4 -- src/librustc_codegen_llvm/base.rs | 1 - src/librustc_driver/pretty.rs | 2 +- src/librustc_mir/monomorphize/mod.rs | 1 - src/librustc_passes/ast_validation.rs | 12 ++--- src/librustc_save_analysis/dump_visitor.rs | 8 +-- src/librustc_save_analysis/lib.rs | 4 +- src/librustc_typeck/astconv.rs | 50 +++++++++++-------- src/librustc_typeck/check/mod.rs | 29 +++++++---- src/librustdoc/clean/mod.rs | 12 ++--- src/libsyntax/ast.rs | 8 +-- src/libsyntax/ext/build.rs | 12 ++--- src/libsyntax/fold.rs | 44 ++++++++-------- src/libsyntax/print/pprust.rs | 14 +++--- src/libsyntax/visit.rs | 6 +-- src/test/ui/error-codes/E0110.stderr | 2 +- .../collections.stderr | 4 +- .../construct_with_other_type.stderr | 6 +-- ...ssociated_type_undeclared_lifetimes.stderr | 6 +-- .../iterable.stderr | 12 ++--- .../parameter_number_and_kind.stderr | 24 ++++----- .../streaming_iterator.rs | 2 +- .../streaming_iterator.stderr | 10 ++-- 28 files changed, 182 insertions(+), 163 deletions(-) diff --git a/src/librustc/hir/lowering.rs b/src/librustc/hir/lowering.rs index 831a689a34997..d00792be4eb56 100644 --- a/src/librustc/hir/lowering.rs +++ b/src/librustc/hir/lowering.rs @@ -1726,7 +1726,7 @@ impl<'a> LoweringContext<'a> { hir::PathSegment::new( self.lower_ident(segment.ident), generic_args, - infer_types + infer_types, ) } @@ -1738,7 +1738,7 @@ impl<'a> LoweringContext<'a> { ) -> (hir::GenericArgs, bool) { let &AngleBracketedArgs { ref args, ref bindings, .. } = data; (hir::GenericArgs { - args: args.iter().map(|p| self.lower_generic_arg(p, itctx)).collect(), + args: args.iter().map(|a| self.lower_generic_arg(a, itctx)).collect(), bindings: bindings.iter().map(|b| self.lower_ty_binding(b, itctx)).collect(), parenthesized: false, }, diff --git a/src/librustc/hir/mod.rs b/src/librustc/hir/mod.rs index 729ac17ae0991..d4785e40b1f8a 100644 --- a/src/librustc/hir/mod.rs +++ b/src/librustc/hir/mod.rs @@ -360,7 +360,7 @@ impl PathSegment { // FIXME: hack required because you can't create a static // GenericArgs, so you can't just return a &GenericArgs. - pub fn with_args(&self, f: F) -> R + pub fn with_generic_args(&self, f: F) -> R where F: FnOnce(&GenericArgs) -> R { let dummy = GenericArgs::none(); diff --git a/src/librustc/hir/print.rs b/src/librustc/hir/print.rs index c12d258b6c7c9..5420be64ca43a 100644 --- a/src/librustc/hir/print.rs +++ b/src/librustc/hir/print.rs @@ -1269,11 +1269,11 @@ impl<'a> State<'a> { self.s.word(".")?; self.print_name(segment.name)?; - segment.with_args(|args| { - if !args.args.is_empty() || - !args.bindings.is_empty() + segment.with_generic_args(|generic_args| { + if !generic_args.args.is_empty() || + !generic_args.bindings.is_empty() { - self.print_generic_args(&args, segment.infer_types, true) + self.print_generic_args(&generic_args, segment.infer_types, true) } else { Ok(()) } @@ -1641,10 +1641,10 @@ impl<'a> State<'a> { if segment.name != keywords::CrateRoot.name() && segment.name != keywords::DollarCrate.name() { self.print_name(segment.name)?; - segment.with_args(|parameters| { - self.print_generic_args(parameters, - segment.infer_types, - colons_before_params) + segment.with_generic_args(|generic_args| { + self.print_generic_args(generic_args, + segment.infer_types, + colons_before_params) })?; } } @@ -1673,10 +1673,10 @@ impl<'a> State<'a> { if segment.name != keywords::CrateRoot.name() && segment.name != keywords::DollarCrate.name() { self.print_name(segment.name)?; - segment.with_args(|parameters| { - self.print_generic_args(parameters, - segment.infer_types, - colons_before_params) + segment.with_generic_args(|generic_args| { + self.print_generic_args(generic_args, + segment.infer_types, + colons_before_params) })?; } } @@ -1685,10 +1685,10 @@ impl<'a> State<'a> { self.s.word("::")?; let item_segment = path.segments.last().unwrap(); self.print_name(item_segment.name)?; - item_segment.with_args(|parameters| { - self.print_generic_args(parameters, - item_segment.infer_types, - colons_before_params) + item_segment.with_generic_args(|generic_args| { + self.print_generic_args(generic_args, + item_segment.infer_types, + colons_before_params) }) } hir::QPath::TypeRelative(ref qself, ref item_segment) => { @@ -1697,10 +1697,10 @@ impl<'a> State<'a> { self.s.word(">")?; self.s.word("::")?; self.print_name(item_segment.name)?; - item_segment.with_args(|parameters| { - self.print_generic_args(parameters, - item_segment.infer_types, - colons_before_params) + item_segment.with_generic_args(|generic_args| { + self.print_generic_args(generic_args, + item_segment.infer_types, + colons_before_params) }) } } @@ -1734,11 +1734,11 @@ impl<'a> State<'a> { let elide_lifetimes = generic_args.lifetimes().all(|lt| lt.is_elided()); if !elide_lifetimes { start_or_comma(self)?; - self.commasep(Inconsistent, &generic_args.args, |s, p| { - match p { + self.commasep(Inconsistent, &generic_args.args, |s, generic_arg| { + match generic_arg { GenericArg::Lifetime(lt) => s.print_lifetime(lt), GenericArg::Type(ty) => s.print_type(ty), - } + } })?; } else if generic_args.types().count() != 0 { start_or_comma(self)?; diff --git a/src/librustc/middle/resolve_lifetime.rs b/src/librustc/middle/resolve_lifetime.rs index 39dfa77ea677e..8f1cd9bb30ecd 100644 --- a/src/librustc/middle/resolve_lifetime.rs +++ b/src/librustc/middle/resolve_lifetime.rs @@ -1601,20 +1601,21 @@ impl<'a, 'tcx> LifetimeContext<'a, 'tcx> { &mut self, def: Def, depth: usize, - args: &'tcx hir::GenericArgs, + generic_args: &'tcx hir::GenericArgs, ) { - if args.parenthesized { + if generic_args.parenthesized { let was_in_fn_syntax = self.is_in_fn_syntax; self.is_in_fn_syntax = true; - self.visit_fn_like_elision(args.inputs(), Some(&args.bindings[0].ty)); + self.visit_fn_like_elision(generic_args.inputs(), + Some(&generic_args.bindings[0].ty)); self.is_in_fn_syntax = was_in_fn_syntax; return; } - if args.lifetimes().all(|l| l.is_elided()) { - self.resolve_elided_lifetimes(args.lifetimes().collect(), true); + if generic_args.lifetimes().all(|l| l.is_elided()) { + self.resolve_elided_lifetimes(generic_args.lifetimes().collect(), true); } else { - for l in args.lifetimes() { + for l in generic_args.lifetimes() { self.visit_lifetime(l); } } @@ -1686,13 +1687,13 @@ impl<'a, 'tcx> LifetimeContext<'a, 'tcx> { } else { Some(Region::Static) }, - Set1::One(r) => r.subst(args.lifetimes(), map), + Set1::One(r) => r.subst(generic_args.lifetimes(), map), Set1::Many => None, }) .collect() }); - for (i, ty) in args.types().enumerate() { + for (i, ty) in generic_args.types().enumerate() { if let Some(<) = object_lifetime_defaults.get(i) { let scope = Scope::ObjectLifetimeDefault { lifetime: lt, @@ -1704,7 +1705,7 @@ impl<'a, 'tcx> LifetimeContext<'a, 'tcx> { } } - for b in &args.bindings { + for b in &generic_args.bindings { self.visit_assoc_type_binding(b); } } diff --git a/src/librustc/ty/instance.rs b/src/librustc/ty/instance.rs index 8b1c31deb1377..66edbeff749f7 100644 --- a/src/librustc/ty/instance.rs +++ b/src/librustc/ty/instance.rs @@ -10,7 +10,6 @@ use hir::def_id::DefId; use ty::{self, Ty, TypeFoldable, Substs, TyCtxt}; -use ty::subst::Kind; use traits; use rustc_target::spec::abi::Abi; use util::ppaux; diff --git a/src/librustc/ty/subst.rs b/src/librustc/ty/subst.rs index 932f082c87cb0..2e3c6df9754df 100644 --- a/src/librustc/ty/subst.rs +++ b/src/librustc/ty/subst.rs @@ -105,10 +105,6 @@ impl<'tcx> From> for Kind<'tcx> { } } -impl<'tcx> Into> for ty::Region<'tcx> {} - -impl<'tcx> Into> for Ty<'tcx> {} - impl<'tcx> Kind<'tcx> { #[inline] pub fn unpack(self) -> UnpackedKind<'tcx> { diff --git a/src/librustc_codegen_llvm/base.rs b/src/librustc_codegen_llvm/base.rs index 7c8ba63c15eb9..322924535d1f7 100644 --- a/src/librustc_codegen_llvm/base.rs +++ b/src/librustc_codegen_llvm/base.rs @@ -40,7 +40,6 @@ use rustc::middle::weak_lang_items; use rustc::mir::mono::{Linkage, Visibility, Stats}; use rustc::middle::cstore::{EncodedMetadata}; use rustc::ty::{self, Ty, TyCtxt}; -use rustc::ty::subst::Kind; use rustc::ty::layout::{self, Align, TyLayout, LayoutOf}; use rustc::ty::query::Providers; use rustc::dep_graph::{DepNode, DepConstructor}; diff --git a/src/librustc_driver/pretty.rs b/src/librustc_driver/pretty.rs index 7468f01de705f..0ea2832bf80d9 100644 --- a/src/librustc_driver/pretty.rs +++ b/src/librustc_driver/pretty.rs @@ -677,7 +677,7 @@ impl<'a> ReplaceBodyWithLoop<'a> { ast::TyKind::Paren(ref subty) => involves_impl_trait(subty), ast::TyKind::Tup(ref tys) => any_involves_impl_trait(tys.iter()), ast::TyKind::Path(_, ref path) => path.segments.iter().any(|seg| { - match seg.args.as_ref().map(|p| &**p) { + match seg.args.as_ref().map(|generic_arg| &**generic_arg) { None => false, Some(&ast::GenericArgs::AngleBracketed(ref data)) => any_involves_impl_trait(data.types().into_iter()) || diff --git a/src/librustc_mir/monomorphize/mod.rs b/src/librustc_mir/monomorphize/mod.rs index 3afe9991c68d0..bf544e5120cd8 100644 --- a/src/librustc_mir/monomorphize/mod.rs +++ b/src/librustc_mir/monomorphize/mod.rs @@ -13,7 +13,6 @@ use rustc::middle::lang_items::DropInPlaceFnLangItem; use rustc::traits; use rustc::ty::adjustment::CustomCoerceUnsized; use rustc::ty::{self, Ty, TyCtxt}; -use rustc::ty::subst::Kind; pub use rustc::ty::Instance; pub use self::item::{MonoItem, MonoItemExt}; diff --git a/src/librustc_passes/ast_validation.rs b/src/librustc_passes/ast_validation.rs index 63c8bd3d1f77a..211a45bc3c5d6 100644 --- a/src/librustc_passes/ast_validation.rs +++ b/src/librustc_passes/ast_validation.rs @@ -523,21 +523,21 @@ impl<'a> Visitor<'a> for NestedImplTraitVisitor<'a> { } fn visit_generic_args(&mut self, _: Span, generic_args: &'a GenericArgs) { match *generic_args { - GenericArgs::AngleBracketed(ref params) => { - for type_ in params.types() { + GenericArgs::AngleBracketed(ref generic_args) => { + for type_ in generic_args.types() { self.visit_ty(type_); } - for type_binding in ¶ms.bindings { + for type_binding in &generic_args.bindings { // Type bindings such as `Item=impl Debug` in `Iterator` // are allowed to contain nested `impl Trait`. self.with_impl_trait(None, |this| visit::walk_ty(this, &type_binding.ty)); } } - GenericArgs::Parenthesized(ref params) => { - for type_ in ¶ms.inputs { + GenericArgs::Parenthesized(ref generic_args) => { + for type_ in &generic_args.inputs { self.visit_ty(type_); } - if let Some(ref type_) = params.output { + if let Some(ref type_) = generic_args.output { // `-> Foo` syntax is essentially an associated type binding, // so it is also allowed to contain nested `impl Trait`. self.with_impl_trait(None, |this| visit::walk_ty(this, type_)); diff --git a/src/librustc_save_analysis/dump_visitor.rs b/src/librustc_save_analysis/dump_visitor.rs index fa055d246f30a..055d58f0b1f5f 100644 --- a/src/librustc_save_analysis/dump_visitor.rs +++ b/src/librustc_save_analysis/dump_visitor.rs @@ -820,8 +820,8 @@ impl<'l, 'tcx: 'l, 'll, O: DumpOutput + 'll> DumpVisitor<'l, 'tcx, 'll, O> { // Type arguments for seg in &path.segments { - if let Some(ref args) = seg.args { - match **args { + if let Some(ref generic_args) = seg.args { + match **generic_args { ast::GenericArgs::AngleBracketed(ref data) => for t in data.types() { self.visit_ty(t); }, @@ -905,8 +905,8 @@ impl<'l, 'tcx: 'l, 'll, O: DumpOutput + 'll> DumpVisitor<'l, 'tcx, 'll, O> { } // Explicit types in the turbo-fish. - if let Some(ref args) = seg.args { - if let ast::GenericArgs::AngleBracketed(ref data) = **args { + if let Some(ref generic_args) = seg.args { + if let ast::GenericArgs::AngleBracketed(ref data) = **generic_args { for t in data.types() { self.visit_ty(t); } diff --git a/src/librustc_save_analysis/lib.rs b/src/librustc_save_analysis/lib.rs index 4f03698d9b17c..8a44f271055e2 100644 --- a/src/librustc_save_analysis/lib.rs +++ b/src/librustc_save_analysis/lib.rs @@ -692,8 +692,8 @@ impl<'l, 'tcx: 'l> SaveContext<'l, 'tcx> { if path.segments.len() != 1 { return false; } - if let Some(ref args) = path.segments[0].args { - if let ast::GenericArgs::Parenthesized(_) = **args { + if let Some(ref generic_args) = path.segments[0].args { + if let ast::GenericArgs::Parenthesized(_) = **generic_args { return true; } } diff --git a/src/librustc_typeck/astconv.rs b/src/librustc_typeck/astconv.rs index be4c423e959bb..e4b3b4e60413d 100644 --- a/src/librustc_typeck/astconv.rs +++ b/src/librustc_typeck/astconv.rs @@ -177,11 +177,11 @@ impl<'o, 'gcx: 'tcx, 'tcx> AstConv<'gcx, 'tcx>+'o { { let (substs, assoc_bindings) = - item_segment.with_args(|args| { + item_segment.with_generic_args(|generic_args| { self.create_substs_for_ast_path( span, def_id, - args, + generic_args, item_segment.infer_types, None) }); @@ -199,7 +199,7 @@ impl<'o, 'gcx: 'tcx, 'tcx> AstConv<'gcx, 'tcx>+'o { fn create_substs_for_ast_path(&self, span: Span, def_id: DefId, - args: &hir::GenericArgs, + generic_args: &hir::GenericArgs, infer_types: bool, self_ty: Option>) -> (&'tcx Substs<'tcx>, Vec>) @@ -207,15 +207,15 @@ impl<'o, 'gcx: 'tcx, 'tcx> AstConv<'gcx, 'tcx>+'o { let tcx = self.tcx(); debug!("create_substs_for_ast_path(def_id={:?}, self_ty={:?}, \ - args={:?})", - def_id, self_ty, args); + generic_args={:?})", + def_id, self_ty, generic_args); // If the type is parameterized by this region, then replace this // region with the current anon region binding (in other words, // whatever & would get replaced with). let decl_generics = tcx.generics_of(def_id); - let ty_provided = args.types().count(); - let lt_provided = args.lifetimes().count(); + let ty_provided = generic_args.types().count(); + let lt_provided = generic_args.lifetimes().count(); let mut lt_accepted = 0; let mut ty_params = ParamRange { required: 0, accepted: 0 }; @@ -269,7 +269,7 @@ impl<'o, 'gcx: 'tcx, 'tcx> AstConv<'gcx, 'tcx>+'o { match param.kind { GenericParamDefKind::Lifetime => { let i = param.index as usize - own_self; - if let Some(lifetime) = args.lifetimes().nth(i) { + if let Some(lifetime) = generic_args.lifetimes().nth(i) { self.ast_region_to_region(lifetime, Some(param)).into() } else { tcx.types.re_static.into() @@ -286,7 +286,7 @@ impl<'o, 'gcx: 'tcx, 'tcx> AstConv<'gcx, 'tcx>+'o { let i = i - (lt_accepted + own_self); if i < ty_provided { // A provided type parameter. - self.ast_ty_to_ty(&args.types().nth(i).unwrap()).into() + self.ast_ty_to_ty(&generic_args.types().nth(i).unwrap()).into() } else if infer_types { // No type parameters were provided, we can infer all. if !default_needs_object_self(param) { @@ -330,7 +330,7 @@ impl<'o, 'gcx: 'tcx, 'tcx> AstConv<'gcx, 'tcx>+'o { } }); - let assoc_bindings = args.bindings.iter().map(|binding| { + let assoc_bindings = generic_args.bindings.iter().map(|binding| { ConvertedBinding { item_name: binding.name, ty: self.ast_ty_to_ty(&binding.ty), @@ -451,7 +451,8 @@ impl<'o, 'gcx: 'tcx, 'tcx> AstConv<'gcx, 'tcx>+'o { let trait_def = self.tcx().trait_def(trait_def_id); if !self.tcx().features().unboxed_closures && - trait_segment.with_args(|p| p.parenthesized) != trait_def.paren_sugar { + trait_segment.with_generic_args(|generic_args| generic_args.parenthesized) + != trait_def.paren_sugar { // For now, require that parenthetical notation be used only with `Fn()` etc. let msg = if trait_def.paren_sugar { "the precise format of `Fn`-family traits' type parameters is subject to change. \ @@ -463,10 +464,10 @@ impl<'o, 'gcx: 'tcx, 'tcx> AstConv<'gcx, 'tcx>+'o { span, GateIssue::Language, msg); } - trait_segment.with_args(|parameters| { + trait_segment.with_generic_args(|generic_args| { self.create_substs_for_ast_path(span, trait_def_id, - parameters, + generic_args, trait_segment.infer_types, Some(self_ty)) }) @@ -970,27 +971,36 @@ impl<'o, 'gcx: 'tcx, 'tcx> AstConv<'gcx, 'tcx>+'o { pub fn prohibit_type_params(&self, segments: &[hir::PathSegment]) { for segment in segments { - segment.with_args(|params| { - for p in ¶ms.args { - let (mut span_err, span, kind) = match p { + segment.with_generic_args(|generic_args| { + let mut err_for_lifetime = false; + let mut err_for_type = false; + for arg in &generic_args.args { + let (mut span_err, span, kind) = match arg { hir::GenericArg::Lifetime(lt) => { + if err_for_lifetime { continue } + err_for_lifetime = true; (struct_span_err!(self.tcx().sess, lt.span, E0110, - "lifetime parameters are not allowed on this type"), + "lifetime parameters are not allowed on \ + this type"), lt.span, "lifetime") } hir::GenericArg::Type(ty) => { + if err_for_type { continue } + err_for_type = true; (struct_span_err!(self.tcx().sess, ty.span, E0109, - "type parameters are not allowed on this type"), + "type parameters are not allowed on this type"), ty.span, "type") } }; span_err.span_label(span, format!("{} parameter not allowed", kind)) .emit(); - break; + if err_for_lifetime && err_for_type { + break; + } } - for binding in ¶ms.bindings { + for binding in &generic_args.bindings { self.prohibit_projection(binding.span); break; } diff --git a/src/librustc_typeck/check/mod.rs b/src/librustc_typeck/check/mod.rs index 5af3d2fc42c9e..c0779235e8939 100644 --- a/src/librustc_typeck/check/mod.rs +++ b/src/librustc_typeck/check/mod.rs @@ -4834,7 +4834,7 @@ impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> { match param.kind { GenericParamDefKind::Lifetime => { let lifetimes = segment.map_or(vec![], |(s, _)| { - s.args.as_ref().map_or(vec![], |p| p.lifetimes().collect()) + s.args.as_ref().map_or(vec![], |arg| arg.lifetimes().collect()) }); if let Some(lifetime) = lifetimes.get(i) { @@ -4845,7 +4845,9 @@ impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> { } GenericParamDefKind::Type {..} => { let (types, infer_types) = segment.map_or((vec![], true), |(s, _)| { - (s.args.as_ref().map_or(vec![], |p| p.types().collect()), s.infer_types) + (s.args.as_ref().map_or(vec![], |arg| { + arg.types().collect() + }), s.infer_types) }); // Skip over the lifetimes in the same segment. @@ -4956,16 +4958,23 @@ impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> { /// Report errors if the provided parameters are too few or too many. fn check_generic_arg_count(&self, - span: Span, - segment: &mut Option<(&hir::PathSegment, &ty::Generics)>, - is_method_call: bool, - supress_mismatch_error: bool) { + span: Span, + segment: &mut Option<(&hir::PathSegment, &ty::Generics)>, + is_method_call: bool, + supress_mismatch_error: bool) { let (lifetimes, types, infer_types, bindings) = segment.map_or( (vec![], vec![], true, &[][..]), - |(s, _)| s.args.as_ref().map_or( - (vec![], vec![], s.infer_types, &[][..]), - |p| (p.lifetimes().collect(), p.types().collect(), - s.infer_types, &p.bindings[..]))); + |(s, _)| { + s.args.as_ref().map_or( + (vec![], vec![], s.infer_types, &[][..]), + |arg| { + (arg.lifetimes().collect(), + arg.types().collect(), + s.infer_types, + &arg.bindings[..]) + } + ) + }); let infer_lifetimes = lifetimes.len() == 0; let count_lifetime_params = |n| { diff --git a/src/librustdoc/clean/mod.rs b/src/librustdoc/clean/mod.rs index 793a8a7f11035..0d44c583cffd4 100644 --- a/src/librustdoc/clean/mod.rs +++ b/src/librustdoc/clean/mod.rs @@ -2851,7 +2851,7 @@ impl Clean for hir::Ty { let provided_params = &path.segments.last().unwrap(); let mut ty_substs = FxHashMap(); let mut lt_substs = FxHashMap(); - provided_params.with_args(|provided_params| { + provided_params.with_generic_args(|generic_args| { let mut indices = GenericParamCount { lifetimes: 0, types: 0 @@ -2859,7 +2859,7 @@ impl Clean for hir::Ty { for param in generics.params.iter() { match param { hir::GenericParam::Lifetime(lt_param) => { - if let Some(lt) = provided_params.lifetimes() + if let Some(lt) = generic_args.lifetimes() .nth(indices.lifetimes).cloned() { if !lt.is_elided() { let lt_def_id = @@ -2872,7 +2872,7 @@ impl Clean for hir::Ty { hir::GenericParam::Type(ty_param) => { let ty_param_def = Def::TyParam(cx.tcx.hir.local_def_id(ty_param.id)); - if let Some(ty) = provided_params.types() + if let Some(ty) = generic_args.types() .nth(indices.types).cloned() { ty_substs.insert(ty_param_def, ty.into_inner().clean(cx)); } else if let Some(default) = ty_param.default.clone() { @@ -3497,9 +3497,9 @@ impl Clean for hir::GenericArgs { lifetimes: if self.lifetimes().all(|lt| lt.is_elided()) { vec![] } else { - self.lifetimes().map(|lp| lp.clean(cx)).collect() + self.lifetimes().map(|lt| lt.clean(cx)).collect() }, - types: self.types().map(|tp| tp.clean(cx)).collect(), + types: self.types().map(|ty| ty.clean(cx)).collect(), bindings: self.bindings.clean(cx), } } @@ -3516,7 +3516,7 @@ impl Clean for hir::PathSegment { fn clean(&self, cx: &DocContext) -> PathSegment { PathSegment { name: self.name.clean(cx), - args: self.with_args(|args| args.clean(cx)) + args: self.with_generic_args(|generic_args| generic_args.clean(cx)) } } } diff --git a/src/libsyntax/ast.rs b/src/libsyntax/ast.rs index 7ff00123624f6..5ae520050e593 100644 --- a/src/libsyntax/ast.rs +++ b/src/libsyntax/ast.rs @@ -188,8 +188,8 @@ pub struct AngleBracketedArgs { impl AngleBracketedArgs { pub fn lifetimes(&self) -> impl DoubleEndedIterator { - self.args.iter().filter_map(|p| { - if let GenericArg::Lifetime(lt) = p { + self.args.iter().filter_map(|arg| { + if let GenericArg::Lifetime(lt) = arg { Some(lt) } else { None @@ -198,8 +198,8 @@ impl AngleBracketedArgs { } pub fn types(&self) -> impl DoubleEndedIterator> { - self.args.iter().filter_map(|p| { - if let GenericArg::Type(ty) = p { + self.args.iter().filter_map(|arg| { + if let GenericArg::Type(ty) = arg { Some(ty) } else { None diff --git a/src/libsyntax/ext/build.rs b/src/libsyntax/ext/build.rs index 05a345fb2a175..c544adb5c1c86 100644 --- a/src/libsyntax/ext/build.rs +++ b/src/libsyntax/ext/build.rs @@ -31,7 +31,7 @@ pub trait AstBuilder { fn path_all(&self, sp: Span, global: bool, idents: Vec, - parameters: Vec, + args: Vec, bindings: Vec) -> ast::Path; @@ -42,7 +42,7 @@ pub trait AstBuilder { fn qpath_all(&self, self_type: P, trait_path: ast::Path, ident: ast::Ident, - parameters: Vec, + args: Vec, bindings: Vec) -> (ast::QSelf, ast::Path); @@ -302,13 +302,13 @@ pub trait AstBuilder { impl<'a> AstBuilder for ExtCtxt<'a> { fn path(&self, span: Span, strs: Vec ) -> ast::Path { - self.path_all(span, false, strs, Vec::new(), Vec::new()) + self.path_all(span, false, strs, vec![], vec![]) } fn path_ident(&self, span: Span, id: ast::Ident) -> ast::Path { self.path(span, vec![id]) } fn path_global(&self, span: Span, strs: Vec ) -> ast::Path { - self.path_all(span, true, strs, Vec::new(), Vec::new()) + self.path_all(span, true, strs, vec![], vec![]) } fn path_all(&self, span: Span, @@ -318,7 +318,7 @@ impl<'a> AstBuilder for ExtCtxt<'a> { bindings: Vec ) -> ast::Path { let last_ident = idents.pop().unwrap(); - let mut segments: Vec = Vec::new(); + let mut segments: Vec = vec![]; segments.extend(idents.into_iter().map(|ident| { ast::PathSegment::from_ident(ident.with_span_pos(span)) @@ -424,7 +424,7 @@ impl<'a> AstBuilder for ExtCtxt<'a> { self.path_all(DUMMY_SP, true, self.std_path(&["option", "Option"]), - vec![ ast::GenericArg::Type(ty) ], + vec![ast::GenericArg::Type(ty)], Vec::new())) } diff --git a/src/libsyntax/fold.rs b/src/libsyntax/fold.rs index dc23ed19d1bee..f74fe1feb40c1 100644 --- a/src/libsyntax/fold.rs +++ b/src/libsyntax/fold.rs @@ -132,10 +132,9 @@ pub trait Folder : Sized { noop_fold_exprs(es, self) } - fn fold_param(&mut self, p: GenericArg) -> GenericArg { - match p { - GenericArg::Lifetime(lt) => - GenericArg::Lifetime(self.fold_lifetime(lt)), + fn fold_generic_arg(&mut self, arg: GenericArg) -> GenericArg { + match arg { + GenericArg::Lifetime(lt) => GenericArg::Lifetime(self.fold_lifetime(lt)), GenericArg::Type(ty) => GenericArg::Type(self.fold_ty(ty)), } } @@ -441,9 +440,9 @@ pub fn noop_fold_usize(i: usize, _: &mut T) -> usize { pub fn noop_fold_path(Path { segments, span }: Path, fld: &mut T) -> Path { Path { - segments: segments.move_map(|PathSegment {ident, args}| PathSegment { + segments: segments.move_map(|PathSegment { ident, args }| PathSegment { ident: fld.fold_ident(ident), - args: args.map(|ps| ps.map(|ps| fld.fold_generic_args(ps))), + args: args.map(|args| args.map(|args| fld.fold_generic_args(args))), }), span: fld.new_span(span) } @@ -462,14 +461,15 @@ pub fn noop_fold_qpath(qself: Option, (qself, fld.fold_path(path)) } -pub fn noop_fold_generic_args(generic_args: GenericArgs, fld: &mut T) - -> GenericArgs +pub fn noop_fold_generic_args(generic_args: GenericArgs, fld: &mut T) -> GenericArgs { match generic_args { - GenericArgs::AngleBracketed(data) => - GenericArgs::AngleBracketed(fld.fold_angle_bracketed_parameter_data(data)), - GenericArgs::Parenthesized(data) => - GenericArgs::Parenthesized(fld.fold_parenthesized_parameter_data(data)), + GenericArgs::AngleBracketed(data) => { + GenericArgs::AngleBracketed(fld.fold_angle_bracketed_parameter_data(data)) + } + GenericArgs::Parenthesized(data) => { + GenericArgs::Parenthesized(fld.fold_parenthesized_parameter_data(data)) + } } } @@ -478,9 +478,11 @@ pub fn noop_fold_angle_bracketed_parameter_data(data: AngleBracketedA -> AngleBracketedArgs { let AngleBracketedArgs { args, bindings, span } = data; - AngleBracketedArgs { args: args.move_map(|p| fld.fold_param(p)), - bindings: bindings.move_map(|b| fld.fold_ty_binding(b)), - span: fld.new_span(span) } + AngleBracketedArgs { + args: args.move_map(|arg| fld.fold_generic_arg(arg)), + bindings: bindings.move_map(|b| fld.fold_ty_binding(b)), + span: fld.new_span(span) + } } pub fn noop_fold_parenthesized_parameter_data(data: ParenthesizedArgData, @@ -488,9 +490,11 @@ pub fn noop_fold_parenthesized_parameter_data(data: ParenthesizedArgD -> ParenthesizedArgData { let ParenthesizedArgData { inputs, output, span } = data; - ParenthesizedArgData { inputs: inputs.move_map(|ty| fld.fold_ty(ty)), - output: output.map(|ty| fld.fold_ty(ty)), - span: fld.new_span(span) } + ParenthesizedArgData { + inputs: inputs.move_map(|ty| fld.fold_ty(ty)), + output: output.map(|ty| fld.fold_ty(ty)), + span: fld.new_span(span) + } } pub fn noop_fold_local(l: P, fld: &mut T) -> P { @@ -1191,8 +1195,8 @@ pub fn noop_fold_expr(Expr {id, node, span, attrs}: Expr, folder: &mu ExprKind::MethodCall( PathSegment { ident: folder.fold_ident(seg.ident), - args: seg.args.map(|ps| { - ps.map(|ps| folder.fold_generic_args(ps)) + args: seg.args.map(|args| { + args.map(|args| folder.fold_generic_args(args)) }), }, folder.fold_exprs(args)) diff --git a/src/libsyntax/print/pprust.rs b/src/libsyntax/print/pprust.rs index 3b487430c52a5..3e0e533bc08a8 100644 --- a/src/libsyntax/print/pprust.rs +++ b/src/libsyntax/print/pprust.rs @@ -1017,8 +1017,8 @@ impl<'a> State<'a> { Ok(()) } - pub fn print_param(&mut self, param: &GenericArg) -> io::Result<()> { - match param { + pub fn print_generic_arg(&mut self, generic_arg: &GenericArg) -> io::Result<()> { + match generic_arg { GenericArg::Lifetime(lt) => self.print_lifetime(lt), GenericArg::Type(ty) => self.print_type(ty), } @@ -2469,9 +2469,9 @@ impl<'a> State<'a> { } fn print_generic_args(&mut self, - args: &ast::GenericArgs, - colons_before_params: bool) - -> io::Result<()> + args: &ast::GenericArgs, + colons_before_params: bool) + -> io::Result<()> { if colons_before_params { self.s.word("::")? @@ -2481,7 +2481,9 @@ impl<'a> State<'a> { ast::GenericArgs::AngleBracketed(ref data) => { self.s.word("<")?; - self.commasep(Inconsistent, &data.args, |s, p| s.print_param(p))?; + self.commasep(Inconsistent, &data.args, |s, generic_arg| { + s.print_generic_arg(generic_arg) + })?; let mut comma = data.args.len() != 0; diff --git a/src/libsyntax/visit.rs b/src/libsyntax/visit.rs index 906f1941cd6a7..5ac33701baf29 100644 --- a/src/libsyntax/visit.rs +++ b/src/libsyntax/visit.rs @@ -131,8 +131,8 @@ pub trait Visitor<'ast>: Sized { fn visit_generic_args(&mut self, path_span: Span, generic_args: &'ast GenericArgs) { walk_generic_args(self, path_span, generic_args) } - fn visit_angle_bracketed_param(&mut self, param: &'ast GenericArg) { - match param { + fn visit_generic_arg(&mut self, generic_arg: &'ast GenericArg) { + match generic_arg { GenericArg::Lifetime(lt) => self.visit_lifetime(lt), GenericArg::Type(ty) => self.visit_ty(ty), } @@ -393,7 +393,7 @@ pub fn walk_generic_args<'a, V>(visitor: &mut V, { match *generic_args { GenericArgs::AngleBracketed(ref data) => { - walk_list!(visitor, visit_angle_bracketed_param, &data.args); + walk_list!(visitor, visit_generic_arg, &data.args); walk_list!(visitor, visit_assoc_type_binding, &data.bindings); } GenericArgs::Parenthesized(ref data) => { diff --git a/src/test/ui/error-codes/E0110.stderr b/src/test/ui/error-codes/E0110.stderr index 10e06ee6d025a..7f5b78684fbc1 100644 --- a/src/test/ui/error-codes/E0110.stderr +++ b/src/test/ui/error-codes/E0110.stderr @@ -2,7 +2,7 @@ error[E0110]: lifetime parameters are not allowed on this type --> $DIR/E0110.rs:11:14 | LL | type X = u32<'static>; //~ ERROR E0110 - | ^^^^^^^ lifetime parameter not allowed on this type + | ^^^^^^^ lifetime parameter not allowed error: aborting due to previous error diff --git a/src/test/ui/rfc1598-generic-associated-types/collections.stderr b/src/test/ui/rfc1598-generic-associated-types/collections.stderr index ed96570583f4f..8c31ab2ca88e4 100644 --- a/src/test/ui/rfc1598-generic-associated-types/collections.stderr +++ b/src/test/ui/rfc1598-generic-associated-types/collections.stderr @@ -20,13 +20,13 @@ error[E0110]: lifetime parameters are not allowed on this type --> $DIR/collections.rs:33:50 | LL | fn iterate<'iter>(&'iter self) -> Self::Iter<'iter>; - | ^^^^^ lifetime parameter not allowed on this type + | ^^^^^ lifetime parameter not allowed error[E0110]: lifetime parameters are not allowed on this type --> $DIR/collections.rs:59:50 | LL | fn iterate<'iter>(&'iter self) -> Self::Iter<'iter> { - | ^^^^^ lifetime parameter not allowed on this type + | ^^^^^ lifetime parameter not allowed error: aborting due to 5 previous errors 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 764a0db2478a8..1746122eb49f4 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 @@ -2,19 +2,19 @@ error[E0110]: lifetime parameters are not allowed on this type --> $DIR/construct_with_other_type.rs:26:46 | LL | type Baa<'a>: Deref as Foo>::Bar<'a, 'static>>; - | ^^ lifetime parameter not allowed on this type + | ^^ lifetime parameter not allowed error[E0110]: lifetime parameters are not allowed on this type --> $DIR/construct_with_other_type.rs:26:63 | LL | type Baa<'a>: Deref as Foo>::Bar<'a, 'static>>; - | ^^ lifetime parameter not allowed on this type + | ^^ lifetime parameter not allowed error[E0110]: lifetime parameters are not allowed on this type --> $DIR/construct_with_other_type.rs:34:40 | LL | type Baa<'a> = &'a ::Bar<'a, 'static>; - | ^^ lifetime parameter not allowed on this type + | ^^ lifetime parameter not allowed error: aborting due to 3 previous errors diff --git a/src/test/ui/rfc1598-generic-associated-types/generic_associated_type_undeclared_lifetimes.stderr b/src/test/ui/rfc1598-generic-associated-types/generic_associated_type_undeclared_lifetimes.stderr index 64e82c0d1097f..d48c21477b310 100644 --- a/src/test/ui/rfc1598-generic-associated-types/generic_associated_type_undeclared_lifetimes.stderr +++ b/src/test/ui/rfc1598-generic-associated-types/generic_associated_type_undeclared_lifetimes.stderr @@ -14,19 +14,19 @@ error[E0110]: lifetime parameters are not allowed on this type --> $DIR/generic_associated_type_undeclared_lifetimes.rs:20:47 | LL | type Iter<'a>: Iterator> - | ^^ lifetime parameter not allowed on this type + | ^^ lifetime parameter not allowed error[E0110]: lifetime parameters are not allowed on this type --> $DIR/generic_associated_type_undeclared_lifetimes.rs:22:37 | LL | + Deref>; - | ^^ lifetime parameter not allowed on this type + | ^^ lifetime parameter not allowed error[E0110]: lifetime parameters are not allowed on this type --> $DIR/generic_associated_type_undeclared_lifetimes.rs:26:41 | LL | fn iter<'a>(&'a self) -> Self::Iter<'undeclared>; - | ^^^^^^^^^^^ lifetime parameter not allowed on this type + | ^^^^^^^^^^^ lifetime parameter not allowed error: aborting due to 5 previous errors diff --git a/src/test/ui/rfc1598-generic-associated-types/iterable.stderr b/src/test/ui/rfc1598-generic-associated-types/iterable.stderr index 0e251300e451f..737a29ec2c8be 100644 --- a/src/test/ui/rfc1598-generic-associated-types/iterable.stderr +++ b/src/test/ui/rfc1598-generic-associated-types/iterable.stderr @@ -2,37 +2,37 @@ error[E0110]: lifetime parameters are not allowed on this type --> $DIR/iterable.rs:20:47 | LL | type Iter<'a>: Iterator>; - | ^^ lifetime parameter not allowed on this type + | ^^ lifetime parameter not allowed error[E0110]: lifetime parameters are not allowed on this type --> $DIR/iterable.rs:49:53 | LL | fn make_iter<'a, I: Iterable>(it: &'a I) -> I::Iter<'a> { - | ^^ lifetime parameter not allowed on this type + | ^^ lifetime parameter not allowed error[E0110]: lifetime parameters are not allowed on this type --> $DIR/iterable.rs:54:60 | LL | fn get_first<'a, I: Iterable>(it: &'a I) -> Option> { - | ^^ lifetime parameter not allowed on this type + | ^^ lifetime parameter not allowed error[E0110]: lifetime parameters are not allowed on this type --> $DIR/iterable.rs:23:41 | LL | fn iter<'a>(&'a self) -> Self::Iter<'a>; - | ^^ lifetime parameter not allowed on this type + | ^^ lifetime parameter not allowed error[E0110]: lifetime parameters are not allowed on this type --> $DIR/iterable.rs:32:41 | LL | fn iter<'a>(&'a self) -> Self::Iter<'a> { - | ^^ lifetime parameter not allowed on this type + | ^^ lifetime parameter not allowed error[E0110]: lifetime parameters are not allowed on this type --> $DIR/iterable.rs:43:41 | LL | fn iter<'a>(&'a self) -> Self::Iter<'a> { - | ^^ lifetime parameter not allowed on this type + | ^^ lifetime parameter not allowed error: aborting due to 6 previous errors diff --git a/src/test/ui/rfc1598-generic-associated-types/parameter_number_and_kind.stderr b/src/test/ui/rfc1598-generic-associated-types/parameter_number_and_kind.stderr index df83fdaad5bfa..c8d37a51fa96b 100644 --- a/src/test/ui/rfc1598-generic-associated-types/parameter_number_and_kind.stderr +++ b/src/test/ui/rfc1598-generic-associated-types/parameter_number_and_kind.stderr @@ -1,3 +1,9 @@ +error[E0110]: lifetime parameters are not allowed on this type + --> $DIR/parameter_number_and_kind.rs:26:27 + | +LL | type FOk = Self::E<'static, T>; + | ^^^^^^^ lifetime parameter not allowed + error[E0109]: type parameters are not allowed on this type --> $DIR/parameter_number_and_kind.rs:26:36 | @@ -5,16 +11,16 @@ LL | type FOk = Self::E<'static, T>; | ^ type parameter not allowed error[E0110]: lifetime parameters are not allowed on this type - --> $DIR/parameter_number_and_kind.rs:26:27 + --> $DIR/parameter_number_and_kind.rs:29:26 | -LL | type FOk = Self::E<'static, T>; - | ^^^^^^^ lifetime parameter not allowed on this type +LL | type FErr1 = Self::E<'static, 'static>; // Error + | ^^^^^^^ lifetime parameter not allowed error[E0110]: lifetime parameters are not allowed on this type - --> $DIR/parameter_number_and_kind.rs:29:26 + --> $DIR/parameter_number_and_kind.rs:31:29 | -LL | type FErr1 = Self::E<'static, 'static>; // Error - | ^^^^^^^ lifetime parameter not allowed on this type +LL | type FErr2 = Self::E<'static, T, u32>; // Error + | ^^^^^^^ lifetime parameter not allowed error[E0109]: type parameters are not allowed on this type --> $DIR/parameter_number_and_kind.rs:31:38 @@ -22,12 +28,6 @@ error[E0109]: type parameters are not allowed on this type LL | type FErr2 = Self::E<'static, T, u32>; // Error | ^ type parameter not allowed -error[E0110]: lifetime parameters are not allowed on this type - --> $DIR/parameter_number_and_kind.rs:31:29 - | -LL | type FErr2 = Self::E<'static, T, u32>; // Error - | ^^^^^^^ lifetime parameter not allowed on this type - error: aborting due to 5 previous errors Some errors occurred: E0109, E0110. diff --git a/src/test/ui/rfc1598-generic-associated-types/streaming_iterator.rs b/src/test/ui/rfc1598-generic-associated-types/streaming_iterator.rs index 3f69de3de834f..522ddb5dc135e 100644 --- a/src/test/ui/rfc1598-generic-associated-types/streaming_iterator.rs +++ b/src/test/ui/rfc1598-generic-associated-types/streaming_iterator.rs @@ -10,7 +10,7 @@ #![feature(generic_associated_types)] -//FIXME(#44265): "lifetime parameter not allowed" errors will be addressed in a +//FIXME(#44265): "lifetime parameter not allowed on this type" errors will be addressed in a // follow-up PR use std::fmt::Display; diff --git a/src/test/ui/rfc1598-generic-associated-types/streaming_iterator.stderr b/src/test/ui/rfc1598-generic-associated-types/streaming_iterator.stderr index 607a4b8d57996..12e206cbd476a 100644 --- a/src/test/ui/rfc1598-generic-associated-types/streaming_iterator.stderr +++ b/src/test/ui/rfc1598-generic-associated-types/streaming_iterator.stderr @@ -2,31 +2,31 @@ error[E0110]: lifetime parameters are not allowed on this type --> $DIR/streaming_iterator.rs:27:41 | LL | bar: ::Item<'static>, - | ^^^^^^^ lifetime parameter not allowed on this type + | ^^^^^^^ lifetime parameter not allowed error[E0110]: lifetime parameters are not allowed on this type --> $DIR/streaming_iterator.rs:35:64 | LL | fn foo(iter: T) where T: StreamingIterator, for<'a> T::Item<'a>: Display { /* ... */ } - | ^^ lifetime parameter not allowed on this type + | ^^ lifetime parameter not allowed error[E0110]: lifetime parameters are not allowed on this type --> $DIR/streaming_iterator.rs:21:48 | LL | fn next<'a>(&'a self) -> Option>; - | ^^ lifetime parameter not allowed on this type + | ^^ lifetime parameter not allowed error[E0110]: lifetime parameters are not allowed on this type --> $DIR/streaming_iterator.rs:47:37 | LL | type Item<'a> = (usize, I::Item<'a>); - | ^^ lifetime parameter not allowed on this type + | ^^ lifetime parameter not allowed error[E0110]: lifetime parameters are not allowed on this type --> $DIR/streaming_iterator.rs:49:48 | LL | fn next<'a>(&'a self) -> Option> { - | ^^ lifetime parameter not allowed on this type + | ^^ lifetime parameter not allowed error: aborting due to 5 previous errors From d643946550fa349729184a4f70abc01e21ceddc0 Mon Sep 17 00:00:00 2001 From: varkor Date: Fri, 25 May 2018 18:41:03 +0100 Subject: [PATCH 07/41] Rename ast::GenericParam and ast::GenericArg It's so confusing to have everything having the same name, at least while refactoring. --- src/librustc/hir/lowering.rs | 22 ++++++++--------- src/librustc/hir/map/def_collector.rs | 6 ++--- src/librustc/lint/context.rs | 2 +- src/librustc/lint/mod.rs | 2 +- src/librustc_passes/ast_validation.rs | 18 +++++++------- src/librustc_resolve/lib.rs | 10 ++++---- src/librustc_save_analysis/dump_visitor.rs | 4 ++-- src/librustc_save_analysis/lib.rs | 4 ++-- src/librustc_save_analysis/sig.rs | 6 ++--- src/libsyntax/ast.rs | 28 +++++++++++----------- src/libsyntax/ext/build.rs | 10 ++++---- src/libsyntax/fold.rs | 22 ++++++++--------- src/libsyntax/parse/parser.rs | 23 +++++++++--------- src/libsyntax/print/pprust.rs | 20 ++++++++-------- src/libsyntax/util/node_count.rs | 2 +- src/libsyntax/visit.rs | 14 +++++------ src/libsyntax_ext/deriving/clone.rs | 4 ++-- src/libsyntax_ext/deriving/cmp/eq.rs | 4 ++-- src/libsyntax_ext/deriving/generic/mod.rs | 20 ++++++++-------- src/libsyntax_ext/deriving/generic/ty.rs | 20 ++++++++-------- src/libsyntax_ext/deriving/mod.rs | 2 +- src/libsyntax_ext/env.rs | 4 ++-- 22 files changed, 123 insertions(+), 124 deletions(-) diff --git a/src/librustc/hir/lowering.rs b/src/librustc/hir/lowering.rs index d00792be4eb56..4660352b28bfc 100644 --- a/src/librustc/hir/lowering.rs +++ b/src/librustc/hir/lowering.rs @@ -810,7 +810,7 @@ impl<'a> LoweringContext<'a> { { let (in_band_defs, (mut lowered_generics, res)) = self.with_in_scope_lifetime_defs( generics.params.iter().filter_map(|p| match p { - GenericParam::Lifetime(ld) => Some(ld), + GenericParamAST::Lifetime(ld) => Some(ld), _ => None, }), |this| { @@ -1040,14 +1040,14 @@ impl<'a> LoweringContext<'a> { } fn lower_generic_arg(&mut self, - p: &ast::GenericArg, + p: &ast::GenericArgAST, itctx: ImplTraitContext) -> hir::GenericArg { match p { - ast::GenericArg::Lifetime(lt) => { + ast::GenericArgAST::Lifetime(lt) => { GenericArg::Lifetime(self.lower_lifetime(<)) } - ast::GenericArg::Type(ty) => { + ast::GenericArgAST::Type(ty) => { GenericArg::Type(self.lower_ty(&ty, itctx)) } } @@ -1069,7 +1069,7 @@ impl<'a> LoweringContext<'a> { } TyKind::BareFn(ref f) => self.with_in_scope_lifetime_defs( f.generic_params.iter().filter_map(|p| match p { - GenericParam::Lifetime(ld) => Some(ld), + GenericParamAST::Lifetime(ld) => Some(ld), _ => None, }), |this| { @@ -1980,17 +1980,17 @@ impl<'a> LoweringContext<'a> { fn lower_generic_params( &mut self, - params: &Vec, + params: &Vec, add_bounds: &NodeMap>, itctx: ImplTraitContext, ) -> hir::HirVec { params .iter() .map(|param| match *param { - GenericParam::Lifetime(ref lifetime_def) => { + GenericParamAST::Lifetime(ref lifetime_def) => { hir::GenericParam::Lifetime(self.lower_lifetime_def(lifetime_def)) } - GenericParam::Type(ref ty_param) => hir::GenericParam::Type(self.lower_ty_param( + GenericParamAST::Type(ref ty_param) => hir::GenericParam::Type(self.lower_ty_param( ty_param, add_bounds.get(&ty_param.id).map_or(&[][..], |x| &x), itctx, @@ -2030,7 +2030,7 @@ impl<'a> LoweringContext<'a> { self.resolver.definitions().as_local_node_id(def_id) { for param in &g.params { - if let GenericParam::Type(ref ty_param) = *param { + if let GenericParamAST::Type(ref ty_param) = *param { if node_id == ty_param.id { add_bounds .entry(ty_param.id) @@ -2078,7 +2078,7 @@ impl<'a> LoweringContext<'a> { }) => { self.with_in_scope_lifetime_defs( bound_generic_params.iter().filter_map(|p| match p { - GenericParam::Lifetime(ld) => Some(ld), + GenericParamAST::Lifetime(ld) => Some(ld), _ => None, }), |this| { @@ -2397,7 +2397,7 @@ impl<'a> LoweringContext<'a> { let new_impl_items = self.with_in_scope_lifetime_defs( ast_generics.params.iter().filter_map(|p| match p { - GenericParam::Lifetime(ld) => Some(ld), + GenericParamAST::Lifetime(ld) => Some(ld), _ => None, }), |this| { diff --git a/src/librustc/hir/map/def_collector.rs b/src/librustc/hir/map/def_collector.rs index 48d959b4f8e41..7ab6e17ac35ea 100644 --- a/src/librustc/hir/map/def_collector.rs +++ b/src/librustc/hir/map/def_collector.rs @@ -170,9 +170,9 @@ impl<'a> visit::Visitor<'a> for DefCollector<'a> { } } - fn visit_generic_param(&mut self, param: &'a GenericParam) { + fn visit_generic_param(&mut self, param: &'a GenericParamAST) { match *param { - GenericParam::Lifetime(ref lifetime_def) => { + GenericParamAST::Lifetime(ref lifetime_def) => { self.create_def( lifetime_def.lifetime.id, DefPathData::LifetimeDef(lifetime_def.lifetime.ident.name.as_interned_str()), @@ -180,7 +180,7 @@ impl<'a> visit::Visitor<'a> for DefCollector<'a> { lifetime_def.lifetime.ident.span ); } - GenericParam::Type(ref ty_param) => { + GenericParamAST::Type(ref ty_param) => { self.create_def( ty_param.id, DefPathData::TypeParam(ty_param.ident.name.as_interned_str()), diff --git a/src/librustc/lint/context.rs b/src/librustc/lint/context.rs index 824930a7eb000..7236eebdb6f2b 100644 --- a/src/librustc/lint/context.rs +++ b/src/librustc/lint/context.rs @@ -990,7 +990,7 @@ impl<'a> ast_visit::Visitor<'a> for EarlyContext<'a> { run_lints!(self, check_expr_post, early_passes, e); } - fn visit_generic_param(&mut self, param: &'a ast::GenericParam) { + fn visit_generic_param(&mut self, param: &'a ast::GenericParamAST) { run_lints!(self, check_generic_param, early_passes, param); ast_visit::walk_generic_param(self, param); } diff --git a/src/librustc/lint/mod.rs b/src/librustc/lint/mod.rs index 9338e235c534d..3d31a651b2f6d 100644 --- a/src/librustc/lint/mod.rs +++ b/src/librustc/lint/mod.rs @@ -254,7 +254,7 @@ pub trait EarlyLintPass: LintPass { fn check_expr(&mut self, _: &EarlyContext, _: &ast::Expr) { } fn check_expr_post(&mut self, _: &EarlyContext, _: &ast::Expr) { } fn check_ty(&mut self, _: &EarlyContext, _: &ast::Ty) { } - fn check_generic_param(&mut self, _: &EarlyContext, _: &ast::GenericParam) { } + fn check_generic_param(&mut self, _: &EarlyContext, _: &ast::GenericParamAST) { } fn check_generics(&mut self, _: &EarlyContext, _: &ast::Generics) { } fn check_where_predicate(&mut self, _: &EarlyContext, _: &ast::WherePredicate) { } fn check_poly_trait_ref(&mut self, _: &EarlyContext, _: &ast::PolyTraitRef, diff --git a/src/librustc_passes/ast_validation.rs b/src/librustc_passes/ast_validation.rs index 211a45bc3c5d6..b50407c82d19c 100644 --- a/src/librustc_passes/ast_validation.rs +++ b/src/librustc_passes/ast_validation.rs @@ -138,12 +138,12 @@ impl<'a> AstValidator<'a> { } } - fn check_late_bound_lifetime_defs(&self, params: &Vec) { + fn check_late_bound_lifetime_defs(&self, params: &Vec) { // Check: Only lifetime parameters let non_lifetime_param_spans : Vec<_> = params.iter() .filter_map(|param| match *param { - GenericParam::Lifetime(_) => None, - GenericParam::Type(ref t) => Some(t.ident.span), + GenericParamAST::Lifetime(_) => None, + GenericParamAST::Type(ref t) => Some(t.ident.span), }).collect(); if !non_lifetime_param_spans.is_empty() { self.err_handler().span_err(non_lifetime_param_spans, @@ -153,14 +153,14 @@ impl<'a> AstValidator<'a> { // Check: No bounds on lifetime parameters for param in params.iter() { match *param { - GenericParam::Lifetime(ref l) => { + GenericParamAST::Lifetime(ref l) => { if !l.bounds.is_empty() { let spans: Vec<_> = l.bounds.iter().map(|b| b.ident.span).collect(); self.err_handler().span_err(spans, "lifetime bounds cannot be used in this context"); } } - GenericParam::Type(_) => {} + GenericParamAST::Type(_) => {} } } } @@ -335,7 +335,7 @@ impl<'a> Visitor<'a> for AstValidator<'a> { } ItemKind::TraitAlias(Generics { ref params, .. }, ..) => { for param in params { - if let GenericParam::Type(TyParam { + if let GenericParamAST::Type(TyParam { ident, ref bounds, ref default, @@ -414,17 +414,17 @@ impl<'a> Visitor<'a> for AstValidator<'a> { let mut seen_default = None; for param in &g.params { match (param, seen_non_lifetime_param) { - (&GenericParam::Lifetime(ref ld), true) => { + (&GenericParamAST::Lifetime(ref ld), true) => { self.err_handler() .span_err(ld.lifetime.ident.span, "lifetime parameters must be leading"); }, - (&GenericParam::Lifetime(_), false) => {} + (&GenericParamAST::Lifetime(_), false) => {} _ => { seen_non_lifetime_param = true; } } - if let GenericParam::Type(ref ty_param @ TyParam { default: Some(_), .. }) = *param { + if let GenericParamAST::Type(ref ty_param @ TyParam { default: Some(_), .. }) = *param { seen_default = Some(ty_param.ident.span); } else if let Some(span) = seen_default { self.err_handler() diff --git a/src/librustc_resolve/lib.rs b/src/librustc_resolve/lib.rs index a2b2096ccaa47..d70a7e2b8278b 100644 --- a/src/librustc_resolve/lib.rs +++ b/src/librustc_resolve/lib.rs @@ -56,7 +56,7 @@ use syntax::util::lev_distance::find_best_match_for_name; use syntax::visit::{self, FnKind, Visitor}; use syntax::attr; use syntax::ast::{Arm, BindingMode, Block, Crate, Expr, ExprKind}; -use syntax::ast::{FnDecl, ForeignItem, ForeignItemKind, GenericParam, Generics}; +use syntax::ast::{FnDecl, ForeignItem, ForeignItemKind, GenericParamAST, Generics}; use syntax::ast::{Item, ItemKind, ImplItem, ImplItemKind}; use syntax::ast::{Label, Local, Mutability, Pat, PatKind, Path}; use syntax::ast::{QSelf, TraitItemKind, TraitRef, Ty, TyKind}; @@ -798,14 +798,14 @@ impl<'a, 'tcx> Visitor<'tcx> for Resolver<'a> { // them one by one as they are processed and become available. let mut default_ban_rib = Rib::new(ForwardTyParamBanRibKind); default_ban_rib.bindings.extend(generics.params.iter() - .filter_map(|p| if let GenericParam::Type(ref tp) = *p { Some(tp) } else { None }) + .filter_map(|p| if let GenericParamAST::Type(ref tp) = *p { Some(tp) } else { None }) .skip_while(|p| p.default.is_none()) .map(|p| (Ident::with_empty_ctxt(p.ident.name), Def::Err))); for param in &generics.params { match *param { - GenericParam::Lifetime(_) => self.visit_generic_param(param), - GenericParam::Type(ref ty_param) => { + GenericParamAST::Lifetime(_) => self.visit_generic_param(param), + GenericParamAST::Type(ref ty_param) => { for bound in &ty_param.bounds { self.visit_ty_param_bound(bound); } @@ -2198,7 +2198,7 @@ impl<'a> Resolver<'a> { let mut function_type_rib = Rib::new(rib_kind); let mut seen_bindings = FxHashMap(); for param in &generics.params { - if let GenericParam::Type(ref type_parameter) = *param { + if let GenericParamAST::Type(ref type_parameter) = *param { let ident = type_parameter.ident.modern(); debug!("with_type_parameter_rib: {}", type_parameter.id); diff --git a/src/librustc_save_analysis/dump_visitor.rs b/src/librustc_save_analysis/dump_visitor.rs index 055d58f0b1f5f..303406dac7661 100644 --- a/src/librustc_save_analysis/dump_visitor.rs +++ b/src/librustc_save_analysis/dump_visitor.rs @@ -370,7 +370,7 @@ impl<'l, 'tcx: 'l, 'll, O: DumpOutput + 'll> DumpVisitor<'l, 'tcx, 'll, O> { id: NodeId, ) { for param in &generics.params { - if let ast::GenericParam::Type(ref ty_param) = *param { + if let ast::GenericParamAST::Type(ref ty_param) = *param { let param_ss = ty_param.ident.span; let name = escape(self.span.snippet(param_ss)); // Append $id to name to make sure each one is unique @@ -1479,7 +1479,7 @@ impl<'l, 'tcx: 'l, 'll, O: DumpOutput + 'll> Visitor<'l> for DumpVisitor<'l, 'tc fn visit_generics(&mut self, generics: &'l ast::Generics) { for param in &generics.params { - if let ast::GenericParam::Type(ref ty_param) = *param { + if let ast::GenericParamAST::Type(ref ty_param) = *param { for bound in ty_param.bounds.iter() { if let ast::TraitTyParamBound(ref trait_ref, _) = *bound { self.process_path(trait_ref.trait_ref.ref_id, &trait_ref.trait_ref.path) diff --git a/src/librustc_save_analysis/lib.rs b/src/librustc_save_analysis/lib.rs index 8a44f271055e2..a634e979363bb 100644 --- a/src/librustc_save_analysis/lib.rs +++ b/src/librustc_save_analysis/lib.rs @@ -935,8 +935,8 @@ fn make_signature(decl: &ast::FnDecl, generics: &ast::Generics) -> String { .params .iter() .map(|param| match *param { - ast::GenericParam::Lifetime(ref l) => l.lifetime.ident.name.to_string(), - ast::GenericParam::Type(ref t) => t.ident.to_string(), + ast::GenericParamAST::Lifetime(ref l) => l.lifetime.ident.name.to_string(), + ast::GenericParamAST::Type(ref t) => t.ident.to_string(), }) .collect::>() .join(", ")); diff --git a/src/librustc_save_analysis/sig.rs b/src/librustc_save_analysis/sig.rs index e3545e8f1a9b8..f5384683506ef 100644 --- a/src/librustc_save_analysis/sig.rs +++ b/src/librustc_save_analysis/sig.rs @@ -224,7 +224,7 @@ impl Sig for ast::Ty { text.push_str(&f.generic_params .iter() .filter_map(|p| match *p { - ast::GenericParam::Lifetime(ref l) => { + ast::GenericParamAST::Lifetime(ref l) => { Some(l.lifetime.ident.to_string()) } _ => None, @@ -618,7 +618,7 @@ impl Sig for ast::Generics { let mut defs = vec![]; for param in &self.params { match *param { - ast::GenericParam::Lifetime(ref l) => { + ast::GenericParamAST::Lifetime(ref l) => { let mut l_text = l.lifetime.ident.to_string(); defs.push(SigElement { id: id_from_node_id(l.lifetime.id, scx), @@ -639,7 +639,7 @@ impl Sig for ast::Generics { text.push_str(&l_text); text.push(','); } - ast::GenericParam::Type(ref t) => { + ast::GenericParamAST::Type(ref t) => { let mut t_text = t.ident.to_string(); defs.push(SigElement { id: id_from_node_id(t.id, scx), diff --git a/src/libsyntax/ast.rs b/src/libsyntax/ast.rs index 5ae520050e593..17df8dd7027e4 100644 --- a/src/libsyntax/ast.rs +++ b/src/libsyntax/ast.rs @@ -168,7 +168,7 @@ impl GenericArgs { } #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)] -pub enum GenericArg { +pub enum GenericArgAST { Lifetime(Lifetime), Type(P), } @@ -179,7 +179,7 @@ pub struct AngleBracketedArgs { /// Overall span pub span: Span, /// The arguments for this path segment. - pub args: Vec, + pub args: Vec, /// Bindings (equality constraints) on associated types, if present. /// /// E.g., `Foo`. @@ -189,7 +189,7 @@ pub struct AngleBracketedArgs { impl AngleBracketedArgs { pub fn lifetimes(&self) -> impl DoubleEndedIterator { self.args.iter().filter_map(|arg| { - if let GenericArg::Lifetime(lt) = arg { + if let GenericArgAST::Lifetime(lt) = arg { Some(lt) } else { None @@ -199,7 +199,7 @@ impl AngleBracketedArgs { pub fn types(&self) -> impl DoubleEndedIterator> { self.args.iter().filter_map(|arg| { - if let GenericArg::Type(ty) = arg { + if let GenericArgAST::Type(ty) = arg { Some(ty) } else { None @@ -338,22 +338,22 @@ pub struct TyParam { } #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)] -pub enum GenericParam { +pub enum GenericParamAST { Lifetime(LifetimeDef), Type(TyParam), } -impl GenericParam { +impl GenericParamAST { pub fn is_lifetime_param(&self) -> bool { match *self { - GenericParam::Lifetime(_) => true, + GenericParamAST::Lifetime(_) => true, _ => false, } } pub fn is_type_param(&self) -> bool { match *self { - GenericParam::Type(_) => true, + GenericParamAST::Type(_) => true, _ => false, } } @@ -363,7 +363,7 @@ impl GenericParam { /// a function, enum, trait, etc. #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)] pub struct Generics { - pub params: Vec, + pub params: Vec, pub where_clause: WhereClause, pub span: Span, } @@ -383,7 +383,7 @@ impl Generics { pub fn span_for_name(&self, name: &str) -> Option { for param in &self.params { - if let GenericParam::Type(ref t) = *param { + if let GenericParamAST::Type(ref t) = *param { if t.ident.name == name { return Some(t.ident.span); } @@ -444,7 +444,7 @@ impl WherePredicate { pub struct WhereBoundPredicate { pub span: Span, /// Any generics from a `for` binding - pub bound_generic_params: Vec, + pub bound_generic_params: Vec, /// The type being bounded pub bounded_ty: P, /// Trait and lifetime bounds (`Clone+Send+'static`) @@ -1576,7 +1576,7 @@ impl fmt::Debug for Ty { pub struct BareFnTy { pub unsafety: Unsafety, pub abi: Abi, - pub generic_params: Vec, + pub generic_params: Vec, pub decl: P } @@ -1955,7 +1955,7 @@ pub struct TraitRef { #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)] pub struct PolyTraitRef { /// The `'a` in `<'a> Foo<&'a T>` - pub bound_generic_params: Vec, + pub bound_generic_params: Vec, /// The `Foo<&'a T>` in `<'a> Foo<&'a T>` pub trait_ref: TraitRef, @@ -1964,7 +1964,7 @@ pub struct PolyTraitRef { } impl PolyTraitRef { - pub fn new(generic_params: Vec, path: Path, span: Span) -> Self { + pub fn new(generic_params: Vec, path: Path, span: Span) -> Self { PolyTraitRef { bound_generic_params: generic_params, trait_ref: TraitRef { path: path, ref_id: DUMMY_NODE_ID }, diff --git a/src/libsyntax/ext/build.rs b/src/libsyntax/ext/build.rs index c544adb5c1c86..1c74a2bd5be0d 100644 --- a/src/libsyntax/ext/build.rs +++ b/src/libsyntax/ext/build.rs @@ -31,7 +31,7 @@ pub trait AstBuilder { fn path_all(&self, sp: Span, global: bool, idents: Vec, - args: Vec, + args: Vec, bindings: Vec) -> ast::Path; @@ -42,7 +42,7 @@ pub trait AstBuilder { fn qpath_all(&self, self_type: P, trait_path: ast::Path, ident: ast::Ident, - args: Vec, + args: Vec, bindings: Vec) -> (ast::QSelf, ast::Path); @@ -314,7 +314,7 @@ impl<'a> AstBuilder for ExtCtxt<'a> { span: Span, global: bool, mut idents: Vec , - args: Vec, + args: Vec, bindings: Vec ) -> ast::Path { let last_ident = idents.pop().unwrap(); @@ -356,7 +356,7 @@ impl<'a> AstBuilder for ExtCtxt<'a> { self_type: P, trait_path: ast::Path, ident: ast::Ident, - args: Vec, + args: Vec, bindings: Vec) -> (ast::QSelf, ast::Path) { let mut path = trait_path; @@ -424,7 +424,7 @@ impl<'a> AstBuilder for ExtCtxt<'a> { self.path_all(DUMMY_SP, true, self.std_path(&["option", "Option"]), - vec![ast::GenericArg::Type(ty)], + vec![ast::GenericArgAST::Type(ty)], Vec::new())) } diff --git a/src/libsyntax/fold.rs b/src/libsyntax/fold.rs index f74fe1feb40c1..1e09c7b2206c6 100644 --- a/src/libsyntax/fold.rs +++ b/src/libsyntax/fold.rs @@ -132,10 +132,10 @@ pub trait Folder : Sized { noop_fold_exprs(es, self) } - fn fold_generic_arg(&mut self, arg: GenericArg) -> GenericArg { + fn fold_generic_arg(&mut self, arg: GenericArgAST) -> GenericArgAST { match arg { - GenericArg::Lifetime(lt) => GenericArg::Lifetime(self.fold_lifetime(lt)), - GenericArg::Type(ty) => GenericArg::Type(self.fold_ty(ty)), + GenericArgAST::Lifetime(lt) => GenericArgAST::Lifetime(self.fold_lifetime(lt)), + GenericArgAST::Type(ty) => GenericArgAST::Type(self.fold_ty(ty)), } } @@ -244,11 +244,11 @@ pub trait Folder : Sized { noop_fold_ty_param(tp, self) } - fn fold_generic_param(&mut self, param: GenericParam) -> GenericParam { + fn fold_generic_param(&mut self, param: GenericParamAST) -> GenericParamAST { noop_fold_generic_param(param, self) } - fn fold_generic_params(&mut self, params: Vec) -> Vec { + fn fold_generic_params(&mut self, params: Vec) -> Vec { noop_fold_generic_params(params, self) } @@ -702,11 +702,11 @@ pub fn noop_fold_ty_param(tp: TyParam, fld: &mut T) -> TyParam { } } -pub fn noop_fold_generic_param(param: GenericParam, fld: &mut T) -> GenericParam { +pub fn noop_fold_generic_param(param: GenericParamAST, fld: &mut T) -> GenericParamAST { match param { - GenericParam::Lifetime(l) => { + GenericParamAST::Lifetime(l) => { let attrs: Vec<_> = l.attrs.into(); - GenericParam::Lifetime(LifetimeDef { + GenericParamAST::Lifetime(LifetimeDef { attrs: attrs.into_iter() .flat_map(|x| fld.fold_attribute(x).into_iter()) .collect::>() @@ -718,14 +718,14 @@ pub fn noop_fold_generic_param(param: GenericParam, fld: &mut T) -> G bounds: l.bounds.move_map(|l| noop_fold_lifetime(l, fld)), }) } - GenericParam::Type(t) => GenericParam::Type(fld.fold_ty_param(t)), + GenericParamAST::Type(t) => GenericParamAST::Type(fld.fold_ty_param(t)), } } pub fn noop_fold_generic_params( - params: Vec, + params: Vec, fld: &mut T -) -> Vec { +) -> Vec { params.move_map(|p| fld.fold_generic_param(p)) } diff --git a/src/libsyntax/parse/parser.rs b/src/libsyntax/parse/parser.rs index a51b3bc0ae41c..be4a4b8b11fba 100644 --- a/src/libsyntax/parse/parser.rs +++ b/src/libsyntax/parse/parser.rs @@ -21,8 +21,8 @@ use ast::EnumDef; use ast::{Expr, ExprKind, RangeLimits}; use ast::{Field, FnDecl}; use ast::{ForeignItem, ForeignItemKind, FunctionRetTy}; -use ast::GenericParam; -use ast::GenericArg; +use ast::GenericParamAST; +use ast::GenericArgAST; use ast::{Ident, ImplItem, IsAuto, Item, ItemKind}; use ast::{Label, Lifetime, LifetimeDef, Lit, LitKind}; use ast::Local; @@ -1246,8 +1246,7 @@ impl<'a> Parser<'a> { } /// parse a TyKind::BareFn type: - fn parse_ty_bare_fn(&mut self, generic_params: Vec) - -> PResult<'a, TyKind> { + fn parse_ty_bare_fn(&mut self, generic_params: Vec) -> PResult<'a, TyKind> { /* [unsafe] [extern "ABI"] fn (S) -> T @@ -1566,7 +1565,7 @@ impl<'a> Parser<'a> { Ok(P(ty)) } - fn parse_remaining_bounds(&mut self, generic_params: Vec, path: ast::Path, + fn parse_remaining_bounds(&mut self, generic_params: Vec, path: ast::Path, lo: Span, parse_plus: bool) -> PResult<'a, TyKind> { let poly_trait_ref = PolyTraitRef::new(generic_params, path, lo.to(self.prev_span)); let mut bounds = vec![TraitTyParamBound(poly_trait_ref, TraitBoundModifier::None)]; @@ -4864,7 +4863,7 @@ impl<'a> Parser<'a> { /// Parses (possibly empty) list of lifetime and type parameters, possibly including /// trailing comma and erroneous trailing attributes. - crate fn parse_generic_params(&mut self) -> PResult<'a, Vec> { + crate fn parse_generic_params(&mut self) -> PResult<'a, Vec> { let mut params = Vec::new(); let mut seen_ty_param = false; loop { @@ -4877,7 +4876,7 @@ impl<'a> Parser<'a> { } else { Vec::new() }; - params.push(ast::GenericParam::Lifetime(LifetimeDef { + params.push(ast::GenericParamAST::Lifetime(LifetimeDef { attrs: attrs.into(), lifetime, bounds, @@ -4888,7 +4887,7 @@ impl<'a> Parser<'a> { } } else if self.check_ident() { // Parse type parameter. - params.push(ast::GenericParam::Type(self.parse_ty_param(attrs)?)); + params.push(ast::GenericParamAST::Type(self.parse_ty_param(attrs)?)); seen_ty_param = true; } else { // Check for trailing attributes and stop parsing. @@ -4938,7 +4937,7 @@ impl<'a> Parser<'a> { /// Parses (possibly empty) list of lifetime and type arguments and associated type bindings, /// possibly including trailing comma. fn parse_generic_args(&mut self) - -> PResult<'a, (Vec, Vec)> { + -> PResult<'a, (Vec, Vec)> { let mut args = Vec::new(); let mut bindings = Vec::new(); let mut seen_type = false; @@ -4946,7 +4945,7 @@ impl<'a> Parser<'a> { loop { if self.check_lifetime() && self.look_ahead(1, |t| !t.is_like_plus()) { // Parse lifetime argument. - args.push(GenericArg::Lifetime(self.expect_lifetime())); + args.push(GenericArgAST::Lifetime(self.expect_lifetime())); if seen_type || seen_binding { self.span_err(self.prev_span, "lifetime parameters must be declared prior to type parameters"); @@ -4971,7 +4970,7 @@ impl<'a> Parser<'a> { self.span_err(ty_param.span, "type parameters must be declared prior to associated type bindings"); } - args.push(GenericArg::Type(ty_param)); + args.push(GenericArgAST::Type(ty_param)); seen_type = true; } else { break @@ -5693,7 +5692,7 @@ impl<'a> Parser<'a> { Ok((keywords::Invalid.ident(), item_kind, Some(attrs))) } - fn parse_late_bound_lifetime_defs(&mut self) -> PResult<'a, Vec> { + fn parse_late_bound_lifetime_defs(&mut self) -> PResult<'a, Vec> { if self.eat_keyword(keywords::For) { self.expect_lt()?; let params = self.parse_generic_params()?; diff --git a/src/libsyntax/print/pprust.rs b/src/libsyntax/print/pprust.rs index 3e0e533bc08a8..a7a85a4c71fa5 100644 --- a/src/libsyntax/print/pprust.rs +++ b/src/libsyntax/print/pprust.rs @@ -13,7 +13,7 @@ pub use self::AnnNode::*; use rustc_target::spec::abi::{self, Abi}; use ast::{self, BlockCheckMode, PatKind, RangeEnd, RangeSyntax}; use ast::{SelfKind, RegionTyParamBound, TraitTyParamBound, TraitBoundModifier}; -use ast::{Attribute, MacDelimiter, GenericArg}; +use ast::{Attribute, MacDelimiter, GenericArgAST}; use util::parser::{self, AssocOp, Fixity}; use attr; use codemap::{self, CodeMap}; @@ -344,7 +344,7 @@ pub fn trait_item_to_string(i: &ast::TraitItem) -> String { to_string(|s| s.print_trait_item(i)) } -pub fn generic_params_to_string(generic_params: &[ast::GenericParam]) -> String { +pub fn generic_params_to_string(generic_params: &[ast::GenericParamAST]) -> String { to_string(|s| s.print_generic_params(generic_params)) } @@ -1017,10 +1017,10 @@ impl<'a> State<'a> { Ok(()) } - pub fn print_generic_arg(&mut self, generic_arg: &GenericArg) -> io::Result<()> { + pub fn print_generic_arg(&mut self, generic_arg: &GenericArgAST) -> io::Result<()> { match generic_arg { - GenericArg::Lifetime(lt) => self.print_lifetime(lt), - GenericArg::Type(ty) => self.print_type(ty), + GenericArgAST::Lifetime(lt) => self.print_lifetime(lt), + GenericArgAST::Type(ty) => self.print_type(ty), } } @@ -1443,7 +1443,7 @@ impl<'a> State<'a> { fn print_formal_generic_params( &mut self, - generic_params: &[ast::GenericParam] + generic_params: &[ast::GenericParamAST] ) -> io::Result<()> { if !generic_params.is_empty() { self.s.word("for")?; @@ -2869,7 +2869,7 @@ impl<'a> State<'a> { pub fn print_generic_params( &mut self, - generic_params: &[ast::GenericParam] + generic_params: &[ast::GenericParamAST] ) -> io::Result<()> { if generic_params.is_empty() { return Ok(()); @@ -2879,11 +2879,11 @@ impl<'a> State<'a> { self.commasep(Inconsistent, &generic_params, |s, param| { match *param { - ast::GenericParam::Lifetime(ref lifetime_def) => { + ast::GenericParamAST::Lifetime(ref lifetime_def) => { s.print_outer_attributes_inline(&lifetime_def.attrs)?; s.print_lifetime_bounds(&lifetime_def.lifetime, &lifetime_def.bounds) }, - ast::GenericParam::Type(ref ty_param) => s.print_ty_param(ty_param), + ast::GenericParamAST::Type(ref ty_param) => s.print_ty_param(ty_param), } })?; @@ -3047,7 +3047,7 @@ impl<'a> State<'a> { unsafety: ast::Unsafety, decl: &ast::FnDecl, name: Option, - generic_params: &Vec) + generic_params: &Vec) -> io::Result<()> { self.ibox(INDENT_UNIT)?; if !generic_params.is_empty() { diff --git a/src/libsyntax/util/node_count.rs b/src/libsyntax/util/node_count.rs index 95ae9f9bcf802..caddd0513d136 100644 --- a/src/libsyntax/util/node_count.rs +++ b/src/libsyntax/util/node_count.rs @@ -71,7 +71,7 @@ impl<'ast> Visitor<'ast> for NodeCounter { self.count += 1; walk_ty(self, t) } - fn visit_generic_param(&mut self, param: &GenericParam) { + fn visit_generic_param(&mut self, param: &GenericParamAST) { self.count += 1; walk_generic_param(self, param) } diff --git a/src/libsyntax/visit.rs b/src/libsyntax/visit.rs index 5ac33701baf29..8a4fde21e63f7 100644 --- a/src/libsyntax/visit.rs +++ b/src/libsyntax/visit.rs @@ -73,7 +73,7 @@ pub trait Visitor<'ast>: Sized { fn visit_expr(&mut self, ex: &'ast Expr) { walk_expr(self, ex) } fn visit_expr_post(&mut self, _ex: &'ast Expr) { } fn visit_ty(&mut self, t: &'ast Ty) { walk_ty(self, t) } - fn visit_generic_param(&mut self, param: &'ast GenericParam) { walk_generic_param(self, param) } + fn visit_generic_param(&mut self, param: &'ast GenericParamAST) { walk_generic_param(self, param) } fn visit_generics(&mut self, g: &'ast Generics) { walk_generics(self, g) } fn visit_where_predicate(&mut self, p: &'ast WherePredicate) { walk_where_predicate(self, p) @@ -131,10 +131,10 @@ pub trait Visitor<'ast>: Sized { fn visit_generic_args(&mut self, path_span: Span, generic_args: &'ast GenericArgs) { walk_generic_args(self, path_span, generic_args) } - fn visit_generic_arg(&mut self, generic_arg: &'ast GenericArg) { + fn visit_generic_arg(&mut self, generic_arg: &'ast GenericArgAST) { match generic_arg { - GenericArg::Lifetime(lt) => self.visit_lifetime(lt), - GenericArg::Type(ty) => self.visit_ty(ty), + GenericArgAST::Lifetime(lt) => self.visit_lifetime(lt), + GenericArgAST::Type(ty) => self.visit_ty(ty), } } fn visit_assoc_type_binding(&mut self, type_binding: &'ast TypeBinding) { @@ -488,14 +488,14 @@ pub fn walk_ty_param_bound<'a, V: Visitor<'a>>(visitor: &mut V, bound: &'a TyPar } } -pub fn walk_generic_param<'a, V: Visitor<'a>>(visitor: &mut V, param: &'a GenericParam) { +pub fn walk_generic_param<'a, V: Visitor<'a>>(visitor: &mut V, param: &'a GenericParamAST) { match *param { - GenericParam::Lifetime(ref l) => { + GenericParamAST::Lifetime(ref l) => { visitor.visit_ident(l.lifetime.ident); walk_list!(visitor, visit_lifetime, &l.bounds); walk_list!(visitor, visit_attribute, &*l.attrs); } - GenericParam::Type(ref t) => { + GenericParamAST::Type(ref t) => { visitor.visit_ident(t.ident); walk_list!(visitor, visit_ty_param_bound, &t.bounds); walk_list!(visitor, visit_ty, &t.default); diff --git a/src/libsyntax_ext/deriving/clone.rs b/src/libsyntax_ext/deriving/clone.rs index 504c3f8e91349..40d49b4996048 100644 --- a/src/libsyntax_ext/deriving/clone.rs +++ b/src/libsyntax_ext/deriving/clone.rs @@ -13,7 +13,7 @@ use deriving::generic::*; use deriving::generic::ty::*; use syntax::ast::{self, Expr, Generics, ItemKind, MetaItem, VariantData}; -use syntax::ast::GenericArg; +use syntax::ast::GenericArgAST; use syntax::attr; use syntax::ext::base::{Annotatable, ExtCtxt}; use syntax::ext::build::AstBuilder; @@ -124,7 +124,7 @@ fn cs_clone_shallow(name: &str, let span = span.with_ctxt(cx.backtrace()); let assert_path = cx.path_all(span, true, cx.std_path(&["clone", helper_name]), - vec![GenericArg::Type(ty)], vec![]); + vec![GenericArgAST::Type(ty)], vec![]); stmts.push(cx.stmt_let_type_only(span, cx.ty_path(assert_path))); } fn process_variant(cx: &mut ExtCtxt, stmts: &mut Vec, variant: &VariantData) { diff --git a/src/libsyntax_ext/deriving/cmp/eq.rs b/src/libsyntax_ext/deriving/cmp/eq.rs index 00ab39032acbd..e9bcf70e90c8e 100644 --- a/src/libsyntax_ext/deriving/cmp/eq.rs +++ b/src/libsyntax_ext/deriving/cmp/eq.rs @@ -12,7 +12,7 @@ use deriving::path_std; use deriving::generic::*; use deriving::generic::ty::*; -use syntax::ast::{self, Expr, MetaItem, GenericArg}; +use syntax::ast::{self, Expr, MetaItem, GenericArgAST}; use syntax::ext::base::{Annotatable, ExtCtxt}; use syntax::ext::build::AstBuilder; use syntax::ptr::P; @@ -62,7 +62,7 @@ fn cs_total_eq_assert(cx: &mut ExtCtxt, trait_span: Span, substr: &Substructure) let span = span.with_ctxt(cx.backtrace()); let assert_path = cx.path_all(span, true, cx.std_path(&["cmp", helper_name]), - vec![GenericArg::Type(ty)], vec![]); + vec![GenericArgAST::Type(ty)], vec![]); stmts.push(cx.stmt_let_type_only(span, cx.ty_path(assert_path))); } fn process_variant(cx: &mut ExtCtxt, stmts: &mut Vec, variant: &ast::VariantData) { diff --git a/src/libsyntax_ext/deriving/generic/mod.rs b/src/libsyntax_ext/deriving/generic/mod.rs index 299c53f310114..f85091b0e719d 100644 --- a/src/libsyntax_ext/deriving/generic/mod.rs +++ b/src/libsyntax_ext/deriving/generic/mod.rs @@ -192,8 +192,8 @@ use std::collections::HashSet; use std::vec; use rustc_target::spec::abi::Abi; -use syntax::ast::{self, BinOpKind, EnumDef, Expr, GenericParam, Generics, Ident, PatKind}; -use syntax::ast::{VariantData, GenericArg}; +use syntax::ast::{self, BinOpKind, EnumDef, Expr, GenericParamAST, Generics, Ident, PatKind}; +use syntax::ast::{VariantData, GenericArgAST}; use syntax::attr; use syntax::ext::base::{Annotatable, ExtCtxt}; use syntax::ext::build::AstBuilder; @@ -548,8 +548,8 @@ impl<'a> TraitDef<'a> { // Create the generic parameters params.extend(generics.params.iter().map(|param| { match *param { - ref l @ GenericParam::Lifetime(_) => l.clone(), - GenericParam::Type(ref ty_param) => { + ref l @ GenericParamAST::Lifetime(_) => l.clone(), + GenericParamAST::Type(ref ty_param) => { // I don't think this can be moved out of the loop, since // a TyParamBound requires an ast id let mut bounds: Vec<_> = @@ -568,7 +568,7 @@ impl<'a> TraitDef<'a> { bounds.push((*declared_bound).clone()); } - GenericParam::Type(cx.typaram(self.span, ty_param.ident, vec![], bounds, None)) + GenericParamAST::Type(cx.typaram(self.span, ty_param.ident, vec![], bounds, None)) } } })); @@ -607,7 +607,7 @@ impl<'a> TraitDef<'a> { let mut ty_params = params.iter() .filter_map(|param| match *param { - ast::GenericParam::Type(ref t) => Some(t), + ast::GenericParamAST::Type(ref t) => Some(t), _ => None, }) .peekable(); @@ -668,7 +668,7 @@ impl<'a> TraitDef<'a> { let self_ty_params: Vec> = generics.params .iter() .filter_map(|param| match *param { - GenericParam::Type(ref ty_param) + GenericParamAST::Type(ref ty_param) => Some(cx.ty_ident(self.span, ty_param.ident)), _ => None, }) @@ -677,15 +677,15 @@ impl<'a> TraitDef<'a> { let self_lifetimes: Vec = generics.params .iter() .filter_map(|param| match *param { - GenericParam::Lifetime(ref ld) => Some(ld.lifetime), + GenericParamAST::Lifetime(ref ld) => Some(ld.lifetime), _ => None, }) .collect(); let self_params = self_lifetimes.into_iter() - .map(|lt| GenericArg::Lifetime(lt)) + .map(|lt| GenericArgAST::Lifetime(lt)) .chain(self_ty_params.into_iter().map(|ty| - GenericArg::Type(ty))) + GenericArgAST::Type(ty))) .collect(); // Create the type of `self`. diff --git a/src/libsyntax_ext/deriving/generic/ty.rs b/src/libsyntax_ext/deriving/generic/ty.rs index 7e6dd5fad2583..92046262ed253 100644 --- a/src/libsyntax_ext/deriving/generic/ty.rs +++ b/src/libsyntax_ext/deriving/generic/ty.rs @@ -15,7 +15,7 @@ pub use self::PtrTy::*; pub use self::Ty::*; use syntax::ast; -use syntax::ast::{Expr, GenericParam, Generics, Ident, SelfKind, GenericArg}; +use syntax::ast::{Expr, GenericParamAST, Generics, Ident, SelfKind, GenericArgAST}; use syntax::ext::base::ExtCtxt; use syntax::ext::build::AstBuilder; use syntax::codemap::{respan, DUMMY_SP}; @@ -89,8 +89,8 @@ impl<'a> Path<'a> { let tys: Vec> = self.params.iter().map(|t| t.to_ty(cx, span, self_ty, self_generics)).collect(); let params = lt.into_iter() - .map(|lt| GenericArg::Lifetime(lt)) - .chain(tys.into_iter().map(|ty| GenericArg::Type(ty))) + .map(|lt| GenericArgAST::Lifetime(lt)) + .chain(tys.into_iter().map(|ty| GenericArgAST::Type(ty))) .collect(); match self.kind { @@ -192,7 +192,7 @@ impl<'a> Ty<'a> { let ty_params: Vec> = self_generics.params .iter() .filter_map(|param| match *param { - GenericParam::Type(ref ty_param) => Some(cx.ty_ident(span, ty_param.ident)), + GenericParamAST::Type(ref ty_param) => Some(cx.ty_ident(span, ty_param.ident)), _ => None, }) .collect(); @@ -200,15 +200,15 @@ impl<'a> Ty<'a> { let lifetimes: Vec = self_generics.params .iter() .filter_map(|param| match *param { - GenericParam::Lifetime(ref ld) => Some(ld.lifetime), + GenericParamAST::Lifetime(ref ld) => Some(ld.lifetime), _ => None, }) .collect(); let params = lifetimes.into_iter() - .map(|lt| GenericArg::Lifetime(lt)) + .map(|lt| GenericArgAST::Lifetime(lt)) .chain(ty_params.into_iter().map(|ty| - GenericArg::Type(ty))) + GenericArgAST::Type(ty))) .collect(); cx.path_all(span, @@ -242,7 +242,7 @@ fn mk_ty_param(cx: &ExtCtxt, cx.typaram(span, cx.ident_of(name), attrs.to_owned(), bounds, None) } -fn mk_generics(params: Vec, span: Span) -> Generics { +fn mk_generics(params: Vec, span: Span) -> Generics { Generics { params, where_clause: ast::WhereClause { @@ -280,13 +280,13 @@ impl<'a> LifetimeBounds<'a> { let bounds = bounds.iter() .map(|b| cx.lifetime(span, Ident::from_str(b))) .collect(); - GenericParam::Lifetime(cx.lifetime_def(span, Ident::from_str(lt), vec![], bounds)) + GenericParamAST::Lifetime(cx.lifetime_def(span, Ident::from_str(lt), vec![], bounds)) }) .chain(self.bounds .iter() .map(|t| { let (name, ref bounds) = *t; - GenericParam::Type(mk_ty_param( + GenericParamAST::Type(mk_ty_param( cx, span, name, &[], &bounds, self_ty, self_generics )) }) diff --git a/src/libsyntax_ext/deriving/mod.rs b/src/libsyntax_ext/deriving/mod.rs index a5b348a661a78..9bc19bb5ede68 100644 --- a/src/libsyntax_ext/deriving/mod.rs +++ b/src/libsyntax_ext/deriving/mod.rs @@ -135,7 +135,7 @@ fn hygienic_type_parameter(item: &Annotatable, base: &str) -> String { ast::ItemKind::Struct(_, ast::Generics { ref params, .. }) | ast::ItemKind::Enum(_, ast::Generics { ref params, .. }) => { for param in params.iter() { - if let ast::GenericParam::Type(ref ty) = *param{ + if let ast::GenericParamAST::Type(ref ty) = *param { typaram.push_str(&ty.ident.as_str()); } } diff --git a/src/libsyntax_ext/env.rs b/src/libsyntax_ext/env.rs index 5c3080260ccd5..a3254788d4529 100644 --- a/src/libsyntax_ext/env.rs +++ b/src/libsyntax_ext/env.rs @@ -13,7 +13,7 @@ // interface. // -use syntax::ast::{self, Ident, GenericArg}; +use syntax::ast::{self, Ident, GenericArgAST}; use syntax::ext::base::*; use syntax::ext::base; use syntax::ext::build::AstBuilder; @@ -39,7 +39,7 @@ pub fn expand_option_env<'cx>(cx: &'cx mut ExtCtxt, cx.expr_path(cx.path_all(sp, true, cx.std_path(&["option", "Option", "None"]), - vec![GenericArg::Type(cx.ty_rptr(sp, + vec![GenericArgAST::Type(cx.ty_rptr(sp, cx.ty_ident(sp, Ident::from_str("str")), Some(lt), ast::Mutability::Immutable))], From 82dba3d419d3cfac00cc90bc8d078e6ae0a724f5 Mon Sep 17 00:00:00 2001 From: varkor Date: Sat, 26 May 2018 00:27:54 +0100 Subject: [PATCH 08/41] Refactor hir::GenericParam as a struct --- src/librustc/hir/intravisit.rs | 25 +- src/librustc/hir/lowering.rs | 211 +++++++------- src/librustc/hir/map/collector.rs | 12 +- src/librustc/hir/map/mod.rs | 69 ++--- src/librustc/hir/mod.rs | 197 ++++++------- src/librustc/hir/print.rs | 59 ++-- src/librustc/ich/impls_hir.rs | 42 +-- src/librustc/infer/error_reporting/mod.rs | 12 +- src/librustc/middle/resolve_lifetime.rs | 295 ++++++++++++-------- src/librustc_lint/bad_style.rs | 23 +- src/librustc_lint/builtin.rs | 12 +- src/librustc_metadata/encoder.rs | 15 +- src/librustc_privacy/lib.rs | 13 +- src/librustc_typeck/check/compare_method.rs | 18 +- src/librustc_typeck/check/mod.rs | 5 +- src/librustc_typeck/check/wfcheck.rs | 7 +- src/librustc_typeck/coherence/unsafety.rs | 14 +- src/librustc_typeck/collect.rs | 155 ++++++---- src/librustc_typeck/lib.rs | 1 + src/librustdoc/clean/mod.rs | 71 +++-- src/libsyntax/visit.rs | 4 +- src/libsyntax_ext/deriving/generic/mod.rs | 3 +- src/libsyntax_ext/deriving/generic/ty.rs | 7 +- 23 files changed, 704 insertions(+), 566 deletions(-) diff --git a/src/librustc/hir/intravisit.rs b/src/librustc/hir/intravisit.rs index fef33939fac6a..4c24c7afd735c 100644 --- a/src/librustc/hir/intravisit.rs +++ b/src/librustc/hir/intravisit.rs @@ -743,26 +743,25 @@ pub fn walk_ty_param_bound<'v, V: Visitor<'v>>(visitor: &mut V, bound: &'v TyPar } pub fn walk_generic_param<'v, V: Visitor<'v>>(visitor: &mut V, param: &'v GenericParam) { - match *param { - GenericParam::Lifetime(ref ld) => { - visitor.visit_id(ld.lifetime.id); - match ld.lifetime.name { + visitor.visit_id(param.id); + match param.kind { + GenericParamKind::Lifetime { ref bounds, ref lifetime_deprecated, .. } => { + match lifetime_deprecated.name { LifetimeName::Name(name) => { - visitor.visit_name(ld.lifetime.span, name); + visitor.visit_name(param.span, name); } LifetimeName::Fresh(_) | LifetimeName::Static | LifetimeName::Implicit | LifetimeName::Underscore => {} } - walk_list!(visitor, visit_lifetime, &ld.bounds); - } - GenericParam::Type(ref ty_param) => { - visitor.visit_id(ty_param.id); - visitor.visit_name(ty_param.span, ty_param.name); - walk_list!(visitor, visit_ty_param_bound, &ty_param.bounds); - walk_list!(visitor, visit_ty, &ty_param.default); - walk_list!(visitor, visit_attribute, ty_param.attrs.iter()); + walk_list!(visitor, visit_lifetime, bounds); + } + GenericParamKind::Type { name, ref bounds, ref default, ref attrs, .. } => { + visitor.visit_name(param.span, name); + walk_list!(visitor, visit_ty_param_bound, bounds); + walk_list!(visitor, visit_ty, default); + walk_list!(visitor, visit_attribute, attrs.iter()); } } } diff --git a/src/librustc/hir/lowering.rs b/src/librustc/hir/lowering.rs index 4660352b28bfc..0c5c79e8e600d 100644 --- a/src/librustc/hir/lowering.rs +++ b/src/librustc/hir/lowering.rs @@ -116,7 +116,7 @@ pub struct LoweringContext<'a> { // When traversing a signature such as `fn foo(x: impl Trait)`, // we record `impl Trait` as a new type parameter, then later // add it on to `foo`s generics. - in_band_ty_params: Vec, + in_band_ty_params: Vec, // Used to create lifetime definitions from in-band lifetime usages. // e.g. `fn foo(x: &'x u8) -> &'x u8` to `fn foo<'x>(x: &'x u8) -> &'x u8` @@ -695,22 +695,23 @@ impl<'a> LoweringContext<'a> { span, ); - hir::GenericParam::Lifetime(hir::LifetimeDef { - lifetime: hir::Lifetime { - id: def_node_id, - span, - name: hir_name, - }, - bounds: Vec::new().into(), + hir::GenericParam { + id: def_node_id, + span, pure_wrt_drop: false, - in_band: true, - }) + kind: hir::GenericParamKind::Lifetime { + name: hir_name, + bounds: vec![].into(), + in_band: true, + lifetime_deprecated: hir::Lifetime { + id: def_node_id, + span, + name: hir_name, + } + } + } }) - .chain( - in_band_ty_params - .into_iter() - .map(|tp| hir::GenericParam::Type(tp)), - ) + .chain(in_band_ty_params.into_iter()) .collect(); (params, res) @@ -778,12 +779,12 @@ impl<'a> LoweringContext<'a> { // This should only be used with generics that have already had their // in-band lifetimes added. In practice, this means that this function is // only used when lowering a child item of a trait or impl. - fn with_parent_impl_lifetime_defs(&mut self, lt_defs: &[hir::LifetimeDef], f: F) -> T + fn with_parent_impl_lifetime_defs(&mut self, params: &[hir::GenericParam], f: F) -> T where F: FnOnce(&mut LoweringContext) -> T, { let old_len = self.in_scope_lifetimes.len(); - let lt_def_names = lt_defs.iter().map(|lt_def| lt_def.lifetime.name.name()); + let lt_def_names = params.iter().map(|param| param.name()); self.in_scope_lifetimes.extend(lt_def_names); let res = f(self); @@ -1252,15 +1253,17 @@ impl<'a> LoweringContext<'a> { let hir_bounds = self.lower_bounds(bounds, itctx); // Set the name to `impl Bound1 + Bound2` let name = Symbol::intern(&pprust::ty_to_string(t)); - self.in_band_ty_params.push(hir::TyParam { - name, + self.in_band_ty_params.push(hir::GenericParam { id: def_node_id, - bounds: hir_bounds, - default: None, span, pure_wrt_drop: false, - synthetic: Some(hir::SyntheticTyParamKind::ImplTrait), - attrs: P::new(), + kind: hir::GenericParamKind::Type { + name, + bounds: hir_bounds, + default: None, + synthetic: Some(hir::SyntheticTyParamKind::ImplTrait), + attrs: P::new(), + } }); hir::TyPath(hir::QPath::Resolved( @@ -1367,10 +1370,10 @@ impl<'a> LoweringContext<'a> { fn visit_generic_param(&mut self, param: &'v hir::GenericParam) { // Record the introduction of 'a in `for<'a> ...` - if let hir::GenericParam::Lifetime(ref lt_def) = *param { + if let hir::GenericParamKind::Lifetime { name, .. } = param.kind { // Introduce lifetimes one at a time so that we can handle // cases like `fn foo<'d>() -> impl for<'a, 'b: 'a, 'c: 'b + 'd>` - self.currently_bound_lifetimes.push(lt_def.lifetime.name); + self.currently_bound_lifetimes.push(name); } hir::intravisit::walk_generic_param(self, param); @@ -1416,18 +1419,22 @@ impl<'a> LoweringContext<'a> { Mark::root(), lifetime.span, ); - let def_lifetime = hir::Lifetime { + + self.output_lifetime_params.push(hir::GenericParam { id: def_node_id, span: lifetime.span, - name, - }; - self.output_lifetime_params - .push(hir::GenericParam::Lifetime(hir::LifetimeDef { - lifetime: def_lifetime, - bounds: Vec::new().into(), - pure_wrt_drop: false, + pure_wrt_drop: false, + kind: hir::GenericParamKind::Lifetime { + name, + bounds: vec![].into(), in_band: false, - })); + lifetime_deprecated: hir::Lifetime { + id: def_node_id, + span: lifetime.span, + name, + } + } + }); } } } @@ -1887,47 +1894,6 @@ impl<'a> LoweringContext<'a> { } } - fn lower_ty_param( - &mut self, - tp: &TyParam, - add_bounds: &[TyParamBound], - itctx: ImplTraitContext, - ) -> hir::TyParam { - let mut name = self.lower_ident(tp.ident); - - // Don't expose `Self` (recovered "keyword used as ident" parse error). - // `rustc::ty` expects `Self` to be only used for a trait's `Self`. - // Instead, use gensym("Self") to create a distinct name that looks the same. - if name == keywords::SelfType.name() { - name = Symbol::gensym("Self"); - } - - let mut bounds = self.lower_bounds(&tp.bounds, itctx); - if !add_bounds.is_empty() { - bounds = bounds - .into_iter() - .chain(self.lower_bounds(add_bounds, itctx).into_iter()) - .collect(); - } - - hir::TyParam { - id: self.lower_node_id(tp.id).node_id, - name, - bounds, - default: tp.default - .as_ref() - .map(|x| self.lower_ty(x, ImplTraitContext::Disallowed)), - span: tp.ident.span, - pure_wrt_drop: attr::contains_name(&tp.attrs, "may_dangle"), - synthetic: tp.attrs - .iter() - .filter(|attr| attr.check_name("rustc_synthetic")) - .map(|_| hir::SyntheticTyParamKind::ImplTrait) - .nth(0), - attrs: self.lower_attrs(&tp.attrs), - } - } - fn lower_lifetime(&mut self, l: &Lifetime) -> hir::Lifetime { let span = l.ident.span; match self.lower_ident(l.ident) { @@ -1962,20 +1928,75 @@ impl<'a> LoweringContext<'a> { } } - fn lower_lifetime_def(&mut self, l: &LifetimeDef) -> hir::LifetimeDef { - let was_collecting_in_band = self.is_collecting_in_band_lifetimes; - self.is_collecting_in_band_lifetimes = false; + fn lower_generic_param(&mut self, + param: &GenericParamAST, + add_bounds: &NodeMap>, + itctx: ImplTraitContext) + -> hir::GenericParam { + match param { + GenericParamAST::Lifetime(ref lifetime_def) => { + let was_collecting_in_band = self.is_collecting_in_band_lifetimes; + self.is_collecting_in_band_lifetimes = false; + + let lifetime = self.lower_lifetime(&lifetime_def.lifetime); + let param = hir::GenericParam { + id: lifetime.id, + span: lifetime.span, + pure_wrt_drop: attr::contains_name(&lifetime_def.attrs, "may_dangle"), + kind: hir::GenericParamKind::Lifetime { + name: lifetime.name, + bounds: lifetime_def.bounds + .iter() + .map(|lt| self.lower_lifetime(lt)).collect(), + in_band: false, + lifetime_deprecated: lifetime, + } + }; - let def = hir::LifetimeDef { - lifetime: self.lower_lifetime(&l.lifetime), - bounds: l.bounds.iter().map(|l| self.lower_lifetime(l)).collect(), - pure_wrt_drop: attr::contains_name(&l.attrs, "may_dangle"), - in_band: false, - }; + self.is_collecting_in_band_lifetimes = was_collecting_in_band; - self.is_collecting_in_band_lifetimes = was_collecting_in_band; + param + } + GenericParamAST::Type(ref ty_param) => { + let mut name = self.lower_ident(ty_param.ident); + + // Don't expose `Self` (recovered "keyword used as ident" parse error). + // `rustc::ty` expects `Self` to be only used for a trait's `Self`. + // Instead, use gensym("Self") to create a distinct name that looks the same. + if name == keywords::SelfType.name() { + name = Symbol::gensym("Self"); + } + + let mut bounds = self.lower_bounds(&ty_param.bounds, itctx); + let add_bounds = add_bounds.get(&ty_param.id).map_or(&[][..], |x| &x); + if !add_bounds.is_empty() { + bounds = bounds + .into_iter() + .chain(self.lower_bounds(add_bounds, itctx).into_iter()) + .collect(); + } - def + hir::GenericParam { + id: self.lower_node_id(ty_param.id).node_id, + span: ty_param.ident.span, + pure_wrt_drop: attr::contains_name(&ty_param.attrs, "may_dangle"), + kind: hir::GenericParamKind::Type { + name, + bounds, + default: ty_param.default.as_ref() + .map(|x| { + self.lower_ty(x, ImplTraitContext::Disallowed) + }), + synthetic: ty_param.attrs + .iter() + .filter(|attr| attr.check_name("rustc_synthetic")) + .map(|_| hir::SyntheticTyParamKind::ImplTrait) + .nth(0), + attrs: self.lower_attrs(&ty_param.attrs), + } + } + } + } } fn lower_generic_params( @@ -1984,19 +2005,7 @@ impl<'a> LoweringContext<'a> { add_bounds: &NodeMap>, itctx: ImplTraitContext, ) -> hir::HirVec { - params - .iter() - .map(|param| match *param { - GenericParamAST::Lifetime(ref lifetime_def) => { - hir::GenericParam::Lifetime(self.lower_lifetime_def(lifetime_def)) - } - GenericParamAST::Type(ref ty_param) => hir::GenericParam::Type(self.lower_ty_param( - ty_param, - add_bounds.get(&ty_param.id).map_or(&[][..], |x| &x), - itctx, - )), - }) - .collect() + params.iter().map(|param| self.lower_generic_param(param, add_bounds, itctx)).collect() } fn lower_generics(&mut self, g: &Generics, itctx: ImplTraitContext) -> hir::Generics { @@ -2175,8 +2184,8 @@ impl<'a> LoweringContext<'a> { let trait_ref = self.with_parent_impl_lifetime_defs( &bound_generic_params .iter() - .filter_map(|p| match *p { - hir::GenericParam::Lifetime(ref ld) => Some(ld.clone()), + .filter_map(|param| match param.kind { + hir::GenericParamKind::Lifetime { .. } => Some(param.clone()), _ => None, }) .collect::>(), diff --git a/src/librustc/hir/map/collector.rs b/src/librustc/hir/map/collector.rs index 7835d4e782c43..d34924547ed66 100644 --- a/src/librustc/hir/map/collector.rs +++ b/src/librustc/hir/map/collector.rs @@ -212,7 +212,7 @@ impl<'a, 'hir> NodeCollector<'a, 'hir> { NodeBlock(n) => EntryBlock(parent, dep_node_index, n), NodeStructCtor(n) => EntryStructCtor(parent, dep_node_index, n), NodeLifetime(n) => EntryLifetime(parent, dep_node_index, n), - NodeTyParam(n) => EntryTyParam(parent, dep_node_index, n), + NodeGenericParam(n) => EntryGenericParam(parent, dep_node_index, n), NodeVisibility(n) => EntryVisibility(parent, dep_node_index, n), NodeLocal(n) => EntryLocal(parent, dep_node_index, n), NodeMacroDef(n) => EntryMacroDef(dep_node_index, n), @@ -347,12 +347,12 @@ impl<'a, 'hir> Visitor<'hir> for NodeCollector<'a, 'hir> { } fn visit_generic_param(&mut self, param: &'hir GenericParam) { - match *param { - GenericParam::Lifetime(ref ld) => { - self.insert(ld.lifetime.id, NodeLifetime(&ld.lifetime)); + match param.kind { + GenericParamKind::Lifetime { ref lifetime_deprecated, .. } => { + self.insert(param.id, NodeLifetime(lifetime_deprecated)); } - GenericParam::Type(ref ty_param) => { - self.insert(ty_param.id, NodeTyParam(ty_param)); + GenericParamKind::Type { .. } => { + self.insert(param.id, NodeGenericParam(param)); } } intravisit::walk_generic_param(self, param); diff --git a/src/librustc/hir/map/mod.rs b/src/librustc/hir/map/mod.rs index d2e04ef31c86a..c46f58137540f 100644 --- a/src/librustc/hir/map/mod.rs +++ b/src/librustc/hir/map/mod.rs @@ -68,7 +68,7 @@ pub enum Node<'hir> { NodeStructCtor(&'hir VariantData), NodeLifetime(&'hir Lifetime), - NodeTyParam(&'hir TyParam), + NodeGenericParam(&'hir GenericParam), NodeVisibility(&'hir Visibility), } @@ -96,7 +96,7 @@ enum MapEntry<'hir> { EntryBlock(NodeId, DepNodeIndex, &'hir Block), EntryStructCtor(NodeId, DepNodeIndex, &'hir VariantData), EntryLifetime(NodeId, DepNodeIndex, &'hir Lifetime), - EntryTyParam(NodeId, DepNodeIndex, &'hir TyParam), + EntryGenericParam(NodeId, DepNodeIndex, &'hir GenericParam), EntryVisibility(NodeId, DepNodeIndex, &'hir Visibility), EntryLocal(NodeId, DepNodeIndex, &'hir Local), @@ -132,7 +132,7 @@ impl<'hir> MapEntry<'hir> { EntryBlock(id, _, _) => id, EntryStructCtor(id, _, _) => id, EntryLifetime(id, _, _) => id, - EntryTyParam(id, _, _) => id, + EntryGenericParam(id, _, _) => id, EntryVisibility(id, _, _) => id, EntryLocal(id, _, _) => id, @@ -160,7 +160,7 @@ impl<'hir> MapEntry<'hir> { EntryBlock(_, _, n) => NodeBlock(n), EntryStructCtor(_, _, n) => NodeStructCtor(n), EntryLifetime(_, _, n) => NodeLifetime(n), - EntryTyParam(_, _, n) => NodeTyParam(n), + EntryGenericParam(_, _, n) => NodeGenericParam(n), EntryVisibility(_, _, n) => NodeVisibility(n), EntryLocal(_, _, n) => NodeLocal(n), EntryMacroDef(_, n) => NodeMacroDef(n), @@ -328,7 +328,7 @@ impl<'hir> Map<'hir> { EntryBlock(_, dep_node_index, _) | EntryStructCtor(_, dep_node_index, _) | EntryLifetime(_, dep_node_index, _) | - EntryTyParam(_, dep_node_index, _) | + EntryGenericParam(_, dep_node_index, _) | EntryVisibility(_, dep_node_index, _) | EntryAnonConst(_, dep_node_index, _) | EntryExpr(_, dep_node_index, _) | @@ -494,7 +494,7 @@ impl<'hir> Map<'hir> { Some(Def::Macro(self.local_def_id(macro_def.id), MacroKind::Bang)) } - NodeTyParam(param) => { + NodeGenericParam(param) => { Some(Def::TyParam(self.local_def_id(param.id))) } } @@ -600,7 +600,7 @@ impl<'hir> Map<'hir> { pub fn ty_param_owner(&self, id: NodeId) -> NodeId { match self.get(id) { NodeItem(&Item { node: ItemTrait(..), .. }) => id, - NodeTyParam(_) => self.get_parent_node(id), + NodeGenericParam(_) => self.get_parent_node(id), _ => { bug!("ty_param_owner: {} not a type parameter", self.node_to_string(id)) @@ -613,7 +613,7 @@ impl<'hir> Map<'hir> { NodeItem(&Item { node: ItemTrait(..), .. }) => { keywords::SelfType.name() } - NodeTyParam(tp) => tp.name, + NodeGenericParam(param) => param.name(), _ => { bug!("ty_param_name: {} not a type parameter", self.node_to_string(id)) @@ -954,7 +954,7 @@ impl<'hir> Map<'hir> { NodeVariant(v) => v.node.name, NodeField(f) => f.ident.name, NodeLifetime(lt) => lt.name.name(), - NodeTyParam(tp) => tp.name, + NodeGenericParam(param) => param.name(), NodeBinding(&Pat { node: PatKind::Binding(_,_,l,_), .. }) => l.node, NodeStructCtor(_) => self.name(self.get_parent(id)), _ => bug!("no name for {}", self.node_to_string(id)) @@ -974,7 +974,12 @@ impl<'hir> Map<'hir> { Some(NodeField(ref f)) => Some(&f.attrs[..]), Some(NodeExpr(ref e)) => Some(&*e.attrs), Some(NodeStmt(ref s)) => Some(s.node.attrs()), - Some(NodeTyParam(tp)) => Some(&tp.attrs[..]), + Some(NodeGenericParam(param)) => { + match param.kind { + GenericParamKind::Type { ref attrs, .. } => Some(&attrs[..]), + _ => bug!("unexpected non-type NodeGenericParam") + } + } // unit/tuple structs take the attributes straight from // the struct definition. Some(NodeStructCtor(_)) => { @@ -1021,7 +1026,7 @@ impl<'hir> Map<'hir> { Some(EntryBlock(_, _, block)) => block.span, Some(EntryStructCtor(_, _, _)) => self.expect_item(self.get_parent(id)).span, Some(EntryLifetime(_, _, lifetime)) => lifetime.span, - Some(EntryTyParam(_, _, ty_param)) => ty_param.span, + Some(EntryGenericParam(_, _, param)) => param.span, Some(EntryVisibility(_, _, &Visibility::Restricted { ref path, .. })) => path.span, Some(EntryVisibility(_, _, v)) => bug!("unexpected Visibility {:?}", v), Some(EntryLocal(_, _, local)) => local.span, @@ -1226,19 +1231,19 @@ impl<'hir> print::PpAnn for Map<'hir> { impl<'a> print::State<'a> { pub fn print_node(&mut self, node: Node) -> io::Result<()> { match node { - NodeItem(a) => self.print_item(&a), - NodeForeignItem(a) => self.print_foreign_item(&a), - NodeTraitItem(a) => self.print_trait_item(a), - NodeImplItem(a) => self.print_impl_item(a), - NodeVariant(a) => self.print_variant(&a), - NodeAnonConst(a) => self.print_anon_const(&a), - NodeExpr(a) => self.print_expr(&a), - NodeStmt(a) => self.print_stmt(&a), - NodeTy(a) => self.print_type(&a), - NodeTraitRef(a) => self.print_trait_ref(&a), + NodeItem(a) => self.print_item(&a), + NodeForeignItem(a) => self.print_foreign_item(&a), + NodeTraitItem(a) => self.print_trait_item(a), + NodeImplItem(a) => self.print_impl_item(a), + NodeVariant(a) => self.print_variant(&a), + NodeAnonConst(a) => self.print_anon_const(&a), + NodeExpr(a) => self.print_expr(&a), + NodeStmt(a) => self.print_stmt(&a), + NodeTy(a) => self.print_type(&a), + NodeTraitRef(a) => self.print_trait_ref(&a), NodeBinding(a) | - NodePat(a) => self.print_pat(&a), - NodeBlock(a) => { + NodePat(a) => self.print_pat(&a), + NodeBlock(a) => { use syntax::print::pprust::PrintState; // containing cbox, will be closed by print-block at } @@ -1247,16 +1252,16 @@ impl<'a> print::State<'a> { self.ibox(0)?; self.print_block(&a) } - NodeLifetime(a) => self.print_lifetime(&a), - NodeVisibility(a) => self.print_visibility(&a), - NodeTyParam(_) => bug!("cannot print TyParam"), - NodeField(_) => bug!("cannot print StructField"), + NodeLifetime(a) => self.print_lifetime(&a), + NodeVisibility(a) => self.print_visibility(&a), + NodeGenericParam(_) => bug!("cannot print NodeGenericParam"), + NodeField(_) => bug!("cannot print StructField"), // these cases do not carry enough information in the // hir_map to reconstruct their full structure for pretty // printing. - NodeStructCtor(_) => bug!("cannot print isolated StructCtor"), - NodeLocal(a) => self.print_local_decl(&a), - NodeMacroDef(_) => bug!("cannot print MacroDef"), + NodeStructCtor(_) => bug!("cannot print isolated StructCtor"), + NodeLocal(a) => self.print_local_decl(&a), + NodeMacroDef(_) => bug!("cannot print MacroDef"), } } } @@ -1371,8 +1376,8 @@ fn node_id_to_string(map: &Map, id: NodeId, include_id: bool) -> String { Some(NodeLifetime(_)) => { format!("lifetime {}{}", map.node_to_pretty_string(id), id_str) } - Some(NodeTyParam(ref ty_param)) => { - format!("typaram {:?}{}", ty_param, id_str) + Some(NodeGenericParam(ref param)) => { + format!("genericparam {:?}{}", param, id_str) } Some(NodeVisibility(ref vis)) => { format!("visibility {:?}{}", vis, id_str) diff --git a/src/librustc/hir/mod.rs b/src/librustc/hir/mod.rs index d4785e40b1f8a..6a0301a556fb1 100644 --- a/src/librustc/hir/mod.rs +++ b/src/librustc/hir/mod.rs @@ -53,8 +53,6 @@ use rustc_data_structures::sync::{ParallelIterator, par_iter, Send, Sync, scope} use serialize::{self, Encoder, Encodable, Decoder, Decodable}; use std::collections::BTreeMap; use std::fmt; -use std::iter; -use std::slice; /// HIR doesn't commit to a concrete storage type and has its own alias for a vector. /// It can be `Vec`, `P<[T]>` or potentially `Box<[T]>`, or some other container with similar @@ -242,6 +240,24 @@ impl LifetimeName { Name(name) => name, } } + + fn is_elided(&self) -> bool { + use self::LifetimeName::*; + match self { + Implicit | Underscore => true, + + // It might seem surprising that `Fresh(_)` counts as + // *not* elided -- but this is because, as far as the code + // in the compiler is concerned -- `Fresh(_)` variants act + // equivalently to "some fresh name". They correspond to + // early-bound regions on an impl, in other words. + Fresh(_) | Static | Name(_) => false, + } + } + + fn is_static(&self) -> bool { + self == &LifetimeName::Static + } } impl fmt::Debug for Lifetime { @@ -255,36 +271,14 @@ impl fmt::Debug for Lifetime { impl Lifetime { pub fn is_elided(&self) -> bool { - use self::LifetimeName::*; - match self.name { - Implicit | Underscore => true, - - // It might seem surprising that `Fresh(_)` counts as - // *not* elided -- but this is because, as far as the code - // in the compiler is concerned -- `Fresh(_)` variants act - // equivalently to "some fresh name". They correspond to - // early-bound regions on an impl, in other words. - Fresh(_) | Static | Name(_) => false, - } + self.name.is_elided() } pub fn is_static(&self) -> bool { - self.name == LifetimeName::Static + self.name.is_static() } } -/// A lifetime definition, eg `'a: 'b+'c+'d` -#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)] -pub struct LifetimeDef { - pub lifetime: Lifetime, - pub bounds: HirVec, - pub pure_wrt_drop: bool, - // Indicates that the lifetime definition was synthetically added - // as a result of an in-band lifetime usage like - // `fn foo(x: &'a u8) -> &'a u8 { x }` - pub in_band: bool, -} - /// A "Path" is essentially Rust's notion of a name; for instance: /// `std::cmp::PartialEq`. It's represented as a sequence of identifiers, /// along with a bunch of supporting information. @@ -466,70 +460,62 @@ pub enum TraitBoundModifier { pub type TyParamBounds = HirVec; #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)] -pub struct TyParam { - pub name: Name, +pub enum GenericParamKind { + /// A lifetime definition, eg `'a: 'b + 'c + 'd`. + Lifetime { + /// Either "'a", referring to a named lifetime definition, + /// or "" (aka keywords::Invalid), for elision placeholders. + /// + /// HIR lowering inserts these placeholders in type paths that + /// refer to type definitions needing lifetime parameters, + /// `&T` and `&mut T`, and trait objects without `... + 'a`. + name: LifetimeName, + bounds: HirVec, + // Indicates that the lifetime definition was synthetically added + // as a result of an in-band lifetime usage like: + // `fn foo(x: &'a u8) -> &'a u8 { x }` + in_band: bool, + // We keep a `Lifetime` around for now just so we can `visit_lifetime`. + lifetime_deprecated: Lifetime, + }, + Type { + name: Name, + bounds: TyParamBounds, + default: Option>, + synthetic: Option, + attrs: HirVec, + } +} + +#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)] +pub struct GenericParam { pub id: NodeId, - pub bounds: TyParamBounds, - pub default: Option>, pub span: Span, pub pure_wrt_drop: bool, - pub synthetic: Option, - pub attrs: HirVec, -} -#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)] -pub enum GenericParam { - Lifetime(LifetimeDef), - Type(TyParam), + pub kind: GenericParamKind, } impl GenericParam { pub fn is_lifetime_param(&self) -> bool { - match *self { - GenericParam::Lifetime(_) => true, + match self.kind { + GenericParamKind::Lifetime { .. } => true, _ => false, } } pub fn is_type_param(&self) -> bool { - match *self { - GenericParam::Type(_) => true, + match self.kind { + GenericParamKind::Type { .. } => true, _ => false, } } -} -pub trait GenericParamsExt { - fn lifetimes<'a>(&'a self) -> iter::FilterMap< - slice::Iter, - fn(&GenericParam) -> Option<&LifetimeDef>, - >; - - fn ty_params<'a>(&'a self) -> iter::FilterMap< - slice::Iter, - fn(&GenericParam) -> Option<&TyParam>, - >; -} - -impl GenericParamsExt for [GenericParam] { - fn lifetimes<'a>(&'a self) -> iter::FilterMap< - slice::Iter, - fn(&GenericParam) -> Option<&LifetimeDef>, - > { - self.iter().filter_map(|param| match *param { - GenericParam::Lifetime(ref l) => Some(l), - _ => None, - }) - } - - fn ty_params<'a>(&'a self) -> iter::FilterMap< - slice::Iter, - fn(&GenericParam) -> Option<&TyParam>, - > { - self.iter().filter_map(|param| match *param { - GenericParam::Type(ref t) => Some(t), - _ => None, - }) + pub fn name(&self) -> Name { + match self.kind { + GenericParamKind::Lifetime { name, .. } => name.name(), + GenericParamKind::Type { name, .. } => name, + } } } @@ -555,54 +541,39 @@ impl Generics { } pub fn is_lt_parameterized(&self) -> bool { - self.params.iter().any(|param| param.is_lifetime_param()) + self.params.iter().any(|param| { + match param.kind { + GenericParamKind::Lifetime { .. } => true, + _ => false, + } + }) } pub fn is_type_parameterized(&self) -> bool { - self.params.iter().any(|param| param.is_type_param()) - } - - pub fn lifetimes<'a>(&'a self) -> impl DoubleEndedIterator { - self.params.lifetimes() - } - - pub fn ty_params<'a>(&'a self) -> impl DoubleEndedIterator { - self.params.ty_params() + self.params.iter().any(|param| { + match param.kind { + GenericParamKind::Type { .. } => true, + _ => false, + } + }) } -} - -pub enum UnsafeGeneric { - Region(LifetimeDef, &'static str), - Type(TyParam, &'static str), -} -impl UnsafeGeneric { - pub fn attr_name(&self) -> &'static str { - match *self { - UnsafeGeneric::Region(_, s) => s, - UnsafeGeneric::Type(_, s) => s, - } + pub fn lifetimes<'a>(&'a self) -> impl DoubleEndedIterator { + self.params.iter().filter(|param| { + match param.kind { + GenericParamKind::Lifetime { .. } => true, + _ => false, + } + }) } -} -impl Generics { - pub fn carries_unsafe_attr(&self) -> Option { - for param in &self.params { - match *param { - GenericParam::Lifetime(ref l) => { - if l.pure_wrt_drop { - return Some(UnsafeGeneric::Region(l.clone(), "may_dangle")); - } - } - GenericParam::Type(ref t) => { - if t.pure_wrt_drop { - return Some(UnsafeGeneric::Type(t.clone(), "may_dangle")); - } - } + pub fn ty_params<'a>(&'a self) -> impl DoubleEndedIterator { + self.params.iter().filter(|param| { + match param.kind { + GenericParamKind::Type { .. } => true, + _ => false, } - } - - None + }) } } diff --git a/src/librustc/hir/print.rs b/src/librustc/hir/print.rs index 5420be64ca43a..afb3a6d0e6c48 100644 --- a/src/librustc/hir/print.rs +++ b/src/librustc/hir/print.rs @@ -25,7 +25,7 @@ use syntax_pos::{self, BytePos, FileName}; use hir; use hir::{PatKind, RegionTyParamBound, TraitTyParamBound, TraitBoundModifier, RangeEnd}; -use hir::GenericArg; +use hir::{GenericParam, GenericParamKind, GenericArg}; use std::cell::Cell; use std::io::{self, Write, Read}; @@ -2094,30 +2094,12 @@ impl<'a> State<'a> { Ok(()) } - pub fn print_lifetime(&mut self, lifetime: &hir::Lifetime) -> io::Result<()> { - self.print_name(lifetime.name.name()) - } - - pub fn print_lifetime_def(&mut self, lifetime: &hir::LifetimeDef) -> io::Result<()> { - self.print_lifetime(&lifetime.lifetime)?; - let mut sep = ":"; - for v in &lifetime.bounds { - self.s.word(sep)?; - self.print_lifetime(v)?; - sep = "+"; - } - Ok(()) - } - - pub fn print_generic_params(&mut self, generic_params: &[hir::GenericParam]) -> io::Result<()> { + pub fn print_generic_params(&mut self, generic_params: &[GenericParam]) -> io::Result<()> { if !generic_params.is_empty() { self.s.word("<")?; self.commasep(Inconsistent, generic_params, |s, param| { - match *param { - hir::GenericParam::Lifetime(ref ld) => s.print_lifetime_def(ld), - hir::GenericParam::Type(ref tp) => s.print_ty_param(tp), - } + s.print_generic_param(param) })?; self.s.word(">")?; @@ -2125,19 +2107,36 @@ impl<'a> State<'a> { Ok(()) } - pub fn print_ty_param(&mut self, param: &hir::TyParam) -> io::Result<()> { - self.print_name(param.name)?; - self.print_bounds(":", ¶m.bounds)?; - match param.default { - Some(ref default) => { - self.s.space()?; - self.word_space("=")?; - self.print_type(&default) + pub fn print_generic_param(&mut self, param: &GenericParam) -> io::Result<()> { + self.print_name(param.name())?; + match param.kind { + GenericParamKind::Lifetime { ref bounds, .. } => { + let mut sep = ":"; + for bound in bounds { + self.s.word(sep)?; + self.print_lifetime(bound)?; + sep = "+"; + } + Ok(()) + } + GenericParamKind::Type { ref bounds, ref default, .. } => { + self.print_bounds(":", bounds)?; + match default { + Some(default) => { + self.s.space()?; + self.word_space("=")?; + self.print_type(&default) + } + _ => Ok(()), + } } - _ => Ok(()), } } + pub fn print_lifetime(&mut self, lifetime: &hir::Lifetime) -> io::Result<()> { + self.print_name(lifetime.name.name()) + } + pub fn print_where_clause(&mut self, where_clause: &hir::WhereClause) -> io::Result<()> { if where_clause.predicates.is_empty() { return Ok(()); diff --git a/src/librustc/ich/impls_hir.rs b/src/librustc/ich/impls_hir.rs index 871e399b4f259..ea12db8681c71 100644 --- a/src/librustc/ich/impls_hir.rs +++ b/src/librustc/ich/impls_hir.rs @@ -161,13 +161,6 @@ impl_stable_hash_for!(struct hir::Lifetime { name }); -impl_stable_hash_for!(struct hir::LifetimeDef { - lifetime, - bounds, - pure_wrt_drop, - in_band -}); - impl_stable_hash_for!(struct hir::Path { span, def, @@ -201,21 +194,36 @@ impl_stable_hash_for!(enum hir::TraitBoundModifier { Maybe }); -impl_stable_hash_for!(struct hir::TyParam { - name, +impl_stable_hash_for!(struct hir::GenericParam { id, - bounds, - default, span, pure_wrt_drop, - synthetic, - attrs + kind }); -impl_stable_hash_for!(enum hir::GenericParam { - Lifetime(lifetime_def), - Type(ty_param) -}); +impl<'a> HashStable> for hir::GenericParamKind { + fn hash_stable(&self, + hcx: &mut StableHashingContext<'a>, + hasher: &mut StableHasher) { + mem::discriminant(self).hash_stable(hcx, hasher); + match self { + hir::GenericParamKind::Lifetime { name, ref bounds, in_band, + ref lifetime_deprecated } => { + name.hash_stable(hcx, hasher); + bounds.hash_stable(hcx, hasher); + in_band.hash_stable(hcx, hasher); + lifetime_deprecated.hash_stable(hcx, hasher); + } + hir::GenericParamKind::Type { name, ref bounds, ref default, synthetic, attrs } => { + name.hash_stable(hcx, hasher); + bounds.hash_stable(hcx, hasher); + default.hash_stable(hcx, hasher); + synthetic.hash_stable(hcx, hasher); + attrs.hash_stable(hcx, hasher); + } + } + } +} impl_stable_hash_for!(struct hir::Generics { params, diff --git a/src/librustc/infer/error_reporting/mod.rs b/src/librustc/infer/error_reporting/mod.rs index 4bde363672dcc..af38e8ba2d492 100644 --- a/src/librustc/infer/error_reporting/mod.rs +++ b/src/librustc/infer/error_reporting/mod.rs @@ -61,7 +61,7 @@ use super::region_constraints::GenericKind; use super::lexical_region_resolve::RegionResolutionError; use std::fmt; -use hir; +use hir::{self, GenericParamKind}; use hir::map as hir_map; use hir::def_id::DefId; use middle::region; @@ -1036,8 +1036,14 @@ impl<'a, 'gcx, 'tcx> InferCtxt<'a, 'gcx, 'tcx> { // Get the `hir::TyParam` to verify whether it already has any bounds. // We do this to avoid suggesting code that ends up as `T: 'a'b`, // instead we suggest `T: 'a + 'b` in that case. - let has_lifetimes = if let hir_map::NodeTyParam(ref p) = hir.get(id) { - p.bounds.len() > 0 + let has_lifetimes = + if let hir_map::NodeGenericParam(ref param) = hir.get(id) { + match param.kind { + GenericParamKind::Type { ref bounds, .. } => { + !bounds.is_empty() + } + _ => bug!("unexpected non-type NodeGenericParam"), + } } else { false }; diff --git a/src/librustc/middle/resolve_lifetime.rs b/src/librustc/middle/resolve_lifetime.rs index 8f1cd9bb30ecd..76680b205355b 100644 --- a/src/librustc/middle/resolve_lifetime.rs +++ b/src/librustc/middle/resolve_lifetime.rs @@ -35,7 +35,7 @@ use syntax_pos::Span; use util::nodemap::{DefIdMap, FxHashMap, FxHashSet, NodeMap, NodeSet}; use hir::intravisit::{self, NestedVisitorMap, Visitor}; -use hir::{self, GenericParamsExt}; +use hir::{self, GenericParamKind}; /// The origin of a named lifetime definition. /// @@ -86,20 +86,30 @@ impl Region { fn early( hir_map: &Map, index: &mut u32, - def: &hir::LifetimeDef, + param: &hir::GenericParam, ) -> (hir::LifetimeName, Region) { let i = *index; *index += 1; - let def_id = hir_map.local_def_id(def.lifetime.id); - let origin = LifetimeDefOrigin::from_is_in_band(def.in_band); + let def_id = hir_map.local_def_id(param.id); + let (name, origin) = match param.kind { + GenericParamKind::Lifetime { name, in_band, .. } => { + (name, LifetimeDefOrigin::from_is_in_band(in_band)) + } + _ => bug!("expected a lifetime param"), + }; debug!("Region::early: index={} def_id={:?}", i, def_id); - (def.lifetime.name, Region::EarlyBound(i, def_id, origin)) + (name, Region::EarlyBound(i, def_id, origin)) } - fn late(hir_map: &Map, def: &hir::LifetimeDef) -> (hir::LifetimeName, Region) { + fn late(hir_map: &Map, param: &hir::GenericParam) -> (hir::LifetimeName, Region) { let depth = ty::INNERMOST; - let def_id = hir_map.local_def_id(def.lifetime.id); - let origin = LifetimeDefOrigin::from_is_in_band(def.in_band); + let def_id = hir_map.local_def_id(param.id); + let (name, origin) = match param.kind { + GenericParamKind::Lifetime { name, in_band, .. } => { + (name, LifetimeDefOrigin::from_is_in_band(in_band)) + } + _ => bug!("expected a lifetime param"), + }; debug!( "Region::late: def={:?} depth={:?} def_id={:?} origin={:?}", def, @@ -107,7 +117,7 @@ impl Region { def_id, origin, ); - (def.lifetime.name, Region::LateBound(depth, def_id, origin)) + (name, Region::LateBound(depth, def_id, origin)) } fn late_anon(index: &Cell) -> Region { @@ -567,9 +577,16 @@ impl<'a, 'tcx> Visitor<'tcx> for LifetimeContext<'a, 'tcx> { self.is_in_fn_syntax = true; let scope = Scope::Binder { lifetimes: c.generic_params - .lifetimes() - .map(|def| Region::late(&self.tcx.hir, def)) - .collect(), + .iter() + .filter_map(|param| { + match param.kind { + GenericParamKind::Lifetime { .. } => { + Some(Region::late(&self.tcx.hir, param)) + } + _ => None, + } + }) + .collect(), s: self.scope, next_early_index, track_lifetime_uses: true, @@ -850,10 +867,15 @@ impl<'a, 'tcx> Visitor<'tcx> for LifetimeContext<'a, 'tcx> { self.tcx, &generics.lifetimes().cloned().collect::>(), ); - for ty_param in generics.ty_params() { - walk_list!(self, visit_ty_param_bound, &ty_param.bounds); - if let Some(ref ty) = ty_param.default { - self.visit_ty(&ty); + for param in &generics.params { + match param.kind { + GenericParamKind::Lifetime { .. } => {} + GenericParamKind::Type { ref bounds, ref default, .. } => { + walk_list!(self, visit_ty_param_bound, bounds); + if let Some(ref ty) = default { + self.visit_ty(&ty); + } + } } } for predicate in &generics.where_clause.predicates { @@ -869,8 +891,15 @@ impl<'a, 'tcx> Visitor<'tcx> for LifetimeContext<'a, 'tcx> { let next_early_index = self.next_early_index(); let scope = Scope::Binder { lifetimes: bound_generic_params - .lifetimes() - .map(|def| Region::late(&self.tcx.hir, def)) + .iter() + .filter_map(|param| { + match param.kind { + GenericParamKind::Lifetime { .. } => { + Some(Region::late(&self.tcx.hir, param)) + } + _ => None, + } + }) .collect(), s: self.scope, next_early_index, @@ -936,8 +965,15 @@ impl<'a, 'tcx> Visitor<'tcx> for LifetimeContext<'a, 'tcx> { let scope = Scope::Binder { lifetimes: trait_ref .bound_generic_params - .lifetimes() - .map(|def| Region::late(&self.tcx.hir, def)) + .iter() + .filter_map(|param| { + match param.kind { + GenericParamKind::Lifetime { .. } => { + Some(Region::late(&self.tcx.hir, param)) + } + _ => None, + } + }) .collect(), s: self.scope, next_early_index, @@ -987,10 +1023,10 @@ fn original_lifetime(span: Span) -> Original { span: span, } } -fn shadower_lifetime(l: &hir::Lifetime) -> Shadower { +fn shadower_lifetime(param: &hir::GenericParam) -> Shadower { Shadower { kind: ShadowKind::Lifetime, - span: l.span, + span: param.span, } } @@ -1005,23 +1041,29 @@ impl ShadowKind { fn check_mixed_explicit_and_in_band_defs( tcx: TyCtxt<'_, '_, '_>, - lifetime_defs: &[hir::LifetimeDef], + params: &[hir::GenericParam], ) { - let oob_def = lifetime_defs.iter().find(|lt| !lt.in_band); - let in_band_def = lifetime_defs.iter().find(|lt| lt.in_band); + let in_bands: Vec<_> = params.iter().map(|param| { + match param.kind { + GenericParamKind::Lifetime { in_band, .. } => (in_band, param.span), + _ => bug!("expected lifetime param"), + } + }).collect(); + let out_of_band = in_bands.iter().find(|(in_band, _)| !in_band); + let in_band = in_bands.iter().find(|(in_band, _)| *in_band); - if let (Some(oob_def), Some(in_band_def)) = (oob_def, in_band_def) { + if let (Some((_, out_of_band_span)), Some((_, in_band_span))) + = (out_of_band, in_band) { struct_span_err!( tcx.sess, - in_band_def.lifetime.span, + *in_band_span, E0688, "cannot mix in-band and explicit lifetime definitions" ).span_label( - in_band_def.lifetime.span, + *in_band_span, "in-band lifetime definition here", - ) - .span_label(oob_def.lifetime.span, "explicit lifetime definition here") - .emit(); + ).span_label(*out_of_band_span, "explicit lifetime definition here") + .emit(); } } @@ -1178,8 +1220,6 @@ fn compute_object_lifetime_defaults( .lifetimes() .nth(i as usize) .unwrap() - .lifetime - .name .name() .to_string(), Set1::One(_) => bug!(), @@ -1213,58 +1253,67 @@ fn object_lifetime_defaults_for_item( } } - generics - .ty_params() - .map(|param| { - let mut set = Set1::Empty; + generics.params.iter().filter_map(|param| { + match param.kind { + GenericParamKind::Lifetime { .. } => None, + GenericParamKind::Type { ref bounds, .. } => { + let mut set = Set1::Empty; - add_bounds(&mut set, ¶m.bounds); + add_bounds(&mut set, &bounds); - 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 { - hir::WherePredicate::BoundPredicate(ref data) => data, - _ => continue, - }; + 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 { + 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_generic_params.is_empty() { - continue; - } + // Ignore `for<'a> type: ...` as they can change what + // lifetimes mean (although we could "just" handle it). + if !data.bound_generic_params.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() + Some(match set { + Set1::Empty => Set1::Empty, + Set1::One(name) => { + if name == hir::LifetimeName::Static { + Set1::One(Region::Static) + } else { + generics.params.iter().filter_map(|param| { + match param.kind { + GenericParamKind::Lifetime { name, in_band, .. } => { + Some((param.id, name, in_band)) + } + _ => None, + } + }) .enumerate() - .find(|&(_, def)| def.lifetime.name == name) - .map_or(Set1::Many, |(i, def)| { - let def_id = tcx.hir.local_def_id(def.lifetime.id); - let origin = LifetimeDefOrigin::from_is_in_band(def.in_band); + .find(|&(_, (_, lt_name, _))| lt_name == name) + .map_or(Set1::Many, |(i, (id, _, in_band))| { + let def_id = tcx.hir.local_def_id(id); + let origin = LifetimeDefOrigin::from_is_in_band(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> { @@ -1438,11 +1487,11 @@ impl<'a, 'tcx> LifetimeContext<'a, 'tcx> { let lifetimes = generics .lifetimes() - .map(|def| { - if self.map.late_bound.contains(&def.lifetime.id) { - Region::late(&self.tcx.hir, def) + .map(|param| { + if self.map.late_bound.contains(¶m.id) { + Region::late(&self.tcx.hir, param) } else { - Region::early(&self.tcx.hir, &mut index, def) + Region::early(&self.tcx.hir, &mut index, param) } }) .collect(); @@ -1943,7 +1992,7 @@ impl<'a, 'tcx> LifetimeContext<'a, 'tcx> { } fn visit_generic_param(&mut self, param: &hir::GenericParam) { - if let hir::GenericParam::Lifetime(_) = *param { + if let hir::GenericParamKind::Lifetime { .. } = param.kind { // FIXME(eddyb) Do we want this? It only makes a difference // if this `for<'a>` lifetime parameter is never used. self.have_bound_regions = true; @@ -2160,20 +2209,26 @@ impl<'a, 'tcx> LifetimeContext<'a, 'tcx> { } fn check_lifetime_params(&mut self, old_scope: ScopeRef, params: &'tcx [hir::GenericParam]) { - for (i, lifetime_i) in params.lifetimes().enumerate() { - match lifetime_i.lifetime.name { + let lifetimes: Vec<_> = params.iter().filter_map(|param| { + match param.kind { + GenericParamKind::Lifetime { name, .. } => Some((param, name)), + _ => None, + } + }).collect(); + for (i, (lifetime_i, lifetime_i_name)) in lifetimes.iter().enumerate() { + match lifetime_i_name { hir::LifetimeName::Static | hir::LifetimeName::Underscore => { let lifetime = lifetime_i.lifetime; - let name = lifetime.name.name(); + let name = lifetime_i.name(); let mut err = struct_span_err!( self.tcx.sess, - lifetime.span, + lifetime_i.span, E0262, "invalid lifetime parameter name: `{}`", name ); err.span_label( - lifetime.span, + lifetime_i.span, format!("{} is a reserved lifetime name", name), ); err.emit(); @@ -2184,24 +2239,28 @@ impl<'a, 'tcx> LifetimeContext<'a, 'tcx> { } // It is a hard error to shadow a lifetime within the same scope. - for lifetime_j in params.lifetimes().skip(i + 1) { - if lifetime_i.lifetime.name == lifetime_j.lifetime.name { + for (lifetime_j, lifetime_j_name) in lifetimes.iter().skip(i + 1) { + if lifetime_i_name == lifetime_j_name { struct_span_err!( self.tcx.sess, - lifetime_j.lifetime.span, + lifetime_j.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") + lifetime_j.name() + ).span_label(lifetime_j.span, "declared twice") + .span_label(lifetime_i.span, "previous declaration here") .emit(); } } // It is a soft error to shadow a lifetime within a parent scope. - self.check_lifetime_def_for_shadowing(old_scope, &lifetime_i.lifetime); + self.check_lifetime_param_for_shadowing(old_scope, &lifetime_i); - for bound in &lifetime_i.bounds { + let bounds = match lifetime_i.kind { + GenericParamKind::Lifetime { ref bounds, .. } => bounds, + _ => bug!(), + }; + for bound in bounds { match bound.name { hir::LifetimeName::Underscore => { let mut err = struct_span_err!( @@ -2218,16 +2277,16 @@ impl<'a, 'tcx> LifetimeContext<'a, 'tcx> { self.tcx .sess .struct_span_warn( - lifetime_i.lifetime.span.to(bound.span), + lifetime_i.span.to(bound.span), &format!( "unnecessary lifetime parameter `{}`", - lifetime_i.lifetime.name.name() + lifetime_i.name() ), ) .help(&format!( "you can use the `'static` lifetime directly, in place \ of `{}`", - lifetime_i.lifetime.name.name() + lifetime_i.name() )) .emit(); } @@ -2241,24 +2300,29 @@ impl<'a, 'tcx> LifetimeContext<'a, 'tcx> { } } - fn check_lifetime_def_for_shadowing( + fn check_lifetime_param_for_shadowing( &self, mut old_scope: ScopeRef, - lifetime: &'tcx hir::Lifetime, + param: &'tcx hir::GenericParam, ) { for &(label, label_span) in &self.labels_in_fn { // FIXME (#24278): non-hygienic comparison - if lifetime.name.name() == label { + if param.name() == label { signal_shadowing_problem( self.tcx, label, original_label(label_span), - shadower_lifetime(&lifetime), + shadower_lifetime(¶m), ); return; } } + let name = match param.kind { + GenericParamKind::Lifetime { name, .. } => name, + _ => bug!("expected lifetime param"), + }; + loop { match *old_scope { Scope::Body { s, .. } @@ -2274,14 +2338,14 @@ impl<'a, 'tcx> LifetimeContext<'a, 'tcx> { Scope::Binder { ref lifetimes, s, .. } => { - if let Some(&def) = lifetimes.get(&lifetime.name) { + if let Some(&def) = lifetimes.get(&name) { let node_id = self.tcx.hir.as_local_node_id(def.id().unwrap()).unwrap(); signal_shadowing_problem( self.tcx, - lifetime.name.name(), + param.name(), original_lifetime(self.tcx.hir.span(node_id)), - shadower_lifetime(&lifetime), + shadower_lifetime(¶m), ); return; } @@ -2429,14 +2493,14 @@ fn insert_late_bound_lifetimes( appears_in_where_clause.visit_generics(generics); for param in &generics.params { - match *param { - hir::GenericParam::Lifetime(ref lifetime_def) => { - if !lifetime_def.bounds.is_empty() { + match param.kind { + hir::GenericParamKind::Lifetime { ref bounds, .. } => { + if !bounds.is_empty() { // `'a: 'b` means both `'a` and `'b` are referenced appears_in_where_clause.regions.insert(lifetime_def.lifetime.name); } } - hir::GenericParam::Type(_) => {} + hir::GenericParamKind::Type { .. } => {} } } @@ -2450,7 +2514,10 @@ fn insert_late_bound_lifetimes( // - do not appear in the where-clauses // - are not implicitly captured by `impl Trait` for lifetime in generics.lifetimes() { - let name = lifetime.lifetime.name; + let name = match lifetime.kind { + GenericParamKind::Lifetime { name, .. } => name, + _ => bug!(), + }; // appears in the where clauses? early-bound. if appears_in_where_clause.regions.contains(&name) { @@ -2464,18 +2531,12 @@ fn insert_late_bound_lifetimes( 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", + name, + lifetime.id); - let inserted = map.late_bound.insert(lifetime.lifetime.id); - assert!( - inserted, - "visited lifetime {:?} twice", - lifetime.lifetime.id - ); + let inserted = map.late_bound.insert(lifetime.id); + assert!(inserted, "visited lifetime {:?} twice", lifetime.id); } return; diff --git a/src/librustc_lint/bad_style.rs b/src/librustc_lint/bad_style.rs index dbf756f80ca38..f456ab3679988 100644 --- a/src/librustc_lint/bad_style.rs +++ b/src/librustc_lint/bad_style.rs @@ -18,7 +18,7 @@ use syntax::ast; use syntax::attr; use syntax_pos::Span; -use rustc::hir::{self, PatKind}; +use rustc::hir::{self, GenericParamKind, PatKind}; use rustc::hir::intravisit::FnKind; #[derive(PartialEq)] @@ -147,9 +147,12 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for NonCamelCaseTypes { } fn check_generic_param(&mut self, cx: &LateContext, param: &hir::GenericParam) { - if let hir::GenericParam::Type(ref gen) = *param { - if gen.synthetic.is_none() { - self.check_case(cx, "type parameter", gen.name, gen.span); + match param.kind { + GenericParamKind::Lifetime { .. } => {} + GenericParamKind::Type { synthetic, .. } => { + if synthetic.is_none() { + self.check_case(cx, "type parameter", param.name(), param.span); + } } } } @@ -253,13 +256,11 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for NonSnakeCase { } fn check_generic_param(&mut self, cx: &LateContext, param: &hir::GenericParam) { - if let hir::GenericParam::Lifetime(ref ld) = *param { - self.check_snake_case( - cx, - "lifetime", - &ld.lifetime.name.name().as_str(), - Some(ld.lifetime.span) - ); + match param.kind { + GenericParamKind::Lifetime { .. } => { + self.check_snake_case(cx, "lifetime", ¶m.name().as_str(), Some(param.span)); + } + GenericParamKind::Type { .. } => {} } } diff --git a/src/librustc_lint/builtin.rs b/src/librustc_lint/builtin.rs index 79796d788719a..b981d075d5344 100644 --- a/src/librustc_lint/builtin.rs +++ b/src/librustc_lint/builtin.rs @@ -49,7 +49,7 @@ use syntax_pos::{BytePos, Span, SyntaxContext}; use syntax::symbol::keywords; use syntax::errors::{Applicability, DiagnosticBuilder}; -use rustc::hir::{self, PatKind}; +use rustc::hir::{self, GenericParamKind, PatKind}; use rustc::hir::intravisit::FnKind; use bad_style::{MethodLateContext, method_context}; @@ -1531,9 +1531,13 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for TypeAliasBounds { } // The parameters must not have bounds for param in type_alias_generics.params.iter() { - let spans : Vec<_> = match param { - &hir::GenericParam::Lifetime(ref l) => l.bounds.iter().map(|b| b.span).collect(), - &hir::GenericParam::Type(ref ty) => ty.bounds.iter().map(|b| b.span()).collect(), + let spans: Vec<_> = match param.kind { + GenericParamKind::Lifetime { ref bounds, .. } => { + bounds.iter().map(|b| b.span).collect() + } + GenericParamKind::Type { ref bounds, .. } => { + bounds.iter().map(|b| b.span()).collect() + } }; if !spans.is_empty() { let mut err = cx.struct_span_lint( diff --git a/src/librustc_metadata/encoder.rs b/src/librustc_metadata/encoder.rs index 33d4df1c3a5dc..c1a22c353c7a8 100644 --- a/src/librustc_metadata/encoder.rs +++ b/src/librustc_metadata/encoder.rs @@ -1645,10 +1645,17 @@ impl<'a, 'b, 'tcx> IndexBuilder<'a, 'b, 'tcx> { } fn encode_info_for_generics(&mut self, generics: &hir::Generics) { - for ty_param in generics.ty_params() { - let def_id = self.tcx.hir.local_def_id(ty_param.id); - let has_default = Untracked(ty_param.default.is_some()); - self.record(def_id, IsolatedEncoder::encode_info_for_ty_param, (def_id, has_default)); + for param in &generics.params { + match param.kind { + hir::GenericParamKind::Lifetime { .. } => {} + hir::GenericParamKind::Type { ref default, .. } => { + let def_id = self.tcx.hir.local_def_id(param.id); + let has_default = Untracked(default.is_some()); + self.record(def_id, + IsolatedEncoder::encode_info_for_ty_param, + (def_id, has_default)); + } + } } } diff --git a/src/librustc_privacy/lib.rs b/src/librustc_privacy/lib.rs index 291092015b57f..19ed04a796843 100644 --- a/src/librustc_privacy/lib.rs +++ b/src/librustc_privacy/lib.rs @@ -22,7 +22,7 @@ extern crate rustc_typeck; extern crate syntax_pos; extern crate rustc_data_structures; -use rustc::hir::{self, PatKind}; +use rustc::hir::{self, GenericParamKind, PatKind}; use rustc::hir::def::Def; use rustc::hir::def_id::{CRATE_DEF_INDEX, LOCAL_CRATE, CrateNum, DefId}; use rustc::hir::intravisit::{self, Visitor, NestedVisitorMap}; @@ -1268,9 +1268,14 @@ impl<'a, 'tcx> Visitor<'tcx> for ObsoleteVisiblePrivateTypesVisitor<'a, 'tcx> { } fn visit_generics(&mut self, generics: &'tcx hir::Generics) { - for ty_param in generics.ty_params() { - for bound in ty_param.bounds.iter() { - self.check_ty_param_bound(bound) + for param in &generics.params { + match param.kind { + GenericParamKind::Lifetime { .. } => {} + GenericParamKind::Type { ref bounds, .. } => { + for bound in bounds { + self.check_ty_param_bound(bound); + } + } } } for predicate in &generics.where_clause.predicates { diff --git a/src/librustc_typeck/check/compare_method.rs b/src/librustc_typeck/check/compare_method.rs index 808c134e99448..f573ad7ef2753 100644 --- a/src/librustc_typeck/check/compare_method.rs +++ b/src/librustc_typeck/check/compare_method.rs @@ -8,7 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -use rustc::hir::{self, ImplItemKind, TraitItemKind}; +use rustc::hir::{self, GenericParamKind, ImplItemKind, TraitItemKind}; use rustc::infer::{self, InferOk}; use rustc::ty::{self, TyCtxt, GenericParamDefKind}; use rustc::ty::util::ExplicitSelf; @@ -843,19 +843,19 @@ fn compare_synthetic_generics<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, } let span = visitor.0?; - let param = impl_m.generics.params.iter().filter_map(|param| { - match param { - hir::GenericParam::Type(param) => { + let bounds = impl_m.generics.params.iter().find_map(|param| { + match param.kind { + GenericParamKind::Lifetime { .. } => None, + GenericParamKind::Type { ref bounds, .. } => { if param.id == impl_node_id { - Some(param) + Some(bounds) } else { None } - }, - hir::GenericParam::Lifetime(..) => None, + } } - }).next()?; - let bounds = param.bounds.first()?.span().to(param.bounds.last()?.span()); + })?; + let bounds = bounds.first()?.span().to(bounds.last()?.span()); let bounds = tcx .sess .codemap() diff --git a/src/librustc_typeck/check/mod.rs b/src/librustc_typeck/check/mod.rs index c0779235e8939..0066e3ce84669 100644 --- a/src/librustc_typeck/check/mod.rs +++ b/src/librustc_typeck/check/mod.rs @@ -5188,9 +5188,8 @@ pub fn check_bounds_are_used<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, for (&used, param) in tps_used.iter().zip(generics.ty_params()) { if !used { - struct_span_err!(tcx.sess, param.span, E0091, - "type parameter `{}` is unused", - param.name) + struct_span_err!(tcx.sess, param.span, E0091, "type parameter `{}` is unused", + param.name()) .span_label(param.span, "unused type parameter") .emit(); } diff --git a/src/librustc_typeck/check/wfcheck.rs b/src/librustc_typeck/check/wfcheck.rs index 7a2c38468e044..8d2c1e07ec8e0 100644 --- a/src/librustc_typeck/check/wfcheck.rs +++ b/src/librustc_typeck/check/wfcheck.rs @@ -631,11 +631,8 @@ fn check_variances_for_type_defn<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, continue; } - let (span, name) = match ast_generics.params[index] { - hir::GenericParam::Lifetime(ref ld) => (ld.lifetime.span, ld.lifetime.name.name()), - hir::GenericParam::Type(ref tp) => (tp.span, tp.name), - }; - report_bivariance(tcx, span, name); + let param = &ast_generics.params[index]; + report_bivariance(tcx, param.span, param.name()); } } diff --git a/src/librustc_typeck/coherence/unsafety.rs b/src/librustc_typeck/coherence/unsafety.rs index 4aa876e85b69a..007ef4dee559c 100644 --- a/src/librustc_typeck/coherence/unsafety.rs +++ b/src/librustc_typeck/coherence/unsafety.rs @@ -35,7 +35,14 @@ impl<'cx, 'tcx, 'v> UnsafetyChecker<'cx, 'tcx> { Some(trait_ref) => { let trait_def = self.tcx.trait_def(trait_ref.def_id); - let unsafe_attr = impl_generics.and_then(|g| g.carries_unsafe_attr()); + let unsafe_attr = impl_generics.and_then(|g| { + for param in &g.params { + if param.pure_wrt_drop { + return Some("may_dangle"); + } + } + None + }); match (trait_def.unsafety, unsafe_attr, unsafety, polarity) { (Unsafety::Normal, None, Unsafety::Unsafe, hir::ImplPolarity::Positive) => { span_err!(self.tcx.sess, @@ -53,13 +60,14 @@ impl<'cx, 'tcx, 'v> UnsafetyChecker<'cx, 'tcx> { trait_ref); } - (Unsafety::Normal, Some(g), Unsafety::Normal, hir::ImplPolarity::Positive) => + (Unsafety::Normal, Some(attr_name), Unsafety::Normal, + hir::ImplPolarity::Positive) => { span_err!(self.tcx.sess, item.span, E0569, "requires an `unsafe impl` declaration due to `#[{}]` attribute", - g.attr_name()); + attr_name); } (_, _, Unsafety::Unsafe, hir::ImplPolarity::Negative) => { diff --git a/src/librustc_typeck/collect.rs b/src/librustc_typeck/collect.rs index 58e804fc13f2d..36436d95e9f17 100644 --- a/src/librustc_typeck/collect.rs +++ b/src/librustc_typeck/collect.rs @@ -49,6 +49,7 @@ use syntax::feature_gate; 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_id::{DefId, LOCAL_CRATE}; @@ -113,10 +114,15 @@ impl<'a, 'tcx> Visitor<'tcx> for CollectItemTypesVisitor<'a, 'tcx> { } fn visit_generics(&mut self, generics: &'tcx hir::Generics) { - for param in generics.ty_params() { - if param.default.is_some() { - let def_id = self.tcx.hir.local_def_id(param.id); - self.tcx.type_of(def_id); + for param in &generics.params { + match param.kind { + hir::GenericParamKind::Lifetime { .. } => {} + hir::GenericParamKind::Type { ref default, .. } => { + if default.is_some() { + let def_id = self.tcx.hir.local_def_id(param.id); + self.tcx.type_of(def_id); + } + } } } intravisit::walk_generics(self, generics); @@ -308,9 +314,20 @@ impl<'a, 'tcx> ItemCtxt<'a, 'tcx> { -> Vec> { let from_ty_params = - ast_generics.ty_params() - .filter(|p| p.id == param_id) - .flat_map(|p| p.bounds.iter()) + ast_generics.params.iter() + .filter_map(|param| { + match param.kind { + GenericParamKind::Type { ref bounds, .. } => { + if param.id == param_id { + Some(bounds) + } else { + None + } + } + _ => None + } + }) + .flat_map(|bounds| bounds.iter()) .flat_map(|b| predicates_from_bound(self, ty, b)); let from_where_clauses = @@ -740,9 +757,9 @@ fn has_late_bound_regions<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, has_late_bound_regions: None, }; for lifetime in generics.lifetimes() { - let hir_id = tcx.hir.node_to_hir_id(lifetime.lifetime.id); + let hir_id = tcx.hir.node_to_hir_id(lifetime.id); if tcx.is_late_bound(hir_id) { - return Some(lifetime.lifetime.span); + return Some(lifetime.span); } } visitor.visit_fn_decl(decl); @@ -883,12 +900,12 @@ 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, l)| { + params.extend(early_lifetimes.enumerate().map(|(i, param)| { ty::GenericParamDef { - name: l.lifetime.name.name().as_interned_str(), + name: param.name().as_interned_str(), index: own_start + i as u32, - def_id: tcx.hir.local_def_id(l.lifetime.id), - pure_wrt_drop: l.pure_wrt_drop, + def_id: tcx.hir.local_def_id(param.id), + pure_wrt_drop: param.pure_wrt_drop, kind: ty::GenericParamDefKind::Lifetime, } })); @@ -898,33 +915,39 @@ 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; - params.extend(ast_generics.ty_params().enumerate().map(|(i, p)| { - if p.name == keywords::SelfType.name() { - span_bug!(p.span, "`Self` should not be the name of a regular parameter"); - } - - if !allow_defaults && p.default.is_some() { - if !tcx.features().default_type_parameter_fallback { - tcx.lint_node( - lint::builtin::INVALID_TYPE_PARAM_DEFAULT, - p.id, - p.span, - &format!("defaults for type parameters are only allowed in `struct`, \ - `enum`, `type`, or `trait` definitions.")); - } - } + params.extend(ast_generics.ty_params().enumerate().map(|(i, param)| { + match param.kind { + GenericParamKind::Type { ref default, synthetic, .. } => { + if param.name() == keywords::SelfType.name() { + span_bug!(param.span, + "`Self` should not be the name of a regular parameter"); + } - ty::GenericParamDef { - index: type_start + i as u32, - name: p.name.as_interned_str(), - def_id: tcx.hir.local_def_id(p.id), - pure_wrt_drop: p.pure_wrt_drop, - kind: ty::GenericParamDefKind::Type { - has_default: p.default.is_some(), - object_lifetime_default: - object_lifetime_defaults.as_ref().map_or(rl::Set1::Empty, |o| o[i]), - synthetic: p.synthetic, - }, + 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.")); + } + } + + ty::GenericParamDef { + index: type_start + i as u32, + name: param.name().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, + }, + } + } + _ => bug!() } })); @@ -1119,8 +1142,13 @@ fn type_of<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, } }, - NodeTyParam(&hir::TyParam { default: Some(ref ty), .. }) => { - icx.to_ty(ty) + NodeGenericParam(param) => { + match param.kind { + hir::GenericParamKind::Type { default: Some(ref ty), .. } => { + icx.to_ty(ty) + } + _ => bug!("unexpected non-type NodeGenericParam"), + } } x => { @@ -1274,15 +1302,18 @@ fn is_unsized<'gcx: 'tcx, 'tcx>(astconv: &AstConv<'gcx, 'tcx>, /// `resolve_lifetime::early_bound_lifetimes`. fn early_bound_lifetimes_from_generics<'a, 'tcx>( tcx: TyCtxt<'a, 'tcx, 'tcx>, - ast_generics: &'a hir::Generics) - -> impl Iterator + Captures<'tcx> + generics: &'a hir::Generics) + -> impl Iterator + Captures<'tcx> { - ast_generics - .lifetimes() - .filter(move |l| { - let hir_id = tcx.hir.node_to_hir_id(l.lifetime.id); - !tcx.is_late_bound(hir_id) - }) + 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_of<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, @@ -1410,28 +1441,38 @@ pub fn explicit_predicates_of<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, let mut index = parent_count + has_own_self as u32; for param in early_bound_lifetimes_from_generics(tcx, ast_generics) { let region = tcx.mk_region(ty::ReEarlyBound(ty::EarlyBoundRegion { - def_id: tcx.hir.local_def_id(param.lifetime.id), + def_id: tcx.hir.local_def_id(param.id), index, - name: param.lifetime.name.name().as_interned_str(), + name: param.name().as_interned_str(), })); index += 1; - for bound in ¶m.bounds { - let bound_region = AstConv::ast_region_to_region(&icx, bound, None); - let outlives = ty::Binder::bind(ty::OutlivesPredicate(region, bound_region)); - predicates.push(outlives.to_predicate()); + match param.kind { + GenericParamKind::Lifetime { ref bounds, .. } => { + for bound in bounds { + let bound_region = AstConv::ast_region_to_region(&icx, bound, None); + let outlives = + ty::Binder::bind(ty::OutlivesPredicate(region, bound_region)); + predicates.push(outlives.to_predicate()); + } + }, + _ => bug!(), } } // Collect the predicates that were written inline by the user on each // type parameter (e.g., ``). for param in ast_generics.ty_params() { - let param_ty = ty::ParamTy::new(index, param.name.as_interned_str()).to_ty(tcx); + let param_ty = ty::ParamTy::new(index, param.name().as_interned_str()).to_ty(tcx); index += 1; + let bounds = match param.kind { + GenericParamKind::Type { ref bounds, .. } => bounds, + _ => bug!(), + }; let bounds = compute_bounds(&icx, param_ty, - ¶m.bounds, + bounds, SizedByDefault::Yes, param.span); predicates.extend(bounds.predicates(tcx, param_ty)); diff --git a/src/librustc_typeck/lib.rs b/src/librustc_typeck/lib.rs index 80f57adf580bf..fb005ba18e9f8 100644 --- a/src/librustc_typeck/lib.rs +++ b/src/librustc_typeck/lib.rs @@ -76,6 +76,7 @@ This API is completely unstable and subject to change. #![feature(crate_visibility_modifier)] #![feature(from_ref)] #![feature(exhaustive_patterns)] +#![feature(iterator_find_map)] #![feature(quote)] #![feature(refcell_replace_swap)] #![feature(rustc_diagnostic_macros)] diff --git a/src/librustdoc/clean/mod.rs b/src/librustdoc/clean/mod.rs index 0d44c583cffd4..40fdd6d8d2de7 100644 --- a/src/librustdoc/clean/mod.rs +++ b/src/librustdoc/clean/mod.rs @@ -1466,14 +1466,19 @@ pub struct TyParam { pub synthetic: Option, } -impl Clean for hir::TyParam { +impl Clean for hir::GenericParam { fn clean(&self, cx: &DocContext) -> TyParam { - TyParam { - name: self.name.clean(cx), - did: cx.tcx.hir.local_def_id(self.id), - bounds: self.bounds.clean(cx), - default: self.default.clean(cx), - synthetic: self.synthetic, + match self.kind { + hir::GenericParamKind::Type { ref bounds, ref default, synthetic, .. } => { + TyParam { + name: self.name().clean(cx), + did: cx.tcx.hir.local_def_id(self.id), + bounds: bounds.clean(cx), + default: default.clean(cx), + synthetic: synthetic, + } + } + _ => panic!(), } } } @@ -1707,18 +1712,21 @@ impl Clean for hir::Lifetime { } } -impl Clean for hir::LifetimeDef { +impl Clean for hir::GenericParam { fn clean(&self, _: &DocContext) -> Lifetime { - if self.bounds.len() > 0 { - let mut s = format!("{}: {}", - self.lifetime.name.name(), - self.bounds[0].name.name()); - for bound in self.bounds.iter().skip(1) { - s.push_str(&format!(" + {}", bound.name.name())); + match self.kind { + hir::GenericParamKind::Lifetime { ref bounds, .. } => { + if bounds.len() > 0 { + let mut s = format!("{}: {}", self.name(), bounds[0].name.name()); + for bound in bounds.iter().skip(1) { + s.push_str(&format!(" + {}", bound.name.name())); + } + Lifetime(s) + } else { + Lifetime(self.name().to_string()) + } } - Lifetime(s) - } else { - Lifetime(self.lifetime.name.name().to_string()) + _ => panic!(), } } } @@ -1880,9 +1888,11 @@ impl GenericParamDef { impl Clean for hir::GenericParam { fn clean(&self, cx: &DocContext) -> GenericParamDef { - match *self { - hir::GenericParam::Lifetime(ref l) => GenericParamDef::Lifetime(l.clean(cx)), - hir::GenericParam::Type(ref t) => GenericParamDef::Type(t.clean(cx)), + match self.kind { + hir::GenericParamKind::Lifetime { .. } => { + GenericParamDef::Lifetime(self.clean(cx)) + } + hir::GenericParamKind::Type { .. } => GenericParamDef::Type(self.clean(cx)), } } } @@ -1900,10 +1910,11 @@ impl Clean for hir::Generics { // In order for normal parameters to be able to refer to synthetic ones, // scans them first. fn is_impl_trait(param: &hir::GenericParam) -> bool { - if let hir::GenericParam::Type(ref tp) = param { - tp.synthetic == Some(hir::SyntheticTyParamKind::ImplTrait) - } else { - false + match param.kind { + hir::GenericParamKind::Type { synthetic, .. } => { + synthetic == Some(hir::SyntheticTyParamKind::ImplTrait) + } + _ => false, } } let impl_trait_params = self.params @@ -2857,25 +2868,25 @@ impl Clean for hir::Ty { types: 0 }; for param in generics.params.iter() { - match param { - hir::GenericParam::Lifetime(lt_param) => { + match param.kind { + hir::GenericParamKind::Lifetime { .. } => { if let Some(lt) = generic_args.lifetimes() .nth(indices.lifetimes).cloned() { if !lt.is_elided() { let lt_def_id = - cx.tcx.hir.local_def_id(lt_param.lifetime.id); + cx.tcx.hir.local_def_id(param.id); lt_substs.insert(lt_def_id, lt.clean(cx)); } } indices.lifetimes += 1; } - hir::GenericParam::Type(ty_param) => { + hir::GenericParamKind::Type { ref default, .. } => { let ty_param_def = - Def::TyParam(cx.tcx.hir.local_def_id(ty_param.id)); + Def::TyParam(cx.tcx.hir.local_def_id(param.id)); if let Some(ty) = generic_args.types() .nth(indices.types).cloned() { ty_substs.insert(ty_param_def, ty.into_inner().clean(cx)); - } else if let Some(default) = ty_param.default.clone() { + } else if let Some(default) = default.clone() { ty_substs.insert(ty_param_def, default.into_inner().clean(cx)); } diff --git a/src/libsyntax/visit.rs b/src/libsyntax/visit.rs index 8a4fde21e63f7..091673bfba996 100644 --- a/src/libsyntax/visit.rs +++ b/src/libsyntax/visit.rs @@ -73,7 +73,9 @@ pub trait Visitor<'ast>: Sized { fn visit_expr(&mut self, ex: &'ast Expr) { walk_expr(self, ex) } fn visit_expr_post(&mut self, _ex: &'ast Expr) { } fn visit_ty(&mut self, t: &'ast Ty) { walk_ty(self, t) } - fn visit_generic_param(&mut self, param: &'ast GenericParamAST) { walk_generic_param(self, param) } + fn visit_generic_param(&mut self, param: &'ast GenericParamAST) { + walk_generic_param(self, param) + } fn visit_generics(&mut self, g: &'ast Generics) { walk_generics(self, g) } fn visit_where_predicate(&mut self, p: &'ast WherePredicate) { walk_where_predicate(self, p) diff --git a/src/libsyntax_ext/deriving/generic/mod.rs b/src/libsyntax_ext/deriving/generic/mod.rs index f85091b0e719d..4bc8d208bab91 100644 --- a/src/libsyntax_ext/deriving/generic/mod.rs +++ b/src/libsyntax_ext/deriving/generic/mod.rs @@ -568,7 +568,8 @@ impl<'a> TraitDef<'a> { bounds.push((*declared_bound).clone()); } - GenericParamAST::Type(cx.typaram(self.span, ty_param.ident, vec![], bounds, None)) + let ty_param = cx.typaram(self.span, ty_param.ident, vec![], bounds, None); + GenericParamAST::Type(ty_param) } } })); diff --git a/src/libsyntax_ext/deriving/generic/ty.rs b/src/libsyntax_ext/deriving/generic/ty.rs index 92046262ed253..22487e7bfe398 100644 --- a/src/libsyntax_ext/deriving/generic/ty.rs +++ b/src/libsyntax_ext/deriving/generic/ty.rs @@ -192,7 +192,9 @@ impl<'a> Ty<'a> { let ty_params: Vec> = self_generics.params .iter() .filter_map(|param| match *param { - GenericParamAST::Type(ref ty_param) => Some(cx.ty_ident(span, ty_param.ident)), + GenericParamAST::Type(ref ty_param) => { + Some(cx.ty_ident(span, ty_param.ident)) + } _ => None, }) .collect(); @@ -280,7 +282,8 @@ impl<'a> LifetimeBounds<'a> { let bounds = bounds.iter() .map(|b| cx.lifetime(span, Ident::from_str(b))) .collect(); - GenericParamAST::Lifetime(cx.lifetime_def(span, Ident::from_str(lt), vec![], bounds)) + let lifetime_def = cx.lifetime_def(span, Ident::from_str(lt), vec![], bounds); + GenericParamAST::Lifetime(lifetime_def) }) .chain(self.bounds .iter() From c818a1df9b4e3b518dcd839d18818f25cf1237a2 Mon Sep 17 00:00:00 2001 From: varkor Date: Sat, 26 May 2018 13:11:39 +0100 Subject: [PATCH 09/41] Remove specific parameter iterators from hir::Generics --- src/librustc/hir/lowering.rs | 31 +++-- src/librustc/hir/mod.rs | 50 +++----- src/librustc/middle/resolve_lifetime.rs | 142 ++++++++++++++------- src/librustc_lint/builtin.rs | 24 ++-- src/librustc_metadata/encoder.rs | 9 +- src/librustc_mir/monomorphize/collector.rs | 7 +- src/librustc_typeck/check/mod.rs | 29 +++-- src/librustc_typeck/collect.rs | 54 ++++---- src/librustdoc/clean/mod.rs | 4 +- 9 files changed, 214 insertions(+), 136 deletions(-) diff --git a/src/librustc/hir/lowering.rs b/src/librustc/hir/lowering.rs index 0c5c79e8e600d..ae7d8bd84037c 100644 --- a/src/librustc/hir/lowering.rs +++ b/src/librustc/hir/lowering.rs @@ -379,22 +379,29 @@ impl<'a> LoweringContext<'a> { let item_lifetimes = match self.lctx.items.get(&item.id).unwrap().node { hir::Item_::ItemImpl(_, _, _, ref generics, ..) | hir::Item_::ItemTrait(_, _, ref generics, ..) => { - generics.lifetimes().cloned().collect::>() + generics.params + .iter() + .filter_map(|param| match param.kind { + hir::GenericParamKind::Lifetime { .. } => { + Some(param.clone()) + } + _ => None, + }) + .collect::>() } _ => Vec::new(), }; - self.lctx - .with_parent_impl_lifetime_defs(&item_lifetimes, |this| { - let this = &mut ItemLowerer { lctx: this }; - if let ItemKind::Impl(_, _, _, _, ref opt_trait_ref, _, _) = item.node { - this.with_trait_impl_ref(opt_trait_ref, |this| { - visit::walk_item(this, item) - }); - } else { - visit::walk_item(this, item); - } - }); + self.lctx.with_parent_impl_lifetime_defs(&item_lifetimes, |this| { + let this = &mut ItemLowerer { lctx: this }; + if let ItemKind::Impl(_, _, _, _, ref opt_trait_ref, _, _) = item.node { + this.with_trait_impl_ref(opt_trait_ref, |this| { + visit::walk_item(this, item) + }); + } else { + visit::walk_item(this, item); + } + }); } } diff --git a/src/librustc/hir/mod.rs b/src/librustc/hir/mod.rs index 6a0301a556fb1..9193f309e3748 100644 --- a/src/librustc/hir/mod.rs +++ b/src/librustc/hir/mod.rs @@ -519,6 +519,11 @@ impl GenericParam { } } +pub struct GenericParamCount { + pub lifetimes: usize, + pub types: usize, +} + /// Represents lifetimes and type parameters attached to a declaration /// of a function, enum, trait, etc. #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)] @@ -540,40 +545,23 @@ impl Generics { } } - pub fn is_lt_parameterized(&self) -> bool { - self.params.iter().any(|param| { - match param.kind { - GenericParamKind::Lifetime { .. } => true, - _ => false, - } - }) - } - - pub fn is_type_parameterized(&self) -> bool { - self.params.iter().any(|param| { - match param.kind { - GenericParamKind::Type { .. } => true, - _ => false, - } - }) - } + pub fn own_counts(&self) -> GenericParamCount { + // We could cache this as a property of `GenericParamCount`, but + // the aim is to refactor this away entirely eventually and the + // presence of this method will be a constant reminder. + let mut own_counts = GenericParamCount { + lifetimes: 0, + types: 0, + }; - pub fn lifetimes<'a>(&'a self) -> impl DoubleEndedIterator { - self.params.iter().filter(|param| { + for param in &self.params { match param.kind { - GenericParamKind::Lifetime { .. } => true, - _ => false, - } - }) - } + GenericParamKind::Lifetime { .. } => own_counts.lifetimes += 1, + GenericParamKind::Type { .. } => own_counts.types += 1, + }; + } - pub fn ty_params<'a>(&'a self) -> impl DoubleEndedIterator { - self.params.iter().filter(|param| { - match param.kind { - GenericParamKind::Type { .. } => true, - _ => false, - } - }) + own_counts } } diff --git a/src/librustc/middle/resolve_lifetime.rs b/src/librustc/middle/resolve_lifetime.rs index 76680b205355b..c65a0e6d1729a 100644 --- a/src/librustc/middle/resolve_lifetime.rs +++ b/src/librustc/middle/resolve_lifetime.rs @@ -532,11 +532,18 @@ impl<'a, 'tcx> Visitor<'tcx> for LifetimeContext<'a, 'tcx> { } else { 0 }; - let lifetimes = generics - .lifetimes() - .map(|def| Region::early(&self.tcx.hir, &mut index, def)) - .collect(); - let next_early_index = index + generics.ty_params().count() as u32; + let mut next_early_index = index; + let lifetimes = generics.params.iter().filter_map(|param| { + match param.kind { + GenericParamKind::Lifetime { .. } => { + Some(Region::early(&self.tcx.hir, &mut index, param)) + } + GenericParamKind::Type { .. } => { + next_early_index += 1; + None + } + } + }).collect(); let scope = Scope::Binder { lifetimes, next_early_index, @@ -691,19 +698,25 @@ impl<'a, 'tcx> Visitor<'tcx> for LifetimeContext<'a, 'tcx> { let mut elision = None; let mut lifetimes = FxHashMap(); - for lt_def in generics.lifetimes() { - let (lt_name, region) = Region::early(&self.tcx.hir, &mut index, <_def); - if let hir::LifetimeName::Underscore = lt_name { - // Pick the elided lifetime "definition" if one exists and use it to make - // an elision scope. - elision = Some(region); - } else { - lifetimes.insert(lt_name, region); + let mut next_early_index = index; + for param in &generics.params { + match param.kind { + GenericParamKind::Lifetime { .. } => { + let (name, reg) = Region::early(&self.tcx.hir, &mut index, ¶m); + if let hir::LifetimeName::Underscore = name { + // Pick the elided lifetime "definition" if one exists + // and use it to make an elision scope. + elision = Some(reg); + } else { + lifetimes.insert(name, reg); + } + } + GenericParamKind::Type { .. } => { + next_early_index += 1; + } } } - let next_early_index = index + generics.ty_params().count() as u32; - if let Some(elision_region) = elision { let scope = Scope::Elision { elide: Elide::Exact(elision_region), @@ -760,12 +773,22 @@ impl<'a, 'tcx> Visitor<'tcx> for LifetimeContext<'a, 'tcx> { let generics = &trait_item.generics; let mut index = self.next_early_index(); debug!("visit_ty: index = {}", index); - let lifetimes = generics - .lifetimes() - .map(|lt_def| Region::early(&self.tcx.hir, &mut index, lt_def)) + let mut next_early_index = index; + let lifetimes = generics.params + .iter() + .filter_map(|param| { + match param.kind { + GenericParamKind::Lifetime { .. } => { + Some(Region::early(&self.tcx.hir, &mut index, param)) + } + GenericParamKind::Type { .. } => { + next_early_index += 1; + None + } + } + }) .collect(); - let next_early_index = index + generics.ty_params().count() as u32; let scope = Scope::Binder { lifetimes, next_early_index, @@ -806,13 +829,23 @@ impl<'a, 'tcx> Visitor<'tcx> for LifetimeContext<'a, 'tcx> { Type(ref ty) => { let generics = &impl_item.generics; let mut index = self.next_early_index(); + let mut next_early_index = index; debug!("visit_ty: index = {}", index); - let lifetimes = generics - .lifetimes() - .map(|lt_def| Region::early(&self.tcx.hir, &mut index, lt_def)) + let lifetimes = generics.params + .iter() + .filter_map(|param| { + match param.kind { + GenericParamKind::Lifetime { .. } => { + Some(Region::early(&self.tcx.hir, &mut index, param)) + } + GenericParamKind::Type { .. } => { + next_early_index += 1; + None + } + } + }) .collect(); - let next_early_index = index + generics.ty_params().count() as u32; let scope = Scope::Binder { lifetimes, next_early_index, @@ -863,9 +896,15 @@ 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.tcx, - &generics.lifetimes().cloned().collect::>(), + &generics.params.iter().filter_map(|param| { + match param.kind { + GenericParamKind::Lifetime { .. } => Some(param.clone()), + _ => None, + } + }).collect::>() ); for param in &generics.params { match param.kind { @@ -1216,12 +1255,18 @@ fn compute_object_lifetime_defaults( .map(|set| match *set { Set1::Empty => "BaseDefault".to_string(), Set1::One(Region::Static) => "'static".to_string(), - Set1::One(Region::EarlyBound(i, _, _)) => generics - .lifetimes() - .nth(i as usize) - .unwrap() - .name() - .to_string(), + Set1::One(Region::EarlyBound(i, _, _)) => { + let mut j = 0; + generics.params.iter().find(|param| { + match param.kind { + GenericParamKind::Lifetime { .. } => j += 1, + _ => {} + } + i == j + }).unwrap() + .name() + .to_string() + } Set1::One(_) => bug!(), Set1::Many => "Ambiguous".to_string(), }) @@ -1485,19 +1530,26 @@ impl<'a, 'tcx> LifetimeContext<'a, 'tcx> { } } - let lifetimes = generics - .lifetimes() - .map(|param| { - if self.map.late_bound.contains(¶m.id) { - Region::late(&self.tcx.hir, param) - } else { - Region::early(&self.tcx.hir, &mut index, param) + let mut next_early_index = index; + let lifetimes = generics.params + .iter() + .filter_map(|param| { + match param.kind { + GenericParamKind::Lifetime { .. } => { + if self.map.late_bound.contains(¶m.id) { + Some(Region::late(&self.tcx.hir, param)) + } else { + Some(Region::early(&self.tcx.hir, &mut index, param)) + } + } + GenericParamKind::Type { .. } => { + next_early_index += 1; + None + } } }) .collect(); - let next_early_index = index + generics.ty_params().count() as u32; - let scope = Scope::Binder { lifetimes, next_early_index, @@ -2513,10 +2565,10 @@ fn insert_late_bound_lifetimes( // - appear in the inputs // - do not appear in the where-clauses // - are not implicitly captured by `impl Trait` - for lifetime in generics.lifetimes() { - let name = match lifetime.kind { + for param in &generics.params { + let name = match param.kind { GenericParamKind::Lifetime { name, .. } => name, - _ => bug!(), + _ => continue, }; // appears in the where clauses? early-bound. @@ -2533,10 +2585,10 @@ fn insert_late_bound_lifetimes( debug!("insert_late_bound_lifetimes: lifetime {:?} with id {:?} is late-bound", name, - lifetime.id); + param.id); - let inserted = map.late_bound.insert(lifetime.id); - assert!(inserted, "visited lifetime {:?} twice", lifetime.id); + let inserted = map.late_bound.insert(param.id); + assert!(inserted, "visited lifetime {:?} twice", param.id); } return; diff --git a/src/librustc_lint/builtin.rs b/src/librustc_lint/builtin.rs index b981d075d5344..18b7024a8986d 100644 --- a/src/librustc_lint/builtin.rs +++ b/src/librustc_lint/builtin.rs @@ -1196,15 +1196,21 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for InvalidNoMangleItems { } err.emit(); } - if generics.is_type_parameterized() { - let mut err = cx.struct_span_lint(NO_MANGLE_GENERIC_ITEMS, - it.span, - "functions generic over \ - types must be mangled"); - err.span_suggestion_short(no_mangle_attr.span, - "remove this attribute", - "".to_owned()); - err.emit(); + for param in &generics.params { + match param.kind { + GenericParamKind::Lifetime { .. } => {} + GenericParamKind::Type { .. } => { + let mut err = cx.struct_span_lint(NO_MANGLE_GENERIC_ITEMS, + it.span, + "functions generic over \ + types must be mangled"); + err.span_suggestion_short(no_mangle_attr.span, + "remove this attribute", + "".to_owned()); + err.emit(); + break; + } + } } } } diff --git a/src/librustc_metadata/encoder.rs b/src/librustc_metadata/encoder.rs index c1a22c353c7a8..a4299f3bf377c 100644 --- a/src/librustc_metadata/encoder.rs +++ b/src/librustc_metadata/encoder.rs @@ -1236,9 +1236,14 @@ impl<'a, 'b: 'a, 'tcx: 'b> IsolatedEncoder<'a, 'b, 'tcx> { } hir::ItemConst(..) => self.encode_optimized_mir(def_id), hir::ItemFn(_, _, constness, _, ref generics, _) => { - let has_tps = generics.ty_params().next().is_some(); + let has_types = generics.params.iter().find(|param| { + match param.kind { + hir::GenericParamKind::Type { .. } => true, + _ => false, + } + }).is_some(); let needs_inline = - (has_tps || tcx.codegen_fn_attrs(def_id).requests_inline()) && + (has_types || tcx.codegen_fn_attrs(def_id).requests_inline()) && !self.metadata_output_only(); let always_encode_mir = self.tcx.sess.opts.debugging_opts.always_encode_mir; if needs_inline || constness == hir::Constness::Const || always_encode_mir { diff --git a/src/librustc_mir/monomorphize/collector.rs b/src/librustc_mir/monomorphize/collector.rs index 96aeb969d89f9..9f5b9d405a1ef 100644 --- a/src/librustc_mir/monomorphize/collector.rs +++ b/src/librustc_mir/monomorphize/collector.rs @@ -1105,8 +1105,11 @@ fn create_mono_items_for_default_impls<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, ref generics, .., ref impl_item_refs) => { - if generics.is_type_parameterized() { - return + for param in &generics.params { + match param.kind { + hir::GenericParamKind::Lifetime { .. } => {} + hir::GenericParamKind::Type { .. } => return, + } } let impl_def_id = tcx.hir.local_def_id(item.id); diff --git a/src/librustc_typeck/check/mod.rs b/src/librustc_typeck/check/mod.rs index 0066e3ce84669..8faef103f81c8 100644 --- a/src/librustc_typeck/check/mod.rs +++ b/src/librustc_typeck/check/mod.rs @@ -5166,27 +5166,34 @@ impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> { pub fn check_bounds_are_used<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, generics: &hir::Generics, ty: Ty<'tcx>) { - debug!("check_bounds_are_used(n_tps={}, ty={:?})", - generics.ty_params().count(), ty); + let own_counts = generics.own_counts(); + debug!("check_bounds_are_used(n_tps={}, ty={:?})", own_counts.types, ty); - // make a vector of booleans initially false, set to true when used - if generics.ty_params().next().is_none() { return; } - let mut tps_used = vec![false; generics.ty_params().count()]; - - let lifetime_count = generics.lifetimes().count(); + if own_counts.types == 0 { + return; + } + // Make a vector of booleans initially false, set to true when used. + let mut types_used = vec![false; own_counts.types]; for leaf_ty in ty.walk() { - if let ty::TyParam(ty::ParamTy {idx, ..}) = leaf_ty.sty { + if let ty::TyParam(ty::ParamTy { idx, .. }) = leaf_ty.sty { debug!("Found use of ty param num {}", idx); - tps_used[idx as usize - lifetime_count] = true; + types_used[idx as usize - own_counts.lifetimes] = true; } else if let ty::TyError = leaf_ty.sty { - // If there already another error, do not emit an error for not using a type Parameter + // If there is already another error, do not emit + // an error for not using a type Parameter. assert!(tcx.sess.err_count() > 0); return; } } - for (&used, param) in tps_used.iter().zip(generics.ty_params()) { + let types = generics.params.iter().filter(|param| { + match param.kind { + hir::GenericParamKind::Type { .. } => true, + _ => false, + } + }); + for (&used, param) in types_used.iter().zip(types) { if !used { struct_span_err!(tcx.sess, param.span, E0091, "type parameter `{}` is unused", param.name()) diff --git a/src/librustc_typeck/collect.rs b/src/librustc_typeck/collect.rs index 36436d95e9f17..ef34c1a1c9c75 100644 --- a/src/librustc_typeck/collect.rs +++ b/src/librustc_typeck/collect.rs @@ -756,10 +756,15 @@ fn has_late_bound_regions<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, outer_index: ty::INNERMOST, has_late_bound_regions: None, }; - for lifetime in generics.lifetimes() { - let hir_id = tcx.hir.node_to_hir_id(lifetime.id); - if tcx.is_late_bound(hir_id) { - return Some(lifetime.span); + for param in &generics.params { + match param.kind { + GenericParamKind::Lifetime { .. } => { + let hir_id = tcx.hir.node_to_hir_id(param.id); + if tcx.is_late_bound(hir_id) { + return Some(param.span); + } + } + _ => {}, } } visitor.visit_fn_decl(decl); @@ -915,7 +920,8 @@ 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; - params.extend(ast_generics.ty_params().enumerate().map(|(i, param)| { + let mut i = 0; + params.extend(ast_generics.params.iter().filter_map(|param| { match param.kind { GenericParamKind::Type { ref default, synthetic, .. } => { if param.name() == keywords::SelfType.name() { @@ -934,7 +940,7 @@ fn generics_of<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, } } - ty::GenericParamDef { + let ty_param = ty::GenericParamDef { index: type_start + i as u32, name: param.name().as_interned_str(), def_id: tcx.hir.local_def_id(param.id), @@ -945,9 +951,11 @@ fn generics_of<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, object_lifetime_defaults.as_ref().map_or(rl::Set1::Empty, |o| o[i]), synthetic, }, - } + }; + i += 1; + Some(ty_param) } - _ => bug!() + _ => None, } })); @@ -1462,20 +1470,22 @@ pub fn explicit_predicates_of<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, // Collect the predicates that were written inline by the user on each // type parameter (e.g., ``). - for param in ast_generics.ty_params() { - let param_ty = ty::ParamTy::new(index, param.name().as_interned_str()).to_ty(tcx); - index += 1; - - let bounds = match param.kind { - GenericParamKind::Type { ref bounds, .. } => bounds, - _ => bug!(), - }; - let bounds = compute_bounds(&icx, - param_ty, - bounds, - SizedByDefault::Yes, - param.span); - predicates.extend(bounds.predicates(tcx, param_ty)); + for param in &ast_generics.params { + match param.kind { + GenericParamKind::Type { ref bounds, .. } => { + let param_ty = ty::ParamTy::new(index, param.name().as_interned_str()) + .to_ty(tcx); + index += 1; + + let bounds = compute_bounds(&icx, + param_ty, + bounds, + SizedByDefault::Yes, + param.span); + predicates.extend(bounds.predicates(tcx, param_ty)); + } + _ => {} + } } // Add in the bounds that appear in the where-clause diff --git a/src/librustdoc/clean/mod.rs b/src/librustdoc/clean/mod.rs index 40fdd6d8d2de7..352c65f792876 100644 --- a/src/librustdoc/clean/mod.rs +++ b/src/librustdoc/clean/mod.rs @@ -41,7 +41,7 @@ use rustc::hir::def::{self, Def, CtorKind}; use rustc::hir::def_id::{CrateNum, DefId, DefIndex, CRATE_DEF_INDEX, LOCAL_CRATE}; use rustc::hir::def_id::DefIndexAddressSpace; use rustc::ty::subst::Substs; -use rustc::ty::{self, TyCtxt, Region, RegionVid, Ty, AdtKind, GenericParamCount}; +use rustc::ty::{self, TyCtxt, Region, RegionVid, Ty, AdtKind}; use rustc::middle::stability; use rustc::util::nodemap::{FxHashMap, FxHashSet}; use rustc_typeck::hir_ty_to_ty; @@ -2863,7 +2863,7 @@ impl Clean for hir::Ty { let mut ty_substs = FxHashMap(); let mut lt_substs = FxHashMap(); provided_params.with_generic_args(|generic_args| { - let mut indices = GenericParamCount { + let mut indices = ty::GenericParamCount { lifetimes: 0, types: 0 }; From fba1fe21084bf248334ad46b0b0a8c40a6d5ee7b Mon Sep 17 00:00:00 2001 From: varkor Date: Sat, 26 May 2018 13:22:51 +0100 Subject: [PATCH 10/41] Remove hir::GenericParam::is_*_param --- src/librustc/hir/mod.rs | 14 ---- src/librustc/middle/reachable.rs | 10 ++- src/librustc/middle/resolve_lifetime.rs | 90 ++++++++++++----------- src/librustc_lint/types.rs | 94 +++++++++++++------------ 4 files changed, 106 insertions(+), 102 deletions(-) diff --git a/src/librustc/hir/mod.rs b/src/librustc/hir/mod.rs index 9193f309e3748..0c378262dca55 100644 --- a/src/librustc/hir/mod.rs +++ b/src/librustc/hir/mod.rs @@ -497,20 +497,6 @@ pub struct GenericParam { } impl GenericParam { - pub fn is_lifetime_param(&self) -> bool { - match self.kind { - GenericParamKind::Lifetime { .. } => true, - _ => false, - } - } - - pub fn is_type_param(&self) -> bool { - match self.kind { - GenericParamKind::Type { .. } => true, - _ => false, - } - } - pub fn name(&self) -> Name { match self.kind { GenericParamKind::Lifetime { name, .. } => name.name(), diff --git a/src/librustc/middle/reachable.rs b/src/librustc/middle/reachable.rs index 40cf78edaecae..9637b376b0e43 100644 --- a/src/librustc/middle/reachable.rs +++ b/src/librustc/middle/reachable.rs @@ -29,7 +29,7 @@ use util::nodemap::{NodeSet, FxHashSet}; use rustc_target::spec::abi::Abi; use syntax::ast; use syntax::attr; -use hir; +use hir::{self, GenericParamKind}; use hir::def_id::LOCAL_CRATE; use hir::intravisit::{Visitor, NestedVisitorMap}; use hir::itemlikevisit::ItemLikeVisitor; @@ -38,7 +38,13 @@ use hir::intravisit; // Returns true if the given set of generics implies that the item it's // associated with must be inlined. fn generics_require_inlining(generics: &hir::Generics) -> bool { - generics.params.iter().any(|param| param.is_type_param()) + for param in &generics.params { + match param.kind { + GenericParamKind::Lifetime { .. } => {} + GenericParamKind::Type { .. } => return true, + } + } + false } // Returns true if the given item must be inlined because it may be diff --git a/src/librustc/middle/resolve_lifetime.rs b/src/librustc/middle/resolve_lifetime.rs index c65a0e6d1729a..dfa205e6a34d2 100644 --- a/src/librustc/middle/resolve_lifetime.rs +++ b/src/librustc/middle/resolve_lifetime.rs @@ -532,21 +532,21 @@ impl<'a, 'tcx> Visitor<'tcx> for LifetimeContext<'a, 'tcx> { } else { 0 }; - let mut next_early_index = index; + let mut type_count = 0; let lifetimes = generics.params.iter().filter_map(|param| { match param.kind { GenericParamKind::Lifetime { .. } => { Some(Region::early(&self.tcx.hir, &mut index, param)) } GenericParamKind::Type { .. } => { - next_early_index += 1; + type_count += 1; None } } }).collect(); let scope = Scope::Binder { lifetimes, - next_early_index, + next_early_index: index + type_count, abstract_type_parent: true, track_lifetime_uses, s: ROOT_SCOPE, @@ -698,7 +698,7 @@ impl<'a, 'tcx> Visitor<'tcx> for LifetimeContext<'a, 'tcx> { let mut elision = None; let mut lifetimes = FxHashMap(); - let mut next_early_index = index; + let mut type_count = 0; for param in &generics.params { match param.kind { GenericParamKind::Lifetime { .. } => { @@ -712,10 +712,11 @@ impl<'a, 'tcx> Visitor<'tcx> for LifetimeContext<'a, 'tcx> { } } GenericParamKind::Type { .. } => { - next_early_index += 1; + type_count += 1; } } } + let next_early_index = index + type_count; if let Some(elision_region) = elision { let scope = Scope::Elision { @@ -773,7 +774,7 @@ impl<'a, 'tcx> Visitor<'tcx> for LifetimeContext<'a, 'tcx> { let generics = &trait_item.generics; let mut index = self.next_early_index(); debug!("visit_ty: index = {}", index); - let mut next_early_index = index; + let mut type_count = 0; let lifetimes = generics.params .iter() .filter_map(|param| { @@ -782,7 +783,7 @@ impl<'a, 'tcx> Visitor<'tcx> for LifetimeContext<'a, 'tcx> { Some(Region::early(&self.tcx.hir, &mut index, param)) } GenericParamKind::Type { .. } => { - next_early_index += 1; + type_count += 1; None } } @@ -791,7 +792,7 @@ impl<'a, 'tcx> Visitor<'tcx> for LifetimeContext<'a, 'tcx> { let scope = Scope::Binder { lifetimes, - next_early_index, + next_early_index: index + type_count, s: self.scope, track_lifetime_uses: true, abstract_type_parent: true, @@ -896,7 +897,6 @@ 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.tcx, &generics.params.iter().filter_map(|param| { @@ -925,21 +925,21 @@ impl<'a, 'tcx> Visitor<'tcx> for LifetimeContext<'a, 'tcx> { ref bound_generic_params, .. }) => { - if bound_generic_params.iter().any(|p| p.is_lifetime_param()) { + let lifetimes: FxHashMap<_, _> = bound_generic_params.iter() + .filter_map(|param| { + match param.kind { + GenericParamKind::Lifetime { .. } => { + Some(Region::late(&self.tcx.hir, param)) + } + _ => None, + } + }) + .collect(); + if !lifetimes.is_empty() { self.trait_ref_hack = true; let next_early_index = self.next_early_index(); let scope = Scope::Binder { - lifetimes: bound_generic_params - .iter() - .filter_map(|param| { - match param.kind { - GenericParamKind::Lifetime { .. } => { - Some(Region::late(&self.tcx.hir, param)) - } - _ => None, - } - }) - .collect(), + lifetimes, s: self.scope, next_early_index, track_lifetime_uses: true, @@ -990,7 +990,12 @@ impl<'a, 'tcx> Visitor<'tcx> for LifetimeContext<'a, 'tcx> { || trait_ref .bound_generic_params .iter() - .any(|p| p.is_lifetime_param()) + .any(|param| { + match param.kind { + GenericParamKind::Lifetime { .. } => true, + _ => false, + } + }) { if self.trait_ref_hack { span_err!( @@ -1259,10 +1264,15 @@ fn compute_object_lifetime_defaults( let mut j = 0; generics.params.iter().find(|param| { match param.kind { - GenericParamKind::Lifetime { .. } => j += 1, + GenericParamKind::Lifetime { .. } => { + if i == j { + return true; + } + j += 1; + } _ => {} } - i == j + false }).unwrap() .name() .to_string() @@ -1530,25 +1540,23 @@ impl<'a, 'tcx> LifetimeContext<'a, 'tcx> { } } - let mut next_early_index = index; - let lifetimes = generics.params - .iter() - .filter_map(|param| { - match param.kind { - GenericParamKind::Lifetime { .. } => { - if self.map.late_bound.contains(¶m.id) { - Some(Region::late(&self.tcx.hir, param)) - } else { - Some(Region::early(&self.tcx.hir, &mut index, param)) - } - } - GenericParamKind::Type { .. } => { - next_early_index += 1; - None + let mut type_count = 0; + let lifetimes = generics.params.iter().filter_map(|param| { + match param.kind { + GenericParamKind::Lifetime { .. } => { + if self.map.late_bound.contains(¶m.id) { + Some(Region::late(&self.tcx.hir, param)) + } else { + Some(Region::early(&self.tcx.hir, &mut index, param)) } } - }) - .collect(); + GenericParamKind::Type { .. } => { + type_count += 1; + None + } + } + }).collect(); + let next_early_index = index + type_count; let scope = Scope::Binder { lifetimes, diff --git a/src/librustc_lint/types.rs b/src/librustc_lint/types.rs index 2abe361233fd0..2149e65428154 100644 --- a/src/librustc_lint/types.rs +++ b/src/librustc_lint/types.rs @@ -810,51 +810,55 @@ impl LintPass for VariantSizeDifferences { impl<'a, 'tcx> LateLintPass<'a, 'tcx> for VariantSizeDifferences { fn check_item(&mut self, cx: &LateContext, it: &hir::Item) { - if let hir::ItemEnum(ref enum_definition, ref gens) = it.node { - if gens.params.iter().all(|param| param.is_lifetime_param()) { - // sizes only make sense for non-generic types - let item_def_id = cx.tcx.hir.local_def_id(it.id); - let t = cx.tcx.type_of(item_def_id); - let ty = cx.tcx.erase_regions(&t); - let layout = cx.layout_of(ty).unwrap_or_else(|e| { - bug!("failed to get layout for `{}`: {}", t, e) - }); - - if let layout::Variants::Tagged { ref variants, ref tag, .. } = layout.variants { - let discr_size = tag.value.size(cx.tcx).bytes(); - - debug!("enum `{}` is {} bytes large with layout:\n{:#?}", - t, layout.size.bytes(), layout); - - let (largest, slargest, largest_index) = enum_definition.variants - .iter() - .zip(variants) - .map(|(variant, variant_layout)| { - // Subtract the size of the enum discriminant - let bytes = variant_layout.size.bytes() - .saturating_sub(discr_size); - - debug!("- variant `{}` is {} bytes large", variant.node.name, bytes); - bytes - }) - .enumerate() - .fold((0, 0, 0), |(l, s, li), (idx, size)| if size > l { - (size, l, idx) - } else if size > s { - (l, size, li) - } else { - (l, s, li) - }); - - // we only warn if the largest variant is at least thrice as large as - // the second-largest. - if largest > slargest * 3 && slargest > 0 { - cx.span_lint(VARIANT_SIZE_DIFFERENCES, - enum_definition.variants[largest_index].span, - &format!("enum variant is more than three times larger \ - ({} bytes) than the next largest", - largest)); - } + if let hir::ItemEnum(ref enum_definition, ref generics) = it.node { + for param in &generics.params { + match param.kind { + hir::GenericParamKind::Lifetime { .. } => {}, + hir::GenericParamKind::Type { .. } => return, + } + } + // Sizes only make sense for non-generic types. + let item_def_id = cx.tcx.hir.local_def_id(it.id); + let t = cx.tcx.type_of(item_def_id); + let ty = cx.tcx.erase_regions(&t); + let layout = cx.layout_of(ty).unwrap_or_else(|e| { + bug!("failed to get layout for `{}`: {}", t, e) + }); + + if let layout::Variants::Tagged { ref variants, ref tag, .. } = layout.variants { + let discr_size = tag.value.size(cx.tcx).bytes(); + + debug!("enum `{}` is {} bytes large with layout:\n{:#?}", + t, layout.size.bytes(), layout); + + let (largest, slargest, largest_index) = enum_definition.variants + .iter() + .zip(variants) + .map(|(variant, variant_layout)| { + // Subtract the size of the enum discriminant. + let bytes = variant_layout.size.bytes() + .saturating_sub(discr_size); + + debug!("- variant `{}` is {} bytes large", variant.node.name, bytes); + bytes + }) + .enumerate() + .fold((0, 0, 0), |(l, s, li), (idx, size)| if size > l { + (size, l, idx) + } else if size > s { + (l, size, li) + } else { + (l, s, li) + }); + + // We only warn if the largest variant is at least thrice as large as + // the second-largest. + if largest > slargest * 3 && slargest > 0 { + cx.span_lint(VARIANT_SIZE_DIFFERENCES, + enum_definition.variants[largest_index].span, + &format!("enum variant is more than three times larger \ + ({} bytes) than the next largest", + largest)); } } } From 2c6ff2469a94e37b9605a43bc861de66830a94d4 Mon Sep 17 00:00:00 2001 From: varkor Date: Sat, 26 May 2018 19:16:21 +0100 Subject: [PATCH 11/41] Refactor ast::GenericParam as a struct --- src/librustc/hir/lowering.rs | 103 +++++++++++---------- src/librustc/hir/map/def_collector.rs | 29 +++--- src/librustc_passes/ast_validation.rs | 88 ++++++++---------- src/librustc_resolve/lib.rs | 73 +++++++++------ src/librustc_save_analysis/dump_visitor.rs | 76 ++++++++------- src/librustc_save_analysis/lib.rs | 6 +- src/librustc_save_analysis/sig.rs | 53 +++++------ src/libsyntax/ast.rs | 47 +++++----- src/libsyntax/ext/build.rs | 27 ++++-- src/libsyntax/fold.rs | 27 ++---- src/libsyntax/parse/parser.rs | 50 +++++----- src/libsyntax/print/pprust.rs | 36 ++++--- src/libsyntax/visit.rs | 18 ++-- src/libsyntax_ext/deriving/generic/mod.rs | 28 +++--- src/libsyntax_ext/deriving/generic/ty.rs | 23 ++--- src/libsyntax_ext/deriving/mod.rs | 9 +- 16 files changed, 338 insertions(+), 355 deletions(-) diff --git a/src/librustc/hir/lowering.rs b/src/librustc/hir/lowering.rs index ae7d8bd84037c..68ceb39d575d6 100644 --- a/src/librustc/hir/lowering.rs +++ b/src/librustc/hir/lowering.rs @@ -759,20 +759,20 @@ impl<'a> LoweringContext<'a> { hir_name } - // Evaluates `f` with the lifetimes in `lt_defs` in-scope. + // Evaluates `f` with the lifetimes in `params` in-scope. // This is used to track which lifetimes have already been defined, and // which are new in-band lifetimes that need to have a definition created // for them. fn with_in_scope_lifetime_defs<'l, T, F>( &mut self, - lt_defs: impl Iterator, + params: impl Iterator, f: F, ) -> T where F: FnOnce(&mut LoweringContext) -> T, { let old_len = self.in_scope_lifetimes.len(); - let lt_def_names = lt_defs.map(|lt_def| lt_def.lifetime.ident.name); + let lt_def_names = params.map(|param| param.ident.name); self.in_scope_lifetimes.extend(lt_def_names); let res = f(self); @@ -781,8 +781,8 @@ impl<'a> LoweringContext<'a> { res } - // Same as the method above, but accepts `hir::LifetimeDef`s - // instead of `ast::LifetimeDef`s. + // Same as the method above, but accepts `hir::GenericParam`s + // instead of `ast::GenericParam`s. // This should only be used with generics that have already had their // in-band lifetimes added. In practice, this means that this function is // only used when lowering a child item of a trait or impl. @@ -817,8 +817,8 @@ impl<'a> LoweringContext<'a> { F: FnOnce(&mut LoweringContext) -> T, { let (in_band_defs, (mut lowered_generics, res)) = self.with_in_scope_lifetime_defs( - generics.params.iter().filter_map(|p| match p { - GenericParamAST::Lifetime(ld) => Some(ld), + generics.params.iter().filter_map(|param| match param.kind { + GenericParamKindAST::Lifetime { .. } => Some(param), _ => None, }), |this| { @@ -1076,8 +1076,8 @@ impl<'a> LoweringContext<'a> { hir::TyRptr(lifetime, self.lower_mt(mt, itctx)) } TyKind::BareFn(ref f) => self.with_in_scope_lifetime_defs( - f.generic_params.iter().filter_map(|p| match p { - GenericParamAST::Lifetime(ld) => Some(ld), + f.generic_params.iter().filter_map(|param| match param.kind { + GenericParamKindAST::Lifetime { .. } => Some(param), _ => None, }), |this| { @@ -1940,21 +1940,19 @@ impl<'a> LoweringContext<'a> { add_bounds: &NodeMap>, itctx: ImplTraitContext) -> hir::GenericParam { - match param { - GenericParamAST::Lifetime(ref lifetime_def) => { + match param.kind { + GenericParamKindAST::Lifetime { ref bounds, ref lifetime, .. } => { let was_collecting_in_band = self.is_collecting_in_band_lifetimes; self.is_collecting_in_band_lifetimes = false; - let lifetime = self.lower_lifetime(&lifetime_def.lifetime); + let lifetime = self.lower_lifetime(lifetime); let param = hir::GenericParam { id: lifetime.id, span: lifetime.span, - pure_wrt_drop: attr::contains_name(&lifetime_def.attrs, "may_dangle"), + pure_wrt_drop: attr::contains_name(¶m.attrs, "may_dangle"), kind: hir::GenericParamKind::Lifetime { name: lifetime.name, - bounds: lifetime_def.bounds - .iter() - .map(|lt| self.lower_lifetime(lt)).collect(), + bounds: bounds.iter().map(|lt| self.lower_lifetime(lt)).collect(), in_band: false, lifetime_deprecated: lifetime, } @@ -1964,8 +1962,8 @@ impl<'a> LoweringContext<'a> { param } - GenericParamAST::Type(ref ty_param) => { - let mut name = self.lower_ident(ty_param.ident); + GenericParamKindAST::Type { ref bounds, ref default } => { + let mut name = self.lower_ident(param.ident); // Don't expose `Self` (recovered "keyword used as ident" parse error). // `rustc::ty` expects `Self` to be only used for a trait's `Self`. @@ -1974,8 +1972,8 @@ impl<'a> LoweringContext<'a> { name = Symbol::gensym("Self"); } - let mut bounds = self.lower_bounds(&ty_param.bounds, itctx); - let add_bounds = add_bounds.get(&ty_param.id).map_or(&[][..], |x| &x); + let mut bounds = self.lower_bounds(bounds, itctx); + let add_bounds = add_bounds.get(¶m.id).map_or(&[][..], |x| &x); if !add_bounds.is_empty() { bounds = bounds .into_iter() @@ -1984,22 +1982,20 @@ impl<'a> LoweringContext<'a> { } hir::GenericParam { - id: self.lower_node_id(ty_param.id).node_id, - span: ty_param.ident.span, - pure_wrt_drop: attr::contains_name(&ty_param.attrs, "may_dangle"), + id: self.lower_node_id(param.id).node_id, + span: param.ident.span, + pure_wrt_drop: attr::contains_name(¶m.attrs, "may_dangle"), kind: hir::GenericParamKind::Type { name, bounds, - default: ty_param.default.as_ref() - .map(|x| { - self.lower_ty(x, ImplTraitContext::Disallowed) - }), - synthetic: ty_param.attrs - .iter() - .filter(|attr| attr.check_name("rustc_synthetic")) - .map(|_| hir::SyntheticTyParamKind::ImplTrait) - .nth(0), - attrs: self.lower_attrs(&ty_param.attrs), + default: default.as_ref().map(|x| { + self.lower_ty(x, ImplTraitContext::Disallowed) + }), + synthetic: param.attrs.iter() + .filter(|attr| attr.check_name("rustc_synthetic")) + .map(|_| hir::SyntheticTyParamKind::ImplTrait) + .nth(0), + attrs: self.lower_attrs(¶m.attrs), } } } @@ -2015,13 +2011,18 @@ impl<'a> LoweringContext<'a> { params.iter().map(|param| self.lower_generic_param(param, add_bounds, itctx)).collect() } - fn lower_generics(&mut self, g: &Generics, itctx: ImplTraitContext) -> hir::Generics { + fn lower_generics( + &mut self, + generics: &Generics, + itctx: ImplTraitContext) + -> hir::Generics + { // Collect `?Trait` bounds in where clause and move them to parameter definitions. // FIXME: This could probably be done with less rightward drift. Also looks like two control // paths where report_error is called are also the only paths that advance to after // the match statement, so the error reporting could probably just be moved there. let mut add_bounds = NodeMap(); - for pred in &g.where_clause.predicates { + for pred in &generics.where_clause.predicates { if let WherePredicate::BoundPredicate(ref bound_pred) = *pred { 'next_bound: for bound in &bound_pred.bounds { if let TraitTyParamBound(_, TraitBoundModifier::Maybe) = *bound { @@ -2045,15 +2046,17 @@ impl<'a> LoweringContext<'a> { if let Some(node_id) = self.resolver.definitions().as_local_node_id(def_id) { - for param in &g.params { - if let GenericParamAST::Type(ref ty_param) = *param { - if node_id == ty_param.id { - add_bounds - .entry(ty_param.id) - .or_insert(Vec::new()) - .push(bound.clone()); - continue 'next_bound; + for param in &generics.params { + match param.kind { + GenericParamKindAST::Type { .. } => { + if node_id == param.id { + add_bounds.entry(param.id) + .or_insert(Vec::new()) + .push(bound.clone()); + continue 'next_bound; + } } + _ => {} } } } @@ -2068,9 +2071,9 @@ impl<'a> LoweringContext<'a> { } hir::Generics { - params: self.lower_generic_params(&g.params, &add_bounds, itctx), - where_clause: self.lower_where_clause(&g.where_clause), - span: g.span, + params: self.lower_generic_params(&generics.params, &add_bounds, itctx), + where_clause: self.lower_where_clause(&generics.where_clause), + span: generics.span, } } @@ -2093,8 +2096,8 @@ impl<'a> LoweringContext<'a> { span, }) => { self.with_in_scope_lifetime_defs( - bound_generic_params.iter().filter_map(|p| match p { - GenericParamAST::Lifetime(ld) => Some(ld), + bound_generic_params.iter().filter_map(|param| match param.kind { + GenericParamKindAST::Lifetime { .. } => Some(param), _ => None, }), |this| { @@ -2412,8 +2415,8 @@ impl<'a> LoweringContext<'a> { ); let new_impl_items = self.with_in_scope_lifetime_defs( - ast_generics.params.iter().filter_map(|p| match p { - GenericParamAST::Lifetime(ld) => Some(ld), + ast_generics.params.iter().filter_map(|param| match param.kind { + GenericParamKindAST::Lifetime { .. } => Some(param), _ => None, }), |this| { diff --git a/src/librustc/hir/map/def_collector.rs b/src/librustc/hir/map/def_collector.rs index 7ab6e17ac35ea..6015063aa821f 100644 --- a/src/librustc/hir/map/def_collector.rs +++ b/src/librustc/hir/map/def_collector.rs @@ -171,24 +171,17 @@ impl<'a> visit::Visitor<'a> for DefCollector<'a> { } fn visit_generic_param(&mut self, param: &'a GenericParamAST) { - match *param { - GenericParamAST::Lifetime(ref lifetime_def) => { - self.create_def( - lifetime_def.lifetime.id, - DefPathData::LifetimeDef(lifetime_def.lifetime.ident.name.as_interned_str()), - REGULAR_SPACE, - lifetime_def.lifetime.ident.span - ); - } - GenericParamAST::Type(ref ty_param) => { - self.create_def( - ty_param.id, - DefPathData::TypeParam(ty_param.ident.name.as_interned_str()), - REGULAR_SPACE, - ty_param.ident.span - ); - } - } + let name = param.ident.name.as_interned_str(); + let def_path_data = match param.kind { + GenericParamKindAST::Lifetime { .. } => DefPathData::LifetimeDef(name), + GenericParamKindAST::Type { .. } => DefPathData::TypeParam(name), + }; + self.create_def( + param.id, + def_path_data, + REGULAR_SPACE, + param.ident.span + ); visit::walk_generic_param(self, param); } diff --git a/src/librustc_passes/ast_validation.rs b/src/librustc_passes/ast_validation.rs index b50407c82d19c..d7ebd40f49b44 100644 --- a/src/librustc_passes/ast_validation.rs +++ b/src/librustc_passes/ast_validation.rs @@ -139,29 +139,23 @@ impl<'a> AstValidator<'a> { } fn check_late_bound_lifetime_defs(&self, params: &Vec) { - // Check: Only lifetime parameters - let non_lifetime_param_spans : Vec<_> = params.iter() - .filter_map(|param| match *param { - GenericParamAST::Lifetime(_) => None, - GenericParamAST::Type(ref t) => Some(t.ident.span), - }).collect(); - if !non_lifetime_param_spans.is_empty() { - self.err_handler().span_err(non_lifetime_param_spans, - "only lifetime parameters can be used in this context"); - } - - // Check: No bounds on lifetime parameters - for param in params.iter() { - match *param { - GenericParamAST::Lifetime(ref l) => { - if !l.bounds.is_empty() { - let spans: Vec<_> = l.bounds.iter().map(|b| b.ident.span).collect(); + // Check only lifetime parameters are present and that the lifetime + // parameters that are present have no bounds. + let non_lifetime_param_spans: Vec<_> = params.iter() + .filter_map(|param| match param.kind { + GenericParamKindAST::Lifetime { ref bounds, .. } => { + if !bounds.is_empty() { + let spans: Vec<_> = bounds.iter().map(|b| b.ident.span).collect(); self.err_handler().span_err(spans, "lifetime bounds cannot be used in this context"); } + None } - GenericParamAST::Type(_) => {} - } + _ => Some(param.ident.span), + }).collect(); + if !non_lifetime_param_spans.is_empty() { + self.err_handler().span_err(non_lifetime_param_spans, + "only lifetime parameters can be used in this context"); } } } @@ -335,22 +329,21 @@ impl<'a> Visitor<'a> for AstValidator<'a> { } ItemKind::TraitAlias(Generics { ref params, .. }, ..) => { for param in params { - if let GenericParamAST::Type(TyParam { - ident, - ref bounds, - ref default, - .. - }) = *param - { - if !bounds.is_empty() { - self.err_handler().span_err(ident.span, - "type parameters on the left side of a \ - trait alias cannot be bounded"); - } - if !default.is_none() { - self.err_handler().span_err(ident.span, - "type parameters on the left side of a \ - trait alias cannot have defaults"); + match param.kind { + GenericParamKindAST::Lifetime { .. } => {} + GenericParamKindAST::Type { ref bounds, ref default, .. } => { + if !bounds.is_empty() { + self.err_handler().span_err(param.ident.span, + "type parameters on the left side \ + of a trait alias cannot be \ + bounded"); + } + if !default.is_none() { + self.err_handler().span_err(param.ident.span, + "type parameters on the left side \ + of a trait alias cannot have \ + defaults"); + } } } } @@ -413,24 +406,23 @@ impl<'a> Visitor<'a> for AstValidator<'a> { let mut seen_non_lifetime_param = false; let mut seen_default = None; for param in &g.params { - match (param, seen_non_lifetime_param) { - (&GenericParamAST::Lifetime(ref ld), true) => { + match (¶m.kind, seen_non_lifetime_param) { + (GenericParamKindAST::Lifetime { .. }, true) => { self.err_handler() - .span_err(ld.lifetime.ident.span, "lifetime parameters must be leading"); + .span_err(param.ident.span, "lifetime parameters must be leading"); }, - (&GenericParamAST::Lifetime(_), false) => {} - _ => { + (GenericParamKindAST::Lifetime { .. }, false) => {} + (GenericParamKindAST::Type { ref default, .. }, _) => { seen_non_lifetime_param = true; + if default.is_some() { + seen_default = Some(param.ident.span); + } else if let Some(span) = seen_default { + self.err_handler() + .span_err(span, "type parameters with a default must be trailing"); + break; + } } } - - if let GenericParamAST::Type(ref ty_param @ TyParam { default: Some(_), .. }) = *param { - seen_default = Some(ty_param.ident.span); - } else if let Some(span) = seen_default { - self.err_handler() - .span_err(span, "type parameters with a default must be trailing"); - break - } } for predicate in &g.where_clause.predicates { if let WherePredicate::EqPredicate(ref predicate) = *predicate { diff --git a/src/librustc_resolve/lib.rs b/src/librustc_resolve/lib.rs index d70a7e2b8278b..37264eb338228 100644 --- a/src/librustc_resolve/lib.rs +++ b/src/librustc_resolve/lib.rs @@ -56,7 +56,7 @@ use syntax::util::lev_distance::find_best_match_for_name; use syntax::visit::{self, FnKind, Visitor}; use syntax::attr; use syntax::ast::{Arm, BindingMode, Block, Crate, Expr, ExprKind}; -use syntax::ast::{FnDecl, ForeignItem, ForeignItemKind, GenericParamAST, Generics}; +use syntax::ast::{FnDecl, ForeignItem, ForeignItemKind, GenericParamKindAST, Generics}; use syntax::ast::{Item, ItemKind, ImplItem, ImplItemKind}; use syntax::ast::{Label, Local, Mutability, Pat, PatKind, Path}; use syntax::ast::{QSelf, TraitItemKind, TraitRef, Ty, TyKind}; @@ -797,31 +797,43 @@ impl<'a, 'tcx> Visitor<'tcx> for Resolver<'a> { // put all the parameters on the ban list and then remove // them one by one as they are processed and become available. let mut default_ban_rib = Rib::new(ForwardTyParamBanRibKind); + let mut found_default = false; default_ban_rib.bindings.extend(generics.params.iter() - .filter_map(|p| if let GenericParamAST::Type(ref tp) = *p { Some(tp) } else { None }) - .skip_while(|p| p.default.is_none()) - .map(|p| (Ident::with_empty_ctxt(p.ident.name), Def::Err))); + .filter_map(|param| match param.kind { + GenericParamKindAST::Lifetime { .. } => None, + GenericParamKindAST::Type { ref default, .. } => { + if default.is_some() { + found_default = true; + } + if found_default { + return Some((Ident::with_empty_ctxt(param.ident.name), Def::Err)); + } + None + } + })); for param in &generics.params { - match *param { - GenericParamAST::Lifetime(_) => self.visit_generic_param(param), - GenericParamAST::Type(ref ty_param) => { - for bound in &ty_param.bounds { + match param.kind { + GenericParamKindAST::Lifetime { .. } => self.visit_generic_param(param), + GenericParamKindAST::Type { ref bounds, ref default, .. } => { + for bound in bounds { self.visit_ty_param_bound(bound); } - if let Some(ref ty) = ty_param.default { + if let Some(ref ty) = default { self.ribs[TypeNS].push(default_ban_rib); self.visit_ty(ty); default_ban_rib = self.ribs[TypeNS].pop().unwrap(); } // Allow all following defaults to refer to this type parameter. - default_ban_rib.bindings.remove(&Ident::with_empty_ctxt(ty_param.ident.name)); + default_ban_rib.bindings.remove(&Ident::with_empty_ctxt(param.ident.name)); } } } - for p in &generics.where_clause.predicates { self.visit_where_predicate(p); } + for p in &generics.where_clause.predicates { + self.visit_where_predicate(p); + } } } @@ -2198,25 +2210,28 @@ impl<'a> Resolver<'a> { let mut function_type_rib = Rib::new(rib_kind); let mut seen_bindings = FxHashMap(); for param in &generics.params { - if let GenericParamAST::Type(ref type_parameter) = *param { - let ident = type_parameter.ident.modern(); - debug!("with_type_parameter_rib: {}", type_parameter.id); - - if seen_bindings.contains_key(&ident) { - let span = seen_bindings.get(&ident).unwrap(); - let err = ResolutionError::NameAlreadyUsedInTypeParameterList( - ident.name, - span, - ); - resolve_error(self, type_parameter.ident.span, err); - } - seen_bindings.entry(ident).or_insert(type_parameter.ident.span); + match param.kind { + GenericParamKindAST::Type { .. } => { + let ident = param.ident.modern(); + debug!("with_type_parameter_rib: {}", param.id); + + if seen_bindings.contains_key(&ident) { + let span = seen_bindings.get(&ident).unwrap(); + let err = ResolutionError::NameAlreadyUsedInTypeParameterList( + ident.name, + span, + ); + resolve_error(self, param.ident.span, err); + } + seen_bindings.entry(ident).or_insert(param.ident.span); - // plain insert (no renaming) - let def_id = self.definitions.local_def_id(type_parameter.id); - let def = Def::TyParam(def_id); - function_type_rib.bindings.insert(ident, def); - self.record_def(type_parameter.id, PathResolution::new(def)); + // plain insert (no renaming) + let def_id = self.definitions.local_def_id(param.id); + let def = Def::TyParam(def_id); + function_type_rib.bindings.insert(ident, def); + self.record_def(param.id, PathResolution::new(def)); + } + _ => {} } } self.ribs[TypeNS].push(function_type_rib); diff --git a/src/librustc_save_analysis/dump_visitor.rs b/src/librustc_save_analysis/dump_visitor.rs index 303406dac7661..94552e08a8cea 100644 --- a/src/librustc_save_analysis/dump_visitor.rs +++ b/src/librustc_save_analysis/dump_visitor.rs @@ -370,35 +370,38 @@ impl<'l, 'tcx: 'l, 'll, O: DumpOutput + 'll> DumpVisitor<'l, 'tcx, 'll, O> { id: NodeId, ) { for param in &generics.params { - if let ast::GenericParamAST::Type(ref ty_param) = *param { - let param_ss = ty_param.ident.span; - let name = escape(self.span.snippet(param_ss)); - // Append $id to name to make sure each one is unique - let qualname = format!("{}::{}${}", prefix, name, id); - if !self.span.filter_generated(Some(param_ss), full_span) { - let id = ::id_from_node_id(ty_param.id, &self.save_ctxt); - let span = self.span_from_span(param_ss); + match param.kind { + ast::GenericParamKindAST::Lifetime { .. } => {} + ast::GenericParamKindAST::Type { .. } => { + let param_ss = param.ident.span; + let name = escape(self.span.snippet(param_ss)); + // Append $id to name to make sure each one is unique. + let qualname = format!("{}::{}${}", prefix, name, id); + if !self.span.filter_generated(Some(param_ss), full_span) { + let id = ::id_from_node_id(param.id, &self.save_ctxt); + let span = self.span_from_span(param_ss); - self.dumper.dump_def( - &Access { - public: false, - reachable: false, - }, - Def { - kind: DefKind::Type, - id, - span, - name, - qualname, - value: String::new(), - parent: None, - children: vec![], - decl_id: None, - docs: String::new(), - sig: None, - attributes: vec![], - }, - ); + self.dumper.dump_def( + &Access { + public: false, + reachable: false, + }, + Def { + kind: DefKind::Type, + id, + span, + name, + qualname, + value: String::new(), + parent: None, + children: vec![], + decl_id: None, + docs: String::new(), + sig: None, + attributes: vec![], + }, + ); + } } } } @@ -1479,14 +1482,17 @@ impl<'l, 'tcx: 'l, 'll, O: DumpOutput + 'll> Visitor<'l> for DumpVisitor<'l, 'tc fn visit_generics(&mut self, generics: &'l ast::Generics) { for param in &generics.params { - if let ast::GenericParamAST::Type(ref ty_param) = *param { - for bound in ty_param.bounds.iter() { - if let ast::TraitTyParamBound(ref trait_ref, _) = *bound { - self.process_path(trait_ref.trait_ref.ref_id, &trait_ref.trait_ref.path) + match param.kind { + ast::GenericParamKindAST::Lifetime { .. } => {} + ast::GenericParamKindAST::Type { ref bounds, ref default, .. } => { + for bound in bounds { + if let ast::TraitTyParamBound(ref trait_ref, _) = *bound { + self.process_path(trait_ref.trait_ref.ref_id, &trait_ref.trait_ref.path) + } + } + if let Some(ref ty) = default { + self.visit_ty(&ty); } - } - if let Some(ref ty) = ty_param.default { - self.visit_ty(&ty); } } } diff --git a/src/librustc_save_analysis/lib.rs b/src/librustc_save_analysis/lib.rs index a634e979363bb..f656b013c0a01 100644 --- a/src/librustc_save_analysis/lib.rs +++ b/src/librustc_save_analysis/lib.rs @@ -934,9 +934,9 @@ fn make_signature(decl: &ast::FnDecl, generics: &ast::Generics) -> String { sig.push_str(&generics .params .iter() - .map(|param| match *param { - ast::GenericParamAST::Lifetime(ref l) => l.lifetime.ident.name.to_string(), - ast::GenericParamAST::Type(ref t) => t.ident.to_string(), + .map(|param| match param.kind { + ast::GenericParamKindAST::Lifetime { .. } => param.ident.name.to_string(), + ast::GenericParamKindAST::Type { .. } => param.ident.to_string(), }) .collect::>() .join(", ")); diff --git a/src/librustc_save_analysis/sig.rs b/src/librustc_save_analysis/sig.rs index f5384683506ef..8e8e0dfa1828e 100644 --- a/src/librustc_save_analysis/sig.rs +++ b/src/librustc_save_analysis/sig.rs @@ -223,9 +223,9 @@ impl Sig for ast::Ty { text.push_str("for<"); text.push_str(&f.generic_params .iter() - .filter_map(|p| match *p { - ast::GenericParamAST::Lifetime(ref l) => { - Some(l.lifetime.ident.to_string()) + .filter_map(|param| match param.kind { + ast::GenericParamKindAST::Lifetime { .. } => { + Some(param.ident.to_string()) } _ => None, }) @@ -617,45 +617,34 @@ impl Sig for ast::Generics { let mut defs = vec![]; for param in &self.params { - match *param { - ast::GenericParamAST::Lifetime(ref l) => { - let mut l_text = l.lifetime.ident.to_string(); - defs.push(SigElement { - id: id_from_node_id(l.lifetime.id, scx), - start: offset + text.len(), - end: offset + text.len() + l_text.len(), - }); - - if !l.bounds.is_empty() { - l_text.push_str(": "); - let bounds = l.bounds - .iter() + let mut param_text = param.ident.to_string(); + defs.push(SigElement { + id: id_from_node_id(param.id, scx), + start: offset + text.len(), + end: offset + text.len() + param_text.len(), + }); + match param.kind { + ast::GenericParamKindAST::Lifetime { ref bounds, .. } => { + if !bounds.is_empty() { + param_text.push_str(": "); + let bounds = bounds.iter() .map(|l| l.ident.to_string()) .collect::>() .join(" + "); - l_text.push_str(&bounds); + param_text.push_str(&bounds); // FIXME add lifetime bounds refs. } - text.push_str(&l_text); - text.push(','); } - ast::GenericParamAST::Type(ref t) => { - let mut t_text = t.ident.to_string(); - defs.push(SigElement { - id: id_from_node_id(t.id, scx), - start: offset + text.len(), - end: offset + text.len() + t_text.len(), - }); - - if !t.bounds.is_empty() { - t_text.push_str(": "); - t_text.push_str(&pprust::bounds_to_string(&t.bounds)); + ast::GenericParamKindAST::Type { ref bounds, .. } => { + if !bounds.is_empty() { + param_text.push_str(": "); + param_text.push_str(&pprust::bounds_to_string(bounds)); // FIXME descend properly into bounds. } - text.push_str(&t_text); - text.push(','); } } + text.push_str(¶m_text); + text.push(','); } text.push('>'); diff --git a/src/libsyntax/ast.rs b/src/libsyntax/ast.rs index 17df8dd7027e4..c354edc5aaff4 100644 --- a/src/libsyntax/ast.rs +++ b/src/libsyntax/ast.rs @@ -58,14 +58,6 @@ impl fmt::Debug for Lifetime { } } -/// A lifetime definition, e.g. `'a: 'b+'c+'d` -#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)] -pub struct LifetimeDef { - pub attrs: ThinVec, - pub lifetime: Lifetime, - pub bounds: Vec -} - /// A "Path" is essentially Rust's notion of a name. /// /// It's represented as a sequence of identifiers, @@ -329,31 +321,38 @@ pub enum TraitBoundModifier { pub type TyParamBounds = Vec; #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)] -pub struct TyParam { - pub attrs: ThinVec, - pub ident: Ident, - pub id: NodeId, - pub bounds: TyParamBounds, - pub default: Option>, +pub enum GenericParamKindAST { + /// A lifetime definition, e.g. `'a: 'b+'c+'d`. + Lifetime { + bounds: Vec, + lifetime: Lifetime, + }, + Type { + bounds: TyParamBounds, + default: Option>, + } } #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)] -pub enum GenericParamAST { - Lifetime(LifetimeDef), - Type(TyParam), +pub struct GenericParamAST { + pub ident: Ident, + pub id: NodeId, + pub attrs: ThinVec, + + pub kind: GenericParamKindAST, } impl GenericParamAST { pub fn is_lifetime_param(&self) -> bool { - match *self { - GenericParamAST::Lifetime(_) => true, + match self.kind { + GenericParamKindAST::Lifetime { .. } => true, _ => false, } } pub fn is_type_param(&self) -> bool { - match *self { - GenericParamAST::Type(_) => true, + match self.kind { + GenericParamKindAST::Type { .. } => true, _ => false, } } @@ -383,10 +382,8 @@ impl Generics { pub fn span_for_name(&self, name: &str) -> Option { for param in &self.params { - if let GenericParamAST::Type(ref t) = *param { - if t.ident.name == name { - return Some(t.ident.span); - } + if param.ident.name == name { + return Some(param.ident.span); } } None diff --git a/src/libsyntax/ext/build.rs b/src/libsyntax/ext/build.rs index 1c74a2bd5be0d..42745c14965a3 100644 --- a/src/libsyntax/ext/build.rs +++ b/src/libsyntax/ext/build.rs @@ -69,7 +69,7 @@ pub trait AstBuilder { id: ast::Ident, attrs: Vec, bounds: ast::TyParamBounds, - default: Option>) -> ast::TyParam; + default: Option>) -> ast::GenericParamAST; fn trait_ref(&self, path: ast::Path) -> ast::TraitRef; fn poly_trait_ref(&self, span: Span, path: ast::Path) -> ast::PolyTraitRef; @@ -80,7 +80,7 @@ pub trait AstBuilder { ident: ast::Ident, attrs: Vec, bounds: Vec) - -> ast::LifetimeDef; + -> ast::GenericParamAST; // statements fn stmt_expr(&self, expr: P) -> ast::Stmt; @@ -437,13 +437,15 @@ impl<'a> AstBuilder for ExtCtxt<'a> { ident: ast::Ident, attrs: Vec, bounds: ast::TyParamBounds, - default: Option>) -> ast::TyParam { - ast::TyParam { + default: Option>) -> ast::GenericParamAST { + ast::GenericParamAST { ident: ident.with_span_pos(span), id: ast::DUMMY_NODE_ID, attrs: attrs.into(), - bounds, - default, + kind: ast::GenericParamKindAST::Type { + bounds, + default, + } } } @@ -475,11 +477,16 @@ impl<'a> AstBuilder for ExtCtxt<'a> { ident: ast::Ident, attrs: Vec, bounds: Vec) - -> ast::LifetimeDef { - ast::LifetimeDef { + -> ast::GenericParamAST { + let lifetime = self.lifetime(span, ident); + ast::GenericParamAST { + ident: lifetime.ident, + id: lifetime.id, attrs: attrs.into(), - lifetime: self.lifetime(span, ident), - bounds, + kind: ast::GenericParamKindAST::Lifetime { + lifetime, + bounds, + } } } diff --git a/src/libsyntax/fold.rs b/src/libsyntax/fold.rs index 1e09c7b2206c6..2f43487e036ac 100644 --- a/src/libsyntax/fold.rs +++ b/src/libsyntax/fold.rs @@ -687,38 +687,23 @@ pub fn noop_fold_ty_param_bound(tpb: TyParamBound, fld: &mut T) } } -pub fn noop_fold_ty_param(tp: TyParam, fld: &mut T) -> TyParam { - let TyParam {attrs, id, ident, bounds, default} = tp; - let attrs: Vec<_> = attrs.into(); - TyParam { - attrs: attrs.into_iter() - .flat_map(|x| fld.fold_attribute(x).into_iter()) - .collect::>() - .into(), - id: fld.new_id(id), - ident: fld.fold_ident(ident), - bounds: fld.fold_bounds(bounds), - default: default.map(|x| fld.fold_ty(x)), - } -} - pub fn noop_fold_generic_param(param: GenericParamAST, fld: &mut T) -> GenericParamAST { match param { - GenericParamAST::Lifetime(l) => { - let attrs: Vec<_> = l.attrs.into(); + GenericParamAST::Lifetime { bounds, lifetime } => { + let attrs: Vec<_> = param.attrs.into(); GenericParamAST::Lifetime(LifetimeDef { attrs: attrs.into_iter() .flat_map(|x| fld.fold_attribute(x).into_iter()) .collect::>() .into(), lifetime: Lifetime { - id: fld.new_id(l.lifetime.id), - ident: fld.fold_ident(l.lifetime.ident), + id: fld.new_id(param.id), + ident: fld.fold_ident(param.ident), }, - bounds: l.bounds.move_map(|l| noop_fold_lifetime(l, fld)), + bounds: bounds.move_map(|l| noop_fold_lifetime(l, fld)), }) } - GenericParamAST::Type(t) => GenericParamAST::Type(fld.fold_ty_param(t)), + GenericParamAST::Type { .. } => GenericParamAST::Type(fld.fold_ty_param(param)), } } diff --git a/src/libsyntax/parse/parser.rs b/src/libsyntax/parse/parser.rs index be4a4b8b11fba..2a1fc6b291c31 100644 --- a/src/libsyntax/parse/parser.rs +++ b/src/libsyntax/parse/parser.rs @@ -21,10 +21,10 @@ use ast::EnumDef; use ast::{Expr, ExprKind, RangeLimits}; use ast::{Field, FnDecl}; use ast::{ForeignItem, ForeignItemKind, FunctionRetTy}; -use ast::GenericParamAST; +use ast::{GenericParamAST, GenericParamKindAST}; use ast::GenericArgAST; use ast::{Ident, ImplItem, IsAuto, Item, ItemKind}; -use ast::{Label, Lifetime, LifetimeDef, Lit, LitKind}; +use ast::{Label, Lifetime, Lit, LitKind}; use ast::Local; use ast::MacStmtStyle; use ast::{Mac, Mac_, MacDelimiter}; @@ -36,7 +36,7 @@ use ast::{VariantData, StructField}; use ast::StrStyle; use ast::SelfKind; use ast::{TraitItem, TraitRef, TraitObjectSyntax}; -use ast::{Ty, TyKind, TypeBinding, TyParam, TyParamBounds}; +use ast::{Ty, TyKind, TypeBinding, TyParamBounds}; use ast::{Visibility, VisibilityKind, WhereClause, CrateSugar}; use ast::{UseTree, UseTreeKind}; use ast::{BinOpKind, UnOp}; @@ -1311,9 +1311,7 @@ impl<'a> Parser<'a> { let lo = self.span; let (name, node, generics) = if self.eat_keyword(keywords::Type) { - let (generics, TyParam {ident, bounds, default, ..}) = - self.parse_trait_item_assoc_ty(vec![])?; - (ident, TraitItemKind::Type(bounds, default), generics) + self.parse_trait_item_assoc_ty()? } else if self.is_const_item() { self.expect_keyword(keywords::Const)?; let ident = self.parse_ident()?; @@ -4805,7 +4803,9 @@ impl<'a> Parser<'a> { } /// Matches typaram = IDENT (`?` unbound)? optbounds ( EQ ty )? - fn parse_ty_param(&mut self, preceding_attrs: Vec) -> PResult<'a, TyParam> { + fn parse_ty_param(&mut self, + preceding_attrs: Vec) + -> PResult<'a, GenericParamAST> { let ident = self.parse_ident()?; // Parse optional colon and param bounds. @@ -4821,19 +4821,21 @@ impl<'a> Parser<'a> { None }; - Ok(TyParam { - attrs: preceding_attrs.into(), + Ok(GenericParamAST { ident, + attrs: preceding_attrs.into(), id: ast::DUMMY_NODE_ID, - bounds, - default, + kind: GenericParamKindAST::Type { + bounds, + default, + } }) } /// Parses the following grammar: /// TraitItemAssocTy = Ident ["<"...">"] [":" [TyParamBounds]] ["where" ...] ["=" Ty] - fn parse_trait_item_assoc_ty(&mut self, preceding_attrs: Vec) - -> PResult<'a, (ast::Generics, TyParam)> { + fn parse_trait_item_assoc_ty(&mut self) + -> PResult<'a, (Ident, TraitItemKind, ast::Generics)> { let ident = self.parse_ident()?; let mut generics = self.parse_generics()?; @@ -4852,13 +4854,7 @@ impl<'a> Parser<'a> { }; self.expect(&token::Semi)?; - Ok((generics, TyParam { - attrs: preceding_attrs.into(), - ident, - id: ast::DUMMY_NODE_ID, - bounds, - default, - })) + Ok((ident, TraitItemKind::Type(bounds, default), generics)) } /// Parses (possibly empty) list of lifetime and type parameters, possibly including @@ -4876,18 +4872,22 @@ impl<'a> Parser<'a> { } else { Vec::new() }; - params.push(ast::GenericParamAST::Lifetime(LifetimeDef { + params.push(ast::GenericParamAST { + ident: lifetime.ident, + id: lifetime.id, attrs: attrs.into(), - lifetime, - bounds, - })); + kind: ast::GenericParamKindAST::Lifetime { + lifetime, + bounds, + } + }); if seen_ty_param { self.span_err(self.prev_span, "lifetime parameters must be declared prior to type parameters"); } } else if self.check_ident() { // Parse type parameter. - params.push(ast::GenericParamAST::Type(self.parse_ty_param(attrs)?)); + params.push(self.parse_ty_param(attrs)?); seen_ty_param = true; } else { // Check for trailing attributes and stop parsing. diff --git a/src/libsyntax/print/pprust.rs b/src/libsyntax/print/pprust.rs index a7a85a4c71fa5..1626135400de8 100644 --- a/src/libsyntax/print/pprust.rs +++ b/src/libsyntax/print/pprust.rs @@ -2878,12 +2878,24 @@ impl<'a> State<'a> { self.s.word("<")?; self.commasep(Inconsistent, &generic_params, |s, param| { - match *param { - ast::GenericParamAST::Lifetime(ref lifetime_def) => { - s.print_outer_attributes_inline(&lifetime_def.attrs)?; - s.print_lifetime_bounds(&lifetime_def.lifetime, &lifetime_def.bounds) + match param.kind { + ast::GenericParamKindAST::Lifetime { ref bounds, ref lifetime } => { + s.print_outer_attributes_inline(¶m.attrs)?; + s.print_lifetime_bounds(lifetime, bounds) }, - ast::GenericParamAST::Type(ref ty_param) => s.print_ty_param(ty_param), + ast::GenericParamKindAST::Type { ref bounds, ref default } => { + s.print_outer_attributes_inline(¶m.attrs)?; + s.print_ident(param.ident)?; + s.print_bounds(":", bounds)?; + match default { + Some(ref default) => { + s.s.space()?; + s.word_space("=")?; + s.print_type(default) + } + _ => Ok(()) + } + } } })?; @@ -2891,20 +2903,6 @@ impl<'a> State<'a> { Ok(()) } - pub fn print_ty_param(&mut self, param: &ast::TyParam) -> io::Result<()> { - self.print_outer_attributes_inline(¶m.attrs)?; - self.print_ident(param.ident)?; - self.print_bounds(":", ¶m.bounds)?; - match param.default { - Some(ref default) => { - self.s.space()?; - self.word_space("=")?; - self.print_type(default) - } - _ => Ok(()) - } - } - pub fn print_where_clause(&mut self, where_clause: &ast::WhereClause) -> io::Result<()> { if where_clause.predicates.is_empty() { diff --git a/src/libsyntax/visit.rs b/src/libsyntax/visit.rs index 091673bfba996..c919f6c355c09 100644 --- a/src/libsyntax/visit.rs +++ b/src/libsyntax/visit.rs @@ -491,17 +491,17 @@ pub fn walk_ty_param_bound<'a, V: Visitor<'a>>(visitor: &mut V, bound: &'a TyPar } pub fn walk_generic_param<'a, V: Visitor<'a>>(visitor: &mut V, param: &'a GenericParamAST) { - match *param { - GenericParamAST::Lifetime(ref l) => { - visitor.visit_ident(l.lifetime.ident); - walk_list!(visitor, visit_lifetime, &l.bounds); - walk_list!(visitor, visit_attribute, &*l.attrs); + match param.kind { + GenericParamKindAST::Lifetime { ref bounds, ref lifetime, .. } => { + visitor.visit_ident(param.ident); + walk_list!(visitor, visit_lifetime, bounds); + walk_list!(visitor, visit_attribute, param.attrs.iter()); } - GenericParamAST::Type(ref t) => { + GenericParamKindAST::Type { ref bounds, ref default, .. } => { visitor.visit_ident(t.ident); - walk_list!(visitor, visit_ty_param_bound, &t.bounds); - walk_list!(visitor, visit_ty, &t.default); - walk_list!(visitor, visit_attribute, &*t.attrs); + walk_list!(visitor, visit_ty_param_bound, bounds); + walk_list!(visitor, visit_ty, default); + walk_list!(visitor, visit_attribute, param.attrs.iter()); } } } diff --git a/src/libsyntax_ext/deriving/generic/mod.rs b/src/libsyntax_ext/deriving/generic/mod.rs index 4bc8d208bab91..cbf7b1e087613 100644 --- a/src/libsyntax_ext/deriving/generic/mod.rs +++ b/src/libsyntax_ext/deriving/generic/mod.rs @@ -192,8 +192,8 @@ use std::collections::HashSet; use std::vec; use rustc_target::spec::abi::Abi; -use syntax::ast::{self, BinOpKind, EnumDef, Expr, GenericParamAST, Generics, Ident, PatKind}; -use syntax::ast::{VariantData, GenericArgAST}; +use syntax::ast::{self, BinOpKind, EnumDef, Expr, Generics, Ident, PatKind}; +use syntax::ast::{VariantData, GenericParamKindAST, GenericArgAST}; use syntax::attr; use syntax::ext::base::{Annotatable, ExtCtxt}; use syntax::ext::build::AstBuilder; @@ -547,9 +547,9 @@ impl<'a> TraitDef<'a> { // Create the generic parameters params.extend(generics.params.iter().map(|param| { - match *param { - ref l @ GenericParamAST::Lifetime(_) => l.clone(), - GenericParamAST::Type(ref ty_param) => { + match param.kind { + GenericParamKindAST::Lifetime { .. } => param.clone(), + GenericParamKindAST::Type { bounds: ref ty_bounds, .. } => { // I don't think this can be moved out of the loop, since // a TyParamBound requires an ast id let mut bounds: Vec<_> = @@ -564,12 +564,11 @@ impl<'a> TraitDef<'a> { bounds.push(cx.typarambound(trait_path.clone())); // also add in any bounds from the declaration - for declared_bound in ty_param.bounds.iter() { + for declared_bound in ty_bounds { bounds.push((*declared_bound).clone()); } - let ty_param = cx.typaram(self.span, ty_param.ident, vec![], bounds, None); - GenericParamAST::Type(ty_param) + cx.typaram(self.span, param.ident, vec![], bounds, None) } } })); @@ -607,8 +606,8 @@ impl<'a> TraitDef<'a> { // Extra scope required here so ty_params goes out of scope before params is moved let mut ty_params = params.iter() - .filter_map(|param| match *param { - ast::GenericParamAST::Type(ref t) => Some(t), + .filter_map(|param| match param.kind { + ast::GenericParamKindAST::Type { .. } => Some(param), _ => None, }) .peekable(); @@ -668,17 +667,16 @@ impl<'a> TraitDef<'a> { // Create the type parameters on the `self` path. let self_ty_params: Vec> = generics.params .iter() - .filter_map(|param| match *param { - GenericParamAST::Type(ref ty_param) - => Some(cx.ty_ident(self.span, ty_param.ident)), + .filter_map(|param| match param.kind { + GenericParamKindAST::Type { .. } => Some(cx.ty_ident(self.span, param.ident)), _ => None, }) .collect(); let self_lifetimes: Vec = generics.params .iter() - .filter_map(|param| match *param { - GenericParamAST::Lifetime(ref ld) => Some(ld.lifetime), + .filter_map(|param| match param.kind { + GenericParamKindAST::Lifetime { ref lifetime, .. } => Some(*lifetime), _ => None, }) .collect(); diff --git a/src/libsyntax_ext/deriving/generic/ty.rs b/src/libsyntax_ext/deriving/generic/ty.rs index 22487e7bfe398..c9f274ed21090 100644 --- a/src/libsyntax_ext/deriving/generic/ty.rs +++ b/src/libsyntax_ext/deriving/generic/ty.rs @@ -15,7 +15,7 @@ pub use self::PtrTy::*; pub use self::Ty::*; use syntax::ast; -use syntax::ast::{Expr, GenericParamAST, Generics, Ident, SelfKind, GenericArgAST}; +use syntax::ast::{Expr, GenericParamKindAST, Generics, Ident, SelfKind, GenericArgAST}; use syntax::ext::base::ExtCtxt; use syntax::ext::build::AstBuilder; use syntax::codemap::{respan, DUMMY_SP}; @@ -191,9 +191,9 @@ impl<'a> Ty<'a> { Self_ => { let ty_params: Vec> = self_generics.params .iter() - .filter_map(|param| match *param { - GenericParamAST::Type(ref ty_param) => { - Some(cx.ty_ident(span, ty_param.ident)) + .filter_map(|param| match param.kind { + GenericParamKindAST::Type { .. } => { + Some(cx.ty_ident(span, param.ident)) } _ => None, }) @@ -201,8 +201,8 @@ impl<'a> Ty<'a> { let lifetimes: Vec = self_generics.params .iter() - .filter_map(|param| match *param { - GenericParamAST::Lifetime(ref ld) => Some(ld.lifetime), + .filter_map(|param| match param.kind { + GenericParamKindAST::Lifetime { ref lifetime, .. } => Some(*lifetime), _ => None, }) .collect(); @@ -234,7 +234,7 @@ fn mk_ty_param(cx: &ExtCtxt, bounds: &[Path], self_ident: Ident, self_generics: &Generics) - -> ast::TyParam { + -> ast::GenericParamAST { let bounds = bounds.iter() .map(|b| { let path = b.to_path(cx, span, self_ident, self_generics); @@ -244,7 +244,7 @@ fn mk_ty_param(cx: &ExtCtxt, cx.typaram(span, cx.ident_of(name), attrs.to_owned(), bounds, None) } -fn mk_generics(params: Vec, span: Span) -> Generics { +fn mk_generics(params: Vec, span: Span) -> Generics { Generics { params, where_clause: ast::WhereClause { @@ -282,16 +282,13 @@ impl<'a> LifetimeBounds<'a> { let bounds = bounds.iter() .map(|b| cx.lifetime(span, Ident::from_str(b))) .collect(); - let lifetime_def = cx.lifetime_def(span, Ident::from_str(lt), vec![], bounds); - GenericParamAST::Lifetime(lifetime_def) + cx.lifetime_def(span, Ident::from_str(lt), vec![], bounds) }) .chain(self.bounds .iter() .map(|t| { let (name, ref bounds) = *t; - GenericParamAST::Type(mk_ty_param( - cx, span, name, &[], &bounds, self_ty, self_generics - )) + mk_ty_param(cx, span, name, &[], &bounds, self_ty, self_generics) }) ) .collect(); diff --git a/src/libsyntax_ext/deriving/mod.rs b/src/libsyntax_ext/deriving/mod.rs index 9bc19bb5ede68..6813ce4c265f9 100644 --- a/src/libsyntax_ext/deriving/mod.rs +++ b/src/libsyntax_ext/deriving/mod.rs @@ -134,9 +134,12 @@ fn hygienic_type_parameter(item: &Annotatable, base: &str) -> String { match item.node { ast::ItemKind::Struct(_, ast::Generics { ref params, .. }) | ast::ItemKind::Enum(_, ast::Generics { ref params, .. }) => { - for param in params.iter() { - if let ast::GenericParamAST::Type(ref ty) = *param { - typaram.push_str(&ty.ident.as_str()); + for param in params { + match param.kind { + ast::GenericParamKindAST::Type { .. } => { + typaram.push_str(¶m.ident.as_str()); + } + _ => {} } } } From e1d888c7225786530dae2461567e991f398388cf Mon Sep 17 00:00:00 2001 From: varkor Date: Sat, 26 May 2018 23:21:08 +0100 Subject: [PATCH 12/41] Remove methods from ast::GenericParam and ast::Generics --- src/librustc/hir/lowering.rs | 5 ++- src/librustc_passes/ast_validation.rs | 2 +- src/libsyntax/ast.rs | 39 ----------------------- src/libsyntax/feature_gate.rs | 4 +-- src/libsyntax/print/pprust.rs | 2 +- src/libsyntax/test.rs | 2 +- src/libsyntax_ext/deriving/clone.rs | 5 ++- src/libsyntax_ext/deriving/generic/mod.rs | 5 ++- 8 files changed, 17 insertions(+), 47 deletions(-) diff --git a/src/librustc/hir/lowering.rs b/src/librustc/hir/lowering.rs index 68ceb39d575d6..67afe58912992 100644 --- a/src/librustc/hir/lowering.rs +++ b/src/librustc/hir/lowering.rs @@ -324,7 +324,10 @@ impl<'a> LoweringContext<'a> { let count = generics .params .iter() - .filter(|param| param.is_lifetime_param()) + .filter(|param| match param.kind { + ast::GenericParamKindAST::Lifetime { .. } => true, + _ => false, + }) .count(); self.lctx.type_def_lifetime_params.insert(def_id, count); } diff --git a/src/librustc_passes/ast_validation.rs b/src/librustc_passes/ast_validation.rs index d7ebd40f49b44..9a1dfbd931a3c 100644 --- a/src/librustc_passes/ast_validation.rs +++ b/src/librustc_passes/ast_validation.rs @@ -294,7 +294,7 @@ impl<'a> Visitor<'a> for AstValidator<'a> { ItemKind::Trait(is_auto, _, ref generics, ref bounds, ref trait_items) => { if is_auto == IsAuto::Yes { // Auto traits cannot have generics, super traits nor contain items. - if generics.is_parameterized() { + if !generics.params.is_empty() { struct_span_err!(self.session, item.span, E0567, "auto traits cannot have generic parameters").emit(); } diff --git a/src/libsyntax/ast.rs b/src/libsyntax/ast.rs index c354edc5aaff4..715e4d233dfbd 100644 --- a/src/libsyntax/ast.rs +++ b/src/libsyntax/ast.rs @@ -342,22 +342,6 @@ pub struct GenericParamAST { pub kind: GenericParamKindAST, } -impl GenericParamAST { - pub fn is_lifetime_param(&self) -> bool { - match self.kind { - GenericParamKindAST::Lifetime { .. } => true, - _ => false, - } - } - - pub fn is_type_param(&self) -> bool { - match self.kind { - GenericParamKindAST::Type { .. } => true, - _ => false, - } - } -} - /// Represents lifetime, type and const parameters attached to a declaration of /// a function, enum, trait, etc. #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)] @@ -367,29 +351,6 @@ pub struct Generics { pub span: Span, } -impl Generics { - pub fn is_lt_parameterized(&self) -> bool { - self.params.iter().any(|param| param.is_lifetime_param()) - } - - pub fn is_type_parameterized(&self) -> bool { - self.params.iter().any(|param| param.is_type_param()) - } - - pub fn is_parameterized(&self) -> bool { - !self.params.is_empty() - } - - pub fn span_for_name(&self, name: &str) -> Option { - for param in &self.params { - if param.ident.name == name { - return Some(param.ident.span); - } - } - None - } -} - impl Default for Generics { /// Creates an instance of `Generics`. fn default() -> Generics { diff --git a/src/libsyntax/feature_gate.rs b/src/libsyntax/feature_gate.rs index a2ea6a214841e..be4cf197be4eb 100644 --- a/src/libsyntax/feature_gate.rs +++ b/src/libsyntax/feature_gate.rs @@ -1797,7 +1797,7 @@ impl<'a> Visitor<'a> for PostExpansionVisitor<'a> { gate_feature_post!(&self, associated_type_defaults, ti.span, "associated type defaults are unstable"); } - if ti.generics.is_parameterized() { + if !ti.generics.params.is_empty() { gate_feature_post!(&self, generic_associated_types, ti.span, "generic associated types are unstable"); } @@ -1824,7 +1824,7 @@ impl<'a> Visitor<'a> for PostExpansionVisitor<'a> { gate_feature_post!(&self, const_fn, ii.span, "const fn is unstable"); } } - ast::ImplItemKind::Type(_) if ii.generics.is_parameterized() => { + ast::ImplItemKind::Type(_) if !ii.generics.params.is_empty() => { gate_feature_post!(&self, generic_associated_types, ii.span, "generic associated types are unstable"); } diff --git a/src/libsyntax/print/pprust.rs b/src/libsyntax/print/pprust.rs index 1626135400de8..458947299c816 100644 --- a/src/libsyntax/print/pprust.rs +++ b/src/libsyntax/print/pprust.rs @@ -1329,7 +1329,7 @@ impl<'a> State<'a> { self.print_unsafety(unsafety)?; self.word_nbsp("impl")?; - if generics.is_parameterized() { + if !generics.params.is_empty() { self.print_generic_params(&generics.params)?; self.s.space()?; } diff --git a/src/libsyntax/test.rs b/src/libsyntax/test.rs index da7deb3c4cfe7..f896fa351b0af 100644 --- a/src/libsyntax/test.rs +++ b/src/libsyntax/test.rs @@ -353,7 +353,7 @@ fn is_test_fn(cx: &TestCtxt, i: &ast::Item) -> bool { match (has_output, has_should_panic_attr) { (true, true) => No(BadTestSignature::ShouldPanicOnlyWithNoArgs), - (true, false) => if generics.is_parameterized() { + (true, false) => if !generics.params.is_empty() { No(BadTestSignature::WrongTypeSignature) } else { Yes diff --git a/src/libsyntax_ext/deriving/clone.rs b/src/libsyntax_ext/deriving/clone.rs index 40d49b4996048..5f943a4cd00d5 100644 --- a/src/libsyntax_ext/deriving/clone.rs +++ b/src/libsyntax_ext/deriving/clone.rs @@ -49,7 +49,10 @@ pub fn expand_deriving_clone(cx: &mut ExtCtxt, ItemKind::Struct(_, Generics { ref params, .. }) | ItemKind::Enum(_, Generics { ref params, .. }) => { if attr::contains_name(&annitem.attrs, "rustc_copy_clone_marker") && - !params.iter().any(|param| param.is_type_param()) + !params.iter().any(|param| match param.kind { + ast::GenericParamKindAST::Type { .. } => true, + _ => false, + }) { bounds = vec![]; is_shallow = true; diff --git a/src/libsyntax_ext/deriving/generic/mod.rs b/src/libsyntax_ext/deriving/generic/mod.rs index cbf7b1e087613..e461c9640d1a7 100644 --- a/src/libsyntax_ext/deriving/generic/mod.rs +++ b/src/libsyntax_ext/deriving/generic/mod.rs @@ -422,7 +422,10 @@ impl<'a> TraitDef<'a> { ast::ItemKind::Struct(_, ref generics) | ast::ItemKind::Enum(_, ref generics) | ast::ItemKind::Union(_, ref generics) => { - !generics.params.iter().any(|p| p.is_type_param()) + !generics.params.iter().any(|param| match param.kind { + ast::GenericParamKindAST::Type { .. } => true, + _ => false, + }) } _ => { // Non-ADT derive is an error, but it should have been From c65454850f80a99e995fc71b74b475a77d0e5f30 Mon Sep 17 00:00:00 2001 From: varkor Date: Sat, 26 May 2018 23:54:48 +0100 Subject: [PATCH 13/41] Remove AngleBracketedArgs impl --- src/librustc/hir/lowering.rs | 6 +++++- src/librustc_driver/pretty.rs | 16 +++++++++++----- src/librustc_passes/ast_validation.rs | 17 ++++++++++------- src/librustc_save_analysis/dump_visitor.rs | 18 +++++++++++++----- src/libsyntax/ast.rs | 22 ---------------------- 5 files changed, 39 insertions(+), 40 deletions(-) diff --git a/src/librustc/hir/lowering.rs b/src/librustc/hir/lowering.rs index 67afe58912992..830481d4f7361 100644 --- a/src/librustc/hir/lowering.rs +++ b/src/librustc/hir/lowering.rs @@ -1754,12 +1754,16 @@ impl<'a> LoweringContext<'a> { itctx: ImplTraitContext, ) -> (hir::GenericArgs, bool) { let &AngleBracketedArgs { ref args, ref bindings, .. } = data; + let has_types = args.iter().any(|arg| match arg { + GenericArgAST::Type(_) => true, + _ => false, + }); (hir::GenericArgs { args: args.iter().map(|a| self.lower_generic_arg(a, itctx)).collect(), bindings: bindings.iter().map(|b| self.lower_ty_binding(b, itctx)).collect(), parenthesized: false, }, - data.types().count() == 0 && param_mode == ParamMode::Optional) + has_types && param_mode == ParamMode::Optional) } fn lower_parenthesized_parameter_data( diff --git a/src/librustc_driver/pretty.rs b/src/librustc_driver/pretty.rs index 0ea2832bf80d9..14003f0fd3719 100644 --- a/src/librustc_driver/pretty.rs +++ b/src/librustc_driver/pretty.rs @@ -679,12 +679,18 @@ impl<'a> ReplaceBodyWithLoop<'a> { ast::TyKind::Path(_, ref path) => path.segments.iter().any(|seg| { match seg.args.as_ref().map(|generic_arg| &**generic_arg) { None => false, - Some(&ast::GenericArgs::AngleBracketed(ref data)) => - any_involves_impl_trait(data.types().into_iter()) || - any_involves_impl_trait(data.bindings.iter().map(|b| &b.ty)), - Some(&ast::GenericArgs::Parenthesized(ref data)) => + Some(&ast::GenericArgs::AngleBracketed(ref data)) => { + let types = data.args.iter().filter_map(|arg| match arg { + ast::GenericArgAST::Type(ty) => Some(ty), + _ => None, + }); + any_involves_impl_trait(types.into_iter()) || + any_involves_impl_trait(data.bindings.iter().map(|b| &b.ty)) + }, + Some(&ast::GenericArgs::Parenthesized(ref data)) => { any_involves_impl_trait(data.inputs.iter()) || - any_involves_impl_trait(data.output.iter()), + any_involves_impl_trait(data.output.iter()) + } } }), _ => false, diff --git a/src/librustc_passes/ast_validation.rs b/src/librustc_passes/ast_validation.rs index 9a1dfbd931a3c..a6ef83671a55e 100644 --- a/src/librustc_passes/ast_validation.rs +++ b/src/librustc_passes/ast_validation.rs @@ -515,21 +515,24 @@ impl<'a> Visitor<'a> for NestedImplTraitVisitor<'a> { } fn visit_generic_args(&mut self, _: Span, generic_args: &'a GenericArgs) { match *generic_args { - GenericArgs::AngleBracketed(ref generic_args) => { - for type_ in generic_args.types() { - self.visit_ty(type_); + GenericArgs::AngleBracketed(ref data) => { + for arg in &data.args { + match arg { + GenericArgAST::Type(ty) => self.visit_ty(ty), + _ => {} + } } - for type_binding in &generic_args.bindings { + for type_binding in &data.bindings { // Type bindings such as `Item=impl Debug` in `Iterator` // are allowed to contain nested `impl Trait`. self.with_impl_trait(None, |this| visit::walk_ty(this, &type_binding.ty)); } } - GenericArgs::Parenthesized(ref generic_args) => { - for type_ in &generic_args.inputs { + GenericArgs::Parenthesized(ref data) => { + for type_ in &data.inputs { self.visit_ty(type_); } - if let Some(ref type_) = generic_args.output { + if let Some(ref type_) = data.output { // `-> Foo` syntax is essentially an associated type binding, // so it is also allowed to contain nested `impl Trait`. self.with_impl_trait(None, |this| visit::walk_ty(this, type_)); diff --git a/src/librustc_save_analysis/dump_visitor.rs b/src/librustc_save_analysis/dump_visitor.rs index 94552e08a8cea..5faa3559c76aa 100644 --- a/src/librustc_save_analysis/dump_visitor.rs +++ b/src/librustc_save_analysis/dump_visitor.rs @@ -825,9 +825,14 @@ impl<'l, 'tcx: 'l, 'll, O: DumpOutput + 'll> DumpVisitor<'l, 'tcx, 'll, O> { for seg in &path.segments { if let Some(ref generic_args) = seg.args { match **generic_args { - ast::GenericArgs::AngleBracketed(ref data) => for t in data.types() { - self.visit_ty(t); - }, + ast::GenericArgs::AngleBracketed(ref data) => { + for arg in &data.args { + match arg { + ast::GenericArgAST::Type(ty) => self.visit_ty(ty), + _ => {} + } + } + } ast::GenericArgs::Parenthesized(ref data) => { for t in &data.inputs { self.visit_ty(t); @@ -910,8 +915,11 @@ impl<'l, 'tcx: 'l, 'll, O: DumpOutput + 'll> DumpVisitor<'l, 'tcx, 'll, O> { // Explicit types in the turbo-fish. if let Some(ref generic_args) = seg.args { if let ast::GenericArgs::AngleBracketed(ref data) = **generic_args { - for t in data.types() { - self.visit_ty(t); + for arg in &data.args { + match arg { + ast::GenericArgAST::Type(ty) => self.visit_ty(ty), + _ => {} + } } } } diff --git a/src/libsyntax/ast.rs b/src/libsyntax/ast.rs index 715e4d233dfbd..c2626c70a4273 100644 --- a/src/libsyntax/ast.rs +++ b/src/libsyntax/ast.rs @@ -178,28 +178,6 @@ pub struct AngleBracketedArgs { pub bindings: Vec, } -impl AngleBracketedArgs { - pub fn lifetimes(&self) -> impl DoubleEndedIterator { - self.args.iter().filter_map(|arg| { - if let GenericArgAST::Lifetime(lt) = arg { - Some(lt) - } else { - None - } - }) - } - - pub fn types(&self) -> impl DoubleEndedIterator> { - self.args.iter().filter_map(|arg| { - if let GenericArgAST::Type(ty) = arg { - Some(ty) - } else { - None - } - }) - } -} - impl Into>> for AngleBracketedArgs { fn into(self) -> Option> { Some(P(GenericArgs::AngleBracketed(self))) From 10229fd9d5701179e2148a1d4bbfda0062a2225f Mon Sep 17 00:00:00 2001 From: varkor Date: Sat, 26 May 2018 23:56:34 +0100 Subject: [PATCH 14/41] Rename DefPathData::LifetimeDef to LifetimeParam --- src/librustc/hir/lowering.rs | 4 ++-- src/librustc/hir/map/def_collector.rs | 2 +- src/librustc/hir/map/definitions.rs | 6 +++--- src/librustc/ty/item_path.rs | 2 +- src/librustc/util/ppaux.rs | 2 +- 5 files changed, 8 insertions(+), 8 deletions(-) diff --git a/src/librustc/hir/lowering.rs b/src/librustc/hir/lowering.rs index 830481d4f7361..4f86f6348d868 100644 --- a/src/librustc/hir/lowering.rs +++ b/src/librustc/hir/lowering.rs @@ -699,7 +699,7 @@ impl<'a> LoweringContext<'a> { self.resolver.definitions().create_def_with_parent( parent_id.index, def_node_id, - DefPathData::LifetimeDef(str_name.as_interned_str()), + DefPathData::LifetimeParam(str_name.as_interned_str()), DefIndexAddressSpace::High, Mark::root(), span, @@ -1424,7 +1424,7 @@ impl<'a> LoweringContext<'a> { self.context.resolver.definitions().create_def_with_parent( self.parent, def_node_id, - DefPathData::LifetimeDef(name.name().as_interned_str()), + DefPathData::LifetimeParam(name.name().as_interned_str()), DefIndexAddressSpace::High, Mark::root(), lifetime.span, diff --git a/src/librustc/hir/map/def_collector.rs b/src/librustc/hir/map/def_collector.rs index 6015063aa821f..6555be110d140 100644 --- a/src/librustc/hir/map/def_collector.rs +++ b/src/librustc/hir/map/def_collector.rs @@ -173,7 +173,7 @@ impl<'a> visit::Visitor<'a> for DefCollector<'a> { fn visit_generic_param(&mut self, param: &'a GenericParamAST) { let name = param.ident.name.as_interned_str(); let def_path_data = match param.kind { - GenericParamKindAST::Lifetime { .. } => DefPathData::LifetimeDef(name), + GenericParamKindAST::Lifetime { .. } => DefPathData::LifetimeParam(name), GenericParamKindAST::Type { .. } => DefPathData::TypeParam(name), }; self.create_def( diff --git a/src/librustc/hir/map/definitions.rs b/src/librustc/hir/map/definitions.rs index 99023a1686741..b1cb9d7fbd4a5 100644 --- a/src/librustc/hir/map/definitions.rs +++ b/src/librustc/hir/map/definitions.rs @@ -360,7 +360,7 @@ pub enum DefPathData { /// A type parameter (generic parameter) TypeParam(InternedString), /// A lifetime definition - LifetimeDef(InternedString), + LifetimeParam(InternedString), /// A variant of a enum EnumVariant(InternedString), /// A struct field @@ -625,7 +625,7 @@ impl DefPathData { Module(name) | MacroDef(name) | TypeParam(name) | - LifetimeDef(name) | + LifetimeParam(name) | EnumVariant(name) | Field(name) | GlobalMetaData(name) => Some(name), @@ -652,7 +652,7 @@ impl DefPathData { Module(name) | MacroDef(name) | TypeParam(name) | - LifetimeDef(name) | + LifetimeParam(name) | EnumVariant(name) | Field(name) | GlobalMetaData(name) => { diff --git a/src/librustc/ty/item_path.rs b/src/librustc/ty/item_path.rs index d858ba7acf786..479fbe2673b97 100644 --- a/src/librustc/ty/item_path.rs +++ b/src/librustc/ty/item_path.rs @@ -215,7 +215,7 @@ impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'tcx> { data @ DefPathData::ValueNs(..) | data @ DefPathData::Module(..) | data @ DefPathData::TypeParam(..) | - data @ DefPathData::LifetimeDef(..) | + data @ DefPathData::LifetimeParam(..) | data @ DefPathData::EnumVariant(..) | data @ DefPathData::Field(..) | data @ DefPathData::AnonConst | diff --git a/src/librustc/util/ppaux.rs b/src/librustc/util/ppaux.rs index 883882dfe6837..772de04d364da 100644 --- a/src/librustc/util/ppaux.rs +++ b/src/librustc/util/ppaux.rs @@ -287,7 +287,7 @@ impl PrintContext { DefPathData::MacroDef(_) | DefPathData::ClosureExpr | DefPathData::TypeParam(_) | - DefPathData::LifetimeDef(_) | + DefPathData::LifetimeParam(_) | DefPathData::Field(_) | DefPathData::StructCtor | DefPathData::AnonConst | From 80b381e041d12259f24b1282e10e0a224bc6ec0e Mon Sep 17 00:00:00 2001 From: varkor Date: Sun, 27 May 2018 01:43:03 +0100 Subject: [PATCH 15/41] Remove all traces of lifetimes() and types() methods --- src/librustc/hir/lowering.rs | 8 +- src/librustc/hir/mod.rs | 32 +- src/librustc/hir/print.rs | 23 +- src/librustc/middle/resolve_lifetime.rs | 317 ++++++++++---------- src/librustc/traits/auto_trait.rs | 8 +- src/librustc/util/ppaux.rs | 10 +- src/librustc_metadata/encoder.rs | 10 +- src/librustc_typeck/astconv.rs | 44 ++- src/librustc_typeck/check/compare_method.rs | 8 +- src/librustc_typeck/check/method/confirm.rs | 33 +- src/librustc_typeck/check/mod.rs | 50 +-- src/librustc_typeck/check/wfcheck.rs | 8 +- src/librustc_typeck/collect.rs | 89 +++--- src/librustdoc/clean/mod.rs | 80 +++-- src/librustdoc/lib.rs | 1 + src/libsyntax_ext/deriving/generic/mod.rs | 44 ++- 16 files changed, 419 insertions(+), 346 deletions(-) diff --git a/src/librustc/hir/lowering.rs b/src/librustc/hir/lowering.rs index 4f86f6348d868..1c62e5813ff36 100644 --- a/src/librustc/hir/lowering.rs +++ b/src/librustc/hir/lowering.rs @@ -1731,7 +1731,11 @@ impl<'a> LoweringContext<'a> { self.lower_angle_bracketed_parameter_data(&Default::default(), param_mode, itctx) }; - if !generic_args.parenthesized && generic_args.lifetimes().count() == 0 { + let has_lifetimes = generic_args.args.iter().any(|arg| match arg { + GenericArg::Lifetime(_) => true, + _ => false, + }); + if !generic_args.parenthesized && !has_lifetimes { generic_args.args = self.elided_path_lifetimes(path_span, expected_lifetimes) .into_iter() @@ -1763,7 +1767,7 @@ impl<'a> LoweringContext<'a> { bindings: bindings.iter().map(|b| self.lower_ty_binding(b, itctx)).collect(), parenthesized: false, }, - has_types && param_mode == ParamMode::Optional) + !has_types && param_mode == ParamMode::Optional) } fn lower_parenthesized_parameter_data( diff --git a/src/librustc/hir/mod.rs b/src/librustc/hir/mod.rs index 0c378262dca55..bb830a042e391 100644 --- a/src/librustc/hir/mod.rs +++ b/src/librustc/hir/mod.rs @@ -400,34 +400,20 @@ impl GenericArgs { pub fn inputs(&self) -> &[P] { if self.parenthesized { - if let Some(ref ty) = self.types().next() { - if let TyTup(ref tys) = ty.node { - return tys; + for arg in &self.args { + match arg { + GenericArg::Lifetime(_) => {} + GenericArg::Type(ref ty) => { + if let TyTup(ref tys) = ty.node { + return tys; + } + break; + } } } } bug!("GenericArgs::inputs: not a `Fn(T) -> U`"); } - - pub fn lifetimes(&self) -> impl DoubleEndedIterator { - self.args.iter().filter_map(|p| { - if let GenericArg::Lifetime(lt) = p { - Some(lt) - } else { - None - } - }) - } - - pub fn types(&self) -> impl DoubleEndedIterator> { - self.args.iter().filter_map(|p| { - if let GenericArg::Type(ty) = p { - Some(ty) - } else { - None - } - }) - } } /// The AST represents all type param bounds as types. diff --git a/src/librustc/hir/print.rs b/src/librustc/hir/print.rs index afb3a6d0e6c48..dc5d9749227dc 100644 --- a/src/librustc/hir/print.rs +++ b/src/librustc/hir/print.rs @@ -1731,20 +1731,31 @@ impl<'a> State<'a> { } }; - let elide_lifetimes = generic_args.lifetimes().all(|lt| lt.is_elided()); + let mut types = vec![]; + let mut elide_lifetimes = true; + for arg in &generic_args.args { + match arg { + GenericArg::Lifetime(lt) => { + if !lt.is_elided() { + elide_lifetimes = false; + } + } + GenericArg::Type(ty) => { + types.push(ty); + } + } + } if !elide_lifetimes { start_or_comma(self)?; self.commasep(Inconsistent, &generic_args.args, |s, generic_arg| { match generic_arg { GenericArg::Lifetime(lt) => s.print_lifetime(lt), GenericArg::Type(ty) => s.print_type(ty), - } + } })?; - } else if generic_args.types().count() != 0 { + } else if !types.is_empty() { start_or_comma(self)?; - self.commasep(Inconsistent, - &generic_args.types().collect::>(), - |s, ty| s.print_type(&ty))?; + self.commasep(Inconsistent, &types, |s, ty| s.print_type(&ty))?; } // FIXME(eddyb) This would leak into error messages, e.g.: diff --git a/src/librustc/middle/resolve_lifetime.rs b/src/librustc/middle/resolve_lifetime.rs index dfa205e6a34d2..358df3a1733c9 100644 --- a/src/librustc/middle/resolve_lifetime.rs +++ b/src/librustc/middle/resolve_lifetime.rs @@ -18,8 +18,7 @@ use hir::def::Def; use hir::def_id::{CrateNum, DefId, LocalDefId, LOCAL_CRATE}; use hir::map::Map; -use hir::ItemLocalId; -use hir::LifetimeName; +use hir::{GenericArg, ItemLocalId, LifetimeName}; use ty::{self, TyCtxt, GenericParamDefKind}; use errors::DiagnosticBuilder; @@ -533,15 +532,13 @@ impl<'a, 'tcx> Visitor<'tcx> for LifetimeContext<'a, 'tcx> { 0 }; let mut type_count = 0; - let lifetimes = generics.params.iter().filter_map(|param| { - match param.kind { - GenericParamKind::Lifetime { .. } => { - Some(Region::early(&self.tcx.hir, &mut index, param)) - } - GenericParamKind::Type { .. } => { - type_count += 1; - None - } + let lifetimes = generics.params.iter().filter_map(|param| match param.kind { + GenericParamKind::Lifetime { .. } => { + Some(Region::early(&self.tcx.hir, &mut index, param)) + } + GenericParamKind::Type { .. } => { + type_count += 1; + None } }).collect(); let scope = Scope::Binder { @@ -585,13 +582,11 @@ impl<'a, 'tcx> Visitor<'tcx> for LifetimeContext<'a, 'tcx> { let scope = Scope::Binder { lifetimes: c.generic_params .iter() - .filter_map(|param| { - match param.kind { - GenericParamKind::Lifetime { .. } => { - Some(Region::late(&self.tcx.hir, param)) - } - _ => None, + .filter_map(|param| match param.kind { + GenericParamKind::Lifetime { .. } => { + Some(Region::late(&self.tcx.hir, param)) } + _ => None, }) .collect(), s: self.scope, @@ -777,15 +772,13 @@ impl<'a, 'tcx> Visitor<'tcx> for LifetimeContext<'a, 'tcx> { let mut type_count = 0; let lifetimes = generics.params .iter() - .filter_map(|param| { - match param.kind { - GenericParamKind::Lifetime { .. } => { - Some(Region::early(&self.tcx.hir, &mut index, param)) - } - GenericParamKind::Type { .. } => { - type_count += 1; - None - } + .filter_map(|param| match param.kind { + GenericParamKind::Lifetime { .. } => { + Some(Region::early(&self.tcx.hir, &mut index, param)) + } + GenericParamKind::Type { .. } => { + type_count += 1; + None } }) .collect(); @@ -834,15 +827,13 @@ impl<'a, 'tcx> Visitor<'tcx> for LifetimeContext<'a, 'tcx> { debug!("visit_ty: index = {}", index); let lifetimes = generics.params .iter() - .filter_map(|param| { - match param.kind { - GenericParamKind::Lifetime { .. } => { - Some(Region::early(&self.tcx.hir, &mut index, param)) - } - GenericParamKind::Type { .. } => { - next_early_index += 1; - None - } + .filter_map(|param| match param.kind { + GenericParamKind::Lifetime { .. } => { + Some(Region::early(&self.tcx.hir, &mut index, param)) + } + GenericParamKind::Type { .. } => { + next_early_index += 1; + None } }) .collect(); @@ -899,11 +890,9 @@ 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.tcx, - &generics.params.iter().filter_map(|param| { - match param.kind { - GenericParamKind::Lifetime { .. } => Some(param.clone()), - _ => None, - } + &generics.params.iter().filter_map(|param| match param.kind { + GenericParamKind::Lifetime { .. } => Some(param.clone()), + _ => None, }).collect::>() ); for param in &generics.params { @@ -926,13 +915,11 @@ impl<'a, 'tcx> Visitor<'tcx> for LifetimeContext<'a, 'tcx> { .. }) => { let lifetimes: FxHashMap<_, _> = bound_generic_params.iter() - .filter_map(|param| { - match param.kind { - GenericParamKind::Lifetime { .. } => { - Some(Region::late(&self.tcx.hir, param)) - } - _ => None, + .filter_map(|param| match param.kind { + GenericParamKind::Lifetime { .. } => { + Some(Region::late(&self.tcx.hir, param)) } + _ => None, }) .collect(); if !lifetimes.is_empty() { @@ -990,11 +977,9 @@ impl<'a, 'tcx> Visitor<'tcx> for LifetimeContext<'a, 'tcx> { || trait_ref .bound_generic_params .iter() - .any(|param| { - match param.kind { - GenericParamKind::Lifetime { .. } => true, - _ => false, - } + .any(|param| match param.kind { + GenericParamKind::Lifetime { .. } => true, + _ => false, }) { if self.trait_ref_hack { @@ -1010,13 +995,11 @@ impl<'a, 'tcx> Visitor<'tcx> for LifetimeContext<'a, 'tcx> { lifetimes: trait_ref .bound_generic_params .iter() - .filter_map(|param| { - match param.kind { - GenericParamKind::Lifetime { .. } => { - Some(Region::late(&self.tcx.hir, param)) - } - _ => None, + .filter_map(|param| match param.kind { + GenericParamKind::Lifetime { .. } => { + Some(Region::late(&self.tcx.hir, param)) } + _ => None, }) .collect(), s: self.scope, @@ -1087,11 +1070,9 @@ fn check_mixed_explicit_and_in_band_defs( tcx: TyCtxt<'_, '_, '_>, params: &[hir::GenericParam], ) { - let in_bands: Vec<_> = params.iter().map(|param| { - match param.kind { - GenericParamKind::Lifetime { in_band, .. } => (in_band, param.span), - _ => bug!("expected lifetime param"), - } + let in_bands: Vec<_> = params.iter().map(|param| match param.kind { + GenericParamKind::Lifetime { in_band, .. } => (in_band, param.span), + _ => bug!("expected lifetime param"), }).collect(); let out_of_band = in_bands.iter().find(|(in_band, _)| !in_band); let in_band = in_bands.iter().find(|(in_band, _)| *in_band); @@ -1262,18 +1243,16 @@ fn compute_object_lifetime_defaults( Set1::One(Region::Static) => "'static".to_string(), Set1::One(Region::EarlyBound(i, _, _)) => { let mut j = 0; - generics.params.iter().find(|param| { - match param.kind { + generics.params.iter().find(|param| match param.kind { GenericParamKind::Lifetime { .. } => { if i == j { return true; } j += 1; + false } - _ => {} - } - false - }).unwrap() + _ => false, + }).unwrap() .name() .to_string() } @@ -1308,64 +1287,60 @@ fn object_lifetime_defaults_for_item( } } - generics.params.iter().filter_map(|param| { - match param.kind { - GenericParamKind::Lifetime { .. } => None, - GenericParamKind::Type { ref bounds, .. } => { - let mut set = Set1::Empty; - - add_bounds(&mut set, &bounds); - - 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 { - hir::WherePredicate::BoundPredicate(ref data) => data, - _ => continue, - }; + generics.params.iter().filter_map(|param| match param.kind { + GenericParamKind::Lifetime { .. } => None, + GenericParamKind::Type { ref bounds, .. } => { + let mut set = Set1::Empty; - // Ignore `for<'a> type: ...` as they can change what - // lifetimes mean (although we could "just" handle it). - if !data.bound_generic_params.is_empty() { - continue; - } + add_bounds(&mut set, &bounds); - let def = match data.bounded_ty.node { - hir::TyPath(hir::QPath::Resolved(None, ref path)) => path.def, - _ => continue, - }; + 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 { + hir::WherePredicate::BoundPredicate(ref data) => data, + _ => continue, + }; - if def == Def::TyParam(param_def_id) { - add_bounds(&mut set, &data.bounds); - } + // Ignore `for<'a> type: ...` as they can change what + // lifetimes mean (although we could "just" handle it). + if !data.bound_generic_params.is_empty() { + continue; } - Some(match set { - Set1::Empty => Set1::Empty, - Set1::One(name) => { - if name == hir::LifetimeName::Static { - Set1::One(Region::Static) - } else { - generics.params.iter().filter_map(|param| { - match param.kind { - GenericParamKind::Lifetime { name, in_band, .. } => { - Some((param.id, name, in_band)) - } - _ => None, - } - }) - .enumerate() - .find(|&(_, (_, lt_name, _))| lt_name == name) - .map_or(Set1::Many, |(i, (id, _, in_band))| { - let def_id = tcx.hir.local_def_id(id); - let origin = LifetimeDefOrigin::from_is_in_band(in_band); - Set1::One(Region::EarlyBound(i as u32, def_id, origin)) - }) - } - } - Set1::Many => Set1::Many, - }) + 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); + } } + + Some(match set { + Set1::Empty => Set1::Empty, + Set1::One(name) => { + if name == hir::LifetimeName::Static { + Set1::One(Region::Static) + } else { + generics.params.iter().filter_map(|param| match param.kind { + GenericParamKind::Lifetime { name, in_band, .. } => { + Some((param.id, name, in_band)) + } + _ => None, + }) + .enumerate() + .find(|&(_, (_, lt_name, _))| lt_name == name) + .map_or(Set1::Many, |(i, (id, _, in_band))| { + let def_id = tcx.hir.local_def_id(id); + let origin = LifetimeDefOrigin::from_is_in_band(in_band); + Set1::One(Region::EarlyBound(i as u32, def_id, origin)) + }) + } + } + Set1::Many => Set1::Many, + }) } }) .collect() @@ -1541,20 +1516,18 @@ impl<'a, 'tcx> LifetimeContext<'a, 'tcx> { } let mut type_count = 0; - let lifetimes = generics.params.iter().filter_map(|param| { - match param.kind { - GenericParamKind::Lifetime { .. } => { - if self.map.late_bound.contains(¶m.id) { - Some(Region::late(&self.tcx.hir, param)) - } else { - Some(Region::early(&self.tcx.hir, &mut index, param)) - } - } - GenericParamKind::Type { .. } => { - type_count += 1; - None + let lifetimes = generics.params.iter().filter_map(|param| match param.kind { + GenericParamKind::Lifetime { .. } => { + if self.map.late_bound.contains(¶m.id) { + Some(Region::late(&self.tcx.hir, param)) + } else { + Some(Region::early(&self.tcx.hir, &mut index, param)) } } + GenericParamKind::Type { .. } => { + type_count += 1; + None + } }).collect(); let next_early_index = index + type_count; @@ -1721,11 +1694,21 @@ impl<'a, 'tcx> LifetimeContext<'a, 'tcx> { return; } - if generic_args.lifetimes().all(|l| l.is_elided()) { - self.resolve_elided_lifetimes(generic_args.lifetimes().collect(), true); + let mut elide_lifetimes = true; + let lifetimes = generic_args.args.iter().filter_map(|arg| match arg { + hir::GenericArg::Lifetime(lt) => { + if !lt.is_elided() { + elide_lifetimes = false; + } + Some(lt) + } + _ => None, + }).collect(); + if elide_lifetimes { + self.resolve_elided_lifetimes(lifetimes, true); } else { - for l in generic_args.lifetimes() { - self.visit_lifetime(l); + for lt in lifetimes { + self.visit_lifetime(lt); } } @@ -1788,29 +1771,41 @@ impl<'a, 'tcx> LifetimeContext<'a, 'tcx> { }).collect() }) }; - unsubst - .iter() - .map(|set| match *set { - Set1::Empty => if in_body { - None - } else { - Some(Region::Static) - }, - Set1::One(r) => r.subst(generic_args.lifetimes(), map), - Set1::Many => None, - }) - .collect() + unsubst.iter() + .map(|set| match *set { + Set1::Empty => if in_body { + None + } else { + Some(Region::Static) + }, + Set1::One(r) => { + let lifetimes = generic_args.args.iter().filter_map(|arg| match arg { + GenericArg::Lifetime(lt) => Some(lt), + _ => None, + }); + r.subst(lifetimes, map) + } + Set1::Many => None, + }) + .collect() }); - for (i, ty) in generic_args.types().enumerate() { - if let Some(<) = object_lifetime_defaults.get(i) { - let scope = Scope::ObjectLifetimeDefault { - lifetime: lt, - s: self.scope, - }; - self.with(scope, |_, this| this.visit_ty(ty)); - } else { - self.visit_ty(ty); + let mut i = 0; + for arg in &generic_args.args { + match arg { + GenericArg::Lifetime(_) => {} + GenericArg::Type(ty) => { + if let Some(<) = object_lifetime_defaults.get(i) { + let scope = Scope::ObjectLifetimeDefault { + lifetime: lt, + s: self.scope, + }; + self.with(scope, |_, this| this.visit_ty(ty)); + } else { + self.visit_ty(ty); + } + i += 1; + } } } @@ -2269,11 +2264,9 @@ impl<'a, 'tcx> LifetimeContext<'a, 'tcx> { } fn check_lifetime_params(&mut self, old_scope: ScopeRef, params: &'tcx [hir::GenericParam]) { - let lifetimes: Vec<_> = params.iter().filter_map(|param| { - match param.kind { - GenericParamKind::Lifetime { name, .. } => Some((param, name)), - _ => None, - } + let lifetimes: Vec<_> = params.iter().filter_map(|param| match param.kind { + GenericParamKind::Lifetime { name, .. } => Some((param, name)), + _ => None, }).collect(); for (i, (lifetime_i, lifetime_i_name)) in lifetimes.iter().enumerate() { match lifetime_i_name { diff --git a/src/librustc/traits/auto_trait.rs b/src/librustc/traits/auto_trait.rs index 227cba40d1463..f48739799203f 100644 --- a/src/librustc/traits/auto_trait.rs +++ b/src/librustc/traits/auto_trait.rs @@ -224,11 +224,9 @@ impl<'a, 'tcx> AutoTraitFinder<'a, 'tcx> { let names_map: FxHashSet = generics .params .iter() - .filter_map(|param| { - match param.kind { - ty::GenericParamDefKind::Lifetime => Some(param.name.to_string()), - _ => None - } + .filter_map(|param| match param.kind { + ty::GenericParamDefKind::Lifetime => Some(param.name.to_string()), + _ => None }) .collect(); diff --git a/src/librustc/util/ppaux.rs b/src/librustc/util/ppaux.rs index 772de04d364da..bd19a575c798e 100644 --- a/src/librustc/util/ppaux.rs +++ b/src/librustc/util/ppaux.rs @@ -336,13 +336,11 @@ impl PrintContext { if !verbose { let mut type_params = - generics.params.iter().rev().filter_map(|param| { - match param.kind { - GenericParamDefKind::Type { has_default, .. } => { - Some((param.def_id, has_default)) - } - GenericParamDefKind::Lifetime => None, + generics.params.iter().rev().filter_map(|param| match param.kind { + GenericParamDefKind::Type { has_default, .. } => { + Some((param.def_id, has_default)) } + GenericParamDefKind::Lifetime => None, }).peekable(); let has_default = { let has_default = type_params.peek().map(|(_, has_default)| has_default); diff --git a/src/librustc_metadata/encoder.rs b/src/librustc_metadata/encoder.rs index a4299f3bf377c..e105c9cd3c2d8 100644 --- a/src/librustc_metadata/encoder.rs +++ b/src/librustc_metadata/encoder.rs @@ -1236,12 +1236,10 @@ impl<'a, 'b: 'a, 'tcx: 'b> IsolatedEncoder<'a, 'b, 'tcx> { } hir::ItemConst(..) => self.encode_optimized_mir(def_id), hir::ItemFn(_, _, constness, _, ref generics, _) => { - let has_types = generics.params.iter().find(|param| { - match param.kind { - hir::GenericParamKind::Type { .. } => true, - _ => false, - } - }).is_some(); + let has_types = generics.params.iter().any(|param| match param.kind { + hir::GenericParamKind::Type { .. } => true, + _ => false, + }); let needs_inline = (has_types || tcx.codegen_fn_attrs(def_id).requests_inline()) && !self.metadata_output_only(); diff --git a/src/librustc_typeck/astconv.rs b/src/librustc_typeck/astconv.rs index e4b3b4e60413d..32c0dbbea6935 100644 --- a/src/librustc_typeck/astconv.rs +++ b/src/librustc_typeck/astconv.rs @@ -13,7 +13,7 @@ //! is parameterized by an instance of `AstConv`. use rustc_data_structures::accumulate_vec::AccumulateVec; -use hir; +use hir::{self, GenericArg}; use hir::def::Def; use hir::def_id::DefId; use middle::resolve_lifetime as rl; @@ -213,10 +213,16 @@ impl<'o, 'gcx: 'tcx, 'tcx> AstConv<'gcx, 'tcx>+'o { // If the type is parameterized by this region, then replace this // region with the current anon region binding (in other words, // whatever & would get replaced with). - let decl_generics = tcx.generics_of(def_id); - let ty_provided = generic_args.types().count(); - let lt_provided = generic_args.lifetimes().count(); + let mut lt_provided = 0; + let mut ty_provided = 0; + for arg in &generic_args.args { + match arg { + GenericArg::Lifetime(_) => lt_provided += 1, + GenericArg::Type(_) => ty_provided += 1, + } + } + let decl_generics = tcx.generics_of(def_id); let mut lt_accepted = 0; let mut ty_params = ParamRange { required: 0, accepted: 0 }; for param in &decl_generics.params { @@ -269,11 +275,19 @@ impl<'o, 'gcx: 'tcx, 'tcx> AstConv<'gcx, 'tcx>+'o { match param.kind { GenericParamDefKind::Lifetime => { let i = param.index as usize - own_self; - if let Some(lifetime) = generic_args.lifetimes().nth(i) { - self.ast_region_to_region(lifetime, Some(param)).into() - } else { - tcx.types.re_static.into() + let mut j = 0; + for arg in &generic_args.args { + match arg { + GenericArg::Lifetime(lt) => { + if i == j { + return self.ast_region_to_region(lt, Some(param)).into(); + } + j += 1; + } + _ => {} + } } + tcx.types.re_static.into() } GenericParamDefKind::Type { has_default, .. } => { let i = param.index as usize; @@ -286,7 +300,19 @@ impl<'o, 'gcx: 'tcx, 'tcx> AstConv<'gcx, 'tcx>+'o { let i = i - (lt_accepted + own_self); if i < ty_provided { // A provided type parameter. - self.ast_ty_to_ty(&generic_args.types().nth(i).unwrap()).into() + let mut j = 0; + for arg in &generic_args.args { + match arg { + GenericArg::Type(ty) => { + if i == j { + return self.ast_ty_to_ty(ty).into(); + } + j += 1; + } + _ => {} + } + } + bug!() } else if infer_types { // No type parameters were provided, we can infer all. if !default_needs_object_self(param) { diff --git a/src/librustc_typeck/check/compare_method.rs b/src/librustc_typeck/check/compare_method.rs index f573ad7ef2753..8a64e4a536785 100644 --- a/src/librustc_typeck/check/compare_method.rs +++ b/src/librustc_typeck/check/compare_method.rs @@ -728,11 +728,9 @@ fn compare_synthetic_generics<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, let mut error_found = false; let impl_m_generics = tcx.generics_of(impl_m.def_id); let trait_m_generics = tcx.generics_of(trait_m.def_id); - let impl_m_type_params = impl_m_generics.params.iter().filter_map(|param| { - match param.kind { - GenericParamDefKind::Type { synthetic, .. } => Some((param.def_id, synthetic)), - GenericParamDefKind::Lifetime => None, - } + let impl_m_type_params = impl_m_generics.params.iter().filter_map(|param| match param.kind { + GenericParamDefKind::Type { synthetic, .. } => Some((param.def_id, synthetic)), + GenericParamDefKind::Lifetime => None, }); let trait_m_type_params = trait_m_generics.params.iter().filter_map(|param| { match param.kind { diff --git a/src/librustc_typeck/check/method/confirm.rs b/src/librustc_typeck/check/method/confirm.rs index bb5bdd4dc7791..4cf05a4891b39 100644 --- a/src/librustc_typeck/check/method/confirm.rs +++ b/src/librustc_typeck/check/method/confirm.rs @@ -12,6 +12,7 @@ use super::{probe, MethodCallee}; use astconv::AstConv; use check::{FnCtxt, PlaceOp, callee, Needs}; +use hir::GenericArg; use hir::def_id::DefId; use rustc::ty::subst::Substs; use rustc::traits; @@ -330,16 +331,40 @@ impl<'a, 'gcx, 'tcx> ConfirmContext<'a, 'gcx, 'tcx> { } else { match param.kind { GenericParamDefKind::Lifetime => { - if let Some(lifetime) = provided.as_ref().and_then(|p| { - p.lifetimes().nth(i - parent_substs.len()) + if let Some(lifetime) = provided.as_ref().and_then(|data| { + let mut j = 0; + for arg in &data.args { + match arg { + GenericArg::Lifetime(lt) => { + if i - parent_substs.len() == j { + return Some(lt); + } + j += 1; + } + _ => {} + } + } + None }) { return AstConv::ast_region_to_region( self.fcx, lifetime, Some(param)).into(); } } GenericParamDefKind::Type {..} => { - if let Some(ast_ty) = provided.as_ref().and_then(|p| { - p.types().nth(i - parent_substs.len() - own_counts.lifetimes) + if let Some(ast_ty) = provided.as_ref().and_then(|data| { + let mut j = 0; + for arg in &data.args { + match arg { + GenericArg::Type(ty) => { + if i - parent_substs.len() - own_counts.lifetimes == j { + return Some(ty); + } + j += 1; + } + _ => {} + } + } + None }) { return self.to_ty(ast_ty).into(); } diff --git a/src/librustc_typeck/check/mod.rs b/src/librustc_typeck/check/mod.rs index 8faef103f81c8..4b731d5b883b1 100644 --- a/src/librustc_typeck/check/mod.rs +++ b/src/librustc_typeck/check/mod.rs @@ -85,6 +85,7 @@ use self::method::MethodCallee; use self::TupleArgumentsFlag::*; use astconv::AstConv; +use hir::GenericArg; use hir::def::Def; use hir::def_id::{CrateNum, DefId, LOCAL_CRATE}; use std::slice; @@ -4834,7 +4835,12 @@ impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> { match param.kind { GenericParamDefKind::Lifetime => { let lifetimes = segment.map_or(vec![], |(s, _)| { - s.args.as_ref().map_or(vec![], |arg| arg.lifetimes().collect()) + s.args.as_ref().map_or(vec![], |data| { + data.args.iter().filter_map(|arg| match arg { + GenericArg::Lifetime(lt) => Some(lt), + _ => None, + }).collect() + }) }); if let Some(lifetime) = lifetimes.get(i) { @@ -4845,8 +4851,11 @@ impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> { } GenericParamDefKind::Type {..} => { let (types, infer_types) = segment.map_or((vec![], true), |(s, _)| { - (s.args.as_ref().map_or(vec![], |arg| { - arg.types().collect() + (s.args.as_ref().map_or(vec![], |data| { + data.args.iter().filter_map(|arg| match arg { + GenericArg::Type(ty) => Some(ty), + _ => None, + }).collect() }), s.infer_types) }); @@ -4967,11 +4976,16 @@ impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> { |(s, _)| { s.args.as_ref().map_or( (vec![], vec![], s.infer_types, &[][..]), - |arg| { - (arg.lifetimes().collect(), - arg.types().collect(), - s.infer_types, - &arg.bindings[..]) + |data| { + let mut lifetimes = vec![]; + let mut types = vec![]; + for arg in &data.args { + match arg { + GenericArg::Lifetime(lt) => lifetimes.push(lt), + GenericArg::Type(ty) => types.push(ty), + } + } + (lifetimes, types, s.infer_types, &data.bindings[..]) } ) }); @@ -5097,13 +5111,11 @@ impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> { -> bool { let segment = segment.map(|(path_segment, generics)| { let explicit = !path_segment.infer_types; - let impl_trait = generics.params.iter().any(|param| { - match param.kind { - ty::GenericParamDefKind::Type { - synthetic: Some(hir::SyntheticTyParamKind::ImplTrait), .. - } => true, - _ => false, - } + let impl_trait = generics.params.iter().any(|param| match param.kind { + ty::GenericParamDefKind::Type { + synthetic: Some(hir::SyntheticTyParamKind::ImplTrait), .. + } => true, + _ => false, }); if explicit && impl_trait { @@ -5187,11 +5199,9 @@ pub fn check_bounds_are_used<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, } } - let types = generics.params.iter().filter(|param| { - match param.kind { - hir::GenericParamKind::Type { .. } => true, - _ => false, - } + let types = generics.params.iter().filter(|param| match param.kind { + hir::GenericParamKind::Type { .. } => true, + _ => false, }); for (&used, param) in types_used.iter().zip(types) { if !used { diff --git a/src/librustc_typeck/check/wfcheck.rs b/src/librustc_typeck/check/wfcheck.rs index 8d2c1e07ec8e0..05d390b8dae9e 100644 --- a/src/librustc_typeck/check/wfcheck.rs +++ b/src/librustc_typeck/check/wfcheck.rs @@ -662,11 +662,9 @@ fn reject_shadowing_parameters(tcx: TyCtxt, def_id: DefId) { let parent = tcx.generics_of(generics.parent.unwrap()); let impl_params: FxHashMap<_, _> = parent.params.iter() - .flat_map(|param| { - match param.kind { - GenericParamDefKind::Lifetime => None, - GenericParamDefKind::Type {..} => Some((param.name, param.def_id)), - } + .flat_map(|param| match param.kind { + GenericParamDefKind::Lifetime => None, + GenericParamDefKind::Type {..} => Some((param.name, param.def_id)), }) .collect(); diff --git a/src/librustc_typeck/collect.rs b/src/librustc_typeck/collect.rs index ef34c1a1c9c75..0a6edd8d0ce70 100644 --- a/src/librustc_typeck/collect.rs +++ b/src/librustc_typeck/collect.rs @@ -315,17 +315,14 @@ impl<'a, 'tcx> ItemCtxt<'a, 'tcx> { { let from_ty_params = ast_generics.params.iter() - .filter_map(|param| { - match param.kind { - GenericParamKind::Type { ref bounds, .. } => { - if param.id == param_id { - Some(bounds) - } else { - None - } + .filter_map(|param| match param.kind { + GenericParamKind::Type { ref bounds, .. } => { + if param.id == param_id { + return Some(bounds); } - _ => None + None } + _ => None }) .flat_map(|bounds| bounds.iter()) .flat_map(|b| predicates_from_bound(self, ty, b)); @@ -921,42 +918,40 @@ 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() == keywords::SelfType.name() { - span_bug!(param.span, - "`Self` should not be the name of a regular parameter"); - } + params.extend(ast_generics.params.iter().filter_map(|param| match param.kind { + GenericParamKind::Type { ref default, synthetic, .. } => { + if param.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.")); - } + 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().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, + + let ty_param = ty::GenericParamDef { + index: type_start + i as u32, + name: param.name().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 @@ -1313,14 +1308,12 @@ fn early_bound_lifetimes_from_generics<'a, '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.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, }) } diff --git a/src/librustdoc/clean/mod.rs b/src/librustdoc/clean/mod.rs index 352c65f792876..a2ae7afbc8386 100644 --- a/src/librustdoc/clean/mod.rs +++ b/src/librustdoc/clean/mod.rs @@ -36,7 +36,7 @@ use rustc::middle::resolve_lifetime as rl; use rustc::ty::fold::TypeFolder; use rustc::middle::lang_items; use rustc::mir::interpret::GlobalId; -use rustc::hir::{self, HirVec}; +use rustc::hir::{self, GenericArg, HirVec}; use rustc::hir::def::{self, Def, CtorKind}; use rustc::hir::def_id::{CrateNum, DefId, DefIndex, CRATE_DEF_INDEX, LOCAL_CRATE}; use rustc::hir::def_id::DefIndexAddressSpace; @@ -1979,16 +1979,14 @@ impl<'a, 'tcx> Clean for (&'a ty::Generics, // Bounds in the type_params and lifetimes fields are repeated in the // predicates field (see rustc_typeck::collect::ty_generics), so remove // them. - let stripped_typarams = gens.params.iter().filter_map(|param| { - if let ty::GenericParamDefKind::Type {..} = param.kind { + let stripped_typarams = gens.params.iter().filter_map(|param| match param.kind { + ty::GenericParamDefKind::Lifetime => None, + ty::GenericParamDefKind::Type { .. } => { if param.name == keywords::SelfType.name().as_str() { assert_eq!(param.index, 0); - None - } else { - Some(param.clean(cx)) + return None; } - } else { - None + Some(param.clean(cx)) } }).collect::>(); @@ -2034,12 +2032,11 @@ impl<'a, 'tcx> Clean for (&'a ty::Generics, Generics { params: gens.params .iter() - .flat_map(|param| { - if let ty::GenericParamDefKind::Lifetime = param.kind { + .flat_map(|param| match param.kind { + ty::GenericParamDefKind::Lifetime => { Some(GenericParamDef::Lifetime(param.clean(cx))) - } else { - None } + ty::GenericParamDefKind::Type { .. } => None, }).chain( simplify::ty_params(stripped_typarams) .into_iter() @@ -2870,8 +2867,20 @@ impl Clean for hir::Ty { for param in generics.params.iter() { match param.kind { hir::GenericParamKind::Lifetime { .. } => { - if let Some(lt) = generic_args.lifetimes() - .nth(indices.lifetimes).cloned() { + let mut j = 0; + let lifetime = generic_args.args.iter().find_map(|arg| { + match arg { + GenericArg::Lifetime(lt) => { + if indices.lifetimes == j { + return Some(lt); + } + j += 1; + None + } + _ => None, + } + }); + if let Some(lt) = lifetime.cloned() { if !lt.is_elided() { let lt_def_id = cx.tcx.hir.local_def_id(param.id); @@ -2883,8 +2892,20 @@ impl Clean for hir::Ty { hir::GenericParamKind::Type { ref default, .. } => { let ty_param_def = Def::TyParam(cx.tcx.hir.local_def_id(param.id)); - if let Some(ty) = generic_args.types() - .nth(indices.types).cloned() { + let mut j = 0; + let type_ = generic_args.args.iter().find_map(|arg| { + match arg { + GenericArg::Type(ty) => { + if indices.types == j { + return Some(ty); + } + j += 1; + None + } + _ => None, + } + }); + if let Some(ty) = type_.cloned() { ty_substs.insert(ty_param_def, ty.into_inner().clean(cx)); } else if let Some(default) = default.clone() { ty_substs.insert(ty_param_def, @@ -3504,13 +3525,28 @@ impl Clean for hir::GenericArgs { output: if output != Type::Tuple(Vec::new()) { Some(output) } else { None } } } else { + let mut lifetimes = vec![]; + let mut types = vec![]; + let mut elided_lifetimes = true; + for arg in &self.args { + match arg { + GenericArg::Lifetime(lt) if elided_lifetimes => { + if lt.is_elided() { + elided_lifetimes = false; + lifetimes = vec![]; + continue; + } + lifetimes.push(lt.clean(cx)); + } + GenericArg::Lifetime(_) => {} + GenericArg::Type(ty) => { + types.push(ty.clean(cx)); + } + } + } GenericArgs::AngleBracketed { - lifetimes: if self.lifetimes().all(|lt| lt.is_elided()) { - vec![] - } else { - self.lifetimes().map(|lt| lt.clean(cx)).collect() - }, - types: self.types().map(|ty| ty.clean(cx)).collect(), + lifetimes, + types, bindings: self.bindings.clean(cx), } } diff --git a/src/librustdoc/lib.rs b/src/librustdoc/lib.rs index 97c84d8348f7c..8e691049d3395 100644 --- a/src/librustdoc/lib.rs +++ b/src/librustdoc/lib.rs @@ -18,6 +18,7 @@ #![feature(box_patterns)] #![feature(box_syntax)] #![feature(fs_read_write)] +#![feature(iterator_find_map)] #![feature(set_stdio)] #![feature(slice_sort_by_cached_key)] #![feature(test)] diff --git a/src/libsyntax_ext/deriving/generic/mod.rs b/src/libsyntax_ext/deriving/generic/mod.rs index e461c9640d1a7..fc244f67bb653 100644 --- a/src/libsyntax_ext/deriving/generic/mod.rs +++ b/src/libsyntax_ext/deriving/generic/mod.rs @@ -549,30 +549,28 @@ impl<'a> TraitDef<'a> { .to_generics(cx, self.span, type_ident, generics); // Create the generic parameters - params.extend(generics.params.iter().map(|param| { - match param.kind { - GenericParamKindAST::Lifetime { .. } => param.clone(), - GenericParamKindAST::Type { bounds: ref ty_bounds, .. } => { - // I don't think this can be moved out of the loop, since - // a TyParamBound requires an ast id - let mut bounds: Vec<_> = - // extra restrictions on the generics parameters to the - // type being derived upon - self.additional_bounds.iter().map(|p| { - cx.typarambound(p.to_path(cx, self.span, - type_ident, generics)) - }).collect(); - - // require the current trait - bounds.push(cx.typarambound(trait_path.clone())); - - // also add in any bounds from the declaration - for declared_bound in ty_bounds { - bounds.push((*declared_bound).clone()); - } - - cx.typaram(self.span, param.ident, vec![], bounds, None) + params.extend(generics.params.iter().map(|param| match param.kind { + GenericParamKindAST::Lifetime { .. } => param.clone(), + GenericParamKindAST::Type { bounds: ref ty_bounds, .. } => { + // I don't think this can be moved out of the loop, since + // a TyParamBound requires an ast id + let mut bounds: Vec<_> = + // extra restrictions on the generics parameters to the + // type being derived upon + self.additional_bounds.iter().map(|p| { + cx.typarambound(p.to_path(cx, self.span, + type_ident, generics)) + }).collect(); + + // require the current trait + bounds.push(cx.typarambound(trait_path.clone())); + + // also add in any bounds from the declaration + for declared_bound in ty_bounds { + bounds.push((*declared_bound).clone()); } + + cx.typaram(self.span, param.ident, vec![], bounds, None) } })); From f457b3d10aa2db4104402e2d04f72fab64a3c62e Mon Sep 17 00:00:00 2001 From: varkor Date: Sun, 27 May 2018 16:56:01 +0100 Subject: [PATCH 16/41] Refactor generic parameters in rustdoc/clean --- src/librustc/hir/intravisit.rs | 4 +- src/librustc/hir/lowering.rs | 101 ++++------- src/librustc/hir/map/def_collector.rs | 7 +- src/librustc/hir/map/mod.rs | 8 +- src/librustc/hir/print.rs | 12 +- src/librustc/infer/error_reporting/mod.rs | 14 +- src/librustc/middle/resolve_lifetime.rs | 117 +++++-------- src/librustc/util/ppaux.rs | 2 +- src/librustc_lint/types.rs | 3 +- src/librustc_metadata/encoder.rs | 19 +-- src/librustc_mir/monomorphize/collector.rs | 7 +- src/librustc_passes/ast_validation.rs | 43 +++-- src/librustc_privacy/lib.rs | 14 +- src/librustc_resolve/lib.rs | 15 +- src/librustc_save_analysis/dump_visitor.rs | 42 ++--- src/librustc_typeck/check/mod.rs | 10 +- src/librustdoc/clean/auto_trait.rs | 23 +-- src/librustdoc/clean/mod.rs | 189 +++++++++++---------- src/librustdoc/clean/simplify.rs | 9 +- src/librustdoc/html/format.rs | 16 +- src/librustdoc/html/render.rs | 8 +- 21 files changed, 296 insertions(+), 367 deletions(-) diff --git a/src/librustc/hir/intravisit.rs b/src/librustc/hir/intravisit.rs index 4c24c7afd735c..51ce134544d08 100644 --- a/src/librustc/hir/intravisit.rs +++ b/src/librustc/hir/intravisit.rs @@ -654,8 +654,8 @@ pub fn walk_path_segment<'v, V: Visitor<'v>>(visitor: &mut V, } pub fn walk_generic_args<'v, V: Visitor<'v>>(visitor: &mut V, - _path_span: Span, - generic_args: &'v GenericArgs) { + _path_span: Span, + generic_args: &'v GenericArgs) { walk_list!(visitor, visit_generic_arg, &generic_args.args); walk_list!(visitor, visit_assoc_type_binding, &generic_args.bindings); } diff --git a/src/librustc/hir/lowering.rs b/src/librustc/hir/lowering.rs index 1c62e5813ff36..c0f94a138afc6 100644 --- a/src/librustc/hir/lowering.rs +++ b/src/librustc/hir/lowering.rs @@ -382,17 +382,9 @@ impl<'a> LoweringContext<'a> { let item_lifetimes = match self.lctx.items.get(&item.id).unwrap().node { hir::Item_::ItemImpl(_, _, _, ref generics, ..) | hir::Item_::ItemTrait(_, _, ref generics, ..) => { - generics.params - .iter() - .filter_map(|param| match param.kind { - hir::GenericParamKind::Lifetime { .. } => { - Some(param.clone()) - } - _ => None, - }) - .collect::>() + generics.params.clone() } - _ => Vec::new(), + _ => HirVec::new(), }; self.lctx.with_parent_impl_lifetime_defs(&item_lifetimes, |this| { @@ -766,16 +758,15 @@ impl<'a> LoweringContext<'a> { // This is used to track which lifetimes have already been defined, and // which are new in-band lifetimes that need to have a definition created // for them. - fn with_in_scope_lifetime_defs<'l, T, F>( - &mut self, - params: impl Iterator, - f: F, - ) -> T + fn with_in_scope_lifetime_defs(&mut self, params: &Vec, f: F) -> T where F: FnOnce(&mut LoweringContext) -> T, { let old_len = self.in_scope_lifetimes.len(); - let lt_def_names = params.map(|param| param.ident.name); + let lt_def_names = params.iter().filter_map(|param| match param.kind { + GenericParamKindAST::Lifetime { .. } => Some(param.ident.name), + _ => None, + }); self.in_scope_lifetimes.extend(lt_def_names); let res = f(self); @@ -789,12 +780,17 @@ impl<'a> LoweringContext<'a> { // This should only be used with generics that have already had their // in-band lifetimes added. In practice, this means that this function is // only used when lowering a child item of a trait or impl. - fn with_parent_impl_lifetime_defs(&mut self, params: &[hir::GenericParam], f: F) -> T - where + fn with_parent_impl_lifetime_defs(&mut self, + params: &HirVec, + f: F + ) -> T where F: FnOnce(&mut LoweringContext) -> T, { let old_len = self.in_scope_lifetimes.len(); - let lt_def_names = params.iter().map(|param| param.name()); + let lt_def_names = params.iter().filter_map(|param| match param.kind { + hir::GenericParamKind::Lifetime { .. } => Some(param.name()), + _ => None, + }); self.in_scope_lifetimes.extend(lt_def_names); let res = f(self); @@ -820,10 +816,7 @@ impl<'a> LoweringContext<'a> { F: FnOnce(&mut LoweringContext) -> T, { let (in_band_defs, (mut lowered_generics, res)) = self.with_in_scope_lifetime_defs( - generics.params.iter().filter_map(|param| match param.kind { - GenericParamKindAST::Lifetime { .. } => Some(param), - _ => None, - }), + &generics.params, |this| { let itctx = ImplTraitContext::Universal(parent_id); this.collect_in_band_defs(parent_id, anonymous_lifetime_mode, |this| { @@ -1051,16 +1044,12 @@ impl<'a> LoweringContext<'a> { } fn lower_generic_arg(&mut self, - p: &ast::GenericArgAST, + arg: &ast::GenericArgAST, itctx: ImplTraitContext) -> hir::GenericArg { - match p { - ast::GenericArgAST::Lifetime(lt) => { - GenericArg::Lifetime(self.lower_lifetime(<)) - } - ast::GenericArgAST::Type(ty) => { - GenericArg::Type(self.lower_ty(&ty, itctx)) - } + match arg { + ast::GenericArgAST::Lifetime(lt) => GenericArg::Lifetime(self.lower_lifetime(<)), + ast::GenericArgAST::Type(ty) => GenericArg::Type(self.lower_ty(&ty, itctx)), } } @@ -1079,10 +1068,7 @@ impl<'a> LoweringContext<'a> { hir::TyRptr(lifetime, self.lower_mt(mt, itctx)) } TyKind::BareFn(ref f) => self.with_in_scope_lifetime_defs( - f.generic_params.iter().filter_map(|param| match param.kind { - GenericParamKindAST::Lifetime { .. } => Some(param), - _ => None, - }), + &f.generic_params, |this| { this.with_anonymous_lifetime_mode( AnonymousLifetimeMode::PassThrough, @@ -1946,6 +1932,15 @@ impl<'a> LoweringContext<'a> { } } + fn lower_generic_params( + &mut self, + params: &Vec, + add_bounds: &NodeMap>, + itctx: ImplTraitContext, + ) -> hir::HirVec { + params.iter().map(|param| self.lower_generic_param(param, add_bounds, itctx)).collect() + } + fn lower_generic_param(&mut self, param: &GenericParamAST, add_bounds: &NodeMap>, @@ -1986,10 +1981,9 @@ impl<'a> LoweringContext<'a> { let mut bounds = self.lower_bounds(bounds, itctx); let add_bounds = add_bounds.get(¶m.id).map_or(&[][..], |x| &x); if !add_bounds.is_empty() { - bounds = bounds - .into_iter() - .chain(self.lower_bounds(add_bounds, itctx).into_iter()) - .collect(); + bounds = bounds.into_iter() + .chain(self.lower_bounds(add_bounds, itctx).into_iter()) + .collect(); } hir::GenericParam { @@ -2005,7 +1999,7 @@ impl<'a> LoweringContext<'a> { synthetic: param.attrs.iter() .filter(|attr| attr.check_name("rustc_synthetic")) .map(|_| hir::SyntheticTyParamKind::ImplTrait) - .nth(0), + .next(), attrs: self.lower_attrs(¶m.attrs), } } @@ -2013,15 +2007,6 @@ impl<'a> LoweringContext<'a> { } } - fn lower_generic_params( - &mut self, - params: &Vec, - add_bounds: &NodeMap>, - itctx: ImplTraitContext, - ) -> hir::HirVec { - params.iter().map(|param| self.lower_generic_param(param, add_bounds, itctx)).collect() - } - fn lower_generics( &mut self, generics: &Generics, @@ -2107,10 +2092,7 @@ impl<'a> LoweringContext<'a> { span, }) => { self.with_in_scope_lifetime_defs( - bound_generic_params.iter().filter_map(|param| match param.kind { - GenericParamKindAST::Lifetime { .. } => Some(param), - _ => None, - }), + &bound_generic_params, |this| { hir::WherePredicate::BoundPredicate(hir::WhereBoundPredicate { bound_generic_params: this.lower_generic_params( @@ -2203,13 +2185,7 @@ impl<'a> LoweringContext<'a> { let bound_generic_params = self.lower_generic_params(&p.bound_generic_params, &NodeMap(), itctx); let trait_ref = self.with_parent_impl_lifetime_defs( - &bound_generic_params - .iter() - .filter_map(|param| match param.kind { - hir::GenericParamKind::Lifetime { .. } => Some(param.clone()), - _ => None, - }) - .collect::>(), + &bound_generic_params, |this| this.lower_trait_ref(&p.trait_ref, itctx), ); @@ -2426,10 +2402,7 @@ impl<'a> LoweringContext<'a> { ); let new_impl_items = self.with_in_scope_lifetime_defs( - ast_generics.params.iter().filter_map(|param| match param.kind { - GenericParamKindAST::Lifetime { .. } => Some(param), - _ => None, - }), + &ast_generics.params, |this| { impl_items .iter() diff --git a/src/librustc/hir/map/def_collector.rs b/src/librustc/hir/map/def_collector.rs index 6555be110d140..ab4a0826584ac 100644 --- a/src/librustc/hir/map/def_collector.rs +++ b/src/librustc/hir/map/def_collector.rs @@ -176,12 +176,7 @@ impl<'a> visit::Visitor<'a> for DefCollector<'a> { GenericParamKindAST::Lifetime { .. } => DefPathData::LifetimeParam(name), GenericParamKindAST::Type { .. } => DefPathData::TypeParam(name), }; - self.create_def( - param.id, - def_path_data, - REGULAR_SPACE, - param.ident.span - ); + self.create_def(param.id, def_path_data, REGULAR_SPACE, param.ident.span); visit::walk_generic_param(self, param); } diff --git a/src/librustc/hir/map/mod.rs b/src/librustc/hir/map/mod.rs index c46f58137540f..1f958d3fe9536 100644 --- a/src/librustc/hir/map/mod.rs +++ b/src/librustc/hir/map/mod.rs @@ -974,11 +974,9 @@ impl<'hir> Map<'hir> { Some(NodeField(ref f)) => Some(&f.attrs[..]), Some(NodeExpr(ref e)) => Some(&*e.attrs), Some(NodeStmt(ref s)) => Some(s.node.attrs()), - Some(NodeGenericParam(param)) => { - match param.kind { - GenericParamKind::Type { ref attrs, .. } => Some(&attrs[..]), - _ => bug!("unexpected non-type NodeGenericParam") - } + Some(NodeGenericParam(param)) => match param.kind { + GenericParamKind::Type { ref attrs, .. } => Some(&attrs[..]), + _ => bug!("unexpected non-type NodeGenericParam") } // unit/tuple structs take the attributes straight from // the struct definition. diff --git a/src/librustc/hir/print.rs b/src/librustc/hir/print.rs index dc5d9749227dc..eabf554bc536f 100644 --- a/src/librustc/hir/print.rs +++ b/src/librustc/hir/print.rs @@ -1270,13 +1270,10 @@ impl<'a> State<'a> { self.print_name(segment.name)?; segment.with_generic_args(|generic_args| { - if !generic_args.args.is_empty() || - !generic_args.bindings.is_empty() - { - self.print_generic_args(&generic_args, segment.infer_types, true) - } else { - Ok(()) + if !generic_args.args.is_empty() || !generic_args.bindings.is_empty() { + return self.print_generic_args(&generic_args, segment.infer_types, true); } + Ok(()) })?; self.print_call_post(base_args) } @@ -1642,8 +1639,7 @@ impl<'a> State<'a> { segment.name != keywords::DollarCrate.name() { self.print_name(segment.name)?; segment.with_generic_args(|generic_args| { - self.print_generic_args(generic_args, - segment.infer_types, + self.print_generic_args(generic_args, segment.infer_types, colons_before_params) })?; } diff --git a/src/librustc/infer/error_reporting/mod.rs b/src/librustc/infer/error_reporting/mod.rs index af38e8ba2d492..b30e5bab968eb 100644 --- a/src/librustc/infer/error_reporting/mod.rs +++ b/src/librustc/infer/error_reporting/mod.rs @@ -1036,21 +1036,19 @@ impl<'a, 'gcx, 'tcx> InferCtxt<'a, 'gcx, 'tcx> { // Get the `hir::TyParam` to verify whether it already has any bounds. // We do this to avoid suggesting code that ends up as `T: 'a'b`, // instead we suggest `T: 'a + 'b` in that case. - let has_lifetimes = - if let hir_map::NodeGenericParam(ref param) = hir.get(id) { + let mut has_bounds = false; + if let hir_map::NodeGenericParam(ref param) = hir.get(id) { match param.kind { GenericParamKind::Type { ref bounds, .. } => { - !bounds.is_empty() + has_bounds = !bounds.is_empty(); } _ => bug!("unexpected non-type NodeGenericParam"), } - } else { - false - }; + } let sp = hir.span(id); // `sp` only covers `T`, change it so that it covers // `T:` when appropriate - let sp = if has_lifetimes { + let sp = if has_bounds { sp.to(self.tcx .sess .codemap() @@ -1058,7 +1056,7 @@ impl<'a, 'gcx, 'tcx> InferCtxt<'a, 'gcx, 'tcx> { } else { sp }; - (sp, has_lifetimes) + (sp, has_bounds) }) } else { None diff --git a/src/librustc/middle/resolve_lifetime.rs b/src/librustc/middle/resolve_lifetime.rs index 358df3a1733c9..67a5448babf83 100644 --- a/src/librustc/middle/resolve_lifetime.rs +++ b/src/librustc/middle/resolve_lifetime.rs @@ -81,6 +81,18 @@ pub enum Region { Free(DefId, /* lifetime decl */ DefId), } +fn new_region(hir_map: &Map, param: &hir::GenericParam) + -> (hir::LifetimeName, DefId, LifetimeDefOrigin) { + let def_id = hir_map.local_def_id(param.id); + let (name, origin) = match param.kind { + GenericParamKind::Lifetime { name, in_band, .. } => { + (name, LifetimeDefOrigin::from_is_in_band(in_band)) + } + _ => bug!("expected a lifetime param"), + }; + (name, def_id, origin) +} + impl Region { fn early( hir_map: &Map, @@ -89,26 +101,14 @@ impl Region { ) -> (hir::LifetimeName, Region) { let i = *index; *index += 1; - let def_id = hir_map.local_def_id(param.id); - let (name, origin) = match param.kind { - GenericParamKind::Lifetime { name, in_band, .. } => { - (name, LifetimeDefOrigin::from_is_in_band(in_band)) - } - _ => bug!("expected a lifetime param"), - }; + let (name, def_id, origin) = new_region(hir_map, param); debug!("Region::early: index={} def_id={:?}", i, def_id); (name, Region::EarlyBound(i, def_id, origin)) } fn late(hir_map: &Map, param: &hir::GenericParam) -> (hir::LifetimeName, Region) { let depth = ty::INNERMOST; - let def_id = hir_map.local_def_id(param.id); - let (name, origin) = match param.kind { - GenericParamKind::Lifetime { name, in_band, .. } => { - (name, LifetimeDefOrigin::from_is_in_band(in_band)) - } - _ => bug!("expected a lifetime param"), - }; + let (name, def_id, origin) = new_region(hir_map, param); debug!( "Region::late: def={:?} depth={:?} def_id={:?} origin={:?}", def, @@ -580,15 +580,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.generic_params - .iter() - .filter_map(|param| match param.kind { - GenericParamKind::Lifetime { .. } => { - Some(Region::late(&self.tcx.hir, param)) - } - _ => None, - }) - .collect(), + lifetimes: c.generic_params.iter().filter_map(|param| match param.kind { + GenericParamKind::Lifetime { .. } => { + Some(Region::late(&self.tcx.hir, param)) + } + _ => None, + }).collect(), s: self.scope, next_early_index, track_lifetime_uses: true, @@ -770,19 +767,15 @@ impl<'a, 'tcx> Visitor<'tcx> for LifetimeContext<'a, 'tcx> { let mut index = self.next_early_index(); debug!("visit_ty: index = {}", index); let mut type_count = 0; - let lifetimes = generics.params - .iter() - .filter_map(|param| match param.kind { - GenericParamKind::Lifetime { .. } => { - Some(Region::early(&self.tcx.hir, &mut index, param)) - } - GenericParamKind::Type { .. } => { - type_count += 1; - None - } - }) - .collect(); - + let lifetimes = generics.params.iter().filter_map(|param| match param.kind { + GenericParamKind::Lifetime { .. } => { + Some(Region::early(&self.tcx.hir, &mut index, param)) + } + GenericParamKind::Type { .. } => { + type_count += 1; + None + } + }).collect(); let scope = Scope::Binder { lifetimes, next_early_index: index + type_count, @@ -825,19 +818,15 @@ impl<'a, 'tcx> Visitor<'tcx> for LifetimeContext<'a, 'tcx> { let mut index = self.next_early_index(); let mut next_early_index = index; debug!("visit_ty: index = {}", index); - let lifetimes = generics.params - .iter() - .filter_map(|param| match param.kind { - GenericParamKind::Lifetime { .. } => { - Some(Region::early(&self.tcx.hir, &mut index, param)) - } - GenericParamKind::Type { .. } => { - next_early_index += 1; - None - } - }) - .collect(); - + let lifetimes = generics.params.iter().filter_map(|param| match param.kind { + GenericParamKind::Lifetime { .. } => { + Some(Region::early(&self.tcx.hir, &mut index, param)) + } + GenericParamKind::Type { .. } => { + next_early_index += 1; + None + } + }).collect(); let scope = Scope::Binder { lifetimes, next_early_index, @@ -888,13 +877,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.tcx, - &generics.params.iter().filter_map(|param| match param.kind { - GenericParamKind::Lifetime { .. } => Some(param.clone()), - _ => None, - }).collect::>() - ); + check_mixed_explicit_and_in_band_defs(self.tcx, &generics.params); for param in &generics.params { match param.kind { GenericParamKind::Lifetime { .. } => {} @@ -920,8 +903,7 @@ impl<'a, 'tcx> Visitor<'tcx> for LifetimeContext<'a, 'tcx> { Some(Region::late(&self.tcx.hir, param)) } _ => None, - }) - .collect(); + }).collect(); if !lifetimes.is_empty() { self.trait_ref_hack = true; let next_early_index = self.next_early_index(); @@ -992,16 +974,13 @@ impl<'a, 'tcx> Visitor<'tcx> for LifetimeContext<'a, 'tcx> { } let next_early_index = self.next_early_index(); let scope = Scope::Binder { - lifetimes: trait_ref - .bound_generic_params - .iter() + lifetimes: trait_ref.bound_generic_params.iter() .filter_map(|param| match param.kind { GenericParamKind::Lifetime { .. } => { Some(Region::late(&self.tcx.hir, param)) } _ => None, - }) - .collect(), + }).collect(), s: self.scope, next_early_index, track_lifetime_uses: true, @@ -1068,11 +1047,11 @@ impl ShadowKind { fn check_mixed_explicit_and_in_band_defs( tcx: TyCtxt<'_, '_, '_>, - params: &[hir::GenericParam], + params: &P<[hir::GenericParam]>, ) { - let in_bands: Vec<_> = params.iter().map(|param| match param.kind { - GenericParamKind::Lifetime { in_band, .. } => (in_band, param.span), - _ => bug!("expected lifetime param"), + let in_bands: Vec<_> = params.iter().filter_map(|param| match param.kind { + GenericParamKind::Lifetime { in_band, .. } => Some((in_band, param.span)), + _ => None, }).collect(); let out_of_band = in_bands.iter().find(|(in_band, _)| !in_band); let in_band = in_bands.iter().find(|(in_band, _)| *in_band); @@ -1707,9 +1686,7 @@ impl<'a, 'tcx> LifetimeContext<'a, 'tcx> { if elide_lifetimes { self.resolve_elided_lifetimes(lifetimes, true); } else { - for lt in lifetimes { - self.visit_lifetime(lt); - } + lifetimes.iter().for_each(|lt| self.visit_lifetime(lt)); } // Figure out if this is a type/trait segment, diff --git a/src/librustc/util/ppaux.rs b/src/librustc/util/ppaux.rs index bd19a575c798e..3252a2cd6ab0f 100644 --- a/src/librustc/util/ppaux.rs +++ b/src/librustc/util/ppaux.rs @@ -337,10 +337,10 @@ impl PrintContext { if !verbose { let mut type_params = generics.params.iter().rev().filter_map(|param| match param.kind { + GenericParamDefKind::Lifetime => None, GenericParamDefKind::Type { has_default, .. } => { Some((param.def_id, has_default)) } - GenericParamDefKind::Lifetime => None, }).peekable(); let has_default = { let has_default = type_params.peek().map(|(_, has_default)| has_default); diff --git a/src/librustc_lint/types.rs b/src/librustc_lint/types.rs index 2149e65428154..2d96c01a6dfe4 100644 --- a/src/librustc_lint/types.rs +++ b/src/librustc_lint/types.rs @@ -836,8 +836,7 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for VariantSizeDifferences { .zip(variants) .map(|(variant, variant_layout)| { // Subtract the size of the enum discriminant. - let bytes = variant_layout.size.bytes() - .saturating_sub(discr_size); + let bytes = variant_layout.size.bytes().saturating_sub(discr_size); debug!("- variant `{}` is {} bytes large", variant.node.name, bytes); bytes diff --git a/src/librustc_metadata/encoder.rs b/src/librustc_metadata/encoder.rs index e105c9cd3c2d8..ed3dab09df91e 100644 --- a/src/librustc_metadata/encoder.rs +++ b/src/librustc_metadata/encoder.rs @@ -1648,18 +1648,15 @@ impl<'a, 'b, 'tcx> IndexBuilder<'a, 'b, 'tcx> { } fn encode_info_for_generics(&mut self, generics: &hir::Generics) { - for param in &generics.params { - match param.kind { - hir::GenericParamKind::Lifetime { .. } => {} - hir::GenericParamKind::Type { ref default, .. } => { - let def_id = self.tcx.hir.local_def_id(param.id); - let has_default = Untracked(default.is_some()); - self.record(def_id, - IsolatedEncoder::encode_info_for_ty_param, - (def_id, has_default)); - } + generics.params.iter().for_each(|param| match param.kind { + hir::GenericParamKind::Lifetime { .. } => {} + hir::GenericParamKind::Type { ref default, .. } => { + let def_id = self.tcx.hir.local_def_id(param.id); + let has_default = Untracked(default.is_some()); + let encode_info = IsolatedEncoder::encode_info_for_ty_param; + self.record(def_id, encode_info, (def_id, has_default)); } - } + }); } fn encode_info_for_ty(&mut self, ty: &hir::Ty) { diff --git a/src/librustc_mir/monomorphize/collector.rs b/src/librustc_mir/monomorphize/collector.rs index 9f5b9d405a1ef..ef69cb574e07e 100644 --- a/src/librustc_mir/monomorphize/collector.rs +++ b/src/librustc_mir/monomorphize/collector.rs @@ -1099,12 +1099,7 @@ fn create_mono_items_for_default_impls<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, item: &'tcx hir::Item, output: &mut Vec>) { match item.node { - hir::ItemImpl(_, - _, - _, - ref generics, - .., - ref impl_item_refs) => { + hir::ItemImpl(_, _, _, ref generics, .., ref impl_item_refs) => { for param in &generics.params { match param.kind { hir::GenericParamKind::Lifetime { .. } => {} diff --git a/src/librustc_passes/ast_validation.rs b/src/librustc_passes/ast_validation.rs index a6ef83671a55e..d9a69f09d34bd 100644 --- a/src/librustc_passes/ast_validation.rs +++ b/src/librustc_passes/ast_validation.rs @@ -141,20 +141,19 @@ impl<'a> AstValidator<'a> { fn check_late_bound_lifetime_defs(&self, params: &Vec) { // Check only lifetime parameters are present and that the lifetime // parameters that are present have no bounds. - let non_lifetime_param_spans: Vec<_> = params.iter() - .filter_map(|param| match param.kind { + let non_lt_param_spans: Vec<_> = params.iter().filter_map(|param| match param.kind { GenericParamKindAST::Lifetime { ref bounds, .. } => { if !bounds.is_empty() { let spans: Vec<_> = bounds.iter().map(|b| b.ident.span).collect(); - self.err_handler().span_err(spans, - "lifetime bounds cannot be used in this context"); + self.err_handler() + .span_err(spans, "lifetime bounds cannot be used in this context"); } None } _ => Some(param.ident.span), }).collect(); - if !non_lifetime_param_spans.is_empty() { - self.err_handler().span_err(non_lifetime_param_spans, + if !non_lt_param_spans.is_empty() { + self.err_handler().span_err(non_lt_param_spans, "only lifetime parameters can be used in this context"); } } @@ -333,16 +332,14 @@ impl<'a> Visitor<'a> for AstValidator<'a> { GenericParamKindAST::Lifetime { .. } => {} GenericParamKindAST::Type { ref bounds, ref default, .. } => { if !bounds.is_empty() { - self.err_handler().span_err(param.ident.span, - "type parameters on the left side \ - of a trait alias cannot be \ - bounded"); + self.err_handler() + .span_err(param.ident.span, "type parameters on the left \ + side of a trait alias cannot be bounded"); } if !default.is_none() { - self.err_handler().span_err(param.ident.span, - "type parameters on the left side \ - of a trait alias cannot have \ - defaults"); + self.err_handler() + .span_err(param.ident.span, "type parameters on the left \ + side of a trait alias cannot have defaults"); } } } @@ -402,10 +399,10 @@ impl<'a> Visitor<'a> for AstValidator<'a> { visit::walk_vis(self, vis) } - fn visit_generics(&mut self, g: &'a Generics) { + fn visit_generics(&mut self, generics: &'a Generics) { let mut seen_non_lifetime_param = false; let mut seen_default = None; - for param in &g.params { + for param in &generics.params { match (¶m.kind, seen_non_lifetime_param) { (GenericParamKindAST::Lifetime { .. }, true) => { self.err_handler() @@ -424,13 +421,13 @@ impl<'a> Visitor<'a> for AstValidator<'a> { } } } - for predicate in &g.where_clause.predicates { + for predicate in &generics.where_clause.predicates { if let WherePredicate::EqPredicate(ref predicate) = *predicate { self.err_handler().span_err(predicate.span, "equality constraints are not yet \ supported in where clauses (#20041)"); } } - visit::walk_generics(self, g) + visit::walk_generics(self, generics) } fn visit_generic_param(&mut self, param: &'a GenericParam) { @@ -516,12 +513,10 @@ impl<'a> Visitor<'a> for NestedImplTraitVisitor<'a> { fn visit_generic_args(&mut self, _: Span, generic_args: &'a GenericArgs) { match *generic_args { GenericArgs::AngleBracketed(ref data) => { - for arg in &data.args { - match arg { - GenericArgAST::Type(ty) => self.visit_ty(ty), - _ => {} - } - } + data.args.iter().for_each(|arg| match arg { + GenericArgAST::Type(ty) => self.visit_ty(ty), + _ => {} + }); for type_binding in &data.bindings { // Type bindings such as `Item=impl Debug` in `Iterator` // are allowed to contain nested `impl Trait`. diff --git a/src/librustc_privacy/lib.rs b/src/librustc_privacy/lib.rs index 19ed04a796843..388ac5cdb50af 100644 --- a/src/librustc_privacy/lib.rs +++ b/src/librustc_privacy/lib.rs @@ -1268,16 +1268,14 @@ impl<'a, 'tcx> Visitor<'tcx> for ObsoleteVisiblePrivateTypesVisitor<'a, 'tcx> { } fn visit_generics(&mut self, generics: &'tcx hir::Generics) { - for param in &generics.params { - match param.kind { - GenericParamKind::Lifetime { .. } => {} - GenericParamKind::Type { ref bounds, .. } => { - for bound in bounds { - self.check_ty_param_bound(bound); - } + generics.params.iter().for_each(|param| match param.kind { + GenericParamKind::Lifetime { .. } => {} + GenericParamKind::Type { ref bounds, .. } => { + for bound in bounds { + self.check_ty_param_bound(bound); } } - } + }); for predicate in &generics.where_clause.predicates { match predicate { &hir::WherePredicate::BoundPredicate(ref bound_pred) => { diff --git a/src/librustc_resolve/lib.rs b/src/librustc_resolve/lib.rs index 37264eb338228..314eae8f338b5 100644 --- a/src/librustc_resolve/lib.rs +++ b/src/librustc_resolve/lib.rs @@ -802,10 +802,8 @@ impl<'a, 'tcx> Visitor<'tcx> for Resolver<'a> { .filter_map(|param| match param.kind { GenericParamKindAST::Lifetime { .. } => None, GenericParamKindAST::Type { ref default, .. } => { - if default.is_some() { + if found_default || default.is_some() { found_default = true; - } - if found_default { return Some((Ident::with_empty_ctxt(param.ident.name), Def::Err)); } None @@ -2209,8 +2207,7 @@ impl<'a> Resolver<'a> { HasTypeParameters(generics, rib_kind) => { let mut function_type_rib = Rib::new(rib_kind); let mut seen_bindings = FxHashMap(); - for param in &generics.params { - match param.kind { + generics.params.iter().for_each(|param| match param.kind { GenericParamKindAST::Type { .. } => { let ident = param.ident.modern(); debug!("with_type_parameter_rib: {}", param.id); @@ -2225,15 +2222,13 @@ impl<'a> Resolver<'a> { } seen_bindings.entry(ident).or_insert(param.ident.span); - // plain insert (no renaming) - let def_id = self.definitions.local_def_id(param.id); - let def = Def::TyParam(def_id); + // Plain insert (no renaming). + let def = Def::TyParam(self.definitions.local_def_id(param.id)); function_type_rib.bindings.insert(ident, def); self.record_def(param.id, PathResolution::new(def)); } _ => {} - } - } + }); self.ribs[TypeNS].push(function_type_rib); } diff --git a/src/librustc_save_analysis/dump_visitor.rs b/src/librustc_save_analysis/dump_visitor.rs index 5faa3559c76aa..ea5f452199adf 100644 --- a/src/librustc_save_analysis/dump_visitor.rs +++ b/src/librustc_save_analysis/dump_visitor.rs @@ -826,12 +826,10 @@ impl<'l, 'tcx: 'l, 'll, O: DumpOutput + 'll> DumpVisitor<'l, 'tcx, 'll, O> { if let Some(ref generic_args) = seg.args { match **generic_args { ast::GenericArgs::AngleBracketed(ref data) => { - for arg in &data.args { - match arg { - ast::GenericArgAST::Type(ty) => self.visit_ty(ty), - _ => {} - } - } + data.args.iter().for_each(|arg| match arg { + ast::GenericArgAST::Type(ty) => self.visit_ty(ty), + _ => {} + }); } ast::GenericArgs::Parenthesized(ref data) => { for t in &data.inputs { @@ -915,12 +913,10 @@ impl<'l, 'tcx: 'l, 'll, O: DumpOutput + 'll> DumpVisitor<'l, 'tcx, 'll, O> { // Explicit types in the turbo-fish. if let Some(ref generic_args) = seg.args { if let ast::GenericArgs::AngleBracketed(ref data) = **generic_args { - for arg in &data.args { - match arg { - ast::GenericArgAST::Type(ty) => self.visit_ty(ty), - _ => {} - } - } + data.args.iter().for_each(|arg| match arg { + ast::GenericArgAST::Type(ty) => self.visit_ty(ty), + _ => {} + }); } } @@ -1489,21 +1485,19 @@ impl<'l, 'tcx: 'l, 'll, O: DumpOutput + 'll> Visitor<'l> for DumpVisitor<'l, 'tc } fn visit_generics(&mut self, generics: &'l ast::Generics) { - for param in &generics.params { - match param.kind { - ast::GenericParamKindAST::Lifetime { .. } => {} - ast::GenericParamKindAST::Type { ref bounds, ref default, .. } => { - for bound in bounds { - if let ast::TraitTyParamBound(ref trait_ref, _) = *bound { - self.process_path(trait_ref.trait_ref.ref_id, &trait_ref.trait_ref.path) - } - } - if let Some(ref ty) = default { - self.visit_ty(&ty); + generics.params.iter().for_each(|param| match param.kind { + ast::GenericParamKindAST::Lifetime { .. } => {} + ast::GenericParamKindAST::Type { ref bounds, ref default, .. } => { + for bound in bounds { + if let ast::TraitTyParamBound(ref trait_ref, _) = *bound { + self.process_path(trait_ref.trait_ref.ref_id, &trait_ref.trait_ref.path) } } + if let Some(ref ty) = default { + self.visit_ty(&ty); + } } - } + }); } fn visit_ty(&mut self, t: &'l ast::Ty) { diff --git a/src/librustc_typeck/check/mod.rs b/src/librustc_typeck/check/mod.rs index 4b731d5b883b1..6ac9a0fdfc049 100644 --- a/src/librustc_typeck/check/mod.rs +++ b/src/librustc_typeck/check/mod.rs @@ -4979,12 +4979,10 @@ impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> { |data| { let mut lifetimes = vec![]; let mut types = vec![]; - for arg in &data.args { - match arg { - GenericArg::Lifetime(lt) => lifetimes.push(lt), - GenericArg::Type(ty) => types.push(ty), - } - } + data.args.iter().for_each(|arg| match arg { + GenericArg::Lifetime(lt) => lifetimes.push(lt), + GenericArg::Type(ty) => types.push(ty), + }); (lifetimes, types, s.infer_types, &data.bindings[..]) } ) diff --git a/src/librustdoc/clean/auto_trait.rs b/src/librustdoc/clean/auto_trait.rs index 4418c10722308..2a63b12486637 100644 --- a/src/librustdoc/clean/auto_trait.rs +++ b/src/librustdoc/clean/auto_trait.rs @@ -521,7 +521,10 @@ impl<'a, 'tcx, 'rcx> AutoTraitFinder<'a, 'tcx, 'rcx> { // We only care about late bound regions, as we need to add them // to the 'for<>' section &ty::ReLateBound(_, ty::BoundRegion::BrNamed(_, name)) => { - Some(GenericParamDef::Lifetime(Lifetime(name.to_string()))) + Some(GenericParamDef { + name: name.to_string(), + kind: GenericParamDefKind::Lifetime, + }) } &ty::ReVar(_) | &ty::ReEarlyBound(_) => None, _ => panic!("Unexpected region type {:?}", r), @@ -867,19 +870,17 @@ impl<'a, 'tcx, 'rcx> AutoTraitFinder<'a, 'tcx, 'rcx> { existing_predicates.extend(final_bounds); - for p in generic_params.iter_mut() { - match p { - &mut GenericParamDef::Type(ref mut ty) => { - // We never want something like 'impl' - ty.default.take(); - - let generic_ty = Type::Generic(ty.name.clone()); - + for param in generic_params.iter_mut() { + match param.kind { + GenericParamDefKind::Type { ref mut default, ref mut bounds, .. } => { + // We never want something like `impl`. + default.take(); + let generic_ty = Type::Generic(param.name.clone()); if !has_sized.contains(&generic_ty) { - ty.bounds.insert(0, TyParamBound::maybe_sized(self.cx)); + bounds.insert(0, TyParamBound::maybe_sized(self.cx)); } } - GenericParamDef::Lifetime(_) => {} + GenericParamDefKind::Lifetime => {} } } diff --git a/src/librustdoc/clean/mod.rs b/src/librustdoc/clean/mod.rs index a2ae7afbc8386..3a4e582622f1c 100644 --- a/src/librustdoc/clean/mod.rs +++ b/src/librustdoc/clean/mod.rs @@ -1457,53 +1457,6 @@ impl Clean for [ast::Attribute] { } } -#[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Eq, Debug, Hash)] -pub struct TyParam { - pub name: String, - pub did: DefId, - pub bounds: Vec, - pub default: Option, - pub synthetic: Option, -} - -impl Clean for hir::GenericParam { - fn clean(&self, cx: &DocContext) -> TyParam { - match self.kind { - hir::GenericParamKind::Type { ref bounds, ref default, synthetic, .. } => { - TyParam { - name: self.name().clean(cx), - did: cx.tcx.hir.local_def_id(self.id), - bounds: bounds.clean(cx), - default: default.clean(cx), - synthetic: synthetic, - } - } - _ => panic!(), - } - } -} - -impl<'tcx> Clean for ty::GenericParamDef { - fn clean(&self, cx: &DocContext) -> TyParam { - cx.renderinfo.borrow_mut().external_typarams.insert(self.def_id, self.name.clean(cx)); - let has_default = match self.kind { - ty::GenericParamDefKind::Type { has_default, .. } => has_default, - _ => panic!("tried to convert a non-type GenericParamDef as a type") - }; - TyParam { - name: self.name.clean(cx), - did: self.def_id, - bounds: vec![], // these are filled in from the where-clauses - default: if has_default { - Some(cx.tcx.type_of(self.def_id).clean(cx)) - } else { - None - }, - synthetic: None, - } - } -} - #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Eq, Debug, Hash)] pub enum TyParamBound { RegionBound(Lifetime), @@ -1634,8 +1587,11 @@ impl<'a, 'tcx> Clean for (&'a ty::TraitRef<'tcx>, Vec if let ty::TyRef(ref reg, _, _) = ty_s.sty { if let &ty::RegionKind::ReLateBound(..) = *reg { debug!(" hit an ReLateBound {:?}", reg); - if let Some(lt) = reg.clean(cx) { - late_bounds.push(GenericParamDef::Lifetime(lt)); + if let Some(Lifetime(name)) = reg.clean(cx) { + late_bounds.push(GenericParamDef { + name, + kind: GenericParamDefKind::Lifetime, + }); } } } @@ -1872,27 +1828,90 @@ impl<'tcx> Clean for ty::ProjectionTy<'tcx> { } #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Eq, Debug, Hash)] -pub enum GenericParamDef { - Lifetime(Lifetime), - Type(TyParam), +pub enum GenericParamDefKind { + Lifetime, + Type { + did: DefId, + bounds: Vec, + default: Option, + synthetic: Option, + }, +} + +#[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Eq, Debug, Hash)] +pub struct GenericParamDef { + pub name: String, + + pub kind: GenericParamDefKind, } impl GenericParamDef { pub fn is_synthetic_type_param(&self) -> bool { - match self { - GenericParamDef::Type(ty) => ty.synthetic.is_some(), - GenericParamDef::Lifetime(_) => false, + match self.kind { + GenericParamDefKind::Lifetime => false, + GenericParamDefKind::Type { ref synthetic, .. } => synthetic.is_some(), + } + } +} + +impl<'tcx> Clean for ty::GenericParamDef { + fn clean(&self, cx: &DocContext) -> GenericParamDef { + let (name, kind) = match self.kind { + ty::GenericParamDefKind::Lifetime => { + (self.name.to_string(), GenericParamDefKind::Lifetime) + } + ty::GenericParamDefKind::Type { has_default, .. } => { + cx.renderinfo.borrow_mut().external_typarams + .insert(self.def_id, self.name.clean(cx)); + let default = if has_default { + Some(cx.tcx.type_of(self.def_id).clean(cx)) + } else { + None + }; + (self.name.clean(cx), GenericParamDefKind::Type { + did: self.def_id, + bounds: vec![], // These are filled in from the where-clauses. + default, + synthetic: None, + }) + } + }; + + GenericParamDef { + name, + kind, } } } impl Clean for hir::GenericParam { fn clean(&self, cx: &DocContext) -> GenericParamDef { - match self.kind { - hir::GenericParamKind::Lifetime { .. } => { - GenericParamDef::Lifetime(self.clean(cx)) + let (name, kind) = match self.kind { + hir::GenericParamKind::Lifetime { ref bounds, .. } => { + let name = if bounds.len() > 0 { + let mut s = format!("{}: {}", self.name(), bounds[0].name.name()); + for bound in bounds.iter().skip(1) { + s.push_str(&format!(" + {}", bound.name.name())); + } + s + } else { + self.name().to_string() + }; + (name, GenericParamDefKind::Lifetime) + } + hir::GenericParamKind::Type { ref bounds, ref default, synthetic, .. } => { + (self.name().clean(cx), GenericParamDefKind::Type { + did: cx.tcx.hir.local_def_id(self.id), + bounds: bounds.clean(cx), + default: default.clean(cx), + synthetic: synthetic, + }) } - hir::GenericParamKind::Type { .. } => GenericParamDef::Type(self.clean(cx)), + }; + + GenericParamDef { + name, + kind, } } } @@ -1919,17 +1938,16 @@ impl Clean for hir::Generics { } let impl_trait_params = self.params .iter() - .filter(|p| is_impl_trait(p)) - .map(|p| { - let p = p.clean(cx); - if let GenericParamDef::Type(ref tp) = p { - cx.impl_trait_bounds - .borrow_mut() - .insert(tp.did, tp.bounds.clone()); - } else { - unreachable!() + .filter(|param| is_impl_trait(param)) + .map(|param| { + let param: GenericParamDef = param.clean(cx); + match param.kind { + GenericParamDefKind::Lifetime => unreachable!(), + GenericParamDefKind::Type { did, ref bounds, .. } => { + cx.impl_trait_bounds.borrow_mut().insert(did, bounds.clone()); + } } - p + param }) .collect::>(); @@ -1940,23 +1958,26 @@ impl Clean for hir::Generics { } params.extend(impl_trait_params); - let mut g = Generics { + let mut generics = Generics { params, - where_predicates: self.where_clause.predicates.clean(cx) + where_predicates: self.where_clause.predicates.clean(cx), }; // Some duplicates are generated for ?Sized bounds between type params and where // predicates. The point in here is to move the bounds definitions from type params // to where predicates when such cases occur. - for where_pred in &mut g.where_predicates { + for where_pred in &mut generics.where_predicates { match *where_pred { WherePredicate::BoundPredicate { ty: Generic(ref name), ref mut bounds } => { if bounds.is_empty() { - for param in &mut g.params { - if let GenericParamDef::Type(ref mut type_param) = *param { - if &type_param.name == name { - mem::swap(bounds, &mut type_param.bounds); - break + for param in &mut generics.params { + match param.kind { + GenericParamDefKind::Lifetime => {} + GenericParamDefKind::Type { bounds: ref mut ty_bounds, .. } => { + if ¶m.name == name { + mem::swap(bounds, ty_bounds); + break + } } } } @@ -1965,7 +1986,7 @@ impl Clean for hir::Generics { _ => continue, } } - g + generics } } @@ -1988,7 +2009,7 @@ impl<'a, 'tcx> Clean for (&'a ty::Generics, } Some(param.clean(cx)) } - }).collect::>(); + }).collect::>(); let mut where_predicates = preds.predicates.to_vec().clean(cx); @@ -2033,15 +2054,9 @@ impl<'a, 'tcx> Clean for (&'a ty::Generics, params: gens.params .iter() .flat_map(|param| match param.kind { - ty::GenericParamDefKind::Lifetime => { - Some(GenericParamDef::Lifetime(param.clean(cx))) - } + ty::GenericParamDefKind::Lifetime => Some(param.clean(cx)), ty::GenericParamDefKind::Type { .. } => None, - }).chain( - simplify::ty_params(stripped_typarams) - .into_iter() - .map(|tp| GenericParamDef::Type(tp)) - ) + }).chain(simplify::ty_params(stripped_typarams).into_iter()) .collect(), where_predicates: simplify::where_clauses(cx, where_predicates), } diff --git a/src/librustdoc/clean/simplify.rs b/src/librustdoc/clean/simplify.rs index ac1952a4babbf..95ceee8569090 100644 --- a/src/librustdoc/clean/simplify.rs +++ b/src/librustdoc/clean/simplify.rs @@ -135,9 +135,14 @@ pub fn where_clauses(cx: &DocContext, clauses: Vec) -> Vec { clauses } -pub fn ty_params(mut params: Vec) -> Vec { +pub fn ty_params(mut params: Vec) -> Vec { for param in &mut params { - param.bounds = ty_bounds(mem::replace(&mut param.bounds, Vec::new())); + match param.kind { + clean::GenericParamDefKind::Type { ref mut bounds, .. } => { + *bounds = ty_bounds(mem::replace(bounds, Vec::new())); + } + _ => panic!("expected only type parameters"), + } } params } diff --git a/src/librustdoc/html/format.rs b/src/librustdoc/html/format.rs index d2d068e520957..86c312275ff28 100644 --- a/src/librustdoc/html/format.rs +++ b/src/librustdoc/html/format.rs @@ -119,20 +119,20 @@ impl<'a> fmt::Display for TyParamBounds<'a> { impl fmt::Display for clean::GenericParamDef { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - match *self { - clean::GenericParamDef::Lifetime(ref lp) => write!(f, "{}", lp), - clean::GenericParamDef::Type(ref tp) => { - f.write_str(&tp.name)?; + match self.kind { + clean::GenericParamDefKind::Lifetime => write!(f, "{}", self.name), + clean::GenericParamDefKind::Type { ref bounds, ref default, .. } => { + f.write_str(&self.name)?; - if !tp.bounds.is_empty() { + if !bounds.is_empty() { if f.alternate() { - write!(f, ": {:#}", TyParamBounds(&tp.bounds))?; + write!(f, ": {:#}", TyParamBounds(bounds))?; } else { - write!(f, ": {}", TyParamBounds(&tp.bounds))?; + write!(f, ": {}", TyParamBounds(bounds))?; } } - if let Some(ref ty) = tp.default { + if let Some(ref ty) = default { if f.alternate() { write!(f, " = {:#}", ty)?; } else { diff --git a/src/librustdoc/html/render.rs b/src/librustdoc/html/render.rs index 5c2ec2058ee9d..675d1097bda4a 100644 --- a/src/librustdoc/html/render.rs +++ b/src/librustdoc/html/render.rs @@ -1453,11 +1453,11 @@ impl DocFolder for Cache { impl<'a> Cache { fn generics(&mut self, generics: &clean::Generics) { for param in &generics.params { - match *param { - clean::GenericParamDef::Type(ref typ) => { - self.typarams.insert(typ.did, typ.name.clone()); + match param.kind { + clean::GenericParamDefKind::Lifetime => {} + clean::GenericParamDefKind::Type { did, .. } => { + self.typarams.insert(did, param.name.clone()); } - clean::GenericParamDef::Lifetime(_) => {} } } } From 3bcb006fd96763b24c34a8cf2abdf081d2e912b1 Mon Sep 17 00:00:00 2001 From: varkor Date: Sun, 27 May 2018 20:07:09 +0100 Subject: [PATCH 17/41] Rename structures in ast --- src/librustc/hir/lowering.rs | 24 +++++++++---------- src/librustc/hir/map/def_collector.rs | 6 ++--- src/librustc/lint/context.rs | 2 +- src/librustc/lint/mod.rs | 2 +- src/librustc_driver/pretty.rs | 2 +- src/librustc_passes/ast_validation.rs | 16 ++++++------- src/librustc_resolve/lib.rs | 12 +++++----- src/librustc_save_analysis/dump_visitor.rs | 12 +++++----- src/librustc_save_analysis/lib.rs | 4 ++-- src/librustc_save_analysis/sig.rs | 6 ++--- src/libsyntax/ast.rs | 20 ++++++++-------- src/libsyntax/ext/build.rs | 26 ++++++++++---------- src/libsyntax/fold.rs | 24 +++++++++---------- src/libsyntax/parse/parser.rs | 28 +++++++++++----------- src/libsyntax/print/pprust.rs | 20 ++++++++-------- src/libsyntax/util/node_count.rs | 2 +- src/libsyntax/visit.rs | 14 +++++------ src/libsyntax_ext/deriving/clone.rs | 6 ++--- src/libsyntax_ext/deriving/cmp/eq.rs | 4 ++-- src/libsyntax_ext/deriving/generic/mod.rs | 18 +++++++------- src/libsyntax_ext/deriving/generic/ty.rs | 18 +++++++------- src/libsyntax_ext/deriving/mod.rs | 2 +- src/libsyntax_ext/env.rs | 4 ++-- 23 files changed, 136 insertions(+), 136 deletions(-) diff --git a/src/librustc/hir/lowering.rs b/src/librustc/hir/lowering.rs index c0f94a138afc6..71b0b66b59a29 100644 --- a/src/librustc/hir/lowering.rs +++ b/src/librustc/hir/lowering.rs @@ -325,7 +325,7 @@ impl<'a> LoweringContext<'a> { .params .iter() .filter(|param| match param.kind { - ast::GenericParamKindAST::Lifetime { .. } => true, + ast::GenericParamKind::Lifetime { .. } => true, _ => false, }) .count(); @@ -758,13 +758,13 @@ impl<'a> LoweringContext<'a> { // This is used to track which lifetimes have already been defined, and // which are new in-band lifetimes that need to have a definition created // for them. - fn with_in_scope_lifetime_defs(&mut self, params: &Vec, f: F) -> T + fn with_in_scope_lifetime_defs(&mut self, params: &Vec, f: F) -> T where F: FnOnce(&mut LoweringContext) -> T, { let old_len = self.in_scope_lifetimes.len(); let lt_def_names = params.iter().filter_map(|param| match param.kind { - GenericParamKindAST::Lifetime { .. } => Some(param.ident.name), + GenericParamKind::Lifetime { .. } => Some(param.ident.name), _ => None, }); self.in_scope_lifetimes.extend(lt_def_names); @@ -1044,12 +1044,12 @@ impl<'a> LoweringContext<'a> { } fn lower_generic_arg(&mut self, - arg: &ast::GenericArgAST, + arg: &ast::GenericArg, itctx: ImplTraitContext) -> hir::GenericArg { match arg { - ast::GenericArgAST::Lifetime(lt) => GenericArg::Lifetime(self.lower_lifetime(<)), - ast::GenericArgAST::Type(ty) => GenericArg::Type(self.lower_ty(&ty, itctx)), + ast::GenericArg::Lifetime(lt) => GenericArg::Lifetime(self.lower_lifetime(<)), + ast::GenericArg::Type(ty) => GenericArg::Type(self.lower_ty(&ty, itctx)), } } @@ -1745,7 +1745,7 @@ impl<'a> LoweringContext<'a> { ) -> (hir::GenericArgs, bool) { let &AngleBracketedArgs { ref args, ref bindings, .. } = data; let has_types = args.iter().any(|arg| match arg { - GenericArgAST::Type(_) => true, + ast::GenericArg::Type(_) => true, _ => false, }); (hir::GenericArgs { @@ -1934,7 +1934,7 @@ impl<'a> LoweringContext<'a> { fn lower_generic_params( &mut self, - params: &Vec, + params: &Vec, add_bounds: &NodeMap>, itctx: ImplTraitContext, ) -> hir::HirVec { @@ -1942,12 +1942,12 @@ impl<'a> LoweringContext<'a> { } fn lower_generic_param(&mut self, - param: &GenericParamAST, + param: &GenericParam, add_bounds: &NodeMap>, itctx: ImplTraitContext) -> hir::GenericParam { match param.kind { - GenericParamKindAST::Lifetime { ref bounds, ref lifetime, .. } => { + GenericParamKind::Lifetime { ref bounds, ref lifetime, .. } => { let was_collecting_in_band = self.is_collecting_in_band_lifetimes; self.is_collecting_in_band_lifetimes = false; @@ -1968,7 +1968,7 @@ impl<'a> LoweringContext<'a> { param } - GenericParamKindAST::Type { ref bounds, ref default } => { + GenericParamKind::Type { ref bounds, ref default } => { let mut name = self.lower_ident(param.ident); // Don't expose `Self` (recovered "keyword used as ident" parse error). @@ -2044,7 +2044,7 @@ impl<'a> LoweringContext<'a> { { for param in &generics.params { match param.kind { - GenericParamKindAST::Type { .. } => { + GenericParamKind::Type { .. } => { if node_id == param.id { add_bounds.entry(param.id) .or_insert(Vec::new()) diff --git a/src/librustc/hir/map/def_collector.rs b/src/librustc/hir/map/def_collector.rs index ab4a0826584ac..8aa5dd4ad80fd 100644 --- a/src/librustc/hir/map/def_collector.rs +++ b/src/librustc/hir/map/def_collector.rs @@ -170,11 +170,11 @@ impl<'a> visit::Visitor<'a> for DefCollector<'a> { } } - fn visit_generic_param(&mut self, param: &'a GenericParamAST) { + fn visit_generic_param(&mut self, param: &'a GenericParam) { let name = param.ident.name.as_interned_str(); let def_path_data = match param.kind { - GenericParamKindAST::Lifetime { .. } => DefPathData::LifetimeParam(name), - GenericParamKindAST::Type { .. } => DefPathData::TypeParam(name), + GenericParamKind::Lifetime { .. } => DefPathData::LifetimeParam(name), + GenericParamKind::Type { .. } => DefPathData::TypeParam(name), }; self.create_def(param.id, def_path_data, REGULAR_SPACE, param.ident.span); diff --git a/src/librustc/lint/context.rs b/src/librustc/lint/context.rs index 7236eebdb6f2b..824930a7eb000 100644 --- a/src/librustc/lint/context.rs +++ b/src/librustc/lint/context.rs @@ -990,7 +990,7 @@ impl<'a> ast_visit::Visitor<'a> for EarlyContext<'a> { run_lints!(self, check_expr_post, early_passes, e); } - fn visit_generic_param(&mut self, param: &'a ast::GenericParamAST) { + fn visit_generic_param(&mut self, param: &'a ast::GenericParam) { run_lints!(self, check_generic_param, early_passes, param); ast_visit::walk_generic_param(self, param); } diff --git a/src/librustc/lint/mod.rs b/src/librustc/lint/mod.rs index 3d31a651b2f6d..9338e235c534d 100644 --- a/src/librustc/lint/mod.rs +++ b/src/librustc/lint/mod.rs @@ -254,7 +254,7 @@ pub trait EarlyLintPass: LintPass { fn check_expr(&mut self, _: &EarlyContext, _: &ast::Expr) { } fn check_expr_post(&mut self, _: &EarlyContext, _: &ast::Expr) { } fn check_ty(&mut self, _: &EarlyContext, _: &ast::Ty) { } - fn check_generic_param(&mut self, _: &EarlyContext, _: &ast::GenericParamAST) { } + fn check_generic_param(&mut self, _: &EarlyContext, _: &ast::GenericParam) { } fn check_generics(&mut self, _: &EarlyContext, _: &ast::Generics) { } fn check_where_predicate(&mut self, _: &EarlyContext, _: &ast::WherePredicate) { } fn check_poly_trait_ref(&mut self, _: &EarlyContext, _: &ast::PolyTraitRef, diff --git a/src/librustc_driver/pretty.rs b/src/librustc_driver/pretty.rs index 14003f0fd3719..67720e61e91af 100644 --- a/src/librustc_driver/pretty.rs +++ b/src/librustc_driver/pretty.rs @@ -681,7 +681,7 @@ impl<'a> ReplaceBodyWithLoop<'a> { None => false, Some(&ast::GenericArgs::AngleBracketed(ref data)) => { let types = data.args.iter().filter_map(|arg| match arg { - ast::GenericArgAST::Type(ty) => Some(ty), + ast::GenericArg::Type(ty) => Some(ty), _ => None, }); any_involves_impl_trait(types.into_iter()) || diff --git a/src/librustc_passes/ast_validation.rs b/src/librustc_passes/ast_validation.rs index d9a69f09d34bd..dfcdb688b00cd 100644 --- a/src/librustc_passes/ast_validation.rs +++ b/src/librustc_passes/ast_validation.rs @@ -138,11 +138,11 @@ impl<'a> AstValidator<'a> { } } - fn check_late_bound_lifetime_defs(&self, params: &Vec) { + fn check_late_bound_lifetime_defs(&self, params: &Vec) { // Check only lifetime parameters are present and that the lifetime // parameters that are present have no bounds. let non_lt_param_spans: Vec<_> = params.iter().filter_map(|param| match param.kind { - GenericParamKindAST::Lifetime { ref bounds, .. } => { + GenericParamKind::Lifetime { ref bounds, .. } => { if !bounds.is_empty() { let spans: Vec<_> = bounds.iter().map(|b| b.ident.span).collect(); self.err_handler() @@ -329,8 +329,8 @@ impl<'a> Visitor<'a> for AstValidator<'a> { ItemKind::TraitAlias(Generics { ref params, .. }, ..) => { for param in params { match param.kind { - GenericParamKindAST::Lifetime { .. } => {} - GenericParamKindAST::Type { ref bounds, ref default, .. } => { + GenericParamKind::Lifetime { .. } => {} + GenericParamKind::Type { ref bounds, ref default, .. } => { if !bounds.is_empty() { self.err_handler() .span_err(param.ident.span, "type parameters on the left \ @@ -404,12 +404,12 @@ impl<'a> Visitor<'a> for AstValidator<'a> { let mut seen_default = None; for param in &generics.params { match (¶m.kind, seen_non_lifetime_param) { - (GenericParamKindAST::Lifetime { .. }, true) => { + (GenericParamKind::Lifetime { .. }, true) => { self.err_handler() .span_err(param.ident.span, "lifetime parameters must be leading"); }, - (GenericParamKindAST::Lifetime { .. }, false) => {} - (GenericParamKindAST::Type { ref default, .. }, _) => { + (GenericParamKind::Lifetime { .. }, false) => {} + (GenericParamKind::Type { ref default, .. }, _) => { seen_non_lifetime_param = true; if default.is_some() { seen_default = Some(param.ident.span); @@ -514,7 +514,7 @@ impl<'a> Visitor<'a> for NestedImplTraitVisitor<'a> { match *generic_args { GenericArgs::AngleBracketed(ref data) => { data.args.iter().for_each(|arg| match arg { - GenericArgAST::Type(ty) => self.visit_ty(ty), + GenericArg::Type(ty) => self.visit_ty(ty), _ => {} }); for type_binding in &data.bindings { diff --git a/src/librustc_resolve/lib.rs b/src/librustc_resolve/lib.rs index 314eae8f338b5..6561202be51b3 100644 --- a/src/librustc_resolve/lib.rs +++ b/src/librustc_resolve/lib.rs @@ -56,7 +56,7 @@ use syntax::util::lev_distance::find_best_match_for_name; use syntax::visit::{self, FnKind, Visitor}; use syntax::attr; use syntax::ast::{Arm, BindingMode, Block, Crate, Expr, ExprKind}; -use syntax::ast::{FnDecl, ForeignItem, ForeignItemKind, GenericParamKindAST, Generics}; +use syntax::ast::{FnDecl, ForeignItem, ForeignItemKind, GenericParamKind, Generics}; use syntax::ast::{Item, ItemKind, ImplItem, ImplItemKind}; use syntax::ast::{Label, Local, Mutability, Pat, PatKind, Path}; use syntax::ast::{QSelf, TraitItemKind, TraitRef, Ty, TyKind}; @@ -800,8 +800,8 @@ impl<'a, 'tcx> Visitor<'tcx> for Resolver<'a> { let mut found_default = false; default_ban_rib.bindings.extend(generics.params.iter() .filter_map(|param| match param.kind { - GenericParamKindAST::Lifetime { .. } => None, - GenericParamKindAST::Type { ref default, .. } => { + GenericParamKind::Lifetime { .. } => None, + GenericParamKind::Type { ref default, .. } => { if found_default || default.is_some() { found_default = true; return Some((Ident::with_empty_ctxt(param.ident.name), Def::Err)); @@ -812,8 +812,8 @@ impl<'a, 'tcx> Visitor<'tcx> for Resolver<'a> { for param in &generics.params { match param.kind { - GenericParamKindAST::Lifetime { .. } => self.visit_generic_param(param), - GenericParamKindAST::Type { ref bounds, ref default, .. } => { + GenericParamKind::Lifetime { .. } => self.visit_generic_param(param), + GenericParamKind::Type { ref bounds, ref default, .. } => { for bound in bounds { self.visit_ty_param_bound(bound); } @@ -2208,7 +2208,7 @@ impl<'a> Resolver<'a> { let mut function_type_rib = Rib::new(rib_kind); let mut seen_bindings = FxHashMap(); generics.params.iter().for_each(|param| match param.kind { - GenericParamKindAST::Type { .. } => { + GenericParamKind::Type { .. } => { let ident = param.ident.modern(); debug!("with_type_parameter_rib: {}", param.id); diff --git a/src/librustc_save_analysis/dump_visitor.rs b/src/librustc_save_analysis/dump_visitor.rs index ea5f452199adf..6cfec57f80e65 100644 --- a/src/librustc_save_analysis/dump_visitor.rs +++ b/src/librustc_save_analysis/dump_visitor.rs @@ -371,8 +371,8 @@ impl<'l, 'tcx: 'l, 'll, O: DumpOutput + 'll> DumpVisitor<'l, 'tcx, 'll, O> { ) { for param in &generics.params { match param.kind { - ast::GenericParamKindAST::Lifetime { .. } => {} - ast::GenericParamKindAST::Type { .. } => { + ast::GenericParamKind::Lifetime { .. } => {} + ast::GenericParamKind::Type { .. } => { let param_ss = param.ident.span; let name = escape(self.span.snippet(param_ss)); // Append $id to name to make sure each one is unique. @@ -827,7 +827,7 @@ impl<'l, 'tcx: 'l, 'll, O: DumpOutput + 'll> DumpVisitor<'l, 'tcx, 'll, O> { match **generic_args { ast::GenericArgs::AngleBracketed(ref data) => { data.args.iter().for_each(|arg| match arg { - ast::GenericArgAST::Type(ty) => self.visit_ty(ty), + ast::GenericArg::Type(ty) => self.visit_ty(ty), _ => {} }); } @@ -914,7 +914,7 @@ impl<'l, 'tcx: 'l, 'll, O: DumpOutput + 'll> DumpVisitor<'l, 'tcx, 'll, O> { if let Some(ref generic_args) = seg.args { if let ast::GenericArgs::AngleBracketed(ref data) = **generic_args { data.args.iter().for_each(|arg| match arg { - ast::GenericArgAST::Type(ty) => self.visit_ty(ty), + ast::GenericArg::Type(ty) => self.visit_ty(ty), _ => {} }); } @@ -1486,8 +1486,8 @@ impl<'l, 'tcx: 'l, 'll, O: DumpOutput + 'll> Visitor<'l> for DumpVisitor<'l, 'tc fn visit_generics(&mut self, generics: &'l ast::Generics) { generics.params.iter().for_each(|param| match param.kind { - ast::GenericParamKindAST::Lifetime { .. } => {} - ast::GenericParamKindAST::Type { ref bounds, ref default, .. } => { + ast::GenericParamKind::Lifetime { .. } => {} + ast::GenericParamKind::Type { ref bounds, ref default, .. } => { for bound in bounds { if let ast::TraitTyParamBound(ref trait_ref, _) = *bound { self.process_path(trait_ref.trait_ref.ref_id, &trait_ref.trait_ref.path) diff --git a/src/librustc_save_analysis/lib.rs b/src/librustc_save_analysis/lib.rs index f656b013c0a01..528f6ba96fa82 100644 --- a/src/librustc_save_analysis/lib.rs +++ b/src/librustc_save_analysis/lib.rs @@ -935,8 +935,8 @@ fn make_signature(decl: &ast::FnDecl, generics: &ast::Generics) -> String { .params .iter() .map(|param| match param.kind { - ast::GenericParamKindAST::Lifetime { .. } => param.ident.name.to_string(), - ast::GenericParamKindAST::Type { .. } => param.ident.to_string(), + ast::GenericParamKind::Lifetime { .. } => param.ident.name.to_string(), + ast::GenericParamKind::Type { .. } => param.ident.to_string(), }) .collect::>() .join(", ")); diff --git a/src/librustc_save_analysis/sig.rs b/src/librustc_save_analysis/sig.rs index 8e8e0dfa1828e..6a63995c0fd5f 100644 --- a/src/librustc_save_analysis/sig.rs +++ b/src/librustc_save_analysis/sig.rs @@ -224,7 +224,7 @@ impl Sig for ast::Ty { text.push_str(&f.generic_params .iter() .filter_map(|param| match param.kind { - ast::GenericParamKindAST::Lifetime { .. } => { + ast::GenericParamKind::Lifetime { .. } => { Some(param.ident.to_string()) } _ => None, @@ -624,7 +624,7 @@ impl Sig for ast::Generics { end: offset + text.len() + param_text.len(), }); match param.kind { - ast::GenericParamKindAST::Lifetime { ref bounds, .. } => { + ast::GenericParamKind::Lifetime { ref bounds, .. } => { if !bounds.is_empty() { param_text.push_str(": "); let bounds = bounds.iter() @@ -635,7 +635,7 @@ impl Sig for ast::Generics { // FIXME add lifetime bounds refs. } } - ast::GenericParamKindAST::Type { ref bounds, .. } => { + ast::GenericParamKind::Type { ref bounds, .. } => { if !bounds.is_empty() { param_text.push_str(": "); param_text.push_str(&pprust::bounds_to_string(bounds)); diff --git a/src/libsyntax/ast.rs b/src/libsyntax/ast.rs index c2626c70a4273..f589057218c80 100644 --- a/src/libsyntax/ast.rs +++ b/src/libsyntax/ast.rs @@ -160,7 +160,7 @@ impl GenericArgs { } #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)] -pub enum GenericArgAST { +pub enum GenericArg { Lifetime(Lifetime), Type(P), } @@ -171,7 +171,7 @@ pub struct AngleBracketedArgs { /// Overall span pub span: Span, /// The arguments for this path segment. - pub args: Vec, + pub args: Vec, /// Bindings (equality constraints) on associated types, if present. /// /// E.g., `Foo`. @@ -299,7 +299,7 @@ pub enum TraitBoundModifier { pub type TyParamBounds = Vec; #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)] -pub enum GenericParamKindAST { +pub enum GenericParamKind { /// A lifetime definition, e.g. `'a: 'b+'c+'d`. Lifetime { bounds: Vec, @@ -312,19 +312,19 @@ pub enum GenericParamKindAST { } #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)] -pub struct GenericParamAST { +pub struct GenericParam { pub ident: Ident, pub id: NodeId, pub attrs: ThinVec, - pub kind: GenericParamKindAST, + pub kind: GenericParamKind, } /// Represents lifetime, type and const parameters attached to a declaration of /// a function, enum, trait, etc. #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)] pub struct Generics { - pub params: Vec, + pub params: Vec, pub where_clause: WhereClause, pub span: Span, } @@ -380,7 +380,7 @@ impl WherePredicate { pub struct WhereBoundPredicate { pub span: Span, /// Any generics from a `for` binding - pub bound_generic_params: Vec, + pub bound_generic_params: Vec, /// The type being bounded pub bounded_ty: P, /// Trait and lifetime bounds (`Clone+Send+'static`) @@ -1512,7 +1512,7 @@ impl fmt::Debug for Ty { pub struct BareFnTy { pub unsafety: Unsafety, pub abi: Abi, - pub generic_params: Vec, + pub generic_params: Vec, pub decl: P } @@ -1891,7 +1891,7 @@ pub struct TraitRef { #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)] pub struct PolyTraitRef { /// The `'a` in `<'a> Foo<&'a T>` - pub bound_generic_params: Vec, + pub bound_generic_params: Vec, /// The `Foo<&'a T>` in `<'a> Foo<&'a T>` pub trait_ref: TraitRef, @@ -1900,7 +1900,7 @@ pub struct PolyTraitRef { } impl PolyTraitRef { - pub fn new(generic_params: Vec, path: Path, span: Span) -> Self { + pub fn new(generic_params: Vec, path: Path, span: Span) -> Self { PolyTraitRef { bound_generic_params: generic_params, trait_ref: TraitRef { path: path, ref_id: DUMMY_NODE_ID }, diff --git a/src/libsyntax/ext/build.rs b/src/libsyntax/ext/build.rs index 42745c14965a3..695ad9c233f2e 100644 --- a/src/libsyntax/ext/build.rs +++ b/src/libsyntax/ext/build.rs @@ -31,7 +31,7 @@ pub trait AstBuilder { fn path_all(&self, sp: Span, global: bool, idents: Vec, - args: Vec, + args: Vec, bindings: Vec) -> ast::Path; @@ -42,7 +42,7 @@ pub trait AstBuilder { fn qpath_all(&self, self_type: P, trait_path: ast::Path, ident: ast::Ident, - args: Vec, + args: Vec, bindings: Vec) -> (ast::QSelf, ast::Path); @@ -69,7 +69,7 @@ pub trait AstBuilder { id: ast::Ident, attrs: Vec, bounds: ast::TyParamBounds, - default: Option>) -> ast::GenericParamAST; + default: Option>) -> ast::GenericParam; fn trait_ref(&self, path: ast::Path) -> ast::TraitRef; fn poly_trait_ref(&self, span: Span, path: ast::Path) -> ast::PolyTraitRef; @@ -80,7 +80,7 @@ pub trait AstBuilder { ident: ast::Ident, attrs: Vec, bounds: Vec) - -> ast::GenericParamAST; + -> ast::GenericParam; // statements fn stmt_expr(&self, expr: P) -> ast::Stmt; @@ -314,7 +314,7 @@ impl<'a> AstBuilder for ExtCtxt<'a> { span: Span, global: bool, mut idents: Vec , - args: Vec, + args: Vec, bindings: Vec ) -> ast::Path { let last_ident = idents.pop().unwrap(); @@ -356,7 +356,7 @@ impl<'a> AstBuilder for ExtCtxt<'a> { self_type: P, trait_path: ast::Path, ident: ast::Ident, - args: Vec, + args: Vec, bindings: Vec) -> (ast::QSelf, ast::Path) { let mut path = trait_path; @@ -424,7 +424,7 @@ impl<'a> AstBuilder for ExtCtxt<'a> { self.path_all(DUMMY_SP, true, self.std_path(&["option", "Option"]), - vec![ast::GenericArgAST::Type(ty)], + vec![ast::GenericArg::Type(ty)], Vec::new())) } @@ -437,12 +437,12 @@ impl<'a> AstBuilder for ExtCtxt<'a> { ident: ast::Ident, attrs: Vec, bounds: ast::TyParamBounds, - default: Option>) -> ast::GenericParamAST { - ast::GenericParamAST { + default: Option>) -> ast::GenericParam { + ast::GenericParam { ident: ident.with_span_pos(span), id: ast::DUMMY_NODE_ID, attrs: attrs.into(), - kind: ast::GenericParamKindAST::Type { + kind: ast::GenericParamKind::Type { bounds, default, } @@ -477,13 +477,13 @@ impl<'a> AstBuilder for ExtCtxt<'a> { ident: ast::Ident, attrs: Vec, bounds: Vec) - -> ast::GenericParamAST { + -> ast::GenericParam { let lifetime = self.lifetime(span, ident); - ast::GenericParamAST { + ast::GenericParam { ident: lifetime.ident, id: lifetime.id, attrs: attrs.into(), - kind: ast::GenericParamKindAST::Lifetime { + kind: ast::GenericParamKind::Lifetime { lifetime, bounds, } diff --git a/src/libsyntax/fold.rs b/src/libsyntax/fold.rs index 2f43487e036ac..ea147186b187e 100644 --- a/src/libsyntax/fold.rs +++ b/src/libsyntax/fold.rs @@ -132,10 +132,10 @@ pub trait Folder : Sized { noop_fold_exprs(es, self) } - fn fold_generic_arg(&mut self, arg: GenericArgAST) -> GenericArgAST { + fn fold_generic_arg(&mut self, arg: GenericArg) -> GenericArg { match arg { - GenericArgAST::Lifetime(lt) => GenericArgAST::Lifetime(self.fold_lifetime(lt)), - GenericArgAST::Type(ty) => GenericArgAST::Type(self.fold_ty(ty)), + GenericArg::Lifetime(lt) => GenericArg::Lifetime(self.fold_lifetime(lt)), + GenericArg::Type(ty) => GenericArg::Type(self.fold_ty(ty)), } } @@ -244,11 +244,11 @@ pub trait Folder : Sized { noop_fold_ty_param(tp, self) } - fn fold_generic_param(&mut self, param: GenericParamAST) -> GenericParamAST { + fn fold_generic_param(&mut self, param: GenericParam) -> GenericParam { noop_fold_generic_param(param, self) } - fn fold_generic_params(&mut self, params: Vec) -> Vec { + fn fold_generic_params(&mut self, params: Vec) -> Vec { noop_fold_generic_params(params, self) } @@ -687,11 +687,11 @@ pub fn noop_fold_ty_param_bound(tpb: TyParamBound, fld: &mut T) } } -pub fn noop_fold_generic_param(param: GenericParamAST, fld: &mut T) -> GenericParamAST { - match param { - GenericParamAST::Lifetime { bounds, lifetime } => { +pub fn noop_fold_generic_param(param: GenericParam, fld: &mut T) -> GenericParam { + match param.kind { + GenericParamKind::Lifetime { bounds, lifetime } => { let attrs: Vec<_> = param.attrs.into(); - GenericParamAST::Lifetime(LifetimeDef { + GenericParamKind::Lifetime(LifetimeDef { attrs: attrs.into_iter() .flat_map(|x| fld.fold_attribute(x).into_iter()) .collect::>() @@ -703,14 +703,14 @@ pub fn noop_fold_generic_param(param: GenericParamAST, fld: &mut T) - bounds: bounds.move_map(|l| noop_fold_lifetime(l, fld)), }) } - GenericParamAST::Type { .. } => GenericParamAST::Type(fld.fold_ty_param(param)), + GenericParamKind::Type { .. } => GenericParamKind::Type(fld.fold_ty_param(param)), } } pub fn noop_fold_generic_params( - params: Vec, + params: Vec, fld: &mut T -) -> Vec { +) -> Vec { params.move_map(|p| fld.fold_generic_param(p)) } diff --git a/src/libsyntax/parse/parser.rs b/src/libsyntax/parse/parser.rs index 2a1fc6b291c31..203b529222d15 100644 --- a/src/libsyntax/parse/parser.rs +++ b/src/libsyntax/parse/parser.rs @@ -21,8 +21,8 @@ use ast::EnumDef; use ast::{Expr, ExprKind, RangeLimits}; use ast::{Field, FnDecl}; use ast::{ForeignItem, ForeignItemKind, FunctionRetTy}; -use ast::{GenericParamAST, GenericParamKindAST}; -use ast::GenericArgAST; +use ast::{GenericParam, GenericParamKind}; +use ast::GenericArg; use ast::{Ident, ImplItem, IsAuto, Item, ItemKind}; use ast::{Label, Lifetime, Lit, LitKind}; use ast::Local; @@ -1246,7 +1246,7 @@ impl<'a> Parser<'a> { } /// parse a TyKind::BareFn type: - fn parse_ty_bare_fn(&mut self, generic_params: Vec) -> PResult<'a, TyKind> { + fn parse_ty_bare_fn(&mut self, generic_params: Vec) -> PResult<'a, TyKind> { /* [unsafe] [extern "ABI"] fn (S) -> T @@ -1563,7 +1563,7 @@ impl<'a> Parser<'a> { Ok(P(ty)) } - fn parse_remaining_bounds(&mut self, generic_params: Vec, path: ast::Path, + fn parse_remaining_bounds(&mut self, generic_params: Vec, path: ast::Path, lo: Span, parse_plus: bool) -> PResult<'a, TyKind> { let poly_trait_ref = PolyTraitRef::new(generic_params, path, lo.to(self.prev_span)); let mut bounds = vec![TraitTyParamBound(poly_trait_ref, TraitBoundModifier::None)]; @@ -4805,7 +4805,7 @@ impl<'a> Parser<'a> { /// Matches typaram = IDENT (`?` unbound)? optbounds ( EQ ty )? fn parse_ty_param(&mut self, preceding_attrs: Vec) - -> PResult<'a, GenericParamAST> { + -> PResult<'a, GenericParam> { let ident = self.parse_ident()?; // Parse optional colon and param bounds. @@ -4821,11 +4821,11 @@ impl<'a> Parser<'a> { None }; - Ok(GenericParamAST { + Ok(GenericParam { ident, attrs: preceding_attrs.into(), id: ast::DUMMY_NODE_ID, - kind: GenericParamKindAST::Type { + kind: GenericParamKind::Type { bounds, default, } @@ -4859,7 +4859,7 @@ impl<'a> Parser<'a> { /// Parses (possibly empty) list of lifetime and type parameters, possibly including /// trailing comma and erroneous trailing attributes. - crate fn parse_generic_params(&mut self) -> PResult<'a, Vec> { + crate fn parse_generic_params(&mut self) -> PResult<'a, Vec> { let mut params = Vec::new(); let mut seen_ty_param = false; loop { @@ -4872,11 +4872,11 @@ impl<'a> Parser<'a> { } else { Vec::new() }; - params.push(ast::GenericParamAST { + params.push(ast::GenericParam { ident: lifetime.ident, id: lifetime.id, attrs: attrs.into(), - kind: ast::GenericParamKindAST::Lifetime { + kind: ast::GenericParamKind::Lifetime { lifetime, bounds, } @@ -4937,7 +4937,7 @@ impl<'a> Parser<'a> { /// Parses (possibly empty) list of lifetime and type arguments and associated type bindings, /// possibly including trailing comma. fn parse_generic_args(&mut self) - -> PResult<'a, (Vec, Vec)> { + -> PResult<'a, (Vec, Vec)> { let mut args = Vec::new(); let mut bindings = Vec::new(); let mut seen_type = false; @@ -4945,7 +4945,7 @@ impl<'a> Parser<'a> { loop { if self.check_lifetime() && self.look_ahead(1, |t| !t.is_like_plus()) { // Parse lifetime argument. - args.push(GenericArgAST::Lifetime(self.expect_lifetime())); + args.push(GenericArg::Lifetime(self.expect_lifetime())); if seen_type || seen_binding { self.span_err(self.prev_span, "lifetime parameters must be declared prior to type parameters"); @@ -4970,7 +4970,7 @@ impl<'a> Parser<'a> { self.span_err(ty_param.span, "type parameters must be declared prior to associated type bindings"); } - args.push(GenericArgAST::Type(ty_param)); + args.push(GenericArg::Type(ty_param)); seen_type = true; } else { break @@ -5692,7 +5692,7 @@ impl<'a> Parser<'a> { Ok((keywords::Invalid.ident(), item_kind, Some(attrs))) } - fn parse_late_bound_lifetime_defs(&mut self) -> PResult<'a, Vec> { + fn parse_late_bound_lifetime_defs(&mut self) -> PResult<'a, Vec> { if self.eat_keyword(keywords::For) { self.expect_lt()?; let params = self.parse_generic_params()?; diff --git a/src/libsyntax/print/pprust.rs b/src/libsyntax/print/pprust.rs index 458947299c816..84a4a51b71600 100644 --- a/src/libsyntax/print/pprust.rs +++ b/src/libsyntax/print/pprust.rs @@ -13,7 +13,7 @@ pub use self::AnnNode::*; use rustc_target::spec::abi::{self, Abi}; use ast::{self, BlockCheckMode, PatKind, RangeEnd, RangeSyntax}; use ast::{SelfKind, RegionTyParamBound, TraitTyParamBound, TraitBoundModifier}; -use ast::{Attribute, MacDelimiter, GenericArgAST}; +use ast::{Attribute, MacDelimiter, GenericArg}; use util::parser::{self, AssocOp, Fixity}; use attr; use codemap::{self, CodeMap}; @@ -344,7 +344,7 @@ pub fn trait_item_to_string(i: &ast::TraitItem) -> String { to_string(|s| s.print_trait_item(i)) } -pub fn generic_params_to_string(generic_params: &[ast::GenericParamAST]) -> String { +pub fn generic_params_to_string(generic_params: &[ast::GenericParam]) -> String { to_string(|s| s.print_generic_params(generic_params)) } @@ -1017,10 +1017,10 @@ impl<'a> State<'a> { Ok(()) } - pub fn print_generic_arg(&mut self, generic_arg: &GenericArgAST) -> io::Result<()> { + pub fn print_generic_arg(&mut self, generic_arg: &GenericArg) -> io::Result<()> { match generic_arg { - GenericArgAST::Lifetime(lt) => self.print_lifetime(lt), - GenericArgAST::Type(ty) => self.print_type(ty), + GenericArg::Lifetime(lt) => self.print_lifetime(lt), + GenericArg::Type(ty) => self.print_type(ty), } } @@ -1443,7 +1443,7 @@ impl<'a> State<'a> { fn print_formal_generic_params( &mut self, - generic_params: &[ast::GenericParamAST] + generic_params: &[ast::GenericParam] ) -> io::Result<()> { if !generic_params.is_empty() { self.s.word("for")?; @@ -2869,7 +2869,7 @@ impl<'a> State<'a> { pub fn print_generic_params( &mut self, - generic_params: &[ast::GenericParamAST] + generic_params: &[ast::GenericParam] ) -> io::Result<()> { if generic_params.is_empty() { return Ok(()); @@ -2879,11 +2879,11 @@ impl<'a> State<'a> { self.commasep(Inconsistent, &generic_params, |s, param| { match param.kind { - ast::GenericParamKindAST::Lifetime { ref bounds, ref lifetime } => { + ast::GenericParamKind::Lifetime { ref bounds, ref lifetime } => { s.print_outer_attributes_inline(¶m.attrs)?; s.print_lifetime_bounds(lifetime, bounds) }, - ast::GenericParamKindAST::Type { ref bounds, ref default } => { + ast::GenericParamKind::Type { ref bounds, ref default } => { s.print_outer_attributes_inline(¶m.attrs)?; s.print_ident(param.ident)?; s.print_bounds(":", bounds)?; @@ -3045,7 +3045,7 @@ impl<'a> State<'a> { unsafety: ast::Unsafety, decl: &ast::FnDecl, name: Option, - generic_params: &Vec) + generic_params: &Vec) -> io::Result<()> { self.ibox(INDENT_UNIT)?; if !generic_params.is_empty() { diff --git a/src/libsyntax/util/node_count.rs b/src/libsyntax/util/node_count.rs index caddd0513d136..95ae9f9bcf802 100644 --- a/src/libsyntax/util/node_count.rs +++ b/src/libsyntax/util/node_count.rs @@ -71,7 +71,7 @@ impl<'ast> Visitor<'ast> for NodeCounter { self.count += 1; walk_ty(self, t) } - fn visit_generic_param(&mut self, param: &GenericParamAST) { + fn visit_generic_param(&mut self, param: &GenericParam) { self.count += 1; walk_generic_param(self, param) } diff --git a/src/libsyntax/visit.rs b/src/libsyntax/visit.rs index c919f6c355c09..3a81796bae4a3 100644 --- a/src/libsyntax/visit.rs +++ b/src/libsyntax/visit.rs @@ -73,7 +73,7 @@ pub trait Visitor<'ast>: Sized { fn visit_expr(&mut self, ex: &'ast Expr) { walk_expr(self, ex) } fn visit_expr_post(&mut self, _ex: &'ast Expr) { } fn visit_ty(&mut self, t: &'ast Ty) { walk_ty(self, t) } - fn visit_generic_param(&mut self, param: &'ast GenericParamAST) { + fn visit_generic_param(&mut self, param: &'ast GenericParam) { walk_generic_param(self, param) } fn visit_generics(&mut self, g: &'ast Generics) { walk_generics(self, g) } @@ -133,10 +133,10 @@ pub trait Visitor<'ast>: Sized { fn visit_generic_args(&mut self, path_span: Span, generic_args: &'ast GenericArgs) { walk_generic_args(self, path_span, generic_args) } - fn visit_generic_arg(&mut self, generic_arg: &'ast GenericArgAST) { + fn visit_generic_arg(&mut self, generic_arg: &'ast GenericArg) { match generic_arg { - GenericArgAST::Lifetime(lt) => self.visit_lifetime(lt), - GenericArgAST::Type(ty) => self.visit_ty(ty), + GenericArg::Lifetime(lt) => self.visit_lifetime(lt), + GenericArg::Type(ty) => self.visit_ty(ty), } } fn visit_assoc_type_binding(&mut self, type_binding: &'ast TypeBinding) { @@ -490,14 +490,14 @@ pub fn walk_ty_param_bound<'a, V: Visitor<'a>>(visitor: &mut V, bound: &'a TyPar } } -pub fn walk_generic_param<'a, V: Visitor<'a>>(visitor: &mut V, param: &'a GenericParamAST) { +pub fn walk_generic_param<'a, V: Visitor<'a>>(visitor: &mut V, param: &'a GenericParam) { match param.kind { - GenericParamKindAST::Lifetime { ref bounds, ref lifetime, .. } => { + GenericParamKind::Lifetime { ref bounds, ref lifetime, .. } => { visitor.visit_ident(param.ident); walk_list!(visitor, visit_lifetime, bounds); walk_list!(visitor, visit_attribute, param.attrs.iter()); } - GenericParamKindAST::Type { ref bounds, ref default, .. } => { + GenericParamKind::Type { ref bounds, ref default, .. } => { visitor.visit_ident(t.ident); walk_list!(visitor, visit_ty_param_bound, bounds); walk_list!(visitor, visit_ty, default); diff --git a/src/libsyntax_ext/deriving/clone.rs b/src/libsyntax_ext/deriving/clone.rs index 5f943a4cd00d5..9aeac5b1ddb2a 100644 --- a/src/libsyntax_ext/deriving/clone.rs +++ b/src/libsyntax_ext/deriving/clone.rs @@ -13,7 +13,7 @@ use deriving::generic::*; use deriving::generic::ty::*; use syntax::ast::{self, Expr, Generics, ItemKind, MetaItem, VariantData}; -use syntax::ast::GenericArgAST; +use syntax::ast::GenericArg; use syntax::attr; use syntax::ext::base::{Annotatable, ExtCtxt}; use syntax::ext::build::AstBuilder; @@ -50,7 +50,7 @@ pub fn expand_deriving_clone(cx: &mut ExtCtxt, ItemKind::Enum(_, Generics { ref params, .. }) => { if attr::contains_name(&annitem.attrs, "rustc_copy_clone_marker") && !params.iter().any(|param| match param.kind { - ast::GenericParamKindAST::Type { .. } => true, + ast::GenericParamKind::Type { .. } => true, _ => false, }) { @@ -127,7 +127,7 @@ fn cs_clone_shallow(name: &str, let span = span.with_ctxt(cx.backtrace()); let assert_path = cx.path_all(span, true, cx.std_path(&["clone", helper_name]), - vec![GenericArgAST::Type(ty)], vec![]); + vec![GenericArg::Type(ty)], vec![]); stmts.push(cx.stmt_let_type_only(span, cx.ty_path(assert_path))); } fn process_variant(cx: &mut ExtCtxt, stmts: &mut Vec, variant: &VariantData) { diff --git a/src/libsyntax_ext/deriving/cmp/eq.rs b/src/libsyntax_ext/deriving/cmp/eq.rs index e9bcf70e90c8e..00ab39032acbd 100644 --- a/src/libsyntax_ext/deriving/cmp/eq.rs +++ b/src/libsyntax_ext/deriving/cmp/eq.rs @@ -12,7 +12,7 @@ use deriving::path_std; use deriving::generic::*; use deriving::generic::ty::*; -use syntax::ast::{self, Expr, MetaItem, GenericArgAST}; +use syntax::ast::{self, Expr, MetaItem, GenericArg}; use syntax::ext::base::{Annotatable, ExtCtxt}; use syntax::ext::build::AstBuilder; use syntax::ptr::P; @@ -62,7 +62,7 @@ fn cs_total_eq_assert(cx: &mut ExtCtxt, trait_span: Span, substr: &Substructure) let span = span.with_ctxt(cx.backtrace()); let assert_path = cx.path_all(span, true, cx.std_path(&["cmp", helper_name]), - vec![GenericArgAST::Type(ty)], vec![]); + vec![GenericArg::Type(ty)], vec![]); stmts.push(cx.stmt_let_type_only(span, cx.ty_path(assert_path))); } fn process_variant(cx: &mut ExtCtxt, stmts: &mut Vec, variant: &ast::VariantData) { diff --git a/src/libsyntax_ext/deriving/generic/mod.rs b/src/libsyntax_ext/deriving/generic/mod.rs index fc244f67bb653..6c9aea51c7ca6 100644 --- a/src/libsyntax_ext/deriving/generic/mod.rs +++ b/src/libsyntax_ext/deriving/generic/mod.rs @@ -193,7 +193,7 @@ use std::vec; use rustc_target::spec::abi::Abi; use syntax::ast::{self, BinOpKind, EnumDef, Expr, Generics, Ident, PatKind}; -use syntax::ast::{VariantData, GenericParamKindAST, GenericArgAST}; +use syntax::ast::{VariantData, GenericParamKind, GenericArg}; use syntax::attr; use syntax::ext::base::{Annotatable, ExtCtxt}; use syntax::ext::build::AstBuilder; @@ -423,7 +423,7 @@ impl<'a> TraitDef<'a> { ast::ItemKind::Enum(_, ref generics) | ast::ItemKind::Union(_, ref generics) => { !generics.params.iter().any(|param| match param.kind { - ast::GenericParamKindAST::Type { .. } => true, + ast::GenericParamKind::Type { .. } => true, _ => false, }) } @@ -550,8 +550,8 @@ impl<'a> TraitDef<'a> { // Create the generic parameters params.extend(generics.params.iter().map(|param| match param.kind { - GenericParamKindAST::Lifetime { .. } => param.clone(), - GenericParamKindAST::Type { bounds: ref ty_bounds, .. } => { + GenericParamKind::Lifetime { .. } => param.clone(), + GenericParamKind::Type { bounds: ref ty_bounds, .. } => { // I don't think this can be moved out of the loop, since // a TyParamBound requires an ast id let mut bounds: Vec<_> = @@ -608,7 +608,7 @@ impl<'a> TraitDef<'a> { let mut ty_params = params.iter() .filter_map(|param| match param.kind { - ast::GenericParamKindAST::Type { .. } => Some(param), + ast::GenericParamKind::Type { .. } => Some(param), _ => None, }) .peekable(); @@ -669,7 +669,7 @@ impl<'a> TraitDef<'a> { let self_ty_params: Vec> = generics.params .iter() .filter_map(|param| match param.kind { - GenericParamKindAST::Type { .. } => Some(cx.ty_ident(self.span, param.ident)), + GenericParamKind::Type { .. } => Some(cx.ty_ident(self.span, param.ident)), _ => None, }) .collect(); @@ -677,15 +677,15 @@ impl<'a> TraitDef<'a> { let self_lifetimes: Vec = generics.params .iter() .filter_map(|param| match param.kind { - GenericParamKindAST::Lifetime { ref lifetime, .. } => Some(*lifetime), + GenericParamKind::Lifetime { ref lifetime, .. } => Some(*lifetime), _ => None, }) .collect(); let self_params = self_lifetimes.into_iter() - .map(|lt| GenericArgAST::Lifetime(lt)) + .map(|lt| GenericArg::Lifetime(lt)) .chain(self_ty_params.into_iter().map(|ty| - GenericArgAST::Type(ty))) + GenericArg::Type(ty))) .collect(); // Create the type of `self`. diff --git a/src/libsyntax_ext/deriving/generic/ty.rs b/src/libsyntax_ext/deriving/generic/ty.rs index c9f274ed21090..78f6a9b913711 100644 --- a/src/libsyntax_ext/deriving/generic/ty.rs +++ b/src/libsyntax_ext/deriving/generic/ty.rs @@ -15,7 +15,7 @@ pub use self::PtrTy::*; pub use self::Ty::*; use syntax::ast; -use syntax::ast::{Expr, GenericParamKindAST, Generics, Ident, SelfKind, GenericArgAST}; +use syntax::ast::{Expr, GenericParamKind, Generics, Ident, SelfKind, GenericArg}; use syntax::ext::base::ExtCtxt; use syntax::ext::build::AstBuilder; use syntax::codemap::{respan, DUMMY_SP}; @@ -89,8 +89,8 @@ impl<'a> Path<'a> { let tys: Vec> = self.params.iter().map(|t| t.to_ty(cx, span, self_ty, self_generics)).collect(); let params = lt.into_iter() - .map(|lt| GenericArgAST::Lifetime(lt)) - .chain(tys.into_iter().map(|ty| GenericArgAST::Type(ty))) + .map(|lt| GenericArg::Lifetime(lt)) + .chain(tys.into_iter().map(|ty| GenericArg::Type(ty))) .collect(); match self.kind { @@ -192,7 +192,7 @@ impl<'a> Ty<'a> { let ty_params: Vec> = self_generics.params .iter() .filter_map(|param| match param.kind { - GenericParamKindAST::Type { .. } => { + GenericParamKind::Type { .. } => { Some(cx.ty_ident(span, param.ident)) } _ => None, @@ -202,15 +202,15 @@ impl<'a> Ty<'a> { let lifetimes: Vec = self_generics.params .iter() .filter_map(|param| match param.kind { - GenericParamKindAST::Lifetime { ref lifetime, .. } => Some(*lifetime), + GenericParamKind::Lifetime { ref lifetime, .. } => Some(*lifetime), _ => None, }) .collect(); let params = lifetimes.into_iter() - .map(|lt| GenericArgAST::Lifetime(lt)) + .map(|lt| GenericArg::Lifetime(lt)) .chain(ty_params.into_iter().map(|ty| - GenericArgAST::Type(ty))) + GenericArg::Type(ty))) .collect(); cx.path_all(span, @@ -234,7 +234,7 @@ fn mk_ty_param(cx: &ExtCtxt, bounds: &[Path], self_ident: Ident, self_generics: &Generics) - -> ast::GenericParamAST { + -> ast::GenericParam { let bounds = bounds.iter() .map(|b| { let path = b.to_path(cx, span, self_ident, self_generics); @@ -244,7 +244,7 @@ fn mk_ty_param(cx: &ExtCtxt, cx.typaram(span, cx.ident_of(name), attrs.to_owned(), bounds, None) } -fn mk_generics(params: Vec, span: Span) -> Generics { +fn mk_generics(params: Vec, span: Span) -> Generics { Generics { params, where_clause: ast::WhereClause { diff --git a/src/libsyntax_ext/deriving/mod.rs b/src/libsyntax_ext/deriving/mod.rs index 6813ce4c265f9..6ff385b18e8bf 100644 --- a/src/libsyntax_ext/deriving/mod.rs +++ b/src/libsyntax_ext/deriving/mod.rs @@ -136,7 +136,7 @@ fn hygienic_type_parameter(item: &Annotatable, base: &str) -> String { ast::ItemKind::Enum(_, ast::Generics { ref params, .. }) => { for param in params { match param.kind { - ast::GenericParamKindAST::Type { .. } => { + ast::GenericParamKind::Type { .. } => { typaram.push_str(¶m.ident.as_str()); } _ => {} diff --git a/src/libsyntax_ext/env.rs b/src/libsyntax_ext/env.rs index a3254788d4529..5c3080260ccd5 100644 --- a/src/libsyntax_ext/env.rs +++ b/src/libsyntax_ext/env.rs @@ -13,7 +13,7 @@ // interface. // -use syntax::ast::{self, Ident, GenericArgAST}; +use syntax::ast::{self, Ident, GenericArg}; use syntax::ext::base::*; use syntax::ext::base; use syntax::ext::build::AstBuilder; @@ -39,7 +39,7 @@ pub fn expand_option_env<'cx>(cx: &'cx mut ExtCtxt, cx.expr_path(cx.path_all(sp, true, cx.std_path(&["option", "Option", "None"]), - vec![GenericArgAST::Type(cx.ty_rptr(sp, + vec![GenericArg::Type(cx.ty_rptr(sp, cx.ty_ident(sp, Ident::from_str("str")), Some(lt), ast::Mutability::Immutable))], From 8bccfe7a526bb03fd656a194a03f6850e16bc4c6 Mon Sep 17 00:00:00 2001 From: varkor Date: Sun, 27 May 2018 20:37:52 +0100 Subject: [PATCH 18/41] Refactor counting methods --- src/librustc/hir/intravisit.rs | 4 ++-- src/librustc/hir/lowering.rs | 8 ++++---- src/librustc/hir/mod.rs | 2 +- src/librustc/ich/impls_hir.rs | 4 ++-- src/librustc/middle/resolve_lifetime.rs | 17 +++++++---------- src/librustc_typeck/astconv.rs | 14 ++++++-------- src/librustc_typeck/check/method/confirm.rs | 12 +++++------- src/libsyntax/visit.rs | 4 ++-- 8 files changed, 29 insertions(+), 36 deletions(-) diff --git a/src/librustc/hir/intravisit.rs b/src/librustc/hir/intravisit.rs index 51ce134544d08..0bbd258080714 100644 --- a/src/librustc/hir/intravisit.rs +++ b/src/librustc/hir/intravisit.rs @@ -745,8 +745,8 @@ pub fn walk_ty_param_bound<'v, V: Visitor<'v>>(visitor: &mut V, bound: &'v TyPar pub fn walk_generic_param<'v, V: Visitor<'v>>(visitor: &mut V, param: &'v GenericParam) { visitor.visit_id(param.id); match param.kind { - GenericParamKind::Lifetime { ref bounds, ref lifetime_deprecated, .. } => { - match lifetime_deprecated.name { + GenericParamKind::Lifetime { ref bounds, ref lifetime, .. } => { + match lifetime.name { LifetimeName::Name(name) => { visitor.visit_name(param.span, name); } diff --git a/src/librustc/hir/lowering.rs b/src/librustc/hir/lowering.rs index 71b0b66b59a29..d8e03bea89df4 100644 --- a/src/librustc/hir/lowering.rs +++ b/src/librustc/hir/lowering.rs @@ -705,7 +705,7 @@ impl<'a> LoweringContext<'a> { name: hir_name, bounds: vec![].into(), in_band: true, - lifetime_deprecated: hir::Lifetime { + lifetime: hir::Lifetime { id: def_node_id, span, name: hir_name, @@ -1424,7 +1424,7 @@ impl<'a> LoweringContext<'a> { name, bounds: vec![].into(), in_band: false, - lifetime_deprecated: hir::Lifetime { + lifetime: hir::Lifetime { id: def_node_id, span: lifetime.span, name, @@ -1947,7 +1947,7 @@ impl<'a> LoweringContext<'a> { itctx: ImplTraitContext) -> hir::GenericParam { match param.kind { - GenericParamKind::Lifetime { ref bounds, ref lifetime, .. } => { + GenericParamKind::Lifetime { ref bounds, ref lifetime } => { let was_collecting_in_band = self.is_collecting_in_band_lifetimes; self.is_collecting_in_band_lifetimes = false; @@ -1960,7 +1960,7 @@ impl<'a> LoweringContext<'a> { name: lifetime.name, bounds: bounds.iter().map(|lt| self.lower_lifetime(lt)).collect(), in_band: false, - lifetime_deprecated: lifetime, + lifetime, } }; diff --git a/src/librustc/hir/mod.rs b/src/librustc/hir/mod.rs index bb830a042e391..9c2aa3c7e4972 100644 --- a/src/librustc/hir/mod.rs +++ b/src/librustc/hir/mod.rs @@ -462,7 +462,7 @@ pub enum GenericParamKind { // `fn foo(x: &'a u8) -> &'a u8 { x }` in_band: bool, // We keep a `Lifetime` around for now just so we can `visit_lifetime`. - lifetime_deprecated: Lifetime, + lifetime: Lifetime, }, Type { name: Name, diff --git a/src/librustc/ich/impls_hir.rs b/src/librustc/ich/impls_hir.rs index ea12db8681c71..fc0eee230cd0d 100644 --- a/src/librustc/ich/impls_hir.rs +++ b/src/librustc/ich/impls_hir.rs @@ -208,11 +208,11 @@ impl<'a> HashStable> for hir::GenericParamKind { mem::discriminant(self).hash_stable(hcx, hasher); match self { hir::GenericParamKind::Lifetime { name, ref bounds, in_band, - ref lifetime_deprecated } => { + ref lifetime } => { name.hash_stable(hcx, hasher); bounds.hash_stable(hcx, hasher); in_band.hash_stable(hcx, hasher); - lifetime_deprecated.hash_stable(hcx, hasher); + lifetime.hash_stable(hcx, hasher); } hir::GenericParamKind::Type { name, ref bounds, ref default, synthetic, attrs } => { name.hash_stable(hcx, hasher); diff --git a/src/librustc/middle/resolve_lifetime.rs b/src/librustc/middle/resolve_lifetime.rs index 67a5448babf83..561e6094c86a4 100644 --- a/src/librustc/middle/resolve_lifetime.rs +++ b/src/librustc/middle/resolve_lifetime.rs @@ -1220,20 +1220,17 @@ fn compute_object_lifetime_defaults( .map(|set| match *set { Set1::Empty => "BaseDefault".to_string(), Set1::One(Region::Static) => "'static".to_string(), - Set1::One(Region::EarlyBound(i, _, _)) => { - let mut j = 0; - generics.params.iter().find(|param| match param.kind { + Set1::One(Region::EarlyBound(mut i, _, _)) => { + generics.params.iter().find_map(|param| match param.kind { GenericParamKind::Lifetime { .. } => { - if i == j { - return true; + if i == 0 { + return Some(param.name().to_string()); } - j += 1; - false + i -= 1; + None } - _ => false, + _ => None, }).unwrap() - .name() - .to_string() } Set1::One(_) => bug!(), Set1::Many => "Ambiguous".to_string(), diff --git a/src/librustc_typeck/astconv.rs b/src/librustc_typeck/astconv.rs index 32c0dbbea6935..9d38865a91bc8 100644 --- a/src/librustc_typeck/astconv.rs +++ b/src/librustc_typeck/astconv.rs @@ -274,15 +274,14 @@ impl<'o, 'gcx: 'tcx, 'tcx> AstConv<'gcx, 'tcx>+'o { let substs = Substs::for_item(tcx, def_id, |param, substs| { match param.kind { GenericParamDefKind::Lifetime => { - let i = param.index as usize - own_self; - let mut j = 0; + let mut i = param.index as usize - own_self; for arg in &generic_args.args { match arg { GenericArg::Lifetime(lt) => { - if i == j { + if i == 0 { return self.ast_region_to_region(lt, Some(param)).into(); } - j += 1; + i -= 1; } _ => {} } @@ -297,17 +296,16 @@ impl<'o, 'gcx: 'tcx, 'tcx> AstConv<'gcx, 'tcx>+'o { return ty.into(); } - let i = i - (lt_accepted + own_self); + let mut i = i - (lt_accepted + own_self); if i < ty_provided { // A provided type parameter. - let mut j = 0; for arg in &generic_args.args { match arg { GenericArg::Type(ty) => { - if i == j { + if i == 0 { return self.ast_ty_to_ty(ty).into(); } - j += 1; + i -= 1; } _ => {} } diff --git a/src/librustc_typeck/check/method/confirm.rs b/src/librustc_typeck/check/method/confirm.rs index 4cf05a4891b39..f6b2ded176c47 100644 --- a/src/librustc_typeck/check/method/confirm.rs +++ b/src/librustc_typeck/check/method/confirm.rs @@ -325,21 +325,20 @@ impl<'a, 'gcx, 'tcx> ConfirmContext<'a, 'gcx, 'tcx> { let provided = &segment.args; let own_counts = method_generics.own_counts(); Substs::for_item(self.tcx, pick.item.def_id, |param, _| { - let i = param.index as usize; + let mut i = param.index as usize; if i < parent_substs.len() { parent_substs[i] } else { match param.kind { GenericParamDefKind::Lifetime => { if let Some(lifetime) = provided.as_ref().and_then(|data| { - let mut j = 0; for arg in &data.args { match arg { GenericArg::Lifetime(lt) => { - if i - parent_substs.len() == j { + if i == parent_substs.len() { return Some(lt); } - j += 1; + i -= 1; } _ => {} } @@ -352,14 +351,13 @@ impl<'a, 'gcx, 'tcx> ConfirmContext<'a, 'gcx, 'tcx> { } GenericParamDefKind::Type {..} => { if let Some(ast_ty) = provided.as_ref().and_then(|data| { - let mut j = 0; for arg in &data.args { match arg { GenericArg::Type(ty) => { - if i - parent_substs.len() - own_counts.lifetimes == j { + if i == parent_substs.len() + own_counts.lifetimes { return Some(ty); } - j += 1; + i -= 1; } _ => {} } diff --git a/src/libsyntax/visit.rs b/src/libsyntax/visit.rs index 3a81796bae4a3..b647dc7923efd 100644 --- a/src/libsyntax/visit.rs +++ b/src/libsyntax/visit.rs @@ -492,12 +492,12 @@ pub fn walk_ty_param_bound<'a, V: Visitor<'a>>(visitor: &mut V, bound: &'a TyPar pub fn walk_generic_param<'a, V: Visitor<'a>>(visitor: &mut V, param: &'a GenericParam) { match param.kind { - GenericParamKind::Lifetime { ref bounds, ref lifetime, .. } => { + GenericParamKind::Lifetime { ref bounds, ref lifetime } => { visitor.visit_ident(param.ident); walk_list!(visitor, visit_lifetime, bounds); walk_list!(visitor, visit_attribute, param.attrs.iter()); } - GenericParamKind::Type { ref bounds, ref default, .. } => { + GenericParamKind::Type { ref bounds, ref default } => { visitor.visit_ident(t.ident); walk_list!(visitor, visit_ty_param_bound, bounds); walk_list!(visitor, visit_ty, default); From a5328bc17b8d18083478554b3381d55183647f15 Mon Sep 17 00:00:00 2001 From: varkor Date: Sun, 27 May 2018 21:54:10 +0100 Subject: [PATCH 19/41] Simply joint lifetime/type iteration --- src/librustc/hir/mod.rs | 6 -- src/librustc_save_analysis/lib.rs | 5 +- src/librustc_typeck/astconv.rs | 13 ++- src/librustc_typeck/check/method/confirm.rs | 54 +++++-------- src/librustc_typeck/check/mod.rs | 89 +++++++++------------ src/librustc_typeck/check/wfcheck.rs | 15 ++-- src/librustc_typeck/coherence/unsafety.rs | 9 +-- src/librustc_typeck/collect.rs | 23 ++---- src/librustc_typeck/diagnostics.rs | 6 +- src/librustc_typeck/lib.rs | 13 +-- src/librustdoc/clean/mod.rs | 12 +-- src/libsyntax/visit.rs | 2 +- src/libsyntax_ext/deriving/generic/mod.rs | 37 +++------ src/libsyntax_ext/deriving/generic/ty.rs | 41 +++------- src/libsyntax_ext/env.rs | 2 +- src/test/compile-fail/issue-1900.rs | 2 +- src/test/ui/error-codes/E0131.stderr | 4 +- src/test/ui/issue-51022.rs | 2 +- src/test/ui/issue-51022.stderr | 4 +- 19 files changed, 122 insertions(+), 217 deletions(-) diff --git a/src/librustc/hir/mod.rs b/src/librustc/hir/mod.rs index 9c2aa3c7e4972..135403c9c2798 100644 --- a/src/librustc/hir/mod.rs +++ b/src/librustc/hir/mod.rs @@ -449,12 +449,6 @@ pub type TyParamBounds = HirVec; pub enum GenericParamKind { /// A lifetime definition, eg `'a: 'b + 'c + 'd`. Lifetime { - /// Either "'a", referring to a named lifetime definition, - /// or "" (aka keywords::Invalid), for elision placeholders. - /// - /// HIR lowering inserts these placeholders in type paths that - /// refer to type definitions needing lifetime parameters, - /// `&T` and `&mut T`, and trait objects without `... + 'a`. name: LifetimeName, bounds: HirVec, // Indicates that the lifetime definition was synthetically added diff --git a/src/librustc_save_analysis/lib.rs b/src/librustc_save_analysis/lib.rs index 528f6ba96fa82..453500d5ab7bd 100644 --- a/src/librustc_save_analysis/lib.rs +++ b/src/librustc_save_analysis/lib.rs @@ -934,10 +934,7 @@ fn make_signature(decl: &ast::FnDecl, generics: &ast::Generics) -> String { sig.push_str(&generics .params .iter() - .map(|param| match param.kind { - ast::GenericParamKind::Lifetime { .. } => param.ident.name.to_string(), - ast::GenericParamKind::Type { .. } => param.ident.to_string(), - }) + .map(|param| param.ident.to_string()) .collect::>() .join(", ")); sig.push_str("> "); diff --git a/src/librustc_typeck/astconv.rs b/src/librustc_typeck/astconv.rs index 9d38865a91bc8..7cd71518bed52 100644 --- a/src/librustc_typeck/astconv.rs +++ b/src/librustc_typeck/astconv.rs @@ -996,13 +996,12 @@ impl<'o, 'gcx: 'tcx, 'tcx> AstConv<'gcx, 'tcx>+'o { pub fn prohibit_type_params(&self, segments: &[hir::PathSegment]) { for segment in segments { segment.with_generic_args(|generic_args| { - let mut err_for_lifetime = false; - let mut err_for_type = false; + let (mut err_for_lt, mut err_for_ty) = (false, false); for arg in &generic_args.args { let (mut span_err, span, kind) = match arg { hir::GenericArg::Lifetime(lt) => { - if err_for_lifetime { continue } - err_for_lifetime = true; + if err_for_lt { continue } + err_for_lt = true; (struct_span_err!(self.tcx().sess, lt.span, E0110, "lifetime parameters are not allowed on \ this type"), @@ -1010,8 +1009,8 @@ impl<'o, 'gcx: 'tcx, 'tcx> AstConv<'gcx, 'tcx>+'o { "lifetime") } hir::GenericArg::Type(ty) => { - if err_for_type { continue } - err_for_type = true; + if err_for_ty { continue } + err_for_ty = true; (struct_span_err!(self.tcx().sess, ty.span, E0109, "type parameters are not allowed on this type"), ty.span, @@ -1020,7 +1019,7 @@ impl<'o, 'gcx: 'tcx, 'tcx> AstConv<'gcx, 'tcx>+'o { }; span_err.span_label(span, format!("{} parameter not allowed", kind)) .emit(); - if err_for_lifetime && err_for_type { + if err_for_lt && err_for_ty { break; } } diff --git a/src/librustc_typeck/check/method/confirm.rs b/src/librustc_typeck/check/method/confirm.rs index f6b2ded176c47..36ce01bcd08b3 100644 --- a/src/librustc_typeck/check/method/confirm.rs +++ b/src/librustc_typeck/check/method/confirm.rs @@ -329,46 +329,32 @@ impl<'a, 'gcx, 'tcx> ConfirmContext<'a, 'gcx, 'tcx> { if i < parent_substs.len() { parent_substs[i] } else { - match param.kind { - GenericParamDefKind::Lifetime => { - if let Some(lifetime) = provided.as_ref().and_then(|data| { - for arg in &data.args { - match arg { - GenericArg::Lifetime(lt) => { - if i == parent_substs.len() { - return Some(lt); - } - i -= 1; - } - _ => {} + let (is_lt, is_ty) = match param.kind { + GenericParamDefKind::Lifetime => (true, false), + GenericParamDefKind::Type { .. } => (false, true), + }; + provided.as_ref().and_then(|data| { + for arg in &data.args { + match arg { + GenericArg::Lifetime(lt) if is_lt => { + if i == parent_substs.len() { + return Some(AstConv::ast_region_to_region( + self.fcx, lt, Some(param)).into()); } + i -= 1; } - None - }) { - return AstConv::ast_region_to_region( - self.fcx, lifetime, Some(param)).into(); - } - } - GenericParamDefKind::Type {..} => { - if let Some(ast_ty) = provided.as_ref().and_then(|data| { - for arg in &data.args { - match arg { - GenericArg::Type(ty) => { - if i == parent_substs.len() + own_counts.lifetimes { - return Some(ty); - } - i -= 1; - } - _ => {} + GenericArg::Lifetime(_) => {} + GenericArg::Type(ty) if is_ty => { + if i == parent_substs.len() + own_counts.lifetimes { + return Some(self.to_ty(ty).into()); } + i -= 1; } - None - }) { - return self.to_ty(ast_ty).into(); + GenericArg::Type(_) => {} } } - } - self.var_for_def(self.span, param) + None + }).unwrap_or_else(|| self.var_for_def(self.span, param)) } }) } diff --git a/src/librustc_typeck/check/mod.rs b/src/librustc_typeck/check/mod.rs index 6ac9a0fdfc049..036c0aa442e56 100644 --- a/src/librustc_typeck/check/mod.rs +++ b/src/librustc_typeck/check/mod.rs @@ -4977,8 +4977,7 @@ impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> { s.args.as_ref().map_or( (vec![], vec![], s.infer_types, &[][..]), |data| { - let mut lifetimes = vec![]; - let mut types = vec![]; + let (mut lifetimes, mut types) = (vec![], vec![]); data.args.iter().for_each(|arg| match arg { GenericArg::Lifetime(lt) => lifetimes.push(lt), GenericArg::Type(ty) => types.push(ty), @@ -4987,14 +4986,6 @@ impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> { } ) }); - let infer_lifetimes = lifetimes.len() == 0; - - let count_lifetime_params = |n| { - format!("{} lifetime parameter{}", n, if n == 1 { "" } else { "s" }) - }; - let count_type_params = |n| { - format!("{} type parameter{}", n, if n == 1 { "" } else { "s" }) - }; // Check provided parameters. let ((ty_required, ty_accepted), lt_accepted) = @@ -5008,9 +4999,7 @@ impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> { let mut ty_params = ParamRange { required: 0, accepted: 0 }; for param in &generics.params { match param.kind { - GenericParamDefKind::Lifetime => { - lt_accepted += 1; - } + GenericParamDefKind::Lifetime => lt_accepted += 1, GenericParamDefKind::Type { has_default, .. } => { ty_params.accepted += 1; if !has_default { @@ -5027,36 +5016,37 @@ impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> { ((ty_params.required, ty_params.accepted), lt_accepted) }); - if types.len() > ty_accepted { - let span = types[ty_accepted].span; - let expected_text = count_type_params(ty_accepted); - let actual_text = count_type_params(types.len()); - struct_span_err!(self.tcx.sess, span, E0087, - "too many type parameters provided: \ - expected at most {}, found {}", - expected_text, actual_text) - .span_label(span, format!("expected {}", expected_text)) - .emit(); - + let count_type_params = |n| { + format!("{} type parameter{}", n, if n == 1 { "" } else { "s" }) + }; + let expected_text = count_type_params(ty_accepted); + let actual_text = count_type_params(types.len()); + if let Some((mut err, span)) = if types.len() > ty_accepted { // To prevent derived errors to accumulate due to extra // type parameters, we force instantiate_value_path to // use inference variables instead of the provided types. *segment = None; + let span = types[ty_accepted].span; + Some((struct_span_err!(self.tcx.sess, span, E0087, + "too many type parameters provided: \ + expected at most {}, found {}", + expected_text, actual_text), span)) } else if types.len() < ty_required && !infer_types && !supress_mismatch_error { - let expected_text = count_type_params(ty_required); - let actual_text = count_type_params(types.len()); - struct_span_err!(self.tcx.sess, span, E0089, - "too few type parameters provided: \ - expected {}, found {}", - expected_text, actual_text) - .span_label(span, format!("expected {}", expected_text)) - .emit(); + Some((struct_span_err!(self.tcx.sess, span, E0089, + "too few type parameters provided: \ + expected {}, found {}", + expected_text, actual_text), span)) + } else { + None + } { + err.span_label(span, format!("expected {}", expected_text)).emit(); } if !bindings.is_empty() { AstConv::prohibit_projection(self, bindings[0].span); } + let infer_lifetimes = lifetimes.len() == 0; // Prohibit explicit lifetime arguments if late bound lifetime parameters are present. let has_late_bound_lifetime_defs = segment.map_or(None, |(_, generics)| generics.has_late_bound_regions); @@ -5080,25 +5070,26 @@ impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> { return; } - if lifetimes.len() > lt_accepted { + let count_lifetime_params = |n| { + format!("{} lifetime parameter{}", n, if n == 1 { "" } else { "s" }) + }; + let expected_text = count_lifetime_params(lt_accepted); + let actual_text = count_lifetime_params(lifetimes.len()); + if let Some((mut err, span)) = if lifetimes.len() > lt_accepted { let span = lifetimes[lt_accepted].span; - let expected_text = count_lifetime_params(lt_accepted); - let actual_text = count_lifetime_params(lifetimes.len()); - struct_span_err!(self.tcx.sess, span, E0088, - "too many lifetime parameters provided: \ - expected at most {}, found {}", - expected_text, actual_text) - .span_label(span, format!("expected {}", expected_text)) - .emit(); + Some((struct_span_err!(self.tcx.sess, span, E0088, + "too many lifetime parameters provided: \ + expected at most {}, found {}", + expected_text, actual_text), span)) } else if lifetimes.len() < lt_accepted && !infer_lifetimes { - let expected_text = count_lifetime_params(lt_accepted); - let actual_text = count_lifetime_params(lifetimes.len()); - struct_span_err!(self.tcx.sess, span, E0090, - "too few lifetime parameters provided: \ - expected {}, found {}", - expected_text, actual_text) - .span_label(span, format!("expected {}", expected_text)) - .emit(); + Some((struct_span_err!(self.tcx.sess, span, E0090, + "too few lifetime parameters provided: \ + expected {}, found {}", + expected_text, actual_text), span)) + } else { + None + } { + err.span_label(span, format!("expected {}", expected_text)).emit(); } } diff --git a/src/librustc_typeck/check/wfcheck.rs b/src/librustc_typeck/check/wfcheck.rs index 05d390b8dae9e..f8f0126279087 100644 --- a/src/librustc_typeck/check/wfcheck.rs +++ b/src/librustc_typeck/check/wfcheck.rs @@ -660,15 +660,12 @@ fn report_bivariance<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, fn reject_shadowing_parameters(tcx: TyCtxt, def_id: DefId) { let generics = tcx.generics_of(def_id); let parent = tcx.generics_of(generics.parent.unwrap()); - let impl_params: FxHashMap<_, _> = - parent.params.iter() - .flat_map(|param| match param.kind { - GenericParamDefKind::Lifetime => None, - GenericParamDefKind::Type {..} => Some((param.name, param.def_id)), - }) - .collect(); - - for method_param in generics.params.iter() { + let impl_params: FxHashMap<_, _> = parent.params.iter().flat_map(|param| match param.kind { + GenericParamDefKind::Lifetime => None, + GenericParamDefKind::Type {..} => Some((param.name, param.def_id)), + }).collect(); + + for method_param in &generics.params { match method_param.kind { // Shadowing is checked in resolve_lifetime. GenericParamDefKind::Lifetime => continue, diff --git a/src/librustc_typeck/coherence/unsafety.rs b/src/librustc_typeck/coherence/unsafety.rs index 007ef4dee559c..5a442881a6315 100644 --- a/src/librustc_typeck/coherence/unsafety.rs +++ b/src/librustc_typeck/coherence/unsafety.rs @@ -35,13 +35,8 @@ impl<'cx, 'tcx, 'v> UnsafetyChecker<'cx, 'tcx> { Some(trait_ref) => { let trait_def = self.tcx.trait_def(trait_ref.def_id); - let unsafe_attr = impl_generics.and_then(|g| { - for param in &g.params { - if param.pure_wrt_drop { - return Some("may_dangle"); - } - } - None + let unsafe_attr = impl_generics.and_then(|generics| { + generics.params.iter().find(|p| p.pure_wrt_drop).map(|_| "may_dangle") }); match (trait_def.unsafety, unsafe_attr, unsafety, polarity) { (Unsafety::Normal, None, Unsafety::Unsafe, hir::ImplPolarity::Positive) => { diff --git a/src/librustc_typeck/collect.rs b/src/librustc_typeck/collect.rs index 0a6edd8d0ce70..2e4ceb5a65c99 100644 --- a/src/librustc_typeck/collect.rs +++ b/src/librustc_typeck/collect.rs @@ -117,12 +117,11 @@ impl<'a, 'tcx> Visitor<'tcx> for CollectItemTypesVisitor<'a, 'tcx> { for param in &generics.params { match param.kind { hir::GenericParamKind::Lifetime { .. } => {} - hir::GenericParamKind::Type { ref default, .. } => { - if default.is_some() { - let def_id = self.tcx.hir.local_def_id(param.id); - self.tcx.type_of(def_id); - } + hir::GenericParamKind::Type { ref default, .. } if default.is_some() => { + let def_id = self.tcx.hir.local_def_id(param.id); + self.tcx.type_of(def_id); } + hir::GenericParamKind::Type { .. } => {} } } intravisit::walk_generics(self, generics); @@ -316,11 +315,8 @@ impl<'a, 'tcx> ItemCtxt<'a, 'tcx> { let from_ty_params = ast_generics.params.iter() .filter_map(|param| match param.kind { - GenericParamKind::Type { ref bounds, .. } => { - if param.id == param_id { - return Some(bounds); - } - None + GenericParamKind::Type { ref bounds, .. } if param.id == param_id => { + Some(bounds) } _ => None }) @@ -1470,11 +1466,8 @@ pub fn explicit_predicates_of<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, .to_ty(tcx); index += 1; - let bounds = compute_bounds(&icx, - param_ty, - bounds, - SizedByDefault::Yes, - param.span); + let bounds = + compute_bounds(&icx, param_ty, bounds, SizedByDefault::Yes, param.span); predicates.extend(bounds.predicates(tcx, param_ty)); } _ => {} diff --git a/src/librustc_typeck/diagnostics.rs b/src/librustc_typeck/diagnostics.rs index da54eeabdb97b..3f7e3529e9648 100644 --- a/src/librustc_typeck/diagnostics.rs +++ b/src/librustc_typeck/diagnostics.rs @@ -1501,12 +1501,12 @@ struct Foo { "##, E0131: r##" -It is not possible to define `main` with type parameters, or even with function -parameters. When `main` is present, it must take no arguments and return `()`. +It is not possible to define `main` with generic parameters. +When `main` is present, it must take no arguments and return `()`. Erroneous code example: ```compile_fail,E0131 -fn main() { // error: main function is not allowed to have type parameters +fn main() { // error: main function is not allowed to have generic parameters } ``` "##, diff --git a/src/librustc_typeck/lib.rs b/src/librustc_typeck/lib.rs index fb005ba18e9f8..dcc5fa53d2f42 100644 --- a/src/librustc_typeck/lib.rs +++ b/src/librustc_typeck/lib.rs @@ -191,16 +191,9 @@ fn check_main_fn_ty<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, hir::ItemFn(.., ref generics, _) => { let mut error = false; if !generics.params.is_empty() { - let param_type = if generics.is_lt_parameterized() { - "lifetime" - } else { - "type" - }; - let msg = - format!("`main` function is not allowed to have {} parameters", - param_type); - let label = - format!("`main` cannot have {} parameters", param_type); + let msg = format!("`main` function is not allowed to have generic \ + parameters"); + let label = format!("`main` cannot have generic parameters"); struct_span_err!(tcx.sess, generics.span, E0131, "{}", msg) .span_label(generics.span, label) .emit(); diff --git a/src/librustdoc/clean/mod.rs b/src/librustdoc/clean/mod.rs index 3a4e582622f1c..89835ab6aaef0 100644 --- a/src/librustdoc/clean/mod.rs +++ b/src/librustdoc/clean/mod.rs @@ -3540,27 +3540,23 @@ impl Clean for hir::GenericArgs { output: if output != Type::Tuple(Vec::new()) { Some(output) } else { None } } } else { - let mut lifetimes = vec![]; - let mut types = vec![]; + let (mut lifetimes, mut types) = (vec![], vec![]); let mut elided_lifetimes = true; for arg in &self.args { match arg { - GenericArg::Lifetime(lt) if elided_lifetimes => { - if lt.is_elided() { + GenericArg::Lifetime(lt) => { + if !lt.is_elided() { elided_lifetimes = false; - lifetimes = vec![]; - continue; } lifetimes.push(lt.clean(cx)); } - GenericArg::Lifetime(_) => {} GenericArg::Type(ty) => { types.push(ty.clean(cx)); } } } GenericArgs::AngleBracketed { - lifetimes, + lifetimes: if elided_lifetimes { vec![] } else { lifetimes }, types, bindings: self.bindings.clean(cx), } diff --git a/src/libsyntax/visit.rs b/src/libsyntax/visit.rs index b647dc7923efd..e12369a522da7 100644 --- a/src/libsyntax/visit.rs +++ b/src/libsyntax/visit.rs @@ -136,7 +136,7 @@ pub trait Visitor<'ast>: Sized { fn visit_generic_arg(&mut self, generic_arg: &'ast GenericArg) { match generic_arg { GenericArg::Lifetime(lt) => self.visit_lifetime(lt), - GenericArg::Type(ty) => self.visit_ty(ty), + GenericArg::Type(ty) => self.visit_ty(ty), } } fn visit_assoc_type_binding(&mut self, type_binding: &'ast TypeBinding) { diff --git a/src/libsyntax_ext/deriving/generic/mod.rs b/src/libsyntax_ext/deriving/generic/mod.rs index 6c9aea51c7ca6..1024d445cdb96 100644 --- a/src/libsyntax_ext/deriving/generic/mod.rs +++ b/src/libsyntax_ext/deriving/generic/mod.rs @@ -665,35 +665,18 @@ impl<'a> TraitDef<'a> { // Create the reference to the trait. let trait_ref = cx.trait_ref(trait_path); - // Create the type parameters on the `self` path. - let self_ty_params: Vec> = generics.params - .iter() - .filter_map(|param| match param.kind { - GenericParamKind::Type { .. } => Some(cx.ty_ident(self.span, param.ident)), - _ => None, - }) - .collect(); - - let self_lifetimes: Vec = generics.params - .iter() - .filter_map(|param| match param.kind { - GenericParamKind::Lifetime { ref lifetime, .. } => Some(*lifetime), - _ => None, - }) - .collect(); - - let self_params = self_lifetimes.into_iter() - .map(|lt| GenericArg::Lifetime(lt)) - .chain(self_ty_params.into_iter().map(|ty| - GenericArg::Type(ty))) - .collect(); + let self_params: Vec<_> = generics.params.iter().map(|param| match param.kind { + GenericParamKind::Lifetime { ref lifetime, .. } => { + GenericArg::Lifetime(*lifetime) + } + GenericParamKind::Type { .. } => { + GenericArg::Type(cx.ty_ident(self.span, param.ident)) + } + }).collect(); // Create the type of `self`. - let self_type = cx.ty_path(cx.path_all(self.span, - false, - vec![type_ident], - self_params, - Vec::new())); + let path = cx.path_all(self.span, false, vec![type_ident], self_params, vec![]); + let self_type = cx.ty_path(path); let attr = cx.attribute(self.span, cx.meta_word(self.span, diff --git a/src/libsyntax_ext/deriving/generic/ty.rs b/src/libsyntax_ext/deriving/generic/ty.rs index 78f6a9b913711..127ed62b8c59d 100644 --- a/src/libsyntax_ext/deriving/generic/ty.rs +++ b/src/libsyntax_ext/deriving/generic/ty.rs @@ -185,41 +185,22 @@ impl<'a> Ty<'a> { cx: &ExtCtxt, span: Span, self_ty: Ident, - self_generics: &Generics) + generics: &Generics) -> ast::Path { match *self { Self_ => { - let ty_params: Vec> = self_generics.params - .iter() - .filter_map(|param| match param.kind { - GenericParamKind::Type { .. } => { - Some(cx.ty_ident(span, param.ident)) - } - _ => None, - }) - .collect(); - - let lifetimes: Vec = self_generics.params - .iter() - .filter_map(|param| match param.kind { - GenericParamKind::Lifetime { ref lifetime, .. } => Some(*lifetime), - _ => None, - }) - .collect(); - - let params = lifetimes.into_iter() - .map(|lt| GenericArg::Lifetime(lt)) - .chain(ty_params.into_iter().map(|ty| - GenericArg::Type(ty))) - .collect(); + let params: Vec<_> = generics.params.iter().map(|param| match param.kind { + GenericParamKind::Lifetime { ref lifetime, .. } => { + GenericArg::Lifetime(*lifetime) + } + GenericParamKind::Type { .. } => { + GenericArg::Type(cx.ty_ident(span, param.ident)) + } + }).collect(); - cx.path_all(span, - false, - vec![self_ty], - params, - Vec::new()) + cx.path_all(span, false, vec![self_ty], params, vec![]) } - Literal(ref p) => p.to_path(cx, span, self_ty, self_generics), + Literal(ref p) => p.to_path(cx, span, self_ty, generics), Ptr(..) => cx.span_bug(span, "pointer in a path in generic `derive`"), Tuple(..) => cx.span_bug(span, "tuple in a path in generic `derive`"), } diff --git a/src/libsyntax_ext/env.rs b/src/libsyntax_ext/env.rs index 5c3080260ccd5..bbc5b03d6885e 100644 --- a/src/libsyntax_ext/env.rs +++ b/src/libsyntax_ext/env.rs @@ -43,7 +43,7 @@ pub fn expand_option_env<'cx>(cx: &'cx mut ExtCtxt, cx.ty_ident(sp, Ident::from_str("str")), Some(lt), ast::Mutability::Immutable))], - Vec::new())) + vec![])) } Ok(s) => { cx.expr_call_global(sp, diff --git a/src/test/compile-fail/issue-1900.rs b/src/test/compile-fail/issue-1900.rs index c7564a9355bc5..ccdd9db25c40a 100644 --- a/src/test/compile-fail/issue-1900.rs +++ b/src/test/compile-fail/issue-1900.rs @@ -8,5 +8,5 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -// error-pattern: `main` function is not allowed to have type parameters +// error-pattern: `main` function is not allowed to have generic parameters fn main() { } diff --git a/src/test/ui/error-codes/E0131.stderr b/src/test/ui/error-codes/E0131.stderr index ba9355763f67a..46bc872746cc3 100644 --- a/src/test/ui/error-codes/E0131.stderr +++ b/src/test/ui/error-codes/E0131.stderr @@ -1,8 +1,8 @@ -error[E0131]: `main` function is not allowed to have type parameters +error[E0131]: `main` function is not allowed to have generic parameters --> $DIR/E0131.rs:11:8 | LL | fn main() { - | ^^^ `main` cannot have type parameters + | ^^^ `main` cannot have generic parameters error: aborting due to previous error diff --git a/src/test/ui/issue-51022.rs b/src/test/ui/issue-51022.rs index f9486fa57b136..831c3e5fda084 100644 --- a/src/test/ui/issue-51022.rs +++ b/src/test/ui/issue-51022.rs @@ -9,4 +9,4 @@ // except according to those terms. fn main<'a>() { } - //~^ ERROR `main` function is not allowed to have lifetime parameters [E0131] + //~^ ERROR `main` function is not allowed to have generic parameters [E0131] diff --git a/src/test/ui/issue-51022.stderr b/src/test/ui/issue-51022.stderr index 3b691bbb0330f..1daa8dfbba689 100644 --- a/src/test/ui/issue-51022.stderr +++ b/src/test/ui/issue-51022.stderr @@ -1,8 +1,8 @@ -error[E0131]: `main` function is not allowed to have lifetime parameters +error[E0131]: `main` function is not allowed to have generic parameters --> $DIR/issue-51022.rs:11:8 | LL | fn main<'a>() { } - | ^^^^ `main` cannot have lifetime parameters + | ^^^^ `main` cannot have generic parameters error: aborting due to previous error From aed530a457dd937fa633dfe52cf07811196d3173 Mon Sep 17 00:00:00 2001 From: varkor Date: Mon, 28 May 2018 13:33:28 +0100 Subject: [PATCH 20/41] Lift bounds into GenericParam --- src/librustc/hir/intravisit.rs | 8 +- src/librustc/hir/lowering.rs | 58 ++++++------- src/librustc/hir/mod.rs | 43 +++++----- src/librustc/hir/print.rs | 27 +++--- src/librustc/ich/impls_hir.rs | 12 ++- src/librustc/infer/error_reporting/mod.rs | 9 +- src/librustc/middle/resolve_lifetime.rs | 89 ++++++++++--------- src/librustc_lint/builtin.rs | 9 +- src/librustc_passes/ast_validation.rs | 14 +-- src/librustc_passes/hir_stats.rs | 8 +- src/librustc_privacy/lib.rs | 6 +- src/librustc_resolve/lib.rs | 4 +- src/librustc_save_analysis/dump_visitor.rs | 8 +- src/librustc_save_analysis/sig.rs | 26 +++--- src/librustc_typeck/check/compare_method.rs | 4 +- src/librustc_typeck/collect.rs | 45 +++++----- src/librustdoc/clean/auto_trait.rs | 18 ++-- src/librustdoc/clean/inline.rs | 4 +- src/librustdoc/clean/mod.rs | 95 +++++++++++---------- src/librustdoc/clean/simplify.rs | 2 +- src/librustdoc/core.rs | 2 +- src/librustdoc/doctree.rs | 2 +- src/librustdoc/html/format.rs | 20 ++--- src/librustdoc/html/render.rs | 6 +- src/libsyntax/ast.rs | 45 +++++----- src/libsyntax/ext/build.rs | 16 ++-- src/libsyntax/fold.rs | 23 +++-- src/libsyntax/parse/parser.rs | 22 ++--- src/libsyntax/print/pprust.rs | 23 +++-- src/libsyntax/util/node_count.rs | 2 +- src/libsyntax/visit.rs | 11 ++- src/libsyntax_ext/deriving/generic/mod.rs | 15 ++-- src/libsyntax_ext/deriving/generic/ty.rs | 7 +- 33 files changed, 339 insertions(+), 344 deletions(-) diff --git a/src/librustc/hir/intravisit.rs b/src/librustc/hir/intravisit.rs index 0bbd258080714..d5c9d964eb2a5 100644 --- a/src/librustc/hir/intravisit.rs +++ b/src/librustc/hir/intravisit.rs @@ -314,7 +314,7 @@ pub trait Visitor<'v> : Sized { fn visit_trait_ref(&mut self, t: &'v TraitRef) { walk_trait_ref(self, t) } - fn visit_ty_param_bound(&mut self, bounds: &'v TyParamBound) { + fn visit_ty_param_bound(&mut self, bounds: &'v ParamBound) { walk_ty_param_bound(self, bounds) } fn visit_poly_trait_ref(&mut self, t: &'v PolyTraitRef, m: TraitBoundModifier) { @@ -731,12 +731,12 @@ pub fn walk_foreign_item<'v, V: Visitor<'v>>(visitor: &mut V, foreign_item: &'v walk_list!(visitor, visit_attribute, &foreign_item.attrs); } -pub fn walk_ty_param_bound<'v, V: Visitor<'v>>(visitor: &mut V, bound: &'v TyParamBound) { +pub fn walk_ty_param_bound<'v, V: Visitor<'v>>(visitor: &mut V, bound: &'v ParamBound) { match *bound { TraitTyParamBound(ref typ, modifier) => { visitor.visit_poly_trait_ref(typ, modifier); } - RegionTyParamBound(ref lifetime) => { + Outlives(ref lifetime) => { visitor.visit_lifetime(lifetime); } } @@ -759,11 +759,11 @@ pub fn walk_generic_param<'v, V: Visitor<'v>>(visitor: &mut V, param: &'v Generi } GenericParamKind::Type { name, ref bounds, ref default, ref attrs, .. } => { visitor.visit_name(param.span, name); - walk_list!(visitor, visit_ty_param_bound, bounds); walk_list!(visitor, visit_ty, default); walk_list!(visitor, visit_attribute, attrs.iter()); } } + walk_list!(visitor, visit_ty_param_bound, ¶m.bounds); } pub fn walk_generics<'v, V: Visitor<'v>>(visitor: &mut V, generics: &'v Generics) { diff --git a/src/librustc/hir/lowering.rs b/src/librustc/hir/lowering.rs index d8e03bea89df4..494e6e1ba33ba 100644 --- a/src/librustc/hir/lowering.rs +++ b/src/librustc/hir/lowering.rs @@ -701,9 +701,9 @@ impl<'a> LoweringContext<'a> { id: def_node_id, span, pure_wrt_drop: false, + bounds: vec![].into(), kind: hir::GenericParamKind::Lifetime { name: hir_name, - bounds: vec![].into(), in_band: true, lifetime: hir::Lifetime { id: def_node_id, @@ -1127,7 +1127,7 @@ impl<'a> LoweringContext<'a> { Some(self.lower_poly_trait_ref(ty, itctx)) } TraitTyParamBound(_, TraitBoundModifier::Maybe) => None, - RegionTyParamBound(ref lifetime) => { + Outlives(ref lifetime) => { if lifetime_bound.is_none() { lifetime_bound = Some(self.lower_lifetime(lifetime)); } @@ -1246,16 +1246,16 @@ impl<'a> LoweringContext<'a> { span, ); - let hir_bounds = self.lower_bounds(bounds, itctx); + let hir_bounds = self.lower_param_bounds(bounds, itctx); // Set the name to `impl Bound1 + Bound2` let name = Symbol::intern(&pprust::ty_to_string(t)); self.in_band_ty_params.push(hir::GenericParam { id: def_node_id, span, pure_wrt_drop: false, + bounds: hir_bounds, kind: hir::GenericParamKind::Type { name, - bounds: hir_bounds, default: None, synthetic: Some(hir::SyntheticTyParamKind::ImplTrait), attrs: P::new(), @@ -1299,7 +1299,7 @@ impl<'a> LoweringContext<'a> { &mut self, exist_ty_id: NodeId, parent_index: DefIndex, - bounds: &hir::TyParamBounds, + bounds: &hir::ParamBounds, ) -> (HirVec, HirVec) { // This visitor walks over impl trait bounds and creates defs for all lifetimes which // appear in the bounds, excluding lifetimes that are created within the bounds. @@ -1420,9 +1420,9 @@ impl<'a> LoweringContext<'a> { id: def_node_id, span: lifetime.span, pure_wrt_drop: false, + bounds: vec![].into(), kind: hir::GenericParamKind::Lifetime { name, - bounds: vec![].into(), in_band: false, lifetime: hir::Lifetime { id: def_node_id, @@ -1882,18 +1882,18 @@ impl<'a> LoweringContext<'a> { }) } - fn lower_ty_param_bound( + fn lower_param_bound( &mut self, - tpb: &TyParamBound, + tpb: &ParamBound, itctx: ImplTraitContext, - ) -> hir::TyParamBound { + ) -> hir::ParamBound { match *tpb { TraitTyParamBound(ref ty, modifier) => hir::TraitTyParamBound( self.lower_poly_trait_ref(ty, itctx), self.lower_trait_bound_modifier(modifier), ), - RegionTyParamBound(ref lifetime) => { - hir::RegionTyParamBound(self.lower_lifetime(lifetime)) + Outlives(ref lifetime) => { + hir::Outlives(self.lower_lifetime(lifetime)) } } } @@ -1935,7 +1935,7 @@ impl<'a> LoweringContext<'a> { fn lower_generic_params( &mut self, params: &Vec, - add_bounds: &NodeMap>, + add_bounds: &NodeMap>, itctx: ImplTraitContext, ) -> hir::HirVec { params.iter().map(|param| self.lower_generic_param(param, add_bounds, itctx)).collect() @@ -1943,11 +1943,12 @@ impl<'a> LoweringContext<'a> { fn lower_generic_param(&mut self, param: &GenericParam, - add_bounds: &NodeMap>, + add_bounds: &NodeMap>, itctx: ImplTraitContext) -> hir::GenericParam { + let mut bounds = self.lower_param_bounds(¶m.bounds, itctx); match param.kind { - GenericParamKind::Lifetime { ref bounds, ref lifetime } => { + GenericParamKind::Lifetime { ref lifetime } => { let was_collecting_in_band = self.is_collecting_in_band_lifetimes; self.is_collecting_in_band_lifetimes = false; @@ -1956,9 +1957,9 @@ impl<'a> LoweringContext<'a> { id: lifetime.id, span: lifetime.span, pure_wrt_drop: attr::contains_name(¶m.attrs, "may_dangle"), + bounds, kind: hir::GenericParamKind::Lifetime { name: lifetime.name, - bounds: bounds.iter().map(|lt| self.lower_lifetime(lt)).collect(), in_band: false, lifetime, } @@ -1968,7 +1969,7 @@ impl<'a> LoweringContext<'a> { param } - GenericParamKind::Type { ref bounds, ref default } => { + GenericParamKind::Type { ref default, .. } => { let mut name = self.lower_ident(param.ident); // Don't expose `Self` (recovered "keyword used as ident" parse error). @@ -1978,11 +1979,10 @@ impl<'a> LoweringContext<'a> { name = Symbol::gensym("Self"); } - let mut bounds = self.lower_bounds(bounds, itctx); let add_bounds = add_bounds.get(¶m.id).map_or(&[][..], |x| &x); if !add_bounds.is_empty() { bounds = bounds.into_iter() - .chain(self.lower_bounds(add_bounds, itctx).into_iter()) + .chain(self.lower_param_bounds(add_bounds, itctx).into_iter()) .collect(); } @@ -1990,9 +1990,9 @@ impl<'a> LoweringContext<'a> { id: self.lower_node_id(param.id).node_id, span: param.ident.span, pure_wrt_drop: attr::contains_name(¶m.attrs, "may_dangle"), + bounds, kind: hir::GenericParamKind::Type { name, - bounds, default: default.as_ref().map(|x| { self.lower_ty(x, ImplTraitContext::Disallowed) }), @@ -2107,7 +2107,7 @@ impl<'a> LoweringContext<'a> { // Ignore `?Trait` bounds. // Tthey were copied into type parameters already. TraitTyParamBound(_, TraitBoundModifier::Maybe) => None, - _ => Some(this.lower_ty_param_bound( + _ => Some(this.lower_param_bound( bound, ImplTraitContext::Disallowed, )), @@ -2228,15 +2228,9 @@ impl<'a> LoweringContext<'a> { } } - fn lower_bounds( - &mut self, - bounds: &[TyParamBound], - itctx: ImplTraitContext, - ) -> hir::TyParamBounds { - bounds - .iter() - .map(|bound| self.lower_ty_param_bound(bound, itctx)) - .collect() + fn lower_param_bounds(&mut self, bounds: &[ParamBound], itctx: ImplTraitContext) + -> hir::ParamBounds { + bounds.iter().map(|bound| self.lower_param_bound(bound, itctx)).collect() } fn lower_block(&mut self, b: &Block, targeted_by_break: bool) -> P { @@ -2422,7 +2416,7 @@ impl<'a> LoweringContext<'a> { ) } ItemKind::Trait(is_auto, unsafety, ref generics, ref bounds, ref items) => { - let bounds = self.lower_bounds(bounds, ImplTraitContext::Disallowed); + let bounds = self.lower_param_bounds(bounds, ImplTraitContext::Disallowed); let items = items .iter() .map(|item| self.lower_trait_item_ref(item)) @@ -2437,7 +2431,7 @@ impl<'a> LoweringContext<'a> { } ItemKind::TraitAlias(ref generics, ref bounds) => hir::ItemTraitAlias( self.lower_generics(generics, ImplTraitContext::Disallowed), - self.lower_bounds(bounds, ImplTraitContext::Disallowed), + self.lower_param_bounds(bounds, ImplTraitContext::Disallowed), ), ItemKind::MacroDef(..) | ItemKind::Mac(..) => panic!("Shouldn't still be around"), } @@ -2664,7 +2658,7 @@ impl<'a> LoweringContext<'a> { TraitItemKind::Type(ref bounds, ref default) => ( self.lower_generics(&i.generics, ImplTraitContext::Disallowed), hir::TraitItemKind::Type( - self.lower_bounds(bounds, ImplTraitContext::Disallowed), + self.lower_param_bounds(bounds, ImplTraitContext::Disallowed), default .as_ref() .map(|x| self.lower_ty(x, ImplTraitContext::Disallowed)), diff --git a/src/librustc/hir/mod.rs b/src/librustc/hir/mod.rs index 135403c9c2798..8253a34f3106a 100644 --- a/src/librustc/hir/mod.rs +++ b/src/librustc/hir/mod.rs @@ -22,7 +22,7 @@ pub use self::Mutability::*; pub use self::PrimTy::*; pub use self::Stmt_::*; pub use self::Ty_::*; -pub use self::TyParamBound::*; +pub use self::ParamBound::*; pub use self::UnOp::*; pub use self::UnsafeSource::*; pub use self::Visibility::{Public, Inherited}; @@ -416,41 +416,42 @@ impl GenericArgs { } } +/// A modifier on a bound, currently this is only used for `?Sized`, where the +/// modifier is `Maybe`. Negative bounds should also be handled here. +#[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)] +pub enum TraitBoundModifier { + None, + Maybe, +} + +pub type Outlives = Lifetime; + /// The AST represents all type param bounds as types. /// typeck::collect::compute_bounds matches these against /// the "special" built-in traits (see middle::lang_items) and /// detects Copy, Send and Sync. #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)] -pub enum TyParamBound { +pub enum ParamBound { TraitTyParamBound(PolyTraitRef, TraitBoundModifier), - RegionTyParamBound(Lifetime), + Outlives(Lifetime), } -impl TyParamBound { +impl ParamBound { pub fn span(&self) -> Span { match self { &TraitTyParamBound(ref t, ..) => t.span, - &RegionTyParamBound(ref l) => l.span, + &Outlives(ref l) => l.span, } } } -/// A modifier on a bound, currently this is only used for `?Sized`, where the -/// modifier is `Maybe`. Negative bounds should also be handled here. -#[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)] -pub enum TraitBoundModifier { - None, - Maybe, -} - -pub type TyParamBounds = HirVec; +pub type ParamBounds = HirVec; #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)] pub enum GenericParamKind { /// A lifetime definition, eg `'a: 'b + 'c + 'd`. Lifetime { name: LifetimeName, - bounds: HirVec, // Indicates that the lifetime definition was synthetically added // as a result of an in-band lifetime usage like: // `fn foo(x: &'a u8) -> &'a u8 { x }` @@ -460,7 +461,6 @@ pub enum GenericParamKind { }, Type { name: Name, - bounds: TyParamBounds, default: Option>, synthetic: Option, attrs: HirVec, @@ -470,6 +470,7 @@ pub enum GenericParamKind { #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)] pub struct GenericParam { pub id: NodeId, + pub bounds: ParamBounds, pub span: Span, pub pure_wrt_drop: bool, @@ -587,7 +588,7 @@ pub struct WhereBoundPredicate { /// The type being bounded pub bounded_ty: P, /// Trait and lifetime bounds (`Clone+Send+'static`) - pub bounds: TyParamBounds, + pub bounds: ParamBounds, } /// A lifetime predicate, e.g. `'a: 'b+'c` @@ -1554,7 +1555,7 @@ pub enum TraitItemKind { Method(MethodSig, TraitMethod), /// An associated type with (possibly empty) bounds and optional concrete /// type - Type(TyParamBounds, Option>), + Type(ParamBounds, Option>), } // The bodies for items are stored "out of line", in a separate @@ -1639,7 +1640,7 @@ pub struct BareFnTy { #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)] pub struct ExistTy { pub generics: Generics, - pub bounds: TyParamBounds, + pub bounds: ParamBounds, pub impl_trait_fn: Option, } @@ -2048,9 +2049,9 @@ pub enum Item_ { /// A union definition, e.g. `union Foo {x: A, y: B}` ItemUnion(VariantData, Generics), /// Represents a Trait Declaration - ItemTrait(IsAuto, Unsafety, Generics, TyParamBounds, HirVec), + ItemTrait(IsAuto, Unsafety, Generics, ParamBounds, HirVec), /// Represents a Trait Alias Declaration - ItemTraitAlias(Generics, TyParamBounds), + ItemTraitAlias(Generics, ParamBounds), /// An implementation, eg `impl Trait for Foo { .. }` ItemImpl(Unsafety, diff --git a/src/librustc/hir/print.rs b/src/librustc/hir/print.rs index eabf554bc536f..4058db17f2fa0 100644 --- a/src/librustc/hir/print.rs +++ b/src/librustc/hir/print.rs @@ -24,7 +24,7 @@ use syntax::util::parser::{self, AssocOp, Fixity}; use syntax_pos::{self, BytePos, FileName}; use hir; -use hir::{PatKind, RegionTyParamBound, TraitTyParamBound, TraitBoundModifier, RangeEnd}; +use hir::{PatKind, Outlives, TraitTyParamBound, TraitBoundModifier, RangeEnd}; use hir::{GenericParam, GenericParamKind, GenericArg}; use std::cell::Cell; @@ -514,7 +514,7 @@ impl<'a> State<'a> { fn print_associated_type(&mut self, name: ast::Name, - bounds: Option<&hir::TyParamBounds>, + bounds: Option<&hir::ParamBounds>, ty: Option<&hir::Ty>) -> io::Result<()> { self.word_space("type")?; @@ -2071,7 +2071,7 @@ impl<'a> State<'a> { } } - pub fn print_bounds(&mut self, prefix: &str, bounds: &[hir::TyParamBound]) -> io::Result<()> { + pub fn print_bounds(&mut self, prefix: &str, bounds: &[hir::ParamBound]) -> io::Result<()> { if !bounds.is_empty() { self.s.word(prefix)?; let mut first = true; @@ -2092,7 +2092,7 @@ impl<'a> State<'a> { } self.print_poly_trait_ref(tref)?; } - RegionTyParamBound(lt) => { + Outlives(lt) => { self.print_lifetime(lt)?; } } @@ -2117,17 +2117,22 @@ impl<'a> State<'a> { pub fn print_generic_param(&mut self, param: &GenericParam) -> io::Result<()> { self.print_name(param.name())?; match param.kind { - GenericParamKind::Lifetime { ref bounds, .. } => { + GenericParamKind::Lifetime { .. } => { let mut sep = ":"; - for bound in bounds { - self.s.word(sep)?; - self.print_lifetime(bound)?; - sep = "+"; + for bound in ¶m.bounds { + match bound { + hir::ParamBound::Outlives(lt) => { + self.s.word(sep)?; + self.print_lifetime(lt)?; + sep = "+"; + } + _ => bug!(), + } } Ok(()) } - GenericParamKind::Type { ref bounds, ref default, .. } => { - self.print_bounds(":", bounds)?; + GenericParamKind::Type { ref default, .. } => { + self.print_bounds(":", ¶m.bounds)?; match default { Some(default) => { self.s.space()?; diff --git a/src/librustc/ich/impls_hir.rs b/src/librustc/ich/impls_hir.rs index fc0eee230cd0d..f8da828d2c3ba 100644 --- a/src/librustc/ich/impls_hir.rs +++ b/src/librustc/ich/impls_hir.rs @@ -184,9 +184,9 @@ impl_stable_hash_for!(struct hir::GenericArgs { parenthesized }); -impl_stable_hash_for!(enum hir::TyParamBound { +impl_stable_hash_for!(enum hir::ParamBound { TraitTyParamBound(poly_trait_ref, trait_bound_modifier), - RegionTyParamBound(lifetime) + Outlives(lifetime) }); impl_stable_hash_for!(enum hir::TraitBoundModifier { @@ -198,6 +198,7 @@ impl_stable_hash_for!(struct hir::GenericParam { id, span, pure_wrt_drop, + bounds, kind }); @@ -207,16 +208,13 @@ impl<'a> HashStable> for hir::GenericParamKind { hasher: &mut StableHasher) { mem::discriminant(self).hash_stable(hcx, hasher); match self { - hir::GenericParamKind::Lifetime { name, ref bounds, in_band, - ref lifetime } => { + hir::GenericParamKind::Lifetime { name, in_band, ref lifetime } => { name.hash_stable(hcx, hasher); - bounds.hash_stable(hcx, hasher); in_band.hash_stable(hcx, hasher); lifetime.hash_stable(hcx, hasher); } - hir::GenericParamKind::Type { name, ref bounds, ref default, synthetic, attrs } => { + hir::GenericParamKind::Type { name, ref default, synthetic, attrs } => { name.hash_stable(hcx, hasher); - bounds.hash_stable(hcx, hasher); default.hash_stable(hcx, hasher); synthetic.hash_stable(hcx, hasher); attrs.hash_stable(hcx, hasher); diff --git a/src/librustc/infer/error_reporting/mod.rs b/src/librustc/infer/error_reporting/mod.rs index b30e5bab968eb..4d6f2fb41b05d 100644 --- a/src/librustc/infer/error_reporting/mod.rs +++ b/src/librustc/infer/error_reporting/mod.rs @@ -61,7 +61,7 @@ use super::region_constraints::GenericKind; use super::lexical_region_resolve::RegionResolutionError; use std::fmt; -use hir::{self, GenericParamKind}; +use hir; use hir::map as hir_map; use hir::def_id::DefId; use middle::region; @@ -1038,12 +1038,7 @@ impl<'a, 'gcx, 'tcx> InferCtxt<'a, 'gcx, 'tcx> { // instead we suggest `T: 'a + 'b` in that case. let mut has_bounds = false; if let hir_map::NodeGenericParam(ref param) = hir.get(id) { - match param.kind { - GenericParamKind::Type { ref bounds, .. } => { - has_bounds = !bounds.is_empty(); - } - _ => bug!("unexpected non-type NodeGenericParam"), - } + has_bounds = !param.bounds.is_empty(); } let sp = hir.span(id); // `sp` only covers `T`, change it so that it covers diff --git a/src/librustc/middle/resolve_lifetime.rs b/src/librustc/middle/resolve_lifetime.rs index 561e6094c86a4..2963227c2117e 100644 --- a/src/librustc/middle/resolve_lifetime.rs +++ b/src/librustc/middle/resolve_lifetime.rs @@ -881,8 +881,8 @@ impl<'a, 'tcx> Visitor<'tcx> for LifetimeContext<'a, 'tcx> { for param in &generics.params { match param.kind { GenericParamKind::Lifetime { .. } => {} - GenericParamKind::Type { ref bounds, ref default, .. } => { - walk_list!(self, visit_ty_param_bound, bounds); + GenericParamKind::Type { ref default, .. } => { + walk_list!(self, visit_ty_param_bound, ¶m.bounds); if let Some(ref ty) = default { self.visit_ty(&ty); } @@ -1255,9 +1255,9 @@ fn object_lifetime_defaults_for_item( tcx: TyCtxt<'_, '_, '_>, generics: &hir::Generics, ) -> Vec { - fn add_bounds(set: &mut Set1, bounds: &[hir::TyParamBound]) { + fn add_bounds(set: &mut Set1, bounds: &[hir::ParamBound]) { for bound in bounds { - if let hir::RegionTyParamBound(ref lifetime) = *bound { + if let hir::Outlives(ref lifetime) = *bound { set.insert(lifetime.name); } } @@ -1265,10 +1265,10 @@ fn object_lifetime_defaults_for_item( generics.params.iter().filter_map(|param| match param.kind { GenericParamKind::Lifetime { .. } => None, - GenericParamKind::Type { ref bounds, .. } => { + GenericParamKind::Type { .. } => { let mut set = Set1::Empty; - add_bounds(&mut set, &bounds); + add_bounds(&mut set, ¶m.bounds); let param_def_id = tcx.hir.local_def_id(param.id); for predicate in &generics.where_clause.predicates { @@ -2283,45 +2283,44 @@ impl<'a, 'tcx> LifetimeContext<'a, 'tcx> { // It is a soft error to shadow a lifetime within a parent scope. self.check_lifetime_param_for_shadowing(old_scope, &lifetime_i); - let bounds = match lifetime_i.kind { - GenericParamKind::Lifetime { ref bounds, .. } => bounds, - _ => bug!(), - }; - for bound in bounds { - match bound.name { - hir::LifetimeName::Underscore => { - let mut err = struct_span_err!( - self.tcx.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.tcx - .sess - .struct_span_warn( - lifetime_i.span.to(bound.span), - &format!( - "unnecessary lifetime parameter `{}`", + for bound in &lifetime_i.bounds { + match bound { + hir::ParamBound::Outlives(lt) => match lt.name { + hir::LifetimeName::Underscore => { + let mut err = struct_span_err!( + self.tcx.sess, + lt.span, + E0637, + "invalid lifetime bound name: `'_`" + ); + err.span_label(lt.span, "`'_` is a reserved lifetime name"); + err.emit(); + } + hir::LifetimeName::Static => { + self.insert_lifetime(lt, Region::Static); + self.tcx + .sess + .struct_span_warn( + lifetime_i.span.to(lt.span), + &format!( + "unnecessary lifetime parameter `{}`", + lifetime_i.name() + ), + ) + .help(&format!( + "you can use the `'static` lifetime directly, in place \ + of `{}`", lifetime_i.name() - ), - ) - .help(&format!( - "you can use the `'static` lifetime directly, in place \ - of `{}`", - lifetime_i.name() - )) - .emit(); - } - hir::LifetimeName::Fresh(_) - | hir::LifetimeName::Implicit - | hir::LifetimeName::Name(_) => { - self.resolve_lifetime_ref(bound); + )) + .emit(); + } + hir::LifetimeName::Fresh(_) + | hir::LifetimeName::Implicit + | hir::LifetimeName::Name(_) => { + self.resolve_lifetime_ref(lt); + } } + _ => bug!(), } } } @@ -2521,8 +2520,8 @@ fn insert_late_bound_lifetimes( for param in &generics.params { match param.kind { - hir::GenericParamKind::Lifetime { ref bounds, .. } => { - if !bounds.is_empty() { + hir::GenericParamKind::Lifetime { .. } => { + if !param.bounds.is_empty() { // `'a: 'b` means both `'a` and `'b` are referenced appears_in_where_clause.regions.insert(lifetime_def.lifetime.name); } diff --git a/src/librustc_lint/builtin.rs b/src/librustc_lint/builtin.rs index 18b7024a8986d..941fabe26a6ed 100644 --- a/src/librustc_lint/builtin.rs +++ b/src/librustc_lint/builtin.rs @@ -1537,14 +1537,7 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for TypeAliasBounds { } // The parameters must not have bounds for param in type_alias_generics.params.iter() { - let spans: Vec<_> = match param.kind { - GenericParamKind::Lifetime { ref bounds, .. } => { - bounds.iter().map(|b| b.span).collect() - } - GenericParamKind::Type { ref bounds, .. } => { - bounds.iter().map(|b| b.span()).collect() - } - }; + let spans: Vec<_> = param.bounds.iter().map(|b| b.span()).collect(); if !spans.is_empty() { let mut err = cx.struct_span_lint( TYPE_ALIAS_BOUNDS, diff --git a/src/librustc_passes/ast_validation.rs b/src/librustc_passes/ast_validation.rs index dfcdb688b00cd..d14a02ec8d155 100644 --- a/src/librustc_passes/ast_validation.rs +++ b/src/librustc_passes/ast_validation.rs @@ -99,7 +99,7 @@ impl<'a> AstValidator<'a> { } } - fn no_questions_in_bounds(&self, bounds: &TyParamBounds, where_: &str, is_trait: bool) { + fn no_questions_in_bounds(&self, bounds: &ParamBounds, where_: &str, is_trait: bool) { for bound in bounds { if let TraitTyParamBound(ref poly, TraitBoundModifier::Maybe) = *bound { let mut err = self.err_handler().struct_span_err(poly.span, @@ -142,9 +142,9 @@ impl<'a> AstValidator<'a> { // Check only lifetime parameters are present and that the lifetime // parameters that are present have no bounds. let non_lt_param_spans: Vec<_> = params.iter().filter_map(|param| match param.kind { - GenericParamKind::Lifetime { ref bounds, .. } => { - if !bounds.is_empty() { - let spans: Vec<_> = bounds.iter().map(|b| b.ident.span).collect(); + GenericParamKind::Lifetime { .. } => { + if !param.bounds.is_empty() { + let spans: Vec<_> = param.bounds.iter().map(|b| b.span()).collect(); self.err_handler() .span_err(spans, "lifetime bounds cannot be used in this context"); } @@ -190,7 +190,7 @@ impl<'a> Visitor<'a> for AstValidator<'a> { TyKind::TraitObject(ref bounds, ..) => { let mut any_lifetime_bounds = false; for bound in bounds { - if let RegionTyParamBound(ref lifetime) = *bound { + if let Outlives(ref lifetime) = *bound { if any_lifetime_bounds { span_err!(self.session, lifetime.ident.span, E0226, "only a single explicit lifetime bound is permitted"); @@ -330,8 +330,8 @@ impl<'a> Visitor<'a> for AstValidator<'a> { for param in params { match param.kind { GenericParamKind::Lifetime { .. } => {} - GenericParamKind::Type { ref bounds, ref default, .. } => { - if !bounds.is_empty() { + GenericParamKind::Type { ref default, .. } => { + if !param.bounds.is_empty() { self.err_handler() .span_err(param.ident.span, "type parameters on the left \ side of a trait alias cannot be bounded"); diff --git a/src/librustc_passes/hir_stats.rs b/src/librustc_passes/hir_stats.rs index ba0be974b2771..c58b6a96ee70e 100644 --- a/src/librustc_passes/hir_stats.rs +++ b/src/librustc_passes/hir_stats.rs @@ -203,8 +203,8 @@ impl<'v> hir_visit::Visitor<'v> for StatCollector<'v> { hir_visit::walk_impl_item(self, ii) } - fn visit_ty_param_bound(&mut self, bounds: &'v hir::TyParamBound) { - self.record("TyParamBound", Id::None, bounds); + fn visit_ty_param_bound(&mut self, bounds: &'v hir::ParamBound) { + self.record("ParamBound", Id::None, bounds); hir_visit::walk_ty_param_bound(self, bounds) } @@ -322,8 +322,8 @@ impl<'v> ast_visit::Visitor<'v> for StatCollector<'v> { ast_visit::walk_impl_item(self, ii) } - fn visit_ty_param_bound(&mut self, bounds: &'v ast::TyParamBound) { - self.record("TyParamBound", Id::None, bounds); + fn visit_ty_param_bound(&mut self, bounds: &'v ast::ParamBound) { + self.record("ParamBound", Id::None, bounds); ast_visit::walk_ty_param_bound(self, bounds) } diff --git a/src/librustc_privacy/lib.rs b/src/librustc_privacy/lib.rs index 388ac5cdb50af..2667f68b26095 100644 --- a/src/librustc_privacy/lib.rs +++ b/src/librustc_privacy/lib.rs @@ -1038,7 +1038,7 @@ impl<'a, 'tcx> ObsoleteVisiblePrivateTypesVisitor<'a, 'tcx> { } fn check_ty_param_bound(&mut self, - ty_param_bound: &hir::TyParamBound) { + ty_param_bound: &hir::ParamBound) { if let hir::TraitTyParamBound(ref trait_ref, _) = *ty_param_bound { if self.path_is_private_type(&trait_ref.trait_ref.path) { self.old_error_set.insert(trait_ref.trait_ref.ref_id); @@ -1270,8 +1270,8 @@ impl<'a, 'tcx> Visitor<'tcx> for ObsoleteVisiblePrivateTypesVisitor<'a, 'tcx> { fn visit_generics(&mut self, generics: &'tcx hir::Generics) { generics.params.iter().for_each(|param| match param.kind { GenericParamKind::Lifetime { .. } => {} - GenericParamKind::Type { ref bounds, .. } => { - for bound in bounds { + GenericParamKind::Type { .. } => { + for bound in ¶m.bounds { self.check_ty_param_bound(bound); } } diff --git a/src/librustc_resolve/lib.rs b/src/librustc_resolve/lib.rs index 6561202be51b3..b51ef90449571 100644 --- a/src/librustc_resolve/lib.rs +++ b/src/librustc_resolve/lib.rs @@ -813,8 +813,8 @@ impl<'a, 'tcx> Visitor<'tcx> for Resolver<'a> { for param in &generics.params { match param.kind { GenericParamKind::Lifetime { .. } => self.visit_generic_param(param), - GenericParamKind::Type { ref bounds, ref default, .. } => { - for bound in bounds { + GenericParamKind::Type { ref default, .. } => { + for bound in ¶m.bounds { self.visit_ty_param_bound(bound); } diff --git a/src/librustc_save_analysis/dump_visitor.rs b/src/librustc_save_analysis/dump_visitor.rs index 6cfec57f80e65..cbae6c1ab1ab8 100644 --- a/src/librustc_save_analysis/dump_visitor.rs +++ b/src/librustc_save_analysis/dump_visitor.rs @@ -718,7 +718,7 @@ impl<'l, 'tcx: 'l, 'll, O: DumpOutput + 'll> DumpVisitor<'l, 'tcx, 'll, O> { &mut self, item: &'l ast::Item, generics: &'l ast::Generics, - trait_refs: &'l ast::TyParamBounds, + trait_refs: &'l ast::ParamBounds, methods: &'l [ast::TraitItem], ) { let name = item.ident.to_string(); @@ -762,7 +762,7 @@ impl<'l, 'tcx: 'l, 'll, O: DumpOutput + 'll> DumpVisitor<'l, 'tcx, 'll, O> { for super_bound in trait_refs.iter() { let trait_ref = match *super_bound { ast::TraitTyParamBound(ref trait_ref, _) => trait_ref, - ast::RegionTyParamBound(..) => { + ast::Outlives(..) => { continue; } }; @@ -1487,8 +1487,8 @@ impl<'l, 'tcx: 'l, 'll, O: DumpOutput + 'll> Visitor<'l> for DumpVisitor<'l, 'tc fn visit_generics(&mut self, generics: &'l ast::Generics) { generics.params.iter().for_each(|param| match param.kind { ast::GenericParamKind::Lifetime { .. } => {} - ast::GenericParamKind::Type { ref bounds, ref default, .. } => { - for bound in bounds { + ast::GenericParamKind::Type { ref default, .. } => { + for bound in ¶m.bounds { if let ast::TraitTyParamBound(ref trait_ref, _) = *bound { self.process_path(trait_ref.trait_ref.ref_id, &trait_ref.trait_ref.path) } diff --git a/src/librustc_save_analysis/sig.rs b/src/librustc_save_analysis/sig.rs index 6a63995c0fd5f..58e2e9b225829 100644 --- a/src/librustc_save_analysis/sig.rs +++ b/src/librustc_save_analysis/sig.rs @@ -104,7 +104,7 @@ pub fn assoc_const_signature( pub fn assoc_type_signature( id: NodeId, ident: ast::Ident, - bounds: Option<&ast::TyParamBounds>, + bounds: Option<&ast::ParamBounds>, default: Option<&ast::Ty>, scx: &SaveContext, ) -> Option { @@ -623,22 +623,22 @@ impl Sig for ast::Generics { start: offset + text.len(), end: offset + text.len() + param_text.len(), }); - match param.kind { - ast::GenericParamKind::Lifetime { ref bounds, .. } => { - if !bounds.is_empty() { - param_text.push_str(": "); - let bounds = bounds.iter() - .map(|l| l.ident.to_string()) + if !param.bounds.is_empty() { + param_text.push_str(": "); + match param.kind { + ast::GenericParamKind::Lifetime { .. } => { + let bounds = param.bounds.iter() + .map(|bound| match bound { + ast::ParamBound::Outlives(lt) => lt.ident.to_string(), + _ => panic!(), + }) .collect::>() .join(" + "); param_text.push_str(&bounds); // FIXME add lifetime bounds refs. } - } - ast::GenericParamKind::Type { ref bounds, .. } => { - if !bounds.is_empty() { - param_text.push_str(": "); - param_text.push_str(&pprust::bounds_to_string(bounds)); + ast::GenericParamKind::Type { .. } => { + param_text.push_str(&pprust::bounds_to_string(¶m.bounds)); // FIXME descend properly into bounds. } } @@ -841,7 +841,7 @@ fn name_and_generics( fn make_assoc_type_signature( id: NodeId, ident: ast::Ident, - bounds: Option<&ast::TyParamBounds>, + bounds: Option<&ast::ParamBounds>, default: Option<&ast::Ty>, scx: &SaveContext, ) -> Result { diff --git a/src/librustc_typeck/check/compare_method.rs b/src/librustc_typeck/check/compare_method.rs index 8a64e4a536785..5f8955612e10c 100644 --- a/src/librustc_typeck/check/compare_method.rs +++ b/src/librustc_typeck/check/compare_method.rs @@ -844,9 +844,9 @@ fn compare_synthetic_generics<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, let bounds = impl_m.generics.params.iter().find_map(|param| { match param.kind { GenericParamKind::Lifetime { .. } => None, - GenericParamKind::Type { ref bounds, .. } => { + GenericParamKind::Type { .. } => { if param.id == impl_node_id { - Some(bounds) + Some(¶m.bounds) } else { None } diff --git a/src/librustc_typeck/collect.rs b/src/librustc_typeck/collect.rs index 2e4ceb5a65c99..f95f6a26f0b92 100644 --- a/src/librustc_typeck/collect.rs +++ b/src/librustc_typeck/collect.rs @@ -315,9 +315,7 @@ impl<'a, 'tcx> ItemCtxt<'a, 'tcx> { let from_ty_params = ast_generics.params.iter() .filter_map(|param| match param.kind { - GenericParamKind::Type { ref bounds, .. } if param.id == param_id => { - Some(bounds) - } + GenericParamKind::Type { .. } if param.id == param_id => Some(¶m.bounds), _ => None }) .flat_map(|bounds| bounds.iter()) @@ -1252,7 +1250,7 @@ fn impl_polarity<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, // Is it marked with ?Sized fn is_unsized<'gcx: 'tcx, 'tcx>(astconv: &AstConv<'gcx, 'tcx>, - ast_bounds: &[hir::TyParamBound], + ast_bounds: &[hir::ParamBound], span: Span) -> bool { let tcx = astconv.tcx(); @@ -1445,13 +1443,15 @@ pub fn explicit_predicates_of<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, index += 1; match param.kind { - GenericParamKind::Lifetime { ref bounds, .. } => { - for bound in bounds { - let bound_region = AstConv::ast_region_to_region(&icx, bound, None); - let outlives = - ty::Binder::bind(ty::OutlivesPredicate(region, bound_region)); - predicates.push(outlives.to_predicate()); - } + GenericParamKind::Lifetime { .. } => { + param.bounds.iter().for_each(|bound| match bound { + hir::ParamBound::Outlives(lt) => { + let bound = AstConv::ast_region_to_region(&icx, <, None); + let outlives = ty::Binder::bind(ty::OutlivesPredicate(region, bound)); + predicates.push(outlives.to_predicate()); + } + _ => bug!(), + }); }, _ => bug!(), } @@ -1461,13 +1461,12 @@ pub fn explicit_predicates_of<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, // type parameter (e.g., ``). for param in &ast_generics.params { match param.kind { - GenericParamKind::Type { ref bounds, .. } => { - let param_ty = ty::ParamTy::new(index, param.name().as_interned_str()) - .to_ty(tcx); + GenericParamKind::Type { .. } => { + let param_ty = ty::ParamTy::new(index, param.name().as_interned_str()).to_ty(tcx); index += 1; - let bounds = - compute_bounds(&icx, param_ty, bounds, SizedByDefault::Yes, param.span); + let sized = SizedByDefault::Yes; + let bounds = compute_bounds(&icx, param_ty, ¶m.bounds, sized, param.span); predicates.extend(bounds.predicates(tcx, param_ty)); } _ => {} @@ -1483,7 +1482,7 @@ pub fn explicit_predicates_of<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, for bound in bound_pred.bounds.iter() { match bound { - &hir::TyParamBound::TraitTyParamBound(ref poly_trait_ref, _) => { + &hir::ParamBound::TraitTyParamBound(ref poly_trait_ref, _) => { let mut projections = Vec::new(); let trait_ref = @@ -1499,7 +1498,7 @@ pub fn explicit_predicates_of<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, } } - &hir::TyParamBound::RegionTyParamBound(ref lifetime) => { + &hir::ParamBound::Outlives(ref lifetime) => { let region = AstConv::ast_region_to_region(&icx, lifetime, None); @@ -1578,7 +1577,7 @@ pub enum SizedByDefault { Yes, No, } /// built-in trait (formerly known as kind): Send. pub fn compute_bounds<'gcx: 'tcx, 'tcx>(astconv: &AstConv<'gcx, 'tcx>, param_ty: Ty<'tcx>, - ast_bounds: &[hir::TyParamBound], + ast_bounds: &[hir::ParamBound], sized_by_default: SizedByDefault, span: Span) -> Bounds<'tcx> @@ -1591,7 +1590,7 @@ pub fn compute_bounds<'gcx: 'tcx, 'tcx>(astconv: &AstConv<'gcx, 'tcx>, trait_bounds.push(b); } hir::TraitTyParamBound(_, hir::TraitBoundModifier::Maybe) => {} - hir::RegionTyParamBound(ref l) => { + hir::Outlives(ref l) => { region_bounds.push(l); } } @@ -1625,14 +1624,14 @@ pub fn compute_bounds<'gcx: 'tcx, 'tcx>(astconv: &AstConv<'gcx, 'tcx>, } } -/// Converts a specific TyParamBound from the AST into a set of +/// Converts a specific ParamBound from the AST into a set of /// predicates that apply to the self-type. A vector is returned /// 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: &AstConv<'tcx, 'tcx>, param_ty: Ty<'tcx>, - bound: &hir::TyParamBound) + bound: &hir::ParamBound) -> Vec> { match *bound { @@ -1646,7 +1645,7 @@ fn predicates_from_bound<'tcx>(astconv: &AstConv<'tcx, 'tcx>, .chain(Some(pred.to_predicate())) .collect() } - hir::RegionTyParamBound(ref lifetime) => { + hir::Outlives(ref lifetime) => { let region = astconv.ast_region_to_region(lifetime, None); let pred = ty::Binder::bind(ty::OutlivesPredicate(param_ty, region)); vec![ty::Predicate::TypeOutlives(pred)] diff --git a/src/librustdoc/clean/auto_trait.rs b/src/librustdoc/clean/auto_trait.rs index 2a63b12486637..2686ad96c6ece 100644 --- a/src/librustdoc/clean/auto_trait.rs +++ b/src/librustdoc/clean/auto_trait.rs @@ -536,7 +536,7 @@ impl<'a, 'tcx, 'rcx> AutoTraitFinder<'a, 'tcx, 'rcx> { fn make_final_bounds<'b, 'c, 'cx>( &self, - ty_to_bounds: FxHashMap>, + ty_to_bounds: FxHashMap>, ty_to_fn: FxHashMap, Option)>, lifetime_to_bounds: FxHashMap>, ) -> Vec { @@ -589,7 +589,7 @@ impl<'a, 'tcx, 'rcx> AutoTraitFinder<'a, 'tcx, 'rcx> { } _ => panic!("Unexpected data: {:?}, {:?}", ty, data), }; - bounds.insert(TyParamBound::TraitBound( + bounds.insert(ParamBound::TraitBound( PolyTrait { trait_: new_ty, generic_params: poly_trait.generic_params, @@ -732,7 +732,7 @@ impl<'a, 'tcx, 'rcx> AutoTraitFinder<'a, 'tcx, 'rcx> { // later let is_fn = match &mut b { - &mut TyParamBound::TraitBound(ref mut p, _) => { + &mut ParamBound::TraitBound(ref mut p, _) => { // Insert regions into the for_generics hash map first, to ensure // that we don't end up with duplicate bounds (e.g. for<'b, 'b>) for_generics.extend(p.generic_params.clone()); @@ -826,7 +826,7 @@ impl<'a, 'tcx, 'rcx> AutoTraitFinder<'a, 'tcx, 'rcx> { .entry(*ty.clone()) .or_insert_with(|| FxHashSet()); - bounds.insert(TyParamBound::TraitBound( + bounds.insert(ParamBound::TraitBound( PolyTrait { trait_: Type::ResolvedPath { path: new_trait_path, @@ -843,7 +843,7 @@ impl<'a, 'tcx, 'rcx> AutoTraitFinder<'a, 'tcx, 'rcx> { // that we don't see a // duplicate bound like `T: Iterator + Iterator` // on the docs page. - bounds.remove(&TyParamBound::TraitBound( + bounds.remove(&ParamBound::TraitBound( PolyTrait { trait_: *trait_.clone(), generic_params: Vec::new(), @@ -877,7 +877,7 @@ impl<'a, 'tcx, 'rcx> AutoTraitFinder<'a, 'tcx, 'rcx> { default.take(); let generic_ty = Type::Generic(param.name.clone()); if !has_sized.contains(&generic_ty) { - bounds.insert(0, TyParamBound::maybe_sized(self.cx)); + bounds.insert(0, ParamBound::maybe_sized(self.cx)); } } GenericParamDefKind::Lifetime => {} @@ -911,7 +911,7 @@ impl<'a, 'tcx, 'rcx> AutoTraitFinder<'a, 'tcx, 'rcx> { // both for visual consistency between 'rustdoc' runs, and to // make writing tests much easier #[inline] - fn sort_where_bounds(&self, mut bounds: &mut Vec) { + fn sort_where_bounds(&self, mut bounds: &mut Vec) { // We should never have identical bounds - and if we do, // they're visually identical as well. Therefore, using // an unstable sort is fine. @@ -939,7 +939,7 @@ impl<'a, 'tcx, 'rcx> AutoTraitFinder<'a, 'tcx, 'rcx> { // to end users, it makes writing tests much more difficult, as predicates // can appear in any order in the final result. // - // To solve this problem, we sort WherePredicates and TyParamBounds + // To solve this problem, we sort WherePredicates and ParamBounds // by their Debug string. The thing to keep in mind is that we don't really // care what the final order is - we're synthesizing an impl or bound // ourselves, so any order can be considered equally valid. By sorting the @@ -949,7 +949,7 @@ impl<'a, 'tcx, 'rcx> AutoTraitFinder<'a, 'tcx, 'rcx> { // Using the Debug impementation for sorting prevents us from needing to // write quite a bit of almost entirely useless code (e.g. how should two // Types be sorted relative to each other). It also allows us to solve the - // problem for both WherePredicates and TyParamBounds at the same time. This + // problem for both WherePredicates and ParamBounds at the same time. This // approach is probably somewhat slower, but the small number of items // involved (impls rarely have more than a few bounds) means that it // shouldn't matter in practice. diff --git a/src/librustdoc/clean/inline.rs b/src/librustdoc/clean/inline.rs index 80eb2d1e214fb..afe959aaec5a5 100644 --- a/src/librustdoc/clean/inline.rs +++ b/src/librustdoc/clean/inline.rs @@ -474,7 +474,7 @@ fn filter_non_trait_generics(trait_did: DefId, mut g: clean::Generics) -> clean: } if *s == "Self" => { bounds.retain(|bound| { match *bound { - clean::TyParamBound::TraitBound(clean::PolyTrait { + clean::ParamBound::TraitBound(clean::PolyTrait { trait_: clean::ResolvedPath { did, .. }, .. }, _) => did != trait_did, @@ -505,7 +505,7 @@ fn filter_non_trait_generics(trait_did: DefId, mut g: clean::Generics) -> clean: /// the metadata for a crate, so we want to separate those out and create a new /// list of explicit supertrait bounds to render nicely. fn separate_supertrait_bounds(mut g: clean::Generics) - -> (clean::Generics, Vec) { + -> (clean::Generics, Vec) { let mut ty_bounds = Vec::new(); g.where_predicates.retain(|pred| { match *pred { diff --git a/src/librustdoc/clean/mod.rs b/src/librustdoc/clean/mod.rs index 89835ab6aaef0..4cc8de91baa6d 100644 --- a/src/librustdoc/clean/mod.rs +++ b/src/librustdoc/clean/mod.rs @@ -14,7 +14,7 @@ pub use self::Type::*; pub use self::Mutability::*; pub use self::ItemEnum::*; -pub use self::TyParamBound::*; +pub use self::ParamBound::*; pub use self::SelfTy::*; pub use self::FunctionRetTy::*; pub use self::Visibility::{Public, Inherited}; @@ -532,7 +532,7 @@ pub enum ItemEnum { MacroItem(Macro), PrimitiveItem(PrimitiveType), AssociatedConstItem(Type, Option), - AssociatedTypeItem(Vec, Option), + AssociatedTypeItem(Vec, Option), /// An item that has been stripped by a rustdoc pass StrippedItem(Box), KeywordItem(String), @@ -1458,13 +1458,13 @@ impl Clean for [ast::Attribute] { } #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Eq, Debug, Hash)] -pub enum TyParamBound { +pub enum ParamBound { RegionBound(Lifetime), TraitBound(PolyTrait, hir::TraitBoundModifier) } -impl TyParamBound { - fn maybe_sized(cx: &DocContext) -> TyParamBound { +impl ParamBound { + fn maybe_sized(cx: &DocContext) -> ParamBound { let did = cx.tcx.require_lang_item(lang_items::SizedTraitLangItem); let empty = cx.tcx.intern_substs(&[]); let path = external_path(cx, &cx.tcx.item_name(did).as_str(), @@ -1483,7 +1483,7 @@ impl TyParamBound { fn is_sized_bound(&self, cx: &DocContext) -> bool { use rustc::hir::TraitBoundModifier as TBM; - if let TyParamBound::TraitBound(PolyTrait { ref trait_, .. }, TBM::None) = *self { + if let ParamBound::TraitBound(PolyTrait { ref trait_, .. }, TBM::None) = *self { if trait_.def_id() == cx.tcx.lang_items().sized_trait() { return true; } @@ -1492,7 +1492,7 @@ impl TyParamBound { } fn get_poly_trait(&self) -> Option { - if let TyParamBound::TraitBound(ref p, _) = *self { + if let ParamBound::TraitBound(ref p, _) = *self { return Some(p.clone()) } None @@ -1500,17 +1500,17 @@ impl TyParamBound { fn get_trait_type(&self) -> Option { - if let TyParamBound::TraitBound(PolyTrait { ref trait_, .. }, _) = *self { + if let ParamBound::TraitBound(PolyTrait { ref trait_, .. }, _) = *self { return Some(trait_.clone()); } None } } -impl Clean for hir::TyParamBound { - fn clean(&self, cx: &DocContext) -> TyParamBound { +impl Clean for hir::ParamBound { + fn clean(&self, cx: &DocContext) -> ParamBound { match *self { - hir::RegionTyParamBound(lt) => RegionBound(lt.clean(cx)), + hir::Outlives(lt) => RegionBound(lt.clean(cx)), hir::TraitTyParamBound(ref t, modifier) => TraitBound(t.clean(cx), modifier), } } @@ -1570,8 +1570,8 @@ fn external_path(cx: &DocContext, name: &str, trait_did: Option, has_self } } -impl<'a, 'tcx> Clean for (&'a ty::TraitRef<'tcx>, Vec) { - fn clean(&self, cx: &DocContext) -> TyParamBound { +impl<'a, 'tcx> Clean for (&'a ty::TraitRef<'tcx>, Vec) { + fn clean(&self, cx: &DocContext) -> ParamBound { let (trait_ref, ref bounds) = *self; inline::record_extern_fqn(cx, trait_ref.def_id, TypeKind::Trait); let path = external_path(cx, &cx.tcx.item_name(trait_ref.def_id).as_str(), @@ -1614,14 +1614,14 @@ impl<'a, 'tcx> Clean for (&'a ty::TraitRef<'tcx>, Vec } } -impl<'tcx> Clean for ty::TraitRef<'tcx> { - fn clean(&self, cx: &DocContext) -> TyParamBound { +impl<'tcx> Clean for ty::TraitRef<'tcx> { + fn clean(&self, cx: &DocContext) -> ParamBound { (self, vec![]).clean(cx) } } -impl<'tcx> Clean>> for Substs<'tcx> { - fn clean(&self, cx: &DocContext) -> Option> { +impl<'tcx> Clean>> for Substs<'tcx> { + fn clean(&self, cx: &DocContext) -> Option> { let mut v = Vec::new(); v.extend(self.regions().filter_map(|r| r.clean(cx)) .map(RegionBound)); @@ -1671,10 +1671,15 @@ impl Clean for hir::Lifetime { impl Clean for hir::GenericParam { fn clean(&self, _: &DocContext) -> Lifetime { match self.kind { - hir::GenericParamKind::Lifetime { ref bounds, .. } => { - if bounds.len() > 0 { - let mut s = format!("{}: {}", self.name(), bounds[0].name.name()); - for bound in bounds.iter().skip(1) { + hir::GenericParamKind::Lifetime { .. } => { + if self.bounds.len() > 0 { + let mut bounds = self.bounds.iter().map(|bound| match bound { + hir::ParamBound::Outlives(lt) => lt, + _ => panic!(), + }); + let name = bounds.next().unwrap().name.name(); + let mut s = format!("{}: {}", self.name(), name); + for bound in bounds { s.push_str(&format!(" + {}", bound.name.name())); } Lifetime(s) @@ -1715,7 +1720,7 @@ impl Clean> for ty::RegionKind { #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Eq, Debug, Hash)] pub enum WherePredicate { - BoundPredicate { ty: Type, bounds: Vec }, + BoundPredicate { ty: Type, bounds: Vec }, RegionPredicate { lifetime: Lifetime, bounds: Vec}, EqPredicate { lhs: Type, rhs: Type }, } @@ -1797,7 +1802,7 @@ impl<'tcx> Clean for ty::OutlivesPredicate, ty::Region< WherePredicate::BoundPredicate { ty: ty.clean(cx), - bounds: vec![TyParamBound::RegionBound(lt.clean(cx).unwrap())] + bounds: vec![ParamBound::RegionBound(lt.clean(cx).unwrap())] } } } @@ -1814,8 +1819,8 @@ impl<'tcx> Clean for ty::ProjectionPredicate<'tcx> { impl<'tcx> Clean for ty::ProjectionTy<'tcx> { fn clean(&self, cx: &DocContext) -> Type { let trait_ = match self.trait_ref(cx.tcx).clean(cx) { - TyParamBound::TraitBound(t, _) => t.trait_, - TyParamBound::RegionBound(_) => { + ParamBound::TraitBound(t, _) => t.trait_, + ParamBound::RegionBound(_) => { panic!("cleaning a trait got a region") } }; @@ -1832,7 +1837,7 @@ pub enum GenericParamDefKind { Lifetime, Type { did: DefId, - bounds: Vec, + bounds: Vec, default: Option, synthetic: Option, }, @@ -1887,10 +1892,15 @@ impl<'tcx> Clean for ty::GenericParamDef { impl Clean for hir::GenericParam { fn clean(&self, cx: &DocContext) -> GenericParamDef { let (name, kind) = match self.kind { - hir::GenericParamKind::Lifetime { ref bounds, .. } => { - let name = if bounds.len() > 0 { - let mut s = format!("{}: {}", self.name(), bounds[0].name.name()); - for bound in bounds.iter().skip(1) { + hir::GenericParamKind::Lifetime { .. } => { + let name = if self.bounds.len() > 0 { + let mut bounds = self.bounds.iter().map(|bound| match bound { + hir::ParamBound::Outlives(lt) => lt, + _ => panic!(), + }); + let name = bounds.next().unwrap().name.name(); + let mut s = format!("{}: {}", self.name(), name); + for bound in bounds { s.push_str(&format!(" + {}", bound.name.name())); } s @@ -1899,10 +1909,10 @@ impl Clean for hir::GenericParam { }; (name, GenericParamDefKind::Lifetime) } - hir::GenericParamKind::Type { ref bounds, ref default, synthetic, .. } => { + hir::GenericParamKind::Type { ref default, synthetic, .. } => { (self.name().clean(cx), GenericParamDefKind::Type { did: cx.tcx.hir.local_def_id(self.id), - bounds: bounds.clean(cx), + bounds: self.bounds.clean(cx), default: default.clean(cx), synthetic: synthetic, }) @@ -2041,7 +2051,7 @@ impl<'a, 'tcx> Clean for (&'a ty::Generics, if !sized_params.contains(&tp.name) { where_predicates.push(WP::BoundPredicate { ty: Type::Generic(tp.name.clone()), - bounds: vec![TyParamBound::maybe_sized(cx)], + bounds: vec![ParamBound::maybe_sized(cx)], }) } } @@ -2282,7 +2292,7 @@ pub struct Trait { pub unsafety: hir::Unsafety, pub items: Vec, pub generics: Generics, - pub bounds: Vec, + pub bounds: Vec, pub is_spotlight: bool, pub is_auto: bool, } @@ -2504,7 +2514,7 @@ impl<'tcx> Clean for ty::AssociatedItem { // at the end. match bounds.iter().position(|b| b.is_sized_bound(cx)) { Some(i) => { bounds.remove(i); } - None => bounds.push(TyParamBound::maybe_sized(cx)), + None => bounds.push(ParamBound::maybe_sized(cx)), } let ty = if self.defaultness.has_value() { @@ -2559,7 +2569,7 @@ pub enum Type { /// structs/enums/traits (most that'd be an hir::TyPath) ResolvedPath { path: Path, - typarams: Option>, + typarams: Option>, did: DefId, /// true if is a `T::Name` path for associated types is_generic: bool, @@ -2595,7 +2605,7 @@ pub enum Type { Infer, // impl TraitA+TraitB - ImplTrait(Vec), + ImplTrait(Vec), } #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Eq, Hash, Copy, Debug)] @@ -3147,7 +3157,6 @@ impl<'tcx> Clean for Ty<'tcx> { } } - let bounds = bounds.predicates.iter().filter_map(|pred| if let ty::Predicate::Projection(proj) = *pred { let proj = proj.skip_binder(); @@ -3169,7 +3178,7 @@ impl<'tcx> Clean for Ty<'tcx> { }).collect::>(); bounds.extend(regions); if !has_sized && !bounds.is_empty() { - bounds.insert(0, TyParamBound::maybe_sized(cx)); + bounds.insert(0, ParamBound::maybe_sized(cx)); } ImplTrait(bounds) } @@ -4465,11 +4474,11 @@ impl AutoTraitResult { } } -impl From for SimpleBound { - fn from(bound: TyParamBound) -> Self { +impl From for SimpleBound { + fn from(bound: ParamBound) -> Self { match bound.clone() { - TyParamBound::RegionBound(l) => SimpleBound::RegionBound(l), - TyParamBound::TraitBound(t, mod_) => match t.trait_ { + ParamBound::RegionBound(l) => SimpleBound::RegionBound(l), + ParamBound::TraitBound(t, mod_) => match t.trait_ { Type::ResolvedPath { path, typarams, .. } => { SimpleBound::TraitBound(path.segments, typarams diff --git a/src/librustdoc/clean/simplify.rs b/src/librustdoc/clean/simplify.rs index 95ceee8569090..81ad2a5bf51a6 100644 --- a/src/librustdoc/clean/simplify.rs +++ b/src/librustdoc/clean/simplify.rs @@ -147,7 +147,7 @@ pub fn ty_params(mut params: Vec) -> Vec) -> Vec { +fn ty_bounds(bounds: Vec) -> Vec { bounds } diff --git a/src/librustdoc/core.rs b/src/librustdoc/core.rs index e858f10860b41..7147e13805f8b 100644 --- a/src/librustdoc/core.rs +++ b/src/librustdoc/core.rs @@ -77,7 +77,7 @@ pub struct DocContext<'a, 'tcx: 'a, 'rcx: 'a> { /// Table node id of lifetime parameter definition -> substituted lifetime pub lt_substs: RefCell>, /// Table DefId of `impl Trait` in argument position -> bounds - pub impl_trait_bounds: RefCell>>, + pub impl_trait_bounds: RefCell>>, pub send_trait: Option, pub fake_def_ids: RefCell>, pub all_fake_def_ids: RefCell>, diff --git a/src/librustdoc/doctree.rs b/src/librustdoc/doctree.rs index f85a70a6d401f..542d753c4f0dc 100644 --- a/src/librustdoc/doctree.rs +++ b/src/librustdoc/doctree.rs @@ -201,7 +201,7 @@ pub struct Trait { pub name: Name, pub items: hir::HirVec, pub generics: hir::Generics, - pub bounds: hir::HirVec, + pub bounds: hir::HirVec, pub attrs: hir::HirVec, pub id: ast::NodeId, pub whence: Span, diff --git a/src/librustdoc/html/format.rs b/src/librustdoc/html/format.rs index 86c312275ff28..4174f656995fe 100644 --- a/src/librustdoc/html/format.rs +++ b/src/librustdoc/html/format.rs @@ -46,7 +46,7 @@ pub struct MutableSpace(pub clean::Mutability); #[derive(Copy, Clone)] pub struct RawMutableSpace(pub clean::Mutability); /// Wrapper struct for emitting type parameter bounds. -pub struct TyParamBounds<'a>(pub &'a [clean::TyParamBound]); +pub struct ParamBounds<'a>(pub &'a [clean::ParamBound]); /// Wrapper struct for emitting a comma-separated list of items pub struct CommaSep<'a, T: 'a>(pub &'a [T]); pub struct AbiSpace(pub Abi); @@ -104,9 +104,9 @@ impl<'a, T: fmt::Display> fmt::Display for CommaSep<'a, T> { } } -impl<'a> fmt::Display for TyParamBounds<'a> { +impl<'a> fmt::Display for ParamBounds<'a> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - let &TyParamBounds(bounds) = self; + let &ParamBounds(bounds) = self; for (i, bound) in bounds.iter().enumerate() { if i > 0 { f.write_str(" + ")?; @@ -126,9 +126,9 @@ impl fmt::Display for clean::GenericParamDef { if !bounds.is_empty() { if f.alternate() { - write!(f, ": {:#}", TyParamBounds(bounds))?; + write!(f, ": {:#}", ParamBounds(bounds))?; } else { - write!(f, ": {}", TyParamBounds(bounds))?; + write!(f, ": {}", ParamBounds(bounds))?; } } @@ -190,9 +190,9 @@ impl<'a> fmt::Display for WhereClause<'a> { &clean::WherePredicate::BoundPredicate { ref ty, ref bounds } => { let bounds = bounds; if f.alternate() { - clause.push_str(&format!("{:#}: {:#}", ty, TyParamBounds(bounds))); + clause.push_str(&format!("{:#}: {:#}", ty, ParamBounds(bounds))); } else { - clause.push_str(&format!("{}: {}", ty, TyParamBounds(bounds))); + clause.push_str(&format!("{}: {}", ty, ParamBounds(bounds))); } } &clean::WherePredicate::RegionPredicate { ref lifetime, @@ -267,7 +267,7 @@ impl fmt::Display for clean::PolyTrait { } } -impl fmt::Display for clean::TyParamBound { +impl fmt::Display for clean::ParamBound { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { clean::RegionBound(ref lt) => { @@ -512,7 +512,7 @@ fn primitive_link(f: &mut fmt::Formatter, /// Helper to render type parameters fn tybounds(w: &mut fmt::Formatter, - typarams: &Option>) -> fmt::Result { + typarams: &Option>) -> fmt::Result { match *typarams { Some(ref params) => { for param in params { @@ -667,7 +667,7 @@ fn fmt_type(t: &clean::Type, f: &mut fmt::Formatter, use_absolute: bool) -> fmt: } } clean::ImplTrait(ref bounds) => { - write!(f, "impl {}", TyParamBounds(bounds)) + write!(f, "impl {}", ParamBounds(bounds)) } clean::QPath { ref name, ref self_type, ref trait_ } => { let should_show_cast = match *trait_ { diff --git a/src/librustdoc/html/render.rs b/src/librustdoc/html/render.rs index 675d1097bda4a..21724c2d730ef 100644 --- a/src/librustdoc/html/render.rs +++ b/src/librustdoc/html/render.rs @@ -69,7 +69,7 @@ use doctree; use fold::DocFolder; use html::escape::Escape; use html::format::{ConstnessSpace}; -use html::format::{TyParamBounds, WhereClause, href, AbiSpace}; +use html::format::{ParamBounds, WhereClause, href, AbiSpace}; use html::format::{VisSpace, Method, UnsafetySpace, MutableSpace}; use html::format::fmt_impl_for_trait_page; use html::item_type::ItemType; @@ -2960,14 +2960,14 @@ fn assoc_const(w: &mut fmt::Formatter, } fn assoc_type(w: &mut W, it: &clean::Item, - bounds: &Vec, + bounds: &Vec, default: Option<&clean::Type>, link: AssocItemLink) -> fmt::Result { write!(w, "type {}", naive_assoc_href(it, link), it.name.as_ref().unwrap())?; if !bounds.is_empty() { - write!(w, ": {}", TyParamBounds(bounds))? + write!(w, ": {}", ParamBounds(bounds))? } if let Some(default) = default { write!(w, " = {}", default)?; diff --git a/src/libsyntax/ast.rs b/src/libsyntax/ast.rs index f589057218c80..b082cde5df7ed 100644 --- a/src/libsyntax/ast.rs +++ b/src/libsyntax/ast.rs @@ -10,7 +10,7 @@ // The Rust abstract syntax tree. -pub use self::TyParamBound::*; +pub use self::ParamBound::*; pub use self::UnsafeSource::*; pub use self::GenericArgs::*; pub use symbol::{Ident, Symbol as Name}; @@ -269,44 +269,42 @@ pub const CRATE_NODE_ID: NodeId = NodeId(0); /// small, positive ids. pub const DUMMY_NODE_ID: NodeId = NodeId(!0); +/// A modifier on a bound, currently this is only used for `?Sized`, where the +/// modifier is `Maybe`. Negative bounds should also be handled here. +#[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)] +pub enum TraitBoundModifier { + None, + Maybe, +} + /// The AST represents all type param bounds as types. /// typeck::collect::compute_bounds matches these against /// the "special" built-in traits (see middle::lang_items) and /// detects Copy, Send and Sync. #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)] -pub enum TyParamBound { +pub enum ParamBound { TraitTyParamBound(PolyTraitRef, TraitBoundModifier), - RegionTyParamBound(Lifetime) + Outlives(Lifetime) } -impl TyParamBound { +impl ParamBound { pub fn span(&self) -> Span { match self { &TraitTyParamBound(ref t, ..) => t.span, - &RegionTyParamBound(ref l) => l.ident.span, + &Outlives(ref l) => l.ident.span, } } } -/// A modifier on a bound, currently this is only used for `?Sized`, where the -/// modifier is `Maybe`. Negative bounds should also be handled here. -#[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)] -pub enum TraitBoundModifier { - None, - Maybe, -} - -pub type TyParamBounds = Vec; +pub type ParamBounds = Vec; #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)] pub enum GenericParamKind { /// A lifetime definition, e.g. `'a: 'b+'c+'d`. Lifetime { - bounds: Vec, lifetime: Lifetime, }, Type { - bounds: TyParamBounds, default: Option>, } } @@ -316,6 +314,7 @@ pub struct GenericParam { pub ident: Ident, pub id: NodeId, pub attrs: ThinVec, + pub bounds: ParamBounds, pub kind: GenericParamKind, } @@ -384,7 +383,7 @@ pub struct WhereBoundPredicate { /// The type being bounded pub bounded_ty: P, /// Trait and lifetime bounds (`Clone+Send+'static`) - pub bounds: TyParamBounds, + pub bounds: ParamBounds, } /// A lifetime predicate. @@ -930,7 +929,7 @@ impl Expr { } } - fn to_bound(&self) -> Option { + fn to_bound(&self) -> Option { match &self.node { ExprKind::Path(None, path) => Some(TraitTyParamBound(PolyTraitRef::new(Vec::new(), path.clone(), self.span), @@ -1355,7 +1354,7 @@ pub struct TraitItem { pub enum TraitItemKind { Const(P, Option>), Method(MethodSig, Option>), - Type(TyParamBounds, Option>), + Type(ParamBounds, Option>), Macro(Mac), } @@ -1540,10 +1539,10 @@ pub enum TyKind { Path(Option, Path), /// A trait object type `Bound1 + Bound2 + Bound3` /// where `Bound` is a trait or a lifetime. - TraitObject(TyParamBounds, TraitObjectSyntax), + TraitObject(ParamBounds, TraitObjectSyntax), /// An `impl Bound1 + Bound2 + Bound3` type /// where `Bound` is a trait or a lifetime. - ImplTrait(TyParamBounds), + ImplTrait(ParamBounds), /// No-op; kept solely so that we can pretty-print faithfully Paren(P), /// Unused for now @@ -2064,11 +2063,11 @@ pub enum ItemKind { /// A Trait declaration (`trait` or `pub trait`). /// /// E.g. `trait Foo { .. }`, `trait Foo { .. }` or `auto trait Foo {}` - Trait(IsAuto, Unsafety, Generics, TyParamBounds, Vec), + Trait(IsAuto, Unsafety, Generics, ParamBounds, Vec), /// Trait alias /// /// E.g. `trait Foo = Bar + Quux;` - TraitAlias(Generics, TyParamBounds), + TraitAlias(Generics, ParamBounds), /// An implementation. /// /// E.g. `impl Foo { .. }` or `impl Trait for Foo { .. }` diff --git a/src/libsyntax/ext/build.rs b/src/libsyntax/ext/build.rs index 695ad9c233f2e..ea151ca68a8be 100644 --- a/src/libsyntax/ext/build.rs +++ b/src/libsyntax/ext/build.rs @@ -68,18 +68,18 @@ pub trait AstBuilder { span: Span, id: ast::Ident, attrs: Vec, - bounds: ast::TyParamBounds, + bounds: ast::ParamBounds, default: Option>) -> ast::GenericParam; fn trait_ref(&self, path: ast::Path) -> ast::TraitRef; fn poly_trait_ref(&self, span: Span, path: ast::Path) -> ast::PolyTraitRef; - fn typarambound(&self, path: ast::Path) -> ast::TyParamBound; + fn ty_param_bound(&self, path: ast::Path) -> ast::ParamBound; fn lifetime(&self, span: Span, ident: ast::Ident) -> ast::Lifetime; fn lifetime_def(&self, span: Span, ident: ast::Ident, attrs: Vec, - bounds: Vec) + bounds: ast::ParamBounds) -> ast::GenericParam; // statements @@ -436,14 +436,14 @@ impl<'a> AstBuilder for ExtCtxt<'a> { span: Span, ident: ast::Ident, attrs: Vec, - bounds: ast::TyParamBounds, + bounds: ast::ParamBounds, default: Option>) -> ast::GenericParam { ast::GenericParam { ident: ident.with_span_pos(span), id: ast::DUMMY_NODE_ID, attrs: attrs.into(), + bounds, kind: ast::GenericParamKind::Type { - bounds, default, } } @@ -464,7 +464,7 @@ impl<'a> AstBuilder for ExtCtxt<'a> { } } - fn typarambound(&self, path: ast::Path) -> ast::TyParamBound { + fn ty_param_bound(&self, path: ast::Path) -> ast::ParamBound { ast::TraitTyParamBound(self.poly_trait_ref(path.span, path), ast::TraitBoundModifier::None) } @@ -476,16 +476,16 @@ impl<'a> AstBuilder for ExtCtxt<'a> { span: Span, ident: ast::Ident, attrs: Vec, - bounds: Vec) + bounds: ast::ParamBounds) -> ast::GenericParam { let lifetime = self.lifetime(span, ident); ast::GenericParam { ident: lifetime.ident, id: lifetime.id, attrs: attrs.into(), + bounds, kind: ast::GenericParamKind::Lifetime { lifetime, - bounds, } } } diff --git a/src/libsyntax/fold.rs b/src/libsyntax/fold.rs index ea147186b187e..a0c69d83e8460 100644 --- a/src/libsyntax/fold.rs +++ b/src/libsyntax/fold.rs @@ -268,17 +268,16 @@ pub trait Folder : Sized { noop_fold_interpolated(nt, self) } - fn fold_opt_bounds(&mut self, b: Option) - -> Option { + fn fold_opt_bounds(&mut self, b: Option) -> Option { noop_fold_opt_bounds(b, self) } - fn fold_bounds(&mut self, b: TyParamBounds) - -> TyParamBounds { + fn fold_bounds(&mut self, b: ParamBounds) + -> ParamBounds { noop_fold_bounds(b, self) } - fn fold_ty_param_bound(&mut self, tpb: TyParamBound) -> TyParamBound { + fn fold_ty_param_bound(&mut self, tpb: ParamBound) -> ParamBound { noop_fold_ty_param_bound(tpb, self) } @@ -678,12 +677,12 @@ pub fn noop_fold_fn_decl(decl: P, fld: &mut T) -> P { }) } -pub fn noop_fold_ty_param_bound(tpb: TyParamBound, fld: &mut T) - -> TyParamBound +pub fn noop_fold_ty_param_bound(tpb: ParamBound, fld: &mut T) + -> ParamBound where T: Folder { match tpb { TraitTyParamBound(ty, modifier) => TraitTyParamBound(fld.fold_poly_trait_ref(ty), modifier), - RegionTyParamBound(lifetime) => RegionTyParamBound(noop_fold_lifetime(lifetime, fld)), + Outlives(lifetime) => Outlives(noop_fold_lifetime(lifetime, fld)), } } @@ -850,13 +849,13 @@ pub fn noop_fold_mt(MutTy {ty, mutbl}: MutTy, folder: &mut T) -> MutT } } -pub fn noop_fold_opt_bounds(b: Option, folder: &mut T) - -> Option { +pub fn noop_fold_opt_bounds(b: Option, folder: &mut T) + -> Option { b.map(|bounds| folder.fold_bounds(bounds)) } -fn noop_fold_bounds(bounds: TyParamBounds, folder: &mut T) - -> TyParamBounds { +fn noop_fold_bounds(bounds: ParamBounds, folder: &mut T) + -> ParamBounds { bounds.move_map(|bound| folder.fold_ty_param_bound(bound)) } diff --git a/src/libsyntax/parse/parser.rs b/src/libsyntax/parse/parser.rs index 203b529222d15..ce79735fff536 100644 --- a/src/libsyntax/parse/parser.rs +++ b/src/libsyntax/parse/parser.rs @@ -10,7 +10,7 @@ use rustc_target::spec::abi::{self, Abi}; use ast::{AngleBracketedArgs, ParenthesizedArgData, AttrStyle, BareFnTy}; -use ast::{RegionTyParamBound, TraitTyParamBound, TraitBoundModifier}; +use ast::{Outlives, TraitTyParamBound, TraitBoundModifier}; use ast::Unsafety; use ast::{Mod, AnonConst, Arg, Arm, Attribute, BindingMode, TraitItemKind}; use ast::Block; @@ -36,7 +36,7 @@ use ast::{VariantData, StructField}; use ast::StrStyle; use ast::SelfKind; use ast::{TraitItem, TraitRef, TraitObjectSyntax}; -use ast::{Ty, TyKind, TypeBinding, TyParamBounds}; +use ast::{Ty, TyKind, TypeBinding, ParamBounds}; use ast::{Visibility, VisibilityKind, WhereClause, CrateSugar}; use ast::{UseTree, UseTreeKind}; use ast::{BinOpKind, UnOp}; @@ -4735,7 +4735,7 @@ impl<'a> Parser<'a> { // LT_BOUND = LIFETIME (e.g. `'a`) // TY_BOUND = TY_BOUND_NOPAREN | (TY_BOUND_NOPAREN) // TY_BOUND_NOPAREN = [?] [for] SIMPLE_PATH (e.g. `?for<'a: 'b> m::Trait<'a>`) - fn parse_ty_param_bounds_common(&mut self, allow_plus: bool) -> PResult<'a, TyParamBounds> { + fn parse_ty_param_bounds_common(&mut self, allow_plus: bool) -> PResult<'a, ParamBounds> { let mut bounds = Vec::new(); loop { // This needs to be syncronized with `Token::can_begin_bound`. @@ -4752,7 +4752,7 @@ impl<'a> Parser<'a> { self.span_err(question_span, "`?` may only modify trait bounds, not lifetime bounds"); } - bounds.push(RegionTyParamBound(self.expect_lifetime())); + bounds.push(Outlives(RegionTyParamBound(self.expect_lifetime()))); if has_parens { self.expect(&token::CloseDelim(token::Paren))?; self.span_err(self.prev_span, @@ -4784,7 +4784,7 @@ impl<'a> Parser<'a> { return Ok(bounds); } - fn parse_ty_param_bounds(&mut self) -> PResult<'a, TyParamBounds> { + fn parse_ty_param_bounds(&mut self) -> PResult<'a, ParamBounds> { self.parse_ty_param_bounds_common(true) } @@ -4823,17 +4823,17 @@ impl<'a> Parser<'a> { Ok(GenericParam { ident, - attrs: preceding_attrs.into(), id: ast::DUMMY_NODE_ID, + attrs: preceding_attrs.into(), + bounds, kind: GenericParamKind::Type { - bounds, default, } }) } /// Parses the following grammar: - /// TraitItemAssocTy = Ident ["<"...">"] [":" [TyParamBounds]] ["where" ...] ["=" Ty] + /// TraitItemAssocTy = Ident ["<"...">"] [":" [ParamBounds]] ["where" ...] ["=" Ty] fn parse_trait_item_assoc_ty(&mut self) -> PResult<'a, (Ident, TraitItemKind, ast::Generics)> { let ident = self.parse_ident()?; @@ -4868,7 +4868,9 @@ impl<'a> Parser<'a> { let lifetime = self.expect_lifetime(); // Parse lifetime parameter. let bounds = if self.eat(&token::Colon) { - self.parse_lt_param_bounds() + self.parse_lt_param_bounds().iter() + .map(|bound| ast::ParamBound::Outlives(*bound)) + .collect() } else { Vec::new() }; @@ -4876,9 +4878,9 @@ impl<'a> Parser<'a> { ident: lifetime.ident, id: lifetime.id, attrs: attrs.into(), + bounds, kind: ast::GenericParamKind::Lifetime { lifetime, - bounds, } }); if seen_ty_param { diff --git a/src/libsyntax/print/pprust.rs b/src/libsyntax/print/pprust.rs index 84a4a51b71600..c8d139c7de904 100644 --- a/src/libsyntax/print/pprust.rs +++ b/src/libsyntax/print/pprust.rs @@ -12,7 +12,7 @@ pub use self::AnnNode::*; use rustc_target::spec::abi::{self, Abi}; use ast::{self, BlockCheckMode, PatKind, RangeEnd, RangeSyntax}; -use ast::{SelfKind, RegionTyParamBound, TraitTyParamBound, TraitBoundModifier}; +use ast::{SelfKind, Outlives, TraitTyParamBound, TraitBoundModifier}; use ast::{Attribute, MacDelimiter, GenericArg}; use util::parser::{self, AssocOp, Fixity}; use attr; @@ -292,7 +292,7 @@ pub fn ty_to_string(ty: &ast::Ty) -> String { to_string(|s| s.print_type(ty)) } -pub fn bounds_to_string(bounds: &[ast::TyParamBound]) -> String { +pub fn bounds_to_string(bounds: &[ast::ParamBound]) -> String { to_string(|s| s.print_bounds("", bounds)) } @@ -1178,7 +1178,7 @@ impl<'a> State<'a> { fn print_associated_type(&mut self, ident: ast::Ident, - bounds: Option<&ast::TyParamBounds>, + bounds: Option<&ast::ParamBounds>, ty: Option<&ast::Ty>) -> io::Result<()> { self.word_space("type")?; @@ -2811,7 +2811,7 @@ impl<'a> State<'a> { pub fn print_bounds(&mut self, prefix: &str, - bounds: &[ast::TyParamBound]) + bounds: &[ast::ParamBound]) -> io::Result<()> { if !bounds.is_empty() { self.s.word(prefix)?; @@ -2833,7 +2833,7 @@ impl<'a> State<'a> { } self.print_poly_trait_ref(tref)?; } - RegionTyParamBound(lt) => { + Outlives(lt) => { self.print_lifetime(lt)?; } } @@ -2879,14 +2879,19 @@ impl<'a> State<'a> { self.commasep(Inconsistent, &generic_params, |s, param| { match param.kind { - ast::GenericParamKind::Lifetime { ref bounds, ref lifetime } => { + ast::GenericParamKind::Lifetime { ref lifetime } => { s.print_outer_attributes_inline(¶m.attrs)?; - s.print_lifetime_bounds(lifetime, bounds) + s.print_lifetime_bounds(lifetime, ¶m.bounds.iter().map(|bound| { + match bound { + ast::ParamBound::Outlives(lt) => *lt, + _ => panic!(), + } + }).collect::>().as_slice()) }, - ast::GenericParamKind::Type { ref bounds, ref default } => { + ast::GenericParamKind::Type { ref default } => { s.print_outer_attributes_inline(¶m.attrs)?; s.print_ident(param.ident)?; - s.print_bounds(":", bounds)?; + s.print_bounds(":", ¶m.bounds)?; match default { Some(ref default) => { s.s.space()?; diff --git a/src/libsyntax/util/node_count.rs b/src/libsyntax/util/node_count.rs index 95ae9f9bcf802..485775765abf8 100644 --- a/src/libsyntax/util/node_count.rs +++ b/src/libsyntax/util/node_count.rs @@ -95,7 +95,7 @@ impl<'ast> Visitor<'ast> for NodeCounter { self.count += 1; walk_trait_ref(self, t) } - fn visit_ty_param_bound(&mut self, bounds: &TyParamBound) { + fn visit_ty_param_bound(&mut self, bounds: &ParamBound) { self.count += 1; walk_ty_param_bound(self, bounds) } diff --git a/src/libsyntax/visit.rs b/src/libsyntax/visit.rs index e12369a522da7..4e0c417d4fba6 100644 --- a/src/libsyntax/visit.rs +++ b/src/libsyntax/visit.rs @@ -86,7 +86,7 @@ pub trait Visitor<'ast>: Sized { fn visit_trait_item(&mut self, ti: &'ast TraitItem) { walk_trait_item(self, ti) } fn visit_impl_item(&mut self, ii: &'ast ImplItem) { walk_impl_item(self, ii) } fn visit_trait_ref(&mut self, t: &'ast TraitRef) { walk_trait_ref(self, t) } - fn visit_ty_param_bound(&mut self, bounds: &'ast TyParamBound) { + fn visit_ty_param_bound(&mut self, bounds: &'ast ParamBound) { walk_ty_param_bound(self, bounds) } fn visit_poly_trait_ref(&mut self, t: &'ast PolyTraitRef, m: &'ast TraitBoundModifier) { @@ -479,31 +479,30 @@ pub fn walk_global_asm<'a, V: Visitor<'a>>(_: &mut V, _: &'a GlobalAsm) { // Empty! } -pub fn walk_ty_param_bound<'a, V: Visitor<'a>>(visitor: &mut V, bound: &'a TyParamBound) { +pub fn walk_ty_param_bound<'a, V: Visitor<'a>>(visitor: &mut V, bound: &'a ParamBound) { match *bound { TraitTyParamBound(ref typ, ref modifier) => { visitor.visit_poly_trait_ref(typ, modifier); } - RegionTyParamBound(ref lifetime) => { + Outlives(ref lifetime) => { visitor.visit_lifetime(lifetime); } } } pub fn walk_generic_param<'a, V: Visitor<'a>>(visitor: &mut V, param: &'a GenericParam) { + visitor.visit_ident(param.ident); match param.kind { GenericParamKind::Lifetime { ref bounds, ref lifetime } => { - visitor.visit_ident(param.ident); walk_list!(visitor, visit_lifetime, bounds); - walk_list!(visitor, visit_attribute, param.attrs.iter()); } GenericParamKind::Type { ref bounds, ref default } => { visitor.visit_ident(t.ident); walk_list!(visitor, visit_ty_param_bound, bounds); walk_list!(visitor, visit_ty, default); - walk_list!(visitor, visit_attribute, param.attrs.iter()); } } + walk_list!(visitor, visit_attribute, param.attrs.iter()); } pub fn walk_generics<'a, V: Visitor<'a>>(visitor: &mut V, generics: &'a Generics) { diff --git a/src/libsyntax_ext/deriving/generic/mod.rs b/src/libsyntax_ext/deriving/generic/mod.rs index 1024d445cdb96..a7d8156f4a043 100644 --- a/src/libsyntax_ext/deriving/generic/mod.rs +++ b/src/libsyntax_ext/deriving/generic/mod.rs @@ -551,22 +551,21 @@ impl<'a> TraitDef<'a> { // Create the generic parameters params.extend(generics.params.iter().map(|param| match param.kind { GenericParamKind::Lifetime { .. } => param.clone(), - GenericParamKind::Type { bounds: ref ty_bounds, .. } => { + GenericParamKind::Type { .. } => { // I don't think this can be moved out of the loop, since - // a TyParamBound requires an ast id + // a ParamBound requires an ast id let mut bounds: Vec<_> = // extra restrictions on the generics parameters to the // type being derived upon self.additional_bounds.iter().map(|p| { - cx.typarambound(p.to_path(cx, self.span, - type_ident, generics)) + cx.ty_param_bound(p.to_path(cx, self.span, type_ident, generics)) }).collect(); // require the current trait - bounds.push(cx.typarambound(trait_path.clone())); + bounds.push(cx.ty_param_bound(trait_path.clone())); // also add in any bounds from the declaration - for declared_bound in ty_bounds { + for declared_bound in ¶m.bounds { bounds.push((*declared_bound).clone()); } @@ -635,12 +634,12 @@ impl<'a> TraitDef<'a> { let mut bounds: Vec<_> = self.additional_bounds .iter() .map(|p| { - cx.typarambound(p.to_path(cx, self.span, type_ident, generics)) + cx.ty_param_bound(p.to_path(cx, self.span, type_ident, generics)) }) .collect(); // require the current trait - bounds.push(cx.typarambound(trait_path.clone())); + bounds.push(cx.ty_param_bound(trait_path.clone())); let predicate = ast::WhereBoundPredicate { span: self.span, diff --git a/src/libsyntax_ext/deriving/generic/ty.rs b/src/libsyntax_ext/deriving/generic/ty.rs index 127ed62b8c59d..327a35d39b327 100644 --- a/src/libsyntax_ext/deriving/generic/ty.rs +++ b/src/libsyntax_ext/deriving/generic/ty.rs @@ -219,7 +219,7 @@ fn mk_ty_param(cx: &ExtCtxt, let bounds = bounds.iter() .map(|b| { let path = b.to_path(cx, span, self_ident, self_generics); - cx.typarambound(path) + cx.ty_param_bound(path) }) .collect(); cx.typaram(span, cx.ident_of(name), attrs.to_owned(), bounds, None) @@ -261,9 +261,8 @@ impl<'a> LifetimeBounds<'a> { .iter() .map(|&(lt, ref bounds)| { let bounds = bounds.iter() - .map(|b| cx.lifetime(span, Ident::from_str(b))) - .collect(); - cx.lifetime_def(span, Ident::from_str(lt), vec![], bounds) + .map(|b| ast::ParamBound::Outlives(cx.lifetime(span, Ident::from_str(b)))); + cx.lifetime_def(span, Ident::from_str(lt), vec![], bounds.collect()) }) .chain(self.bounds .iter() From 80dbe58efc7152cc9925012de0e568f36a9893a8 Mon Sep 17 00:00:00 2001 From: varkor Date: Mon, 28 May 2018 15:23:16 +0100 Subject: [PATCH 21/41] Use ParamBounds in WhereRegionPredicate --- src/librustc/hir/intravisit.rs | 18 ++++++------ src/librustc/hir/lowering.rs | 7 ++--- src/librustc/hir/mod.rs | 2 +- src/librustc/hir/print.rs | 7 ++++- src/librustc/middle/resolve_lifetime.rs | 16 +++++----- src/librustc_passes/hir_stats.rs | 8 ++--- src/librustc_resolve/lib.rs | 6 ++-- src/librustc_typeck/collect.rs | 7 ++++- src/librustdoc/clean/auto_trait.rs | 19 +++--------- src/librustdoc/clean/inline.rs | 2 +- src/librustdoc/clean/mod.rs | 39 ++++++++++--------------- src/librustdoc/clean/simplify.rs | 2 +- src/librustdoc/html/format.rs | 2 +- src/libsyntax/ast.rs | 2 +- src/libsyntax/parse/parser.rs | 10 +++---- src/libsyntax/print/pprust.rs | 32 ++++++++++---------- src/libsyntax/util/node_count.rs | 4 +-- src/libsyntax/visit.rs | 18 ++++++------ 18 files changed, 92 insertions(+), 109 deletions(-) diff --git a/src/librustc/hir/intravisit.rs b/src/librustc/hir/intravisit.rs index d5c9d964eb2a5..a550f60fb4b79 100644 --- a/src/librustc/hir/intravisit.rs +++ b/src/librustc/hir/intravisit.rs @@ -314,8 +314,8 @@ pub trait Visitor<'v> : Sized { fn visit_trait_ref(&mut self, t: &'v TraitRef) { walk_trait_ref(self, t) } - fn visit_ty_param_bound(&mut self, bounds: &'v ParamBound) { - walk_ty_param_bound(self, bounds) + fn visit_param_bound(&mut self, bounds: &'v ParamBound) { + walk_param_bound(self, bounds) } fn visit_poly_trait_ref(&mut self, t: &'v PolyTraitRef, m: TraitBoundModifier) { walk_poly_trait_ref(self, t, m) @@ -537,13 +537,13 @@ pub fn walk_item<'v, V: Visitor<'v>>(visitor: &mut V, item: &'v Item) { ItemTrait(.., ref generics, ref bounds, ref trait_item_refs) => { visitor.visit_id(item.id); visitor.visit_generics(generics); - walk_list!(visitor, visit_ty_param_bound, bounds); + walk_list!(visitor, visit_param_bound, bounds); walk_list!(visitor, visit_trait_item_ref, trait_item_refs); } ItemTraitAlias(ref generics, ref bounds) => { visitor.visit_id(item.id); visitor.visit_generics(generics); - walk_list!(visitor, visit_ty_param_bound, bounds); + walk_list!(visitor, visit_param_bound, bounds); } } walk_list!(visitor, visit_attribute, &item.attrs); @@ -731,7 +731,7 @@ pub fn walk_foreign_item<'v, V: Visitor<'v>>(visitor: &mut V, foreign_item: &'v walk_list!(visitor, visit_attribute, &foreign_item.attrs); } -pub fn walk_ty_param_bound<'v, V: Visitor<'v>>(visitor: &mut V, bound: &'v ParamBound) { +pub fn walk_param_bound<'v, V: Visitor<'v>>(visitor: &mut V, bound: &'v ParamBound) { match *bound { TraitTyParamBound(ref typ, modifier) => { visitor.visit_poly_trait_ref(typ, modifier); @@ -763,7 +763,7 @@ pub fn walk_generic_param<'v, V: Visitor<'v>>(visitor: &mut V, param: &'v Generi walk_list!(visitor, visit_attribute, attrs.iter()); } } - walk_list!(visitor, visit_ty_param_bound, ¶m.bounds); + walk_list!(visitor, visit_param_bound, ¶m.bounds); } pub fn walk_generics<'v, V: Visitor<'v>>(visitor: &mut V, generics: &'v Generics) { @@ -782,14 +782,14 @@ pub fn walk_where_predicate<'v, V: Visitor<'v>>( ref bound_generic_params, ..}) => { visitor.visit_ty(bounded_ty); - walk_list!(visitor, visit_ty_param_bound, bounds); + walk_list!(visitor, visit_param_bound, bounds); walk_list!(visitor, visit_generic_param, bound_generic_params); } &WherePredicate::RegionPredicate(WhereRegionPredicate{ref lifetime, ref bounds, ..}) => { visitor.visit_lifetime(lifetime); - walk_list!(visitor, visit_lifetime, bounds); + walk_list!(visitor, visit_param_bound, bounds); } &WherePredicate::EqPredicate(WhereEqPredicate{id, ref lhs_ty, @@ -866,7 +866,7 @@ pub fn walk_trait_item<'v, V: Visitor<'v>>(visitor: &mut V, trait_item: &'v Trai } TraitItemKind::Type(ref bounds, ref default) => { visitor.visit_id(trait_item.id); - walk_list!(visitor, visit_ty_param_bound, bounds); + walk_list!(visitor, visit_param_bound, bounds); walk_list!(visitor, visit_ty, default); } } diff --git a/src/librustc/hir/lowering.rs b/src/librustc/hir/lowering.rs index 494e6e1ba33ba..fed4f150075b5 100644 --- a/src/librustc/hir/lowering.rs +++ b/src/librustc/hir/lowering.rs @@ -1447,7 +1447,7 @@ impl<'a> LoweringContext<'a> { }; for bound in bounds { - hir::intravisit::walk_ty_param_bound(&mut lifetime_collector, &bound); + hir::intravisit::walk_param_bound(&mut lifetime_collector, &bound); } ( @@ -2125,10 +2125,7 @@ impl<'a> LoweringContext<'a> { }) => hir::WherePredicate::RegionPredicate(hir::WhereRegionPredicate { span, lifetime: self.lower_lifetime(lifetime), - bounds: bounds - .iter() - .map(|bound| self.lower_lifetime(bound)) - .collect(), + bounds: self.lower_param_bounds(bounds, ImplTraitContext::Disallowed), }), WherePredicate::EqPredicate(WhereEqPredicate { id, diff --git a/src/librustc/hir/mod.rs b/src/librustc/hir/mod.rs index 8253a34f3106a..8249b306a0c3b 100644 --- a/src/librustc/hir/mod.rs +++ b/src/librustc/hir/mod.rs @@ -596,7 +596,7 @@ pub struct WhereBoundPredicate { pub struct WhereRegionPredicate { pub span: Span, pub lifetime: Lifetime, - pub bounds: HirVec, + pub bounds: ParamBounds, } /// An equality predicate (unsupported), e.g. `T=int` diff --git a/src/librustc/hir/print.rs b/src/librustc/hir/print.rs index 4058db17f2fa0..10cecdb2d47aa 100644 --- a/src/librustc/hir/print.rs +++ b/src/librustc/hir/print.rs @@ -2180,7 +2180,12 @@ impl<'a> State<'a> { self.s.word(":")?; for (i, bound) in bounds.iter().enumerate() { - self.print_lifetime(bound)?; + match bound { + hir::ParamBound::Outlives(lt) => { + self.print_lifetime(lt)?; + } + _ => bug!(), + } if i != 0 { self.s.word(":")?; diff --git a/src/librustc/middle/resolve_lifetime.rs b/src/librustc/middle/resolve_lifetime.rs index 2963227c2117e..fc160b35ae494 100644 --- a/src/librustc/middle/resolve_lifetime.rs +++ b/src/librustc/middle/resolve_lifetime.rs @@ -726,7 +726,7 @@ impl<'a, 'tcx> Visitor<'tcx> for LifetimeContext<'a, 'tcx> { this.with(scope, |_old_scope, this| { this.visit_generics(generics); for bound in bounds { - this.visit_ty_param_bound(bound); + this.visit_param_bound(bound); } }); }); @@ -741,7 +741,7 @@ impl<'a, 'tcx> Visitor<'tcx> for LifetimeContext<'a, 'tcx> { self.with(scope, |_old_scope, this| { this.visit_generics(generics); for bound in bounds { - this.visit_ty_param_bound(bound); + this.visit_param_bound(bound); } }); } @@ -786,7 +786,7 @@ impl<'a, 'tcx> Visitor<'tcx> for LifetimeContext<'a, 'tcx> { self.with(scope, |_old_scope, this| { this.visit_generics(generics); for bound in bounds { - this.visit_ty_param_bound(bound); + this.visit_param_bound(bound); } if let Some(ty) = ty { this.visit_ty(ty); @@ -882,7 +882,7 @@ impl<'a, 'tcx> Visitor<'tcx> for LifetimeContext<'a, 'tcx> { match param.kind { GenericParamKind::Lifetime { .. } => {} GenericParamKind::Type { ref default, .. } => { - walk_list!(self, visit_ty_param_bound, ¶m.bounds); + walk_list!(self, visit_param_bound, ¶m.bounds); if let Some(ref ty) = default { self.visit_ty(&ty); } @@ -917,13 +917,13 @@ impl<'a, 'tcx> Visitor<'tcx> for LifetimeContext<'a, 'tcx> { let result = self.with(scope, |old_scope, this| { this.check_lifetime_params(old_scope, &bound_generic_params); this.visit_ty(&bounded_ty); - walk_list!(this, visit_ty_param_bound, bounds); + walk_list!(this, visit_param_bound, bounds); }); self.trait_ref_hack = false; result } else { self.visit_ty(&bounded_ty); - walk_list!(self, visit_ty_param_bound, bounds); + walk_list!(self, visit_param_bound, bounds); } } &hir::WherePredicate::RegionPredicate(hir::WhereRegionPredicate { @@ -932,9 +932,7 @@ impl<'a, 'tcx> Visitor<'tcx> for LifetimeContext<'a, 'tcx> { .. }) => { self.visit_lifetime(lifetime); - for bound in bounds { - self.visit_lifetime(bound); - } + walk_list!(self, visit_param_bound, bounds); } &hir::WherePredicate::EqPredicate(hir::WhereEqPredicate { ref lhs_ty, diff --git a/src/librustc_passes/hir_stats.rs b/src/librustc_passes/hir_stats.rs index c58b6a96ee70e..879adebf7ea95 100644 --- a/src/librustc_passes/hir_stats.rs +++ b/src/librustc_passes/hir_stats.rs @@ -203,9 +203,9 @@ impl<'v> hir_visit::Visitor<'v> for StatCollector<'v> { hir_visit::walk_impl_item(self, ii) } - fn visit_ty_param_bound(&mut self, bounds: &'v hir::ParamBound) { + fn visit_param_bound(&mut self, bounds: &'v hir::ParamBound) { self.record("ParamBound", Id::None, bounds); - hir_visit::walk_ty_param_bound(self, bounds) + hir_visit::walk_param_bound(self, bounds) } fn visit_struct_field(&mut self, s: &'v hir::StructField) { @@ -322,9 +322,9 @@ impl<'v> ast_visit::Visitor<'v> for StatCollector<'v> { ast_visit::walk_impl_item(self, ii) } - fn visit_ty_param_bound(&mut self, bounds: &'v ast::ParamBound) { + fn visit_param_bound(&mut self, bounds: &'v ast::ParamBound) { self.record("ParamBound", Id::None, bounds); - ast_visit::walk_ty_param_bound(self, bounds) + ast_visit::walk_param_bound(self, bounds) } fn visit_struct_field(&mut self, s: &'v ast::StructField) { diff --git a/src/librustc_resolve/lib.rs b/src/librustc_resolve/lib.rs index b51ef90449571..731c6e2ef8295 100644 --- a/src/librustc_resolve/lib.rs +++ b/src/librustc_resolve/lib.rs @@ -815,7 +815,7 @@ impl<'a, 'tcx> Visitor<'tcx> for Resolver<'a> { GenericParamKind::Lifetime { .. } => self.visit_generic_param(param), GenericParamKind::Type { ref default, .. } => { for bound in ¶m.bounds { - self.visit_ty_param_bound(bound); + self.visit_param_bound(bound); } if let Some(ref ty) = default { @@ -2076,7 +2076,7 @@ impl<'a> Resolver<'a> { let local_def_id = this.definitions.local_def_id(item.id); this.with_self_rib(Def::SelfTy(Some(local_def_id), None), |this| { this.visit_generics(generics); - walk_list!(this, visit_ty_param_bound, bounds); + walk_list!(this, visit_param_bound, bounds); for trait_item in trait_items { this.check_proc_macro_attrs(&trait_item.attrs); @@ -2119,7 +2119,7 @@ impl<'a> Resolver<'a> { let local_def_id = this.definitions.local_def_id(item.id); this.with_self_rib(Def::SelfTy(Some(local_def_id), None), |this| { this.visit_generics(generics); - walk_list!(this, visit_ty_param_bound, bounds); + walk_list!(this, visit_param_bound, bounds); }); }); } diff --git a/src/librustc_typeck/collect.rs b/src/librustc_typeck/collect.rs index f95f6a26f0b92..c2b52e0de7522 100644 --- a/src/librustc_typeck/collect.rs +++ b/src/librustc_typeck/collect.rs @@ -1512,7 +1512,12 @@ pub fn explicit_predicates_of<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, &hir::WherePredicate::RegionPredicate(ref region_pred) => { let r1 = AstConv::ast_region_to_region(&icx, ®ion_pred.lifetime, None); for bound in ®ion_pred.bounds { - let r2 = AstConv::ast_region_to_region(&icx, bound, None); + let r2 = match bound { + hir::ParamBound::Outlives(lt) => { + AstConv::ast_region_to_region(&icx, lt, None) + } + _ => bug!(), + }; let pred = ty::Binder::bind(ty::OutlivesPredicate(r1, r2)); predicates.push(ty::Predicate::RegionOutlives(pred)) } diff --git a/src/librustdoc/clean/auto_trait.rs b/src/librustdoc/clean/auto_trait.rs index 2686ad96c6ece..9671007a06b9f 100644 --- a/src/librustdoc/clean/auto_trait.rs +++ b/src/librustdoc/clean/auto_trait.rs @@ -486,11 +486,8 @@ impl<'a, 'tcx, 'rcx> AutoTraitFinder<'a, 'tcx, 'rcx> { .iter() .flat_map(|(name, lifetime)| { let empty = Vec::new(); - let bounds: FxHashSet = finished - .get(name) - .unwrap_or(&empty) - .iter() - .map(|region| self.get_lifetime(region, names_map)) + let bounds: FxHashSet = finished.get(name).unwrap_or(&empty).iter() + .map(|region| ParamBound::Outlives(self.get_lifetime(region, names_map))) .collect(); if bounds.is_empty() { @@ -538,7 +535,7 @@ impl<'a, 'tcx, 'rcx> AutoTraitFinder<'a, 'tcx, 'rcx> { &self, ty_to_bounds: FxHashMap>, ty_to_fn: FxHashMap, Option)>, - lifetime_to_bounds: FxHashMap>, + lifetime_to_bounds: FxHashMap>, ) -> Vec { ty_to_bounds .into_iter() @@ -615,7 +612,7 @@ impl<'a, 'tcx, 'rcx> AutoTraitFinder<'a, 'tcx, 'rcx> { .filter(|&(_, ref bounds)| !bounds.is_empty()) .map(|(lifetime, bounds)| { let mut bounds_vec = bounds.into_iter().collect(); - self.sort_where_lifetimes(&mut bounds_vec); + self.sort_where_bounds(&mut bounds_vec); WherePredicate::RegionPredicate { lifetime, bounds: bounds_vec, @@ -918,14 +915,6 @@ impl<'a, 'tcx, 'rcx> AutoTraitFinder<'a, 'tcx, 'rcx> { self.unstable_debug_sort(&mut bounds); } - #[inline] - fn sort_where_lifetimes(&self, mut bounds: &mut Vec) { - // We should never have identical bounds - and if we do, - // they're visually identical as well. Therefore, using - // an unstable sort is fine. - self.unstable_debug_sort(&mut bounds); - } - // This might look horrendously hacky, but it's actually not that bad. // // For performance reasons, we use several different FxHashMaps diff --git a/src/librustdoc/clean/inline.rs b/src/librustdoc/clean/inline.rs index afe959aaec5a5..c85178961c16a 100644 --- a/src/librustdoc/clean/inline.rs +++ b/src/librustdoc/clean/inline.rs @@ -375,7 +375,7 @@ pub fn build_impl(cx: &DocContext, did: DefId, ret: &mut Vec) { let trait_ = associated_trait.clean(cx).map(|bound| { match bound { clean::TraitBound(polyt, _) => polyt.trait_, - clean::RegionBound(..) => unreachable!(), + clean::Outlives(..) => unreachable!(), } }); if trait_.def_id() == tcx.lang_items().deref_trait() { diff --git a/src/librustdoc/clean/mod.rs b/src/librustdoc/clean/mod.rs index 4cc8de91baa6d..2f48267579a61 100644 --- a/src/librustdoc/clean/mod.rs +++ b/src/librustdoc/clean/mod.rs @@ -1459,8 +1459,8 @@ impl Clean for [ast::Attribute] { #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Eq, Debug, Hash)] pub enum ParamBound { - RegionBound(Lifetime), - TraitBound(PolyTrait, hir::TraitBoundModifier) + TraitBound(PolyTrait, hir::TraitBoundModifier), + Outlives(Lifetime), } impl ParamBound { @@ -1510,7 +1510,7 @@ impl ParamBound { impl Clean for hir::ParamBound { fn clean(&self, cx: &DocContext) -> ParamBound { match *self { - hir::Outlives(lt) => RegionBound(lt.clean(cx)), + hir::Outlives(lt) => Outlives(lt.clean(cx)), hir::TraitTyParamBound(ref t, modifier) => TraitBound(t.clean(cx), modifier), } } @@ -1624,7 +1624,7 @@ impl<'tcx> Clean>> for Substs<'tcx> { fn clean(&self, cx: &DocContext) -> Option> { let mut v = Vec::new(); v.extend(self.regions().filter_map(|r| r.clean(cx)) - .map(RegionBound)); + .map(Outlives)); v.extend(self.types().map(|t| TraitBound(PolyTrait { trait_: t.clean(cx), generic_params: Vec::new(), @@ -1721,7 +1721,7 @@ impl Clean> for ty::RegionKind { #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Eq, Debug, Hash)] pub enum WherePredicate { BoundPredicate { ty: Type, bounds: Vec }, - RegionPredicate { lifetime: Lifetime, bounds: Vec}, + RegionPredicate { lifetime: Lifetime, bounds: Vec }, EqPredicate { lhs: Type, rhs: Type }, } @@ -1791,7 +1791,7 @@ impl<'tcx> Clean for ty::OutlivesPredicate, ty: let ty::OutlivesPredicate(ref a, ref b) = *self; WherePredicate::RegionPredicate { lifetime: a.clean(cx).unwrap(), - bounds: vec![b.clean(cx).unwrap()] + bounds: vec![ParamBound::Outlives(b.clean(cx).unwrap())] } } } @@ -1802,7 +1802,7 @@ impl<'tcx> Clean for ty::OutlivesPredicate, ty::Region< WherePredicate::BoundPredicate { ty: ty.clean(cx), - bounds: vec![ParamBound::RegionBound(lt.clean(cx).unwrap())] + bounds: vec![ParamBound::Outlives(lt.clean(cx).unwrap())] } } } @@ -1820,9 +1820,7 @@ impl<'tcx> Clean for ty::ProjectionTy<'tcx> { fn clean(&self, cx: &DocContext) -> Type { let trait_ = match self.trait_ref(cx.tcx).clean(cx) { ParamBound::TraitBound(t, _) => t.trait_, - ParamBound::RegionBound(_) => { - panic!("cleaning a trait got a region") - } + ParamBound::Outlives(_) => panic!("cleaning a trait got a lifetime"), }; Type::QPath { name: cx.tcx.associated_item(self.item_def_id).name.clean(cx), @@ -2979,18 +2977,13 @@ impl Clean for hir::Ty { TyTraitObject(ref bounds, ref lifetime) => { match bounds[0].clean(cx).trait_ { ResolvedPath { path, typarams: None, did, is_generic } => { - let mut bounds: Vec<_> = bounds[1..].iter().map(|bound| { + let mut bounds: Vec = bounds[1..].iter().map(|bound| { TraitBound(bound.clean(cx), hir::TraitBoundModifier::None) }).collect(); if !lifetime.is_elided() { - bounds.push(RegionBound(lifetime.clean(cx))); - } - ResolvedPath { - path, - typarams: Some(bounds), - did, - is_generic, + bounds.push(self::Outlives(lifetime.clean(cx))); } + ResolvedPath { path, typarams: Some(bounds), did, is_generic, } } _ => Infer // shouldn't happen } @@ -3087,7 +3080,7 @@ impl<'tcx> Clean for Ty<'tcx> { inline::record_extern_fqn(cx, did, TypeKind::Trait); let mut typarams = vec![]; - reg.clean(cx).map(|b| typarams.push(RegionBound(b))); + reg.clean(cx).map(|b| typarams.push(Outlives(b))); for did in obj.auto_traits() { let empty = cx.tcx.intern_substs(&[]); let path = external_path(cx, &cx.tcx.item_name(did).as_str(), @@ -3144,7 +3137,7 @@ impl<'tcx> Clean for Ty<'tcx> { tr } else if let ty::Predicate::TypeOutlives(pred) = *predicate { // these should turn up at the end - pred.skip_binder().1.clean(cx).map(|r| regions.push(RegionBound(r))); + pred.skip_binder().1.clean(cx).map(|r| regions.push(Outlives(r))); return None; } else { return None; @@ -4455,8 +4448,8 @@ struct RegionDeps<'tcx> { #[derive(Eq, PartialEq, Hash, Debug)] enum SimpleBound { - RegionBound(Lifetime), - TraitBound(Vec, Vec, Vec, hir::TraitBoundModifier) + TraitBound(Vec, Vec, Vec, hir::TraitBoundModifier), + Outlives(Lifetime), } enum AutoTraitResult { @@ -4477,7 +4470,7 @@ impl AutoTraitResult { impl From for SimpleBound { fn from(bound: ParamBound) -> Self { match bound.clone() { - ParamBound::RegionBound(l) => SimpleBound::RegionBound(l), + ParamBound::Outlives(l) => SimpleBound::Outlives(l), ParamBound::TraitBound(t, mod_) => match t.trait_ { Type::ResolvedPath { path, typarams, .. } => { SimpleBound::TraitBound(path.segments, diff --git a/src/librustdoc/clean/simplify.rs b/src/librustdoc/clean/simplify.rs index 81ad2a5bf51a6..c7477645d6a2e 100644 --- a/src/librustdoc/clean/simplify.rs +++ b/src/librustdoc/clean/simplify.rs @@ -84,7 +84,7 @@ pub fn where_clauses(cx: &DocContext, clauses: Vec) -> Vec { !bounds.iter_mut().any(|b| { let trait_ref = match *b { clean::TraitBound(ref mut tr, _) => tr, - clean::RegionBound(..) => return false, + clean::Outlives(..) => return false, }; let (did, path) = match trait_ref.trait_ { clean::ResolvedPath { did, ref mut path, ..} => (did, path), diff --git a/src/librustdoc/html/format.rs b/src/librustdoc/html/format.rs index 4174f656995fe..bd9194a8669f2 100644 --- a/src/librustdoc/html/format.rs +++ b/src/librustdoc/html/format.rs @@ -270,7 +270,7 @@ impl fmt::Display for clean::PolyTrait { impl fmt::Display for clean::ParamBound { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { - clean::RegionBound(ref lt) => { + clean::Outlives(ref lt) => { write!(f, "{}", *lt) } clean::TraitBound(ref ty, modifier) => { diff --git a/src/libsyntax/ast.rs b/src/libsyntax/ast.rs index b082cde5df7ed..67679468fe42c 100644 --- a/src/libsyntax/ast.rs +++ b/src/libsyntax/ast.rs @@ -393,7 +393,7 @@ pub struct WhereBoundPredicate { pub struct WhereRegionPredicate { pub span: Span, pub lifetime: Lifetime, - pub bounds: Vec, + pub bounds: ParamBounds, } /// An equality predicate (unsupported). diff --git a/src/libsyntax/parse/parser.rs b/src/libsyntax/parse/parser.rs index ce79735fff536..66e485120659c 100644 --- a/src/libsyntax/parse/parser.rs +++ b/src/libsyntax/parse/parser.rs @@ -1610,7 +1610,7 @@ impl<'a> Parser<'a> { s.print_mutability(mut_ty.mutbl)?; s.popen()?; s.print_type(&mut_ty.ty)?; - s.print_bounds(" +", &bounds)?; + s.print_type_bounds(" +", &bounds)?; s.pclose() }); err.span_suggestion_with_applicability( @@ -4790,10 +4790,10 @@ impl<'a> Parser<'a> { // Parse bounds of a lifetime parameter `BOUND + BOUND + BOUND`, possibly with trailing `+`. // BOUND = LT_BOUND (e.g. `'a`) - fn parse_lt_param_bounds(&mut self) -> Vec { + fn parse_lt_param_bounds(&mut self) -> ParamBounds { let mut lifetimes = Vec::new(); while self.check_lifetime() { - lifetimes.push(self.expect_lifetime()); + lifetimes.push(ast::ParamBound::Outlives(self.expect_lifetime())); if !self.eat_plus() { break @@ -4868,9 +4868,7 @@ impl<'a> Parser<'a> { let lifetime = self.expect_lifetime(); // Parse lifetime parameter. let bounds = if self.eat(&token::Colon) { - self.parse_lt_param_bounds().iter() - .map(|bound| ast::ParamBound::Outlives(*bound)) - .collect() + self.parse_lt_param_bounds() } else { Vec::new() }; diff --git a/src/libsyntax/print/pprust.rs b/src/libsyntax/print/pprust.rs index c8d139c7de904..c672b01fb2725 100644 --- a/src/libsyntax/print/pprust.rs +++ b/src/libsyntax/print/pprust.rs @@ -293,7 +293,7 @@ pub fn ty_to_string(ty: &ast::Ty) -> String { } pub fn bounds_to_string(bounds: &[ast::ParamBound]) -> String { - to_string(|s| s.print_bounds("", bounds)) + to_string(|s| s.print_type_bounds("", bounds)) } pub fn pat_to_string(pat: &ast::Pat) -> String { @@ -1078,10 +1078,10 @@ impl<'a> State<'a> { } ast::TyKind::TraitObject(ref bounds, syntax) => { let prefix = if syntax == ast::TraitObjectSyntax::Dyn { "dyn" } else { "" }; - self.print_bounds(prefix, &bounds[..])?; + self.print_type_bounds(prefix, &bounds[..])?; } ast::TyKind::ImplTrait(ref bounds) => { - self.print_bounds("impl", &bounds[..])?; + self.print_type_bounds("impl", &bounds[..])?; } ast::TyKind::Array(ref ty, ref length) => { self.s.word("[")?; @@ -1184,7 +1184,7 @@ impl<'a> State<'a> { self.word_space("type")?; self.print_ident(ident)?; if let Some(bounds) = bounds { - self.print_bounds(":", bounds)?; + self.print_type_bounds(":", bounds)?; } if let Some(ty) = ty { self.s.space()?; @@ -1373,7 +1373,7 @@ impl<'a> State<'a> { real_bounds.push(b.clone()); } } - self.print_bounds(":", &real_bounds[..])?; + self.print_type_bounds(":", &real_bounds[..])?; self.print_where_clause(&generics.where_clause)?; self.s.word(" ")?; self.bopen()?; @@ -1400,7 +1400,7 @@ impl<'a> State<'a> { } } self.nbsp()?; - self.print_bounds("=", &real_bounds[..])?; + self.print_type_bounds("=", &real_bounds[..])?; self.print_where_clause(&generics.where_clause)?; self.s.word(";")?; } @@ -2809,7 +2809,7 @@ impl<'a> State<'a> { } } - pub fn print_bounds(&mut self, + pub fn print_type_bounds(&mut self, prefix: &str, bounds: &[ast::ParamBound]) -> io::Result<()> { @@ -2851,7 +2851,7 @@ impl<'a> State<'a> { pub fn print_lifetime_bounds(&mut self, lifetime: &ast::Lifetime, - bounds: &[ast::Lifetime]) + bounds: &ast::ParamBounds) -> io::Result<()> { self.print_lifetime(lifetime)?; @@ -2861,7 +2861,10 @@ impl<'a> State<'a> { if i != 0 { self.s.word(" + ")?; } - self.print_lifetime(bound)?; + match bound { + ast::ParamBound::Outlives(lt) => self.print_lifetime(lt)?, + _ => panic!(), + } } } Ok(()) @@ -2881,17 +2884,12 @@ impl<'a> State<'a> { match param.kind { ast::GenericParamKind::Lifetime { ref lifetime } => { s.print_outer_attributes_inline(¶m.attrs)?; - s.print_lifetime_bounds(lifetime, ¶m.bounds.iter().map(|bound| { - match bound { - ast::ParamBound::Outlives(lt) => *lt, - _ => panic!(), - } - }).collect::>().as_slice()) + s.print_lifetime_bounds(lifetime, ¶m.bounds) }, ast::GenericParamKind::Type { ref default } => { s.print_outer_attributes_inline(¶m.attrs)?; s.print_ident(param.ident)?; - s.print_bounds(":", ¶m.bounds)?; + s.print_type_bounds(":", ¶m.bounds)?; match default { Some(ref default) => { s.s.space()?; @@ -2931,7 +2929,7 @@ impl<'a> State<'a> { }) => { self.print_formal_generic_params(bound_generic_params)?; self.print_type(bounded_ty)?; - self.print_bounds(":", bounds)?; + self.print_type_bounds(":", bounds)?; } ast::WherePredicate::RegionPredicate(ast::WhereRegionPredicate{ref lifetime, ref bounds, diff --git a/src/libsyntax/util/node_count.rs b/src/libsyntax/util/node_count.rs index 485775765abf8..2d92f4b9531ad 100644 --- a/src/libsyntax/util/node_count.rs +++ b/src/libsyntax/util/node_count.rs @@ -95,9 +95,9 @@ impl<'ast> Visitor<'ast> for NodeCounter { self.count += 1; walk_trait_ref(self, t) } - fn visit_ty_param_bound(&mut self, bounds: &ParamBound) { + fn visit_param_bound(&mut self, bounds: &ParamBound) { self.count += 1; - walk_ty_param_bound(self, bounds) + walk_param_bound(self, bounds) } fn visit_poly_trait_ref(&mut self, t: &PolyTraitRef, m: &TraitBoundModifier) { self.count += 1; diff --git a/src/libsyntax/visit.rs b/src/libsyntax/visit.rs index 4e0c417d4fba6..1d535ab6bf0c1 100644 --- a/src/libsyntax/visit.rs +++ b/src/libsyntax/visit.rs @@ -86,8 +86,8 @@ pub trait Visitor<'ast>: Sized { fn visit_trait_item(&mut self, ti: &'ast TraitItem) { walk_trait_item(self, ti) } fn visit_impl_item(&mut self, ii: &'ast ImplItem) { walk_impl_item(self, ii) } fn visit_trait_ref(&mut self, t: &'ast TraitRef) { walk_trait_ref(self, t) } - fn visit_ty_param_bound(&mut self, bounds: &'ast ParamBound) { - walk_ty_param_bound(self, bounds) + fn visit_param_bound(&mut self, bounds: &'ast ParamBound) { + walk_param_bound(self, bounds) } fn visit_poly_trait_ref(&mut self, t: &'ast PolyTraitRef, m: &'ast TraitBoundModifier) { walk_poly_trait_ref(self, t, m) @@ -276,12 +276,12 @@ pub fn walk_item<'a, V: Visitor<'a>>(visitor: &mut V, item: &'a Item) { } ItemKind::Trait(.., ref generics, ref bounds, ref methods) => { visitor.visit_generics(generics); - walk_list!(visitor, visit_ty_param_bound, bounds); + walk_list!(visitor, visit_param_bound, bounds); walk_list!(visitor, visit_trait_item, methods); } ItemKind::TraitAlias(ref generics, ref bounds) => { visitor.visit_generics(generics); - walk_list!(visitor, visit_ty_param_bound, bounds); + walk_list!(visitor, visit_param_bound, bounds); } ItemKind::Mac(ref mac) => visitor.visit_mac(mac), ItemKind::MacroDef(ref ts) => visitor.visit_mac_def(ts, item.id), @@ -341,7 +341,7 @@ pub fn walk_ty<'a, V: Visitor<'a>>(visitor: &mut V, typ: &'a Ty) { } TyKind::TraitObject(ref bounds, ..) | TyKind::ImplTrait(ref bounds) => { - walk_list!(visitor, visit_ty_param_bound, bounds); + walk_list!(visitor, visit_param_bound, bounds); } TyKind::Typeof(ref expression) => { visitor.visit_anon_const(expression) @@ -479,7 +479,7 @@ pub fn walk_global_asm<'a, V: Visitor<'a>>(_: &mut V, _: &'a GlobalAsm) { // Empty! } -pub fn walk_ty_param_bound<'a, V: Visitor<'a>>(visitor: &mut V, bound: &'a ParamBound) { +pub fn walk_param_bound<'a, V: Visitor<'a>>(visitor: &mut V, bound: &'a ParamBound) { match *bound { TraitTyParamBound(ref typ, ref modifier) => { visitor.visit_poly_trait_ref(typ, modifier); @@ -517,14 +517,14 @@ pub fn walk_where_predicate<'a, V: Visitor<'a>>(visitor: &mut V, predicate: &'a ref bound_generic_params, ..}) => { visitor.visit_ty(bounded_ty); - walk_list!(visitor, visit_ty_param_bound, bounds); + walk_list!(visitor, visit_param_bound, bounds); walk_list!(visitor, visit_generic_param, bound_generic_params); } WherePredicate::RegionPredicate(WhereRegionPredicate{ref lifetime, ref bounds, ..}) => { visitor.visit_lifetime(lifetime); - walk_list!(visitor, visit_lifetime, bounds); + walk_list!(visitor, visit_param_bound, bounds); } WherePredicate::EqPredicate(WhereEqPredicate{ref lhs_ty, ref rhs_ty, @@ -585,7 +585,7 @@ pub fn walk_trait_item<'a, V: Visitor<'a>>(visitor: &mut V, trait_item: &'a Trai &sig.decl, trait_item.span, trait_item.id); } TraitItemKind::Type(ref bounds, ref default) => { - walk_list!(visitor, visit_ty_param_bound, bounds); + walk_list!(visitor, visit_param_bound, bounds); walk_list!(visitor, visit_ty, default); } TraitItemKind::Macro(ref mac) => { From 32b2dacdf8c0e2eaf5fd919e6c35ee3819101e0a Mon Sep 17 00:00:00 2001 From: varkor Date: Mon, 28 May 2018 14:05:06 +0100 Subject: [PATCH 22/41] Handle lifetimes in NodeGenericParam also --- src/librustc/hir/map/mod.rs | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/src/librustc/hir/map/mod.rs b/src/librustc/hir/map/mod.rs index 1f958d3fe9536..cb93c7e70d179 100644 --- a/src/librustc/hir/map/mod.rs +++ b/src/librustc/hir/map/mod.rs @@ -495,7 +495,10 @@ impl<'hir> Map<'hir> { MacroKind::Bang)) } NodeGenericParam(param) => { - Some(Def::TyParam(self.local_def_id(param.id))) + Some(match param.kind { + GenericParamKind::Lifetime { .. } => Def::Local(param.id), + GenericParamKind::Type { .. } => Def::TyParam(self.local_def_id(param.id)) + }) } } } @@ -975,8 +978,8 @@ impl<'hir> Map<'hir> { Some(NodeExpr(ref e)) => Some(&*e.attrs), Some(NodeStmt(ref s)) => Some(s.node.attrs()), Some(NodeGenericParam(param)) => match param.kind { + GenericParamKind::Lifetime { .. } => None, GenericParamKind::Type { ref attrs, .. } => Some(&attrs[..]), - _ => bug!("unexpected non-type NodeGenericParam") } // unit/tuple structs take the attributes straight from // the struct definition. @@ -1375,7 +1378,7 @@ fn node_id_to_string(map: &Map, id: NodeId, include_id: bool) -> String { format!("lifetime {}{}", map.node_to_pretty_string(id), id_str) } Some(NodeGenericParam(ref param)) => { - format!("genericparam {:?}{}", param, id_str) + format!("generic_param {:?}{}", param, id_str) } Some(NodeVisibility(ref vis)) => { format!("visibility {:?}{}", vis, id_str) From c4e8e718807d1925769bdcdd055c6d8de05f20ce Mon Sep 17 00:00:00 2001 From: varkor Date: Mon, 28 May 2018 14:55:23 +0100 Subject: [PATCH 23/41] Lift name into GenericParam --- src/librustc/hir/lowering.rs | 24 ++++++++++---------- src/librustc/hir/map/mod.rs | 4 ++-- src/librustc/hir/mod.rs | 15 ++----------- src/librustc/hir/print.rs | 2 +- src/librustc/ich/impls_hir.rs | 8 +++---- src/librustc/middle/resolve_lifetime.rs | 30 ++++++++++++------------- src/librustc_lint/bad_style.rs | 4 ++-- src/librustc_typeck/check/mod.rs | 2 +- src/librustc_typeck/check/wfcheck.rs | 2 +- src/librustc_typeck/collect.rs | 13 +++++------ src/librustdoc/clean/mod.rs | 10 ++++----- 11 files changed, 51 insertions(+), 63 deletions(-) diff --git a/src/librustc/hir/lowering.rs b/src/librustc/hir/lowering.rs index fed4f150075b5..d0a3f0d097fd0 100644 --- a/src/librustc/hir/lowering.rs +++ b/src/librustc/hir/lowering.rs @@ -699,11 +699,12 @@ impl<'a> LoweringContext<'a> { hir::GenericParam { id: def_node_id, + name: hir_name.name(), span, pure_wrt_drop: false, bounds: vec![].into(), kind: hir::GenericParamKind::Lifetime { - name: hir_name, + lt_name: hir_name, in_band: true, lifetime: hir::Lifetime { id: def_node_id, @@ -734,10 +735,7 @@ impl<'a> LoweringContext<'a> { let hir_name = hir::LifetimeName::Name(name); - if self.lifetimes_to_define - .iter() - .any(|(_, lt_name)| *lt_name == hir_name) - { + if self.lifetimes_to_define.iter().any(|(_, lt_name)| *lt_name == hir_name) { return; } @@ -788,7 +786,7 @@ impl<'a> LoweringContext<'a> { { let old_len = self.in_scope_lifetimes.len(); let lt_def_names = params.iter().filter_map(|param| match param.kind { - hir::GenericParamKind::Lifetime { .. } => Some(param.name()), + hir::GenericParamKind::Lifetime { .. } => Some(param.name), _ => None, }); self.in_scope_lifetimes.extend(lt_def_names); @@ -1251,11 +1249,11 @@ impl<'a> LoweringContext<'a> { let name = Symbol::intern(&pprust::ty_to_string(t)); self.in_band_ty_params.push(hir::GenericParam { id: def_node_id, + name, span, pure_wrt_drop: false, bounds: hir_bounds, kind: hir::GenericParamKind::Type { - name, default: None, synthetic: Some(hir::SyntheticTyParamKind::ImplTrait), attrs: P::new(), @@ -1366,10 +1364,10 @@ impl<'a> LoweringContext<'a> { fn visit_generic_param(&mut self, param: &'v hir::GenericParam) { // Record the introduction of 'a in `for<'a> ...` - if let hir::GenericParamKind::Lifetime { name, .. } = param.kind { + if let hir::GenericParamKind::Lifetime { lt_name, .. } = param.kind { // Introduce lifetimes one at a time so that we can handle // cases like `fn foo<'d>() -> impl for<'a, 'b: 'a, 'c: 'b + 'd>` - self.currently_bound_lifetimes.push(name); + self.currently_bound_lifetimes.push(lt_name); } hir::intravisit::walk_generic_param(self, param); @@ -1418,11 +1416,12 @@ impl<'a> LoweringContext<'a> { self.output_lifetime_params.push(hir::GenericParam { id: def_node_id, + name: name.name(), span: lifetime.span, pure_wrt_drop: false, bounds: vec![].into(), kind: hir::GenericParamKind::Lifetime { - name, + lt_name: name, in_band: false, lifetime: hir::Lifetime { id: def_node_id, @@ -1955,11 +1954,12 @@ impl<'a> LoweringContext<'a> { let lifetime = self.lower_lifetime(lifetime); let param = hir::GenericParam { id: lifetime.id, + name: lifetime.name.name(), span: lifetime.span, pure_wrt_drop: attr::contains_name(¶m.attrs, "may_dangle"), bounds, kind: hir::GenericParamKind::Lifetime { - name: lifetime.name, + lt_name: lifetime.name, in_band: false, lifetime, } @@ -1988,11 +1988,11 @@ impl<'a> LoweringContext<'a> { hir::GenericParam { id: self.lower_node_id(param.id).node_id, + name, span: param.ident.span, pure_wrt_drop: attr::contains_name(¶m.attrs, "may_dangle"), bounds, kind: hir::GenericParamKind::Type { - name, default: default.as_ref().map(|x| { self.lower_ty(x, ImplTraitContext::Disallowed) }), diff --git a/src/librustc/hir/map/mod.rs b/src/librustc/hir/map/mod.rs index cb93c7e70d179..999103980625c 100644 --- a/src/librustc/hir/map/mod.rs +++ b/src/librustc/hir/map/mod.rs @@ -616,7 +616,7 @@ impl<'hir> Map<'hir> { NodeItem(&Item { node: ItemTrait(..), .. }) => { keywords::SelfType.name() } - NodeGenericParam(param) => param.name(), + NodeGenericParam(param) => param.name, _ => { bug!("ty_param_name: {} not a type parameter", self.node_to_string(id)) @@ -957,7 +957,7 @@ impl<'hir> Map<'hir> { NodeVariant(v) => v.node.name, NodeField(f) => f.ident.name, NodeLifetime(lt) => lt.name.name(), - NodeGenericParam(param) => param.name(), + NodeGenericParam(param) => param.name, NodeBinding(&Pat { node: PatKind::Binding(_,_,l,_), .. }) => l.node, NodeStructCtor(_) => self.name(self.get_parent(id)), _ => bug!("no name for {}", self.node_to_string(id)) diff --git a/src/librustc/hir/mod.rs b/src/librustc/hir/mod.rs index 8249b306a0c3b..b4470ed7c1eb0 100644 --- a/src/librustc/hir/mod.rs +++ b/src/librustc/hir/mod.rs @@ -424,8 +424,6 @@ pub enum TraitBoundModifier { Maybe, } -pub type Outlives = Lifetime; - /// The AST represents all type param bounds as types. /// typeck::collect::compute_bounds matches these against /// the "special" built-in traits (see middle::lang_items) and @@ -451,7 +449,7 @@ pub type ParamBounds = HirVec; pub enum GenericParamKind { /// A lifetime definition, eg `'a: 'b + 'c + 'd`. Lifetime { - name: LifetimeName, + lt_name: LifetimeName, // Indicates that the lifetime definition was synthetically added // as a result of an in-band lifetime usage like: // `fn foo(x: &'a u8) -> &'a u8 { x }` @@ -460,7 +458,6 @@ pub enum GenericParamKind { lifetime: Lifetime, }, Type { - name: Name, default: Option>, synthetic: Option, attrs: HirVec, @@ -470,6 +467,7 @@ pub enum GenericParamKind { #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)] pub struct GenericParam { pub id: NodeId, + pub name: Name, pub bounds: ParamBounds, pub span: Span, pub pure_wrt_drop: bool, @@ -477,15 +475,6 @@ pub struct GenericParam { pub kind: GenericParamKind, } -impl GenericParam { - pub fn name(&self) -> Name { - match self.kind { - GenericParamKind::Lifetime { name, .. } => name.name(), - GenericParamKind::Type { name, .. } => name, - } - } -} - pub struct GenericParamCount { pub lifetimes: usize, pub types: usize, diff --git a/src/librustc/hir/print.rs b/src/librustc/hir/print.rs index 10cecdb2d47aa..a4cbd6515955d 100644 --- a/src/librustc/hir/print.rs +++ b/src/librustc/hir/print.rs @@ -2115,7 +2115,7 @@ impl<'a> State<'a> { } pub fn print_generic_param(&mut self, param: &GenericParam) -> io::Result<()> { - self.print_name(param.name())?; + self.print_name(param.name)?; match param.kind { GenericParamKind::Lifetime { .. } => { let mut sep = ":"; diff --git a/src/librustc/ich/impls_hir.rs b/src/librustc/ich/impls_hir.rs index f8da828d2c3ba..0c31134ae9cb3 100644 --- a/src/librustc/ich/impls_hir.rs +++ b/src/librustc/ich/impls_hir.rs @@ -196,6 +196,7 @@ impl_stable_hash_for!(enum hir::TraitBoundModifier { impl_stable_hash_for!(struct hir::GenericParam { id, + name, span, pure_wrt_drop, bounds, @@ -208,13 +209,12 @@ impl<'a> HashStable> for hir::GenericParamKind { hasher: &mut StableHasher) { mem::discriminant(self).hash_stable(hcx, hasher); match self { - hir::GenericParamKind::Lifetime { name, in_band, ref lifetime } => { - name.hash_stable(hcx, hasher); + hir::GenericParamKind::Lifetime { lt_name, in_band, ref lifetime } => { + lt_name.hash_stable(hcx, hasher); in_band.hash_stable(hcx, hasher); lifetime.hash_stable(hcx, hasher); } - hir::GenericParamKind::Type { name, ref default, synthetic, attrs } => { - name.hash_stable(hcx, hasher); + hir::GenericParamKind::Type { ref default, synthetic, attrs } => { default.hash_stable(hcx, hasher); synthetic.hash_stable(hcx, hasher); attrs.hash_stable(hcx, hasher); diff --git a/src/librustc/middle/resolve_lifetime.rs b/src/librustc/middle/resolve_lifetime.rs index fc160b35ae494..cc39456c2fe36 100644 --- a/src/librustc/middle/resolve_lifetime.rs +++ b/src/librustc/middle/resolve_lifetime.rs @@ -84,13 +84,13 @@ pub enum Region { fn new_region(hir_map: &Map, param: &hir::GenericParam) -> (hir::LifetimeName, DefId, LifetimeDefOrigin) { let def_id = hir_map.local_def_id(param.id); - let (name, origin) = match param.kind { - GenericParamKind::Lifetime { name, in_band, .. } => { - (name, LifetimeDefOrigin::from_is_in_band(in_band)) + let (lt_name, origin) = match param.kind { + GenericParamKind::Lifetime { lt_name, in_band, .. } => { + (lt_name, LifetimeDefOrigin::from_is_in_band(in_band)) } _ => bug!("expected a lifetime param"), }; - (name, def_id, origin) + (lt_name, def_id, origin) } impl Region { @@ -1222,7 +1222,7 @@ fn compute_object_lifetime_defaults( generics.params.iter().find_map(|param| match param.kind { GenericParamKind::Lifetime { .. } => { if i == 0 { - return Some(param.name().to_string()); + return Some(param.name.to_string()); } i -= 1; None @@ -1299,8 +1299,8 @@ fn object_lifetime_defaults_for_item( Set1::One(Region::Static) } else { generics.params.iter().filter_map(|param| match param.kind { - GenericParamKind::Lifetime { name, in_band, .. } => { - Some((param.id, name, in_band)) + GenericParamKind::Lifetime { lt_name, in_band, .. } => { + Some((param.id, lt_name, in_band)) } _ => None, }) @@ -2237,7 +2237,7 @@ impl<'a, 'tcx> LifetimeContext<'a, 'tcx> { fn check_lifetime_params(&mut self, old_scope: ScopeRef, params: &'tcx [hir::GenericParam]) { let lifetimes: Vec<_> = params.iter().filter_map(|param| match param.kind { - GenericParamKind::Lifetime { name, .. } => Some((param, name)), + GenericParamKind::Lifetime { lt_name, .. } => Some((param, lt_name)), _ => None, }).collect(); for (i, (lifetime_i, lifetime_i_name)) in lifetimes.iter().enumerate() { @@ -2271,7 +2271,7 @@ impl<'a, 'tcx> LifetimeContext<'a, 'tcx> { lifetime_j.span, E0263, "lifetime name `{}` declared twice in the same scope", - lifetime_j.name() + lifetime_j.name ).span_label(lifetime_j.span, "declared twice") .span_label(lifetime_i.span, "previous declaration here") .emit(); @@ -2302,13 +2302,13 @@ impl<'a, 'tcx> LifetimeContext<'a, 'tcx> { lifetime_i.span.to(lt.span), &format!( "unnecessary lifetime parameter `{}`", - lifetime_i.name() + lifetime_i.name ), ) .help(&format!( "you can use the `'static` lifetime directly, in place \ of `{}`", - lifetime_i.name() + lifetime_i.name )) .emit(); } @@ -2331,7 +2331,7 @@ impl<'a, 'tcx> LifetimeContext<'a, 'tcx> { ) { for &(label, label_span) in &self.labels_in_fn { // FIXME (#24278): non-hygienic comparison - if param.name() == label { + if param.name == label { signal_shadowing_problem( self.tcx, label, @@ -2343,7 +2343,7 @@ impl<'a, 'tcx> LifetimeContext<'a, 'tcx> { } let name = match param.kind { - GenericParamKind::Lifetime { name, .. } => name, + GenericParamKind::Lifetime { lt_name, .. } => lt_name, _ => bug!("expected lifetime param"), }; @@ -2367,7 +2367,7 @@ impl<'a, 'tcx> LifetimeContext<'a, 'tcx> { signal_shadowing_problem( self.tcx, - param.name(), + param.name, original_lifetime(self.tcx.hir.span(node_id)), shadower_lifetime(¶m), ); @@ -2539,7 +2539,7 @@ fn insert_late_bound_lifetimes( // - are not implicitly captured by `impl Trait` for param in &generics.params { let name = match param.kind { - GenericParamKind::Lifetime { name, .. } => name, + GenericParamKind::Lifetime { lt_name, .. } => lt_name, _ => continue, }; diff --git a/src/librustc_lint/bad_style.rs b/src/librustc_lint/bad_style.rs index f456ab3679988..aeeb812dd77d4 100644 --- a/src/librustc_lint/bad_style.rs +++ b/src/librustc_lint/bad_style.rs @@ -151,7 +151,7 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for NonCamelCaseTypes { GenericParamKind::Lifetime { .. } => {} GenericParamKind::Type { synthetic, .. } => { if synthetic.is_none() { - self.check_case(cx, "type parameter", param.name(), param.span); + self.check_case(cx, "type parameter", param.name, param.span); } } } @@ -258,7 +258,7 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for NonSnakeCase { fn check_generic_param(&mut self, cx: &LateContext, param: &hir::GenericParam) { match param.kind { GenericParamKind::Lifetime { .. } => { - self.check_snake_case(cx, "lifetime", ¶m.name().as_str(), Some(param.span)); + self.check_snake_case(cx, "lifetime", ¶m.name.as_str(), Some(param.span)); } GenericParamKind::Type { .. } => {} } diff --git a/src/librustc_typeck/check/mod.rs b/src/librustc_typeck/check/mod.rs index 036c0aa442e56..9ff400d013bf8 100644 --- a/src/librustc_typeck/check/mod.rs +++ b/src/librustc_typeck/check/mod.rs @@ -5195,7 +5195,7 @@ pub fn check_bounds_are_used<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, for (&used, param) in types_used.iter().zip(types) { if !used { struct_span_err!(tcx.sess, param.span, E0091, "type parameter `{}` is unused", - param.name()) + param.name) .span_label(param.span, "unused type parameter") .emit(); } diff --git a/src/librustc_typeck/check/wfcheck.rs b/src/librustc_typeck/check/wfcheck.rs index f8f0126279087..9df8502461cc0 100644 --- a/src/librustc_typeck/check/wfcheck.rs +++ b/src/librustc_typeck/check/wfcheck.rs @@ -632,7 +632,7 @@ fn check_variances_for_type_defn<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, } let param = &ast_generics.params[index]; - report_bivariance(tcx, param.span, param.name()); + report_bivariance(tcx, param.span, param.name); } } diff --git a/src/librustc_typeck/collect.rs b/src/librustc_typeck/collect.rs index c2b52e0de7522..d53efe1460004 100644 --- a/src/librustc_typeck/collect.rs +++ b/src/librustc_typeck/collect.rs @@ -898,7 +898,7 @@ fn generics_of<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, let early_lifetimes = early_bound_lifetimes_from_generics(tcx, ast_generics); params.extend(early_lifetimes.enumerate().map(|(i, param)| { ty::GenericParamDef { - name: param.name().as_interned_str(), + name: param.name.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, @@ -914,9 +914,8 @@ fn generics_of<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, let mut i = 0; params.extend(ast_generics.params.iter().filter_map(|param| match param.kind { GenericParamKind::Type { ref default, synthetic, .. } => { - if param.name() == keywords::SelfType.name() { - span_bug!(param.span, - "`Self` should not be the name of a regular parameter"); + if param.name == keywords::SelfType.name() { + span_bug!(param.span, "`Self` should not be the name of a regular parameter"); } if !allow_defaults && default.is_some() { @@ -932,7 +931,7 @@ fn generics_of<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, let ty_param = ty::GenericParamDef { index: type_start + i as u32, - name: param.name().as_interned_str(), + name: param.name.as_interned_str(), def_id: tcx.hir.local_def_id(param.id), pure_wrt_drop: param.pure_wrt_drop, kind: ty::GenericParamDefKind::Type { @@ -1438,7 +1437,7 @@ pub fn explicit_predicates_of<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, let region = tcx.mk_region(ty::ReEarlyBound(ty::EarlyBoundRegion { def_id: tcx.hir.local_def_id(param.id), index, - name: param.name().as_interned_str(), + name: param.name.as_interned_str(), })); index += 1; @@ -1462,7 +1461,7 @@ pub fn explicit_predicates_of<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, for param in &ast_generics.params { match param.kind { GenericParamKind::Type { .. } => { - let param_ty = ty::ParamTy::new(index, param.name().as_interned_str()).to_ty(tcx); + let param_ty = ty::ParamTy::new(index, param.name.as_interned_str()).to_ty(tcx); index += 1; let sized = SizedByDefault::Yes; diff --git a/src/librustdoc/clean/mod.rs b/src/librustdoc/clean/mod.rs index 2f48267579a61..cea29ab30dfe7 100644 --- a/src/librustdoc/clean/mod.rs +++ b/src/librustdoc/clean/mod.rs @@ -1678,13 +1678,13 @@ impl Clean for hir::GenericParam { _ => panic!(), }); let name = bounds.next().unwrap().name.name(); - let mut s = format!("{}: {}", self.name(), name); + let mut s = format!("{}: {}", self.name, name); for bound in bounds { s.push_str(&format!(" + {}", bound.name.name())); } Lifetime(s) } else { - Lifetime(self.name().to_string()) + Lifetime(self.name.to_string()) } } _ => panic!(), @@ -1897,18 +1897,18 @@ impl Clean for hir::GenericParam { _ => panic!(), }); let name = bounds.next().unwrap().name.name(); - let mut s = format!("{}: {}", self.name(), name); + let mut s = format!("{}: {}", self.name, name); for bound in bounds { s.push_str(&format!(" + {}", bound.name.name())); } s } else { - self.name().to_string() + self.name.to_string() }; (name, GenericParamDefKind::Lifetime) } hir::GenericParamKind::Type { ref default, synthetic, .. } => { - (self.name().clean(cx), GenericParamDefKind::Type { + (self.name.clean(cx), GenericParamDefKind::Type { did: cx.tcx.hir.local_def_id(self.id), bounds: self.bounds.clean(cx), default: default.clean(cx), From 6015edf9af375385ca9eb2ebbb8794c782fa7244 Mon Sep 17 00:00:00 2001 From: varkor Date: Wed, 30 May 2018 16:49:39 +0100 Subject: [PATCH 24/41] Remove name from GenericParamKind::Lifetime --- src/librustc/hir/intravisit.rs | 4 +-- src/librustc/hir/lowering.rs | 23 ++++---------- src/librustc/hir/mod.rs | 2 -- src/librustc/ich/impls_hir.rs | 3 +- src/libsyntax/ast.rs | 4 +-- src/libsyntax/ext/build.rs | 4 +-- src/libsyntax/parse/parser.rs | 4 +-- src/libsyntax/print/pprust.rs | 37 +++++++++-------------- src/libsyntax_ext/deriving/generic/mod.rs | 4 +-- src/libsyntax_ext/deriving/generic/ty.rs | 4 +-- 10 files changed, 30 insertions(+), 59 deletions(-) diff --git a/src/librustc/hir/intravisit.rs b/src/librustc/hir/intravisit.rs index a550f60fb4b79..5a41d71b93d1f 100644 --- a/src/librustc/hir/intravisit.rs +++ b/src/librustc/hir/intravisit.rs @@ -736,9 +736,7 @@ pub fn walk_param_bound<'v, V: Visitor<'v>>(visitor: &mut V, bound: &'v ParamBou TraitTyParamBound(ref typ, modifier) => { visitor.visit_poly_trait_ref(typ, modifier); } - Outlives(ref lifetime) => { - visitor.visit_lifetime(lifetime); - } + Outlives(ref lifetime) => visitor.visit_lifetime(lifetime), } } diff --git a/src/librustc/hir/lowering.rs b/src/librustc/hir/lowering.rs index d0a3f0d097fd0..ec162adf52bf9 100644 --- a/src/librustc/hir/lowering.rs +++ b/src/librustc/hir/lowering.rs @@ -706,13 +706,8 @@ impl<'a> LoweringContext<'a> { kind: hir::GenericParamKind::Lifetime { lt_name: hir_name, in_band: true, - lifetime: hir::Lifetime { - id: def_node_id, - span, - name: hir_name, } } - } }) .chain(in_band_ty_params.into_iter()) .collect(); @@ -1423,12 +1418,7 @@ impl<'a> LoweringContext<'a> { kind: hir::GenericParamKind::Lifetime { lt_name: name, in_band: false, - lifetime: hir::Lifetime { - id: def_node_id, - span: lifetime.span, - name, } - } }); } } @@ -1947,21 +1937,20 @@ impl<'a> LoweringContext<'a> { -> hir::GenericParam { let mut bounds = self.lower_param_bounds(¶m.bounds, itctx); match param.kind { - GenericParamKind::Lifetime { ref lifetime } => { + GenericParamKind::Lifetime => { let was_collecting_in_band = self.is_collecting_in_band_lifetimes; self.is_collecting_in_band_lifetimes = false; - let lifetime = self.lower_lifetime(lifetime); + let lt = self.lower_lifetime(&Lifetime { id: param.id, ident: param.ident }); let param = hir::GenericParam { - id: lifetime.id, - name: lifetime.name.name(), - span: lifetime.span, + id: lt.id, + name: lt.name.name(), + span: lt.span, pure_wrt_drop: attr::contains_name(¶m.attrs, "may_dangle"), bounds, kind: hir::GenericParamKind::Lifetime { - lt_name: lifetime.name, + lt_name: lt.name, in_band: false, - lifetime, } }; diff --git a/src/librustc/hir/mod.rs b/src/librustc/hir/mod.rs index b4470ed7c1eb0..cf0ae5aa94da5 100644 --- a/src/librustc/hir/mod.rs +++ b/src/librustc/hir/mod.rs @@ -454,8 +454,6 @@ pub enum GenericParamKind { // as a result of an in-band lifetime usage like: // `fn foo(x: &'a u8) -> &'a u8 { x }` in_band: bool, - // We keep a `Lifetime` around for now just so we can `visit_lifetime`. - lifetime: Lifetime, }, Type { default: Option>, diff --git a/src/librustc/ich/impls_hir.rs b/src/librustc/ich/impls_hir.rs index 0c31134ae9cb3..ae2bf1e4c7429 100644 --- a/src/librustc/ich/impls_hir.rs +++ b/src/librustc/ich/impls_hir.rs @@ -209,10 +209,9 @@ impl<'a> HashStable> for hir::GenericParamKind { hasher: &mut StableHasher) { mem::discriminant(self).hash_stable(hcx, hasher); match self { - hir::GenericParamKind::Lifetime { lt_name, in_band, ref lifetime } => { + hir::GenericParamKind::Lifetime { lt_name, in_band } => { lt_name.hash_stable(hcx, hasher); in_band.hash_stable(hcx, hasher); - lifetime.hash_stable(hcx, hasher); } hir::GenericParamKind::Type { ref default, synthetic, attrs } => { default.hash_stable(hcx, hasher); diff --git a/src/libsyntax/ast.rs b/src/libsyntax/ast.rs index 67679468fe42c..98f786628f95b 100644 --- a/src/libsyntax/ast.rs +++ b/src/libsyntax/ast.rs @@ -301,9 +301,7 @@ pub type ParamBounds = Vec; #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)] pub enum GenericParamKind { /// A lifetime definition, e.g. `'a: 'b+'c+'d`. - Lifetime { - lifetime: Lifetime, - }, + Lifetime, Type { default: Option>, } diff --git a/src/libsyntax/ext/build.rs b/src/libsyntax/ext/build.rs index ea151ca68a8be..cc0bc7f0c745f 100644 --- a/src/libsyntax/ext/build.rs +++ b/src/libsyntax/ext/build.rs @@ -484,9 +484,7 @@ impl<'a> AstBuilder for ExtCtxt<'a> { id: lifetime.id, attrs: attrs.into(), bounds, - kind: ast::GenericParamKind::Lifetime { - lifetime, - } + kind: ast::GenericParamKind::Lifetime, } } diff --git a/src/libsyntax/parse/parser.rs b/src/libsyntax/parse/parser.rs index 66e485120659c..b2cfb459c359a 100644 --- a/src/libsyntax/parse/parser.rs +++ b/src/libsyntax/parse/parser.rs @@ -4877,9 +4877,7 @@ impl<'a> Parser<'a> { id: lifetime.id, attrs: attrs.into(), bounds, - kind: ast::GenericParamKind::Lifetime { - lifetime, - } + kind: ast::GenericParamKind::Lifetime, }); if seen_ty_param { self.span_err(self.prev_span, diff --git a/src/libsyntax/print/pprust.rs b/src/libsyntax/print/pprust.rs index c672b01fb2725..5d39367f4b0d4 100644 --- a/src/libsyntax/print/pprust.rs +++ b/src/libsyntax/print/pprust.rs @@ -308,8 +308,8 @@ pub fn expr_to_string(e: &ast::Expr) -> String { to_string(|s| s.print_expr(e)) } -pub fn lifetime_to_string(e: &ast::Lifetime) -> String { - to_string(|s| s.print_lifetime(e)) +pub fn lifetime_to_string(lt: &ast::Lifetime) -> String { + to_string(|s| s.print_lifetime(*lt)) } pub fn tt_to_string(tt: tokenstream::TokenTree) -> String { @@ -1008,10 +1008,9 @@ impl<'a> State<'a> { Ok(()) } - pub fn print_opt_lifetime(&mut self, - lifetime: &Option) -> io::Result<()> { - if let Some(l) = *lifetime { - self.print_lifetime(&l)?; + pub fn print_opt_lifetime(&mut self, lifetime: &Option) -> io::Result<()> { + if let Some(lt) = *lifetime { + self.print_lifetime(lt)?; self.nbsp()?; } Ok(()) @@ -1019,7 +1018,7 @@ impl<'a> State<'a> { pub fn print_generic_arg(&mut self, generic_arg: &GenericArg) -> io::Result<()> { match generic_arg { - GenericArg::Lifetime(lt) => self.print_lifetime(lt), + GenericArg::Lifetime(lt) => self.print_lifetime(*lt), GenericArg::Type(ty) => self.print_type(ty), } } @@ -2833,26 +2832,19 @@ impl<'a> State<'a> { } self.print_poly_trait_ref(tref)?; } - Outlives(lt) => { - self.print_lifetime(lt)?; - } + Outlives(lt) => self.print_lifetime(*lt)?, } } } Ok(()) } - pub fn print_lifetime(&mut self, - lifetime: &ast::Lifetime) - -> io::Result<()> - { + pub fn print_lifetime(&mut self, lifetime: ast::Lifetime) -> io::Result<()> { self.print_name(lifetime.ident.name) } - pub fn print_lifetime_bounds(&mut self, - lifetime: &ast::Lifetime, - bounds: &ast::ParamBounds) - -> io::Result<()> + pub fn print_lifetime_bounds(&mut self, lifetime: ast::Lifetime, bounds: &ast::ParamBounds) + -> io::Result<()> { self.print_lifetime(lifetime)?; if !bounds.is_empty() { @@ -2862,7 +2854,7 @@ impl<'a> State<'a> { self.s.word(" + ")?; } match bound { - ast::ParamBound::Outlives(lt) => self.print_lifetime(lt)?, + ast::ParamBound::Outlives(lt) => self.print_lifetime(*lt)?, _ => panic!(), } } @@ -2882,9 +2874,10 @@ impl<'a> State<'a> { self.commasep(Inconsistent, &generic_params, |s, param| { match param.kind { - ast::GenericParamKind::Lifetime { ref lifetime } => { + ast::GenericParamKind::Lifetime => { s.print_outer_attributes_inline(¶m.attrs)?; - s.print_lifetime_bounds(lifetime, ¶m.bounds) + let lt = ast::Lifetime { id: param.id, ident: param.ident }; + s.print_lifetime_bounds(lt, ¶m.bounds) }, ast::GenericParamKind::Type { ref default } => { s.print_outer_attributes_inline(¶m.attrs)?; @@ -2934,7 +2927,7 @@ impl<'a> State<'a> { ast::WherePredicate::RegionPredicate(ast::WhereRegionPredicate{ref lifetime, ref bounds, ..}) => { - self.print_lifetime_bounds(lifetime, bounds)?; + self.print_lifetime_bounds(*lifetime, bounds)?; } ast::WherePredicate::EqPredicate(ast::WhereEqPredicate{ref lhs_ty, ref rhs_ty, diff --git a/src/libsyntax_ext/deriving/generic/mod.rs b/src/libsyntax_ext/deriving/generic/mod.rs index a7d8156f4a043..89b500441292d 100644 --- a/src/libsyntax_ext/deriving/generic/mod.rs +++ b/src/libsyntax_ext/deriving/generic/mod.rs @@ -665,8 +665,8 @@ impl<'a> TraitDef<'a> { let trait_ref = cx.trait_ref(trait_path); let self_params: Vec<_> = generics.params.iter().map(|param| match param.kind { - GenericParamKind::Lifetime { ref lifetime, .. } => { - GenericArg::Lifetime(*lifetime) + GenericParamKind::Lifetime { .. } => { + GenericArg::Lifetime(ast::Lifetime { id: param.id, ident: param.ident }) } GenericParamKind::Type { .. } => { GenericArg::Type(cx.ty_ident(self.span, param.ident)) diff --git a/src/libsyntax_ext/deriving/generic/ty.rs b/src/libsyntax_ext/deriving/generic/ty.rs index 327a35d39b327..99b6398160e5f 100644 --- a/src/libsyntax_ext/deriving/generic/ty.rs +++ b/src/libsyntax_ext/deriving/generic/ty.rs @@ -190,8 +190,8 @@ impl<'a> Ty<'a> { match *self { Self_ => { let params: Vec<_> = generics.params.iter().map(|param| match param.kind { - GenericParamKind::Lifetime { ref lifetime, .. } => { - GenericArg::Lifetime(*lifetime) + GenericParamKind::Lifetime { .. } => { + GenericArg::Lifetime(ast::Lifetime { id: param.id, ident: param.ident }) } GenericParamKind::Type { .. } => { GenericArg::Type(cx.ty_ident(span, param.ident)) From 831b5c02df7235f2df804ee62e7cd2caf02bdad1 Mon Sep 17 00:00:00 2001 From: varkor Date: Thu, 31 May 2018 15:52:17 +0100 Subject: [PATCH 25/41] Take advantage of the lifetime refactoring --- src/librustc/hir/intravisit.rs | 11 +++-- src/librustc/hir/lowering.rs | 8 ++-- src/librustc/hir/map/collector.rs | 9 +--- src/librustc/middle/resolve_lifetime.rs | 11 +++-- src/librustc_passes/ast_validation.rs | 4 +- src/libsyntax/ast.rs | 2 +- src/libsyntax/fold.rs | 60 ++++++++++++------------- src/libsyntax/visit.rs | 11 ++--- 8 files changed, 50 insertions(+), 66 deletions(-) diff --git a/src/librustc/hir/intravisit.rs b/src/librustc/hir/intravisit.rs index 5a41d71b93d1f..e3ded0279b44a 100644 --- a/src/librustc/hir/intravisit.rs +++ b/src/librustc/hir/intravisit.rs @@ -743,20 +743,19 @@ pub fn walk_param_bound<'v, V: Visitor<'v>>(visitor: &mut V, bound: &'v ParamBou pub fn walk_generic_param<'v, V: Visitor<'v>>(visitor: &mut V, param: &'v GenericParam) { visitor.visit_id(param.id); match param.kind { - GenericParamKind::Lifetime { ref bounds, ref lifetime, .. } => { - match lifetime.name { + GenericParamKind::Lifetime { ref lt_name, .. } => { + match lt_name { LifetimeName::Name(name) => { - visitor.visit_name(param.span, name); + visitor.visit_name(param.span, *name); } LifetimeName::Fresh(_) | LifetimeName::Static | LifetimeName::Implicit | LifetimeName::Underscore => {} } - walk_list!(visitor, visit_lifetime, bounds); } - GenericParamKind::Type { name, ref bounds, ref default, ref attrs, .. } => { - visitor.visit_name(param.span, name); + GenericParamKind::Type { ref default, ref attrs, .. } => { + visitor.visit_name(param.span, param.name); walk_list!(visitor, visit_ty, default); walk_list!(visitor, visit_attribute, attrs.iter()); } diff --git a/src/librustc/hir/lowering.rs b/src/librustc/hir/lowering.rs index ec162adf52bf9..969072a65ae1e 100644 --- a/src/librustc/hir/lowering.rs +++ b/src/librustc/hir/lowering.rs @@ -1747,8 +1747,8 @@ impl<'a> LoweringContext<'a> { fn lower_parenthesized_parameter_data( &mut self, - data: &ParenthesizedParameterData, - ) -> (hir::PathParameters, bool) { + data: &ParenthesizedArgData, + ) -> (hir::GenericArgs, bool) { // Switch to `PassThrough` mode for anonymous lifetimes: this // means that we permit things like `&Ref`, where `Ref` has // a hidden lifetime parameter. This is needed for backwards @@ -1758,7 +1758,7 @@ impl<'a> LoweringContext<'a> { AnonymousLifetimeMode::PassThrough, |this| { const DISALLOWED: ImplTraitContext = ImplTraitContext::Disallowed; - let &ParenthesizedParameterData { ref inputs, ref output, span } = data; + let &ParenthesizedArgData { ref inputs, ref output, span } = data; let inputs = inputs.iter().map(|ty| this.lower_ty(ty, DISALLOWED)).collect(); let mk_tup = |this: &mut Self, tys, span| { let LoweredNodeId { node_id, hir_id } = this.next_id(); @@ -1767,7 +1767,7 @@ impl<'a> LoweringContext<'a> { ( hir::GenericArgs { - parameters: hir_vec![GenericArg::Type(mk_tup(this, inputs, span))], + args: hir_vec![GenericArg::Type(mk_tup(this, inputs, span))], bindings: hir_vec![ hir::TypeBinding { id: this.next_id().node_id, diff --git a/src/librustc/hir/map/collector.rs b/src/librustc/hir/map/collector.rs index d34924547ed66..14cecba490d0a 100644 --- a/src/librustc/hir/map/collector.rs +++ b/src/librustc/hir/map/collector.rs @@ -347,14 +347,7 @@ impl<'a, 'hir> Visitor<'hir> for NodeCollector<'a, 'hir> { } fn visit_generic_param(&mut self, param: &'hir GenericParam) { - match param.kind { - GenericParamKind::Lifetime { ref lifetime_deprecated, .. } => { - self.insert(param.id, NodeLifetime(lifetime_deprecated)); - } - GenericParamKind::Type { .. } => { - self.insert(param.id, NodeGenericParam(param)); - } - } + self.insert(param.id, NodeGenericParam(param)); intravisit::walk_generic_param(self, param); } diff --git a/src/librustc/middle/resolve_lifetime.rs b/src/librustc/middle/resolve_lifetime.rs index cc39456c2fe36..883f24b37db9d 100644 --- a/src/librustc/middle/resolve_lifetime.rs +++ b/src/librustc/middle/resolve_lifetime.rs @@ -110,8 +110,8 @@ impl Region { let depth = ty::INNERMOST; let (name, def_id, origin) = new_region(hir_map, param); debug!( - "Region::late: def={:?} depth={:?} def_id={:?} origin={:?}", - def, + "Region::late: param={:?} depth={:?} def_id={:?} origin={:?}", + param, depth, def_id, origin, @@ -2243,8 +2243,7 @@ impl<'a, 'tcx> LifetimeContext<'a, 'tcx> { for (i, (lifetime_i, lifetime_i_name)) in lifetimes.iter().enumerate() { match lifetime_i_name { hir::LifetimeName::Static | hir::LifetimeName::Underscore => { - let lifetime = lifetime_i.lifetime; - let name = lifetime_i.name(); + let name = lifetime_i.name; let mut err = struct_span_err!( self.tcx.sess, lifetime_i.span, @@ -2518,10 +2517,10 @@ fn insert_late_bound_lifetimes( for param in &generics.params { match param.kind { - hir::GenericParamKind::Lifetime { .. } => { + hir::GenericParamKind::Lifetime { lt_name, .. } => { if !param.bounds.is_empty() { // `'a: 'b` means both `'a` and `'b` are referenced - appears_in_where_clause.regions.insert(lifetime_def.lifetime.name); + appears_in_where_clause.regions.insert(lt_name); } } hir::GenericParamKind::Type { .. } => {} diff --git a/src/librustc_passes/ast_validation.rs b/src/librustc_passes/ast_validation.rs index d14a02ec8d155..3411c28f35bca 100644 --- a/src/librustc_passes/ast_validation.rs +++ b/src/librustc_passes/ast_validation.rs @@ -431,8 +431,8 @@ impl<'a> Visitor<'a> for AstValidator<'a> { } fn visit_generic_param(&mut self, param: &'a GenericParam) { - if let GenericParam::Lifetime(ref ld) = *param { - self.check_lifetime(ld.lifetime.ident); + if let GenericParamKind::Lifetime { .. } = param.kind { + self.check_lifetime(param.ident); } visit::walk_generic_param(self, param); } diff --git a/src/libsyntax/ast.rs b/src/libsyntax/ast.rs index 98f786628f95b..389afa96ea026 100644 --- a/src/libsyntax/ast.rs +++ b/src/libsyntax/ast.rs @@ -309,8 +309,8 @@ pub enum GenericParamKind { #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)] pub struct GenericParam { - pub ident: Ident, pub id: NodeId, + pub ident: Ident, pub attrs: ThinVec, pub bounds: ParamBounds, diff --git a/src/libsyntax/fold.rs b/src/libsyntax/fold.rs index a0c69d83e8460..804b1410b0786 100644 --- a/src/libsyntax/fold.rs +++ b/src/libsyntax/fold.rs @@ -143,6 +143,10 @@ pub trait Folder : Sized { noop_fold_ty(t, self) } + fn fold_lifetime(&mut self, l: Lifetime) -> Lifetime { + noop_fold_lifetime(l, self) + } + fn fold_ty_binding(&mut self, t: TypeBinding) -> TypeBinding { noop_fold_ty_binding(t, self) } @@ -240,10 +244,6 @@ pub trait Folder : Sized { noop_fold_variant_data(vdata, self) } - fn fold_ty_param(&mut self, tp: TyParam) -> TyParam { - noop_fold_ty_param(tp, self) - } - fn fold_generic_param(&mut self, param: GenericParam) -> GenericParam { noop_fold_generic_param(param, self) } @@ -268,17 +268,16 @@ pub trait Folder : Sized { noop_fold_interpolated(nt, self) } - fn fold_opt_bounds(&mut self, b: Option) -> Option { + fn fold_opt_bounds(&mut self, b: Option) -> Option { noop_fold_opt_bounds(b, self) } - fn fold_bounds(&mut self, b: ParamBounds) - -> ParamBounds { + fn fold_bounds(&mut self, b: ParamBounds) -> ParamBounds { noop_fold_bounds(b, self) } - fn fold_ty_param_bound(&mut self, tpb: ParamBound) -> ParamBound { - noop_fold_ty_param_bound(tpb, self) + fn fold_param_bound(&mut self, tpb: ParamBound) -> ParamBound { + noop_fold_param_bound(tpb, self) } fn fold_mt(&mut self, mt: MutTy) -> MutTy { @@ -391,10 +390,10 @@ pub fn noop_fold_ty(t: P, fld: &mut T) -> P { TyKind::Typeof(fld.fold_anon_const(expr)) } TyKind::TraitObject(bounds, syntax) => { - TyKind::TraitObject(bounds.move_map(|b| fld.fold_ty_param_bound(b)), syntax) + TyKind::TraitObject(bounds.move_map(|b| fld.fold_param_bound(b)), syntax) } TyKind::ImplTrait(bounds) => { - TyKind::ImplTrait(bounds.move_map(|b| fld.fold_ty_param_bound(b))) + TyKind::ImplTrait(bounds.move_map(|b| fld.fold_param_bound(b))) } TyKind::Mac(mac) => { TyKind::Mac(fld.fold_mac(mac)) @@ -677,32 +676,31 @@ pub fn noop_fold_fn_decl(decl: P, fld: &mut T) -> P { }) } -pub fn noop_fold_ty_param_bound(tpb: ParamBound, fld: &mut T) - -> ParamBound - where T: Folder { - match tpb { - TraitTyParamBound(ty, modifier) => TraitTyParamBound(fld.fold_poly_trait_ref(ty), modifier), +pub fn noop_fold_param_bound(pb: ParamBound, fld: &mut T) -> ParamBound where T: Folder { + match pb { + TraitTyParamBound(ty, modifier) => { + TraitTyParamBound(fld.fold_poly_trait_ref(ty), modifier) + } Outlives(lifetime) => Outlives(noop_fold_lifetime(lifetime, fld)), } } pub fn noop_fold_generic_param(param: GenericParam, fld: &mut T) -> GenericParam { - match param.kind { - GenericParamKind::Lifetime { bounds, lifetime } => { - let attrs: Vec<_> = param.attrs.into(); - GenericParamKind::Lifetime(LifetimeDef { - attrs: attrs.into_iter() + let attrs: Vec<_> = param.attrs.into(); + GenericParam { + ident: fld.fold_ident(param.ident), + id: fld.new_id(param.id), + attrs: attrs.into_iter() .flat_map(|x| fld.fold_attribute(x).into_iter()) .collect::>() .into(), - lifetime: Lifetime { - id: fld.new_id(param.id), - ident: fld.fold_ident(param.ident), - }, - bounds: bounds.move_map(|l| noop_fold_lifetime(l, fld)), - }) + bounds: param.bounds.move_map(|l| noop_fold_param_bound(l, fld)), + kind: match param.kind { + GenericParamKind::Lifetime => GenericParamKind::Lifetime, + GenericParamKind::Type { default } => GenericParamKind::Type { + default: default.map(|ty| fld.fold_ty(ty)) + } } - GenericParamKind::Type { .. } => GenericParamKind::Type(fld.fold_ty_param(param)), } } @@ -760,7 +758,7 @@ pub fn noop_fold_where_predicate( ast::WherePredicate::BoundPredicate(ast::WhereBoundPredicate { bound_generic_params: fld.fold_generic_params(bound_generic_params), bounded_ty: fld.fold_ty(bounded_ty), - bounds: bounds.move_map(|x| fld.fold_ty_param_bound(x)), + bounds: bounds.move_map(|x| fld.fold_param_bound(x)), span: fld.new_span(span) }) } @@ -770,7 +768,7 @@ pub fn noop_fold_where_predicate( ast::WherePredicate::RegionPredicate(ast::WhereRegionPredicate { span: fld.new_span(span), lifetime: noop_fold_lifetime(lifetime, fld), - bounds: bounds.move_map(|bound| noop_fold_lifetime(bound, fld)) + bounds: bounds.move_map(|bound| noop_fold_param_bound(bound, fld)) }) } ast::WherePredicate::EqPredicate(ast::WhereEqPredicate{id, @@ -856,7 +854,7 @@ pub fn noop_fold_opt_bounds(b: Option, folder: &mut T) fn noop_fold_bounds(bounds: ParamBounds, folder: &mut T) -> ParamBounds { - bounds.move_map(|bound| folder.fold_ty_param_bound(bound)) + bounds.move_map(|bound| folder.fold_param_bound(bound)) } pub fn noop_fold_block(b: P, folder: &mut T) -> P { diff --git a/src/libsyntax/visit.rs b/src/libsyntax/visit.rs index 1d535ab6bf0c1..f63b474f450aa 100644 --- a/src/libsyntax/visit.rs +++ b/src/libsyntax/visit.rs @@ -492,15 +492,10 @@ pub fn walk_param_bound<'a, V: Visitor<'a>>(visitor: &mut V, bound: &'a ParamBou pub fn walk_generic_param<'a, V: Visitor<'a>>(visitor: &mut V, param: &'a GenericParam) { visitor.visit_ident(param.ident); + walk_list!(visitor, visit_param_bound, ¶m.bounds); match param.kind { - GenericParamKind::Lifetime { ref bounds, ref lifetime } => { - walk_list!(visitor, visit_lifetime, bounds); - } - GenericParamKind::Type { ref bounds, ref default } => { - visitor.visit_ident(t.ident); - walk_list!(visitor, visit_ty_param_bound, bounds); - walk_list!(visitor, visit_ty, default); - } + GenericParamKind::Lifetime => {} + GenericParamKind::Type { ref default } => walk_list!(visitor, visit_ty, default), } walk_list!(visitor, visit_attribute, param.attrs.iter()); } From 59feafd9d8de7c458498f1a8de2bd8afc30f4fbd Mon Sep 17 00:00:00 2001 From: varkor Date: Thu, 31 May 2018 22:00:35 +0100 Subject: [PATCH 26/41] Fix NodeLifetime/NodeGenericParam confusion --- src/librustc/middle/resolve_lifetime.rs | 66 ++++++++++++------------- 1 file changed, 32 insertions(+), 34 deletions(-) diff --git a/src/librustc/middle/resolve_lifetime.rs b/src/librustc/middle/resolve_lifetime.rs index 883f24b37db9d..c49625216b46c 100644 --- a/src/librustc/middle/resolve_lifetime.rs +++ b/src/librustc/middle/resolve_lifetime.rs @@ -1397,25 +1397,22 @@ impl<'a, 'tcx> LifetimeContext<'a, 'tcx> { Some(LifetimeUseSet::One(_)) => { let node_id = self.tcx.hir.as_local_node_id(def_id).unwrap(); debug!("node id first={:?}", node_id); - if let hir::map::NodeLifetime(hir_lifetime) = self.tcx.hir.get(node_id) { - let span = hir_lifetime.span; - let id = hir_lifetime.id; - debug!( - "id ={:?} span = {:?} hir_lifetime = {:?}", - node_id, span, hir_lifetime - ); - - self.tcx - .struct_span_lint_node( - lint::builtin::SINGLE_USE_LIFETIMES, - id, - span, - &format!( - "lifetime parameter `{}` only used once", - hir_lifetime.name.name() - ), - ) - .emit(); + if let Some((id, span, name)) = match self.tcx.hir.get(node_id) { + hir::map::NodeLifetime(hir_lifetime) => { + Some((hir_lifetime.id, hir_lifetime.span, hir_lifetime.name.name())) + } + hir::map::NodeGenericParam(param) => { + Some((param.id, param.span, param.name)) + } + _ => None, + } { + debug!("id = {:?} span = {:?} name = {:?}", node_id, span, name); + self.tcx.struct_span_lint_node( + lint::builtin::SINGLE_USE_LIFETIMES, + id, + span, + &format!("lifetime parameter `{}` only used once", name), + ).emit(); } } Some(LifetimeUseSet::Many) => { @@ -1423,21 +1420,22 @@ impl<'a, 'tcx> LifetimeContext<'a, 'tcx> { } None => { let node_id = self.tcx.hir.as_local_node_id(def_id).unwrap(); - if let hir::map::NodeLifetime(hir_lifetime) = self.tcx.hir.get(node_id) { - let span = hir_lifetime.span; - let id = hir_lifetime.id; - - self.tcx - .struct_span_lint_node( - lint::builtin::UNUSED_LIFETIMES, - id, - span, - &format!( - "lifetime parameter `{}` never used", - hir_lifetime.name.name() - ), - ) - .emit(); + if let Some((id, span, name)) = match self.tcx.hir.get(node_id) { + hir::map::NodeLifetime(hir_lifetime) => { + Some((hir_lifetime.id, hir_lifetime.span, hir_lifetime.name.name())) + } + hir::map::NodeGenericParam(param) => { + Some((param.id, param.span, param.name)) + } + _ => None, + } { + debug!("id ={:?} span = {:?} name = {:?}", node_id, span, name); + self.tcx.struct_span_lint_node( + lint::builtin::UNUSED_LIFETIMES, + id, + span, + &format!("lifetime parameter `{}` never used", name) + ).emit(); } } } From 390aa5d42152909d927a84a04621f334397d3164 Mon Sep 17 00:00:00 2001 From: varkor Date: Fri, 1 Jun 2018 23:23:48 +0100 Subject: [PATCH 27/41] Introduce ParamName and use it in place of LifetimeName --- src/librustc/hir/intravisit.rs | 21 ++-- src/librustc/hir/lowering.rs | 74 ++++++------ src/librustc/hir/map/mod.rs | 11 +- src/librustc/hir/mod.rs | 42 ++++--- src/librustc/hir/print.rs | 2 +- src/librustc/ich/impls_hir.rs | 11 +- src/librustc/middle/resolve_lifetime.rs | 147 +++++++++++------------- src/librustc_lint/bad_style.rs | 5 +- src/librustc_typeck/check/mod.rs | 2 +- src/librustc_typeck/check/wfcheck.rs | 2 +- src/librustc_typeck/collect.rs | 11 +- src/librustdoc/clean/auto_trait.rs | 6 +- src/librustdoc/clean/mod.rs | 10 +- 13 files changed, 170 insertions(+), 174 deletions(-) diff --git a/src/librustc/hir/intravisit.rs b/src/librustc/hir/intravisit.rs index e3ded0279b44a..9c154d2e4af12 100644 --- a/src/librustc/hir/intravisit.rs +++ b/src/librustc/hir/intravisit.rs @@ -433,10 +433,10 @@ pub fn walk_label<'v, V: Visitor<'v>>(visitor: &mut V, label: &'v Label) { pub fn walk_lifetime<'v, V: Visitor<'v>>(visitor: &mut V, lifetime: &'v Lifetime) { visitor.visit_id(lifetime.id); match lifetime.name { - LifetimeName::Name(name) => { + LifetimeName::Param(ParamName::Plain(name)) => { visitor.visit_name(lifetime.span, name); } - LifetimeName::Fresh(_) | + LifetimeName::Param(ParamName::Fresh(_)) | LifetimeName::Static | LifetimeName::Implicit | LifetimeName::Underscore => {} @@ -742,20 +742,13 @@ pub fn walk_param_bound<'v, V: Visitor<'v>>(visitor: &mut V, bound: &'v ParamBou pub fn walk_generic_param<'v, V: Visitor<'v>>(visitor: &mut V, param: &'v GenericParam) { visitor.visit_id(param.id); + match param.name { + ParamName::Plain(name) => visitor.visit_name(param.span, name), + ParamName::Fresh(_) => {} + } match param.kind { - GenericParamKind::Lifetime { ref lt_name, .. } => { - match lt_name { - LifetimeName::Name(name) => { - visitor.visit_name(param.span, *name); - } - LifetimeName::Fresh(_) | - LifetimeName::Static | - LifetimeName::Implicit | - LifetimeName::Underscore => {} - } - } + GenericParamKind::Lifetime { .. } => {} GenericParamKind::Type { ref default, ref attrs, .. } => { - visitor.visit_name(param.span, param.name); walk_list!(visitor, visit_ty, default); walk_list!(visitor, visit_attribute, attrs.iter()); } diff --git a/src/librustc/hir/lowering.rs b/src/librustc/hir/lowering.rs index 969072a65ae1e..7ef72fd75423a 100644 --- a/src/librustc/hir/lowering.rs +++ b/src/librustc/hir/lowering.rs @@ -41,7 +41,7 @@ //! in the HIR, especially for multiple identifiers. use dep_graph::DepGraph; -use hir; +use hir::{self, ParamName}; use hir::HirVec; use hir::map::{DefKey, DefPathData, Definitions}; use hir::def_id::{DefId, DefIndex, DefIndexAddressSpace, CRATE_DEF_INDEX}; @@ -125,7 +125,7 @@ pub struct LoweringContext<'a> { // (i.e. it doesn't appear in the in_scope_lifetimes list), it is added // to this list. The results of this list are then added to the list of // lifetime definitions in the corresponding impl or function generics. - lifetimes_to_define: Vec<(Span, hir::LifetimeName)>, + lifetimes_to_define: Vec<(Span, ParamName)>, // Whether or not in-band lifetimes are being collected. This is used to // indicate whether or not we're in a place where new lifetimes will result @@ -678,13 +678,8 @@ impl<'a> LoweringContext<'a> { // that collisions are ok here and this shouldn't // really show up for end-user. let str_name = match hir_name { - hir::LifetimeName::Name(n) => n.as_str(), - hir::LifetimeName::Fresh(_) => keywords::UnderscoreLifetime.name().as_str(), - hir::LifetimeName::Implicit - | hir::LifetimeName::Underscore - | hir::LifetimeName::Static => { - span_bug!(span, "unexpected in-band lifetime name: {:?}", hir_name) - } + ParamName::Plain(name) => name.as_str(), + ParamName::Fresh(_) => keywords::UnderscoreLifetime.name().as_str(), }; // Add a definition for the in-band lifetime def @@ -699,15 +694,12 @@ impl<'a> LoweringContext<'a> { hir::GenericParam { id: def_node_id, - name: hir_name.name(), + name: hir_name, span, pure_wrt_drop: false, bounds: vec![].into(), - kind: hir::GenericParamKind::Lifetime { - lt_name: hir_name, - in_band: true, - } - } + kind: hir::GenericParamKind::Lifetime { in_band: true } + } }) .chain(in_band_ty_params.into_iter()) .collect(); @@ -728,7 +720,7 @@ impl<'a> LoweringContext<'a> { return; } - let hir_name = hir::LifetimeName::Name(name); + let hir_name = ParamName::Plain(name); if self.lifetimes_to_define.iter().any(|(_, lt_name)| *lt_name == hir_name) { return; @@ -739,10 +731,10 @@ impl<'a> LoweringContext<'a> { /// When we have either an elided or `'_` lifetime in an impl /// header, we convert it to - fn collect_fresh_in_band_lifetime(&mut self, span: Span) -> hir::LifetimeName { + fn collect_fresh_in_band_lifetime(&mut self, span: Span) -> ParamName { assert!(self.is_collecting_in_band_lifetimes); let index = self.lifetimes_to_define.len(); - let hir_name = hir::LifetimeName::Fresh(index); + let hir_name = ParamName::Fresh(index); self.lifetimes_to_define.push((span, hir_name)); hir_name } @@ -781,7 +773,7 @@ impl<'a> LoweringContext<'a> { { let old_len = self.in_scope_lifetimes.len(); let lt_def_names = params.iter().filter_map(|param| match param.kind { - hir::GenericParamKind::Lifetime { .. } => Some(param.name), + hir::GenericParamKind::Lifetime { .. } => Some(param.name.name()), _ => None, }); self.in_scope_lifetimes.extend(lt_def_names); @@ -1244,7 +1236,7 @@ impl<'a> LoweringContext<'a> { let name = Symbol::intern(&pprust::ty_to_string(t)); self.in_band_ty_params.push(hir::GenericParam { id: def_node_id, - name, + name: ParamName::Plain(name), span, pure_wrt_drop: false, bounds: hir_bounds, @@ -1359,9 +1351,10 @@ impl<'a> LoweringContext<'a> { fn visit_generic_param(&mut self, param: &'v hir::GenericParam) { // Record the introduction of 'a in `for<'a> ...` - if let hir::GenericParamKind::Lifetime { lt_name, .. } = param.kind { + if let hir::GenericParamKind::Lifetime { .. } = param.kind { // Introduce lifetimes one at a time so that we can handle // cases like `fn foo<'d>() -> impl for<'a, 'b: 'a, 'c: 'b + 'd>` + let lt_name = hir::LifetimeName::Param(param.name); self.currently_bound_lifetimes.push(lt_name); } @@ -1379,14 +1372,12 @@ impl<'a> LoweringContext<'a> { return; } } - name @ hir::LifetimeName::Fresh(_) => name, - name @ hir::LifetimeName::Name(_) => name, + hir::LifetimeName::Param(_) => lifetime.name, hir::LifetimeName::Static => return, }; if !self.currently_bound_lifetimes.contains(&name) - && !self.already_defined_lifetimes.contains(&name) - { + && !self.already_defined_lifetimes.contains(&name) { self.already_defined_lifetimes.insert(name); self.output_lifetimes.push(hir::Lifetime { @@ -1409,16 +1400,23 @@ impl<'a> LoweringContext<'a> { lifetime.span, ); + let name = match name { + hir::LifetimeName::Underscore => { + hir::ParamName::Plain(keywords::UnderscoreLifetime.name()) + } + hir::LifetimeName::Param(param_name) => param_name, + _ => bug!("expected LifetimeName::Param or ParamName::Plain"), + }; + self.output_lifetime_params.push(hir::GenericParam { id: def_node_id, - name: name.name(), + name, span: lifetime.span, pure_wrt_drop: false, bounds: vec![].into(), kind: hir::GenericParamKind::Lifetime { - lt_name: name, in_band: false, - } + } }); } } @@ -1894,7 +1892,7 @@ impl<'a> LoweringContext<'a> { x if x == "'_" => match self.anonymous_lifetime_mode { AnonymousLifetimeMode::CreateParameter => { let fresh_name = self.collect_fresh_in_band_lifetime(span); - self.new_named_lifetime(l.id, span, fresh_name) + self.new_named_lifetime(l.id, span, hir::LifetimeName::Param(fresh_name)) } AnonymousLifetimeMode::PassThrough => { @@ -1903,7 +1901,8 @@ impl<'a> LoweringContext<'a> { }, name => { self.maybe_collect_in_band_lifetime(span, name); - self.new_named_lifetime(l.id, span, hir::LifetimeName::Name(name)) + let param_name = ParamName::Plain(name); + self.new_named_lifetime(l.id, span, hir::LifetimeName::Param(param_name)) } } } @@ -1942,16 +1941,17 @@ impl<'a> LoweringContext<'a> { self.is_collecting_in_band_lifetimes = false; let lt = self.lower_lifetime(&Lifetime { id: param.id, ident: param.ident }); + let param_name = match lt.name { + hir::LifetimeName::Param(param_name) => param_name, + _ => hir::ParamName::Plain(lt.name.name()), + }; let param = hir::GenericParam { id: lt.id, - name: lt.name.name(), + name: param_name, span: lt.span, pure_wrt_drop: attr::contains_name(¶m.attrs, "may_dangle"), bounds, - kind: hir::GenericParamKind::Lifetime { - lt_name: lt.name, - in_band: false, - } + kind: hir::GenericParamKind::Lifetime { in_band: false } }; self.is_collecting_in_band_lifetimes = was_collecting_in_band; @@ -1977,7 +1977,7 @@ impl<'a> LoweringContext<'a> { hir::GenericParam { id: self.lower_node_id(param.id).node_id, - name, + name: hir::ParamName::Plain(name), span: param.ident.span, pure_wrt_drop: attr::contains_name(¶m.attrs, "may_dangle"), bounds, @@ -4193,7 +4193,7 @@ impl<'a> LoweringContext<'a> { hir::Lifetime { id: self.next_id().node_id, span, - name: fresh_name, + name: hir::LifetimeName::Param(fresh_name), } } diff --git a/src/librustc/hir/map/mod.rs b/src/librustc/hir/map/mod.rs index 999103980625c..5ea9348403a94 100644 --- a/src/librustc/hir/map/mod.rs +++ b/src/librustc/hir/map/mod.rs @@ -497,7 +497,7 @@ impl<'hir> Map<'hir> { NodeGenericParam(param) => { Some(match param.kind { GenericParamKind::Lifetime { .. } => Def::Local(param.id), - GenericParamKind::Type { .. } => Def::TyParam(self.local_def_id(param.id)) + GenericParamKind::Type { .. } => Def::TyParam(self.local_def_id(param.id)), }) } } @@ -616,11 +616,8 @@ impl<'hir> Map<'hir> { NodeItem(&Item { node: ItemTrait(..), .. }) => { keywords::SelfType.name() } - NodeGenericParam(param) => param.name, - _ => { - bug!("ty_param_name: {} not a type parameter", - self.node_to_string(id)) - } + NodeGenericParam(param) => param.name.name(), + _ => bug!("ty_param_name: {} not a type parameter", self.node_to_string(id)), } } @@ -957,7 +954,7 @@ impl<'hir> Map<'hir> { NodeVariant(v) => v.node.name, NodeField(f) => f.ident.name, NodeLifetime(lt) => lt.name.name(), - NodeGenericParam(param) => param.name, + NodeGenericParam(param) => param.name.name(), NodeBinding(&Pat { node: PatKind::Binding(_,_,l,_), .. }) => l.node, NodeStructCtor(_) => self.name(self.get_parent(id)), _ => bug!("no name for {}", self.node_to_string(id)) diff --git a/src/librustc/hir/mod.rs b/src/librustc/hir/mod.rs index cf0ae5aa94da5..ab7e8c4e81341 100644 --- a/src/librustc/hir/mod.rs +++ b/src/librustc/hir/mod.rs @@ -201,12 +201,9 @@ pub struct Lifetime { } #[derive(Debug, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Copy)] -pub enum LifetimeName { - /// User typed nothing. e.g. the lifetime in `&u32`. - Implicit, - - /// User typed `'_`. - Underscore, +pub enum ParamName { + /// Some user-given name like `T` or `'x`. + Plain(Name), /// Synthetic name generated when user elided a lifetime in an impl header, /// e.g. the lifetimes in cases like these: @@ -222,12 +219,30 @@ pub enum LifetimeName { /// where `'f` is something like `Fresh(0)`. The indices are /// unique per impl, but not necessarily continuous. Fresh(usize), +} + +impl ParamName { + pub fn name(&self) -> Name { + match *self { + ParamName::Plain(name) => name, + ParamName::Fresh(_) => keywords::UnderscoreLifetime.name(), + } + } +} + +#[derive(Debug, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Copy)] +pub enum LifetimeName { + /// User-given names or fresh (synthetic) names. + Param(ParamName), + + /// User typed nothing. e.g. the lifetime in `&u32`. + Implicit, + + /// User typed `'_`. + Underscore, /// User wrote `'static` Static, - - /// Some user-given name like `'x` - Name(Name), } impl LifetimeName { @@ -235,9 +250,9 @@ impl LifetimeName { use self::LifetimeName::*; match *self { Implicit => keywords::Invalid.name(), - Fresh(_) | Underscore => keywords::UnderscoreLifetime.name(), + Underscore => keywords::UnderscoreLifetime.name(), Static => keywords::StaticLifetime.name(), - Name(name) => name, + Param(param_name) => param_name.name(), } } @@ -251,7 +266,7 @@ impl LifetimeName { // in the compiler is concerned -- `Fresh(_)` variants act // equivalently to "some fresh name". They correspond to // early-bound regions on an impl, in other words. - Fresh(_) | Static | Name(_) => false, + Param(_) | Static => false, } } @@ -449,7 +464,6 @@ pub type ParamBounds = HirVec; pub enum GenericParamKind { /// A lifetime definition, eg `'a: 'b + 'c + 'd`. Lifetime { - lt_name: LifetimeName, // Indicates that the lifetime definition was synthetically added // as a result of an in-band lifetime usage like: // `fn foo(x: &'a u8) -> &'a u8 { x }` @@ -465,7 +479,7 @@ pub enum GenericParamKind { #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)] pub struct GenericParam { pub id: NodeId, - pub name: Name, + pub name: ParamName, pub bounds: ParamBounds, pub span: Span, pub pure_wrt_drop: bool, diff --git a/src/librustc/hir/print.rs b/src/librustc/hir/print.rs index a4cbd6515955d..56a4c2d3cb567 100644 --- a/src/librustc/hir/print.rs +++ b/src/librustc/hir/print.rs @@ -2115,7 +2115,7 @@ impl<'a> State<'a> { } pub fn print_generic_param(&mut self, param: &GenericParam) -> io::Result<()> { - self.print_name(param.name)?; + self.print_name(param.name.name())?; match param.kind { GenericParamKind::Lifetime { .. } => { let mut sep = ":"; diff --git a/src/librustc/ich/impls_hir.rs b/src/librustc/ich/impls_hir.rs index ae2bf1e4c7429..51934ad8e6a8c 100644 --- a/src/librustc/ich/impls_hir.rs +++ b/src/librustc/ich/impls_hir.rs @@ -142,12 +142,16 @@ impl<'a> HashStable> for hir::ImplItemId { } } +impl_stable_hash_for!(enum hir::ParamName { + Plain(name), + Fresh(index) +}); + impl_stable_hash_for!(enum hir::LifetimeName { + Param(param_name), Implicit, Underscore, - Fresh(index), Static, - Name(name) }); impl_stable_hash_for!(struct hir::Label { @@ -209,8 +213,7 @@ impl<'a> HashStable> for hir::GenericParamKind { hasher: &mut StableHasher) { mem::discriminant(self).hash_stable(hcx, hasher); match self { - hir::GenericParamKind::Lifetime { lt_name, in_band } => { - lt_name.hash_stable(hcx, hasher); + hir::GenericParamKind::Lifetime { in_band } => { in_band.hash_stable(hcx, hasher); } hir::GenericParamKind::Type { ref default, synthetic, attrs } => { diff --git a/src/librustc/middle/resolve_lifetime.rs b/src/librustc/middle/resolve_lifetime.rs index c49625216b46c..2461a1436bced 100644 --- a/src/librustc/middle/resolve_lifetime.rs +++ b/src/librustc/middle/resolve_lifetime.rs @@ -18,7 +18,7 @@ use hir::def::Def; use hir::def_id::{CrateNum, DefId, LocalDefId, LOCAL_CRATE}; use hir::map::Map; -use hir::{GenericArg, ItemLocalId, LifetimeName}; +use hir::{GenericArg, GenericParam, ItemLocalId, LifetimeName, ParamName}; use ty::{self, TyCtxt, GenericParamDefKind}; use errors::DiagnosticBuilder; @@ -30,6 +30,7 @@ use std::mem::replace; use syntax::ast; use syntax::attr; use syntax::ptr::P; +use syntax::symbol::keywords; use syntax_pos::Span; use util::nodemap::{DefIdMap, FxHashMap, FxHashSet, NodeMap, NodeSet}; @@ -81,34 +82,29 @@ pub enum Region { Free(DefId, /* lifetime decl */ DefId), } -fn new_region(hir_map: &Map, param: &hir::GenericParam) - -> (hir::LifetimeName, DefId, LifetimeDefOrigin) { +fn new_region(hir_map: &Map, param: &GenericParam) -> (DefId, LifetimeDefOrigin) { let def_id = hir_map.local_def_id(param.id); - let (lt_name, origin) = match param.kind { - GenericParamKind::Lifetime { lt_name, in_band, .. } => { - (lt_name, LifetimeDefOrigin::from_is_in_band(in_band)) + let origin = match param.kind { + GenericParamKind::Lifetime { in_band, .. } => { + LifetimeDefOrigin::from_is_in_band(in_band) } _ => bug!("expected a lifetime param"), }; - (lt_name, def_id, origin) + (def_id, origin) } impl Region { - fn early( - hir_map: &Map, - index: &mut u32, - param: &hir::GenericParam, - ) -> (hir::LifetimeName, Region) { + fn early(hir_map: &Map, index: &mut u32, param: &GenericParam) -> (ParamName, Region) { let i = *index; *index += 1; - let (name, def_id, origin) = new_region(hir_map, param); + let (def_id, origin) = new_region(hir_map, param); debug!("Region::early: index={} def_id={:?}", i, def_id); - (name, Region::EarlyBound(i, def_id, origin)) + (param.name, Region::EarlyBound(i, def_id, origin)) } - fn late(hir_map: &Map, param: &hir::GenericParam) -> (hir::LifetimeName, Region) { + fn late(hir_map: &Map, param: &GenericParam) -> (ParamName, Region) { let depth = ty::INNERMOST; - let (name, def_id, origin) = new_region(hir_map, param); + let (def_id, origin) = new_region(hir_map, param); debug!( "Region::late: param={:?} depth={:?} def_id={:?} origin={:?}", param, @@ -116,7 +112,7 @@ impl Region { def_id, origin, ); - (name, Region::LateBound(depth, def_id, origin)) + (param.name, Region::LateBound(depth, def_id, origin)) } fn late_anon(index: &Cell) -> Region { @@ -277,7 +273,7 @@ enum Scope<'a> { /// it should be shifted by the number of `Binder`s in between the /// declaration `Binder` and the location it's referenced from. Binder { - lifetimes: FxHashMap, + lifetimes: FxHashMap, /// if we extend this scope with another scope, what is the next index /// we should use for an early-bound region? @@ -619,7 +615,7 @@ impl<'a, 'tcx> Visitor<'tcx> for LifetimeContext<'a, 'tcx> { // cc #48468 self.resolve_elided_lifetimes(vec![lifetime], false) } - LifetimeName::Fresh(_) | LifetimeName::Static | LifetimeName::Name(_) => { + LifetimeName::Param(_) | LifetimeName::Static => { // If the user wrote an explicit name, use that. self.visit_lifetime(lifetime); } @@ -695,10 +691,14 @@ impl<'a, 'tcx> Visitor<'tcx> for LifetimeContext<'a, 'tcx> { match param.kind { GenericParamKind::Lifetime { .. } => { let (name, reg) = Region::early(&self.tcx.hir, &mut index, ¶m); - if let hir::LifetimeName::Underscore = name { - // Pick the elided lifetime "definition" if one exists - // and use it to make an elision scope. - elision = Some(reg); + if let hir::ParamName::Plain(param_name) = name { + if param_name == keywords::UnderscoreLifetime.name() { + // Pick the elided lifetime "definition" if one exists + // and use it to make an elision scope. + elision = Some(reg); + } else { + lifetimes.insert(name, reg); + } } else { lifetimes.insert(name, reg); } @@ -1180,7 +1180,8 @@ fn extract_labels(ctxt: &mut LifetimeContext<'_, '_>, body: &hir::Body) { ref lifetimes, s, .. } => { // FIXME (#24278): non-hygienic comparison - if let Some(def) = lifetimes.get(&hir::LifetimeName::Name(label)) { + let param_name = hir::ParamName::Plain(label); + if let Some(def) = lifetimes.get(¶m_name) { let node_id = tcx.hir.as_local_node_id(def.id().unwrap()).unwrap(); signal_shadowing_problem( @@ -1222,7 +1223,7 @@ fn compute_object_lifetime_defaults( generics.params.iter().find_map(|param| match param.kind { GenericParamKind::Lifetime { .. } => { if i == 0 { - return Some(param.name.to_string()); + return Some(param.name.name().to_string()); } i -= 1; None @@ -1299,8 +1300,8 @@ fn object_lifetime_defaults_for_item( Set1::One(Region::Static) } else { generics.params.iter().filter_map(|param| match param.kind { - GenericParamKind::Lifetime { lt_name, in_band, .. } => { - Some((param.id, lt_name, in_band)) + GenericParamKind::Lifetime { in_band } => { + Some((param.id, hir::LifetimeName::Param(param.name), in_band)) } _ => None, }) @@ -1402,7 +1403,7 @@ impl<'a, 'tcx> LifetimeContext<'a, 'tcx> { Some((hir_lifetime.id, hir_lifetime.span, hir_lifetime.name.name())) } hir::map::NodeGenericParam(param) => { - Some((param.id, param.span, param.name)) + Some((param.id, param.span, param.name.name())) } _ => None, } { @@ -1425,7 +1426,7 @@ impl<'a, 'tcx> LifetimeContext<'a, 'tcx> { Some((hir_lifetime.id, hir_lifetime.span, hir_lifetime.name.name())) } hir::map::NodeGenericParam(param) => { - Some((param.id, param.span, param.name)) + Some((param.id, param.span, param.name.name())) } _ => None, } { @@ -1573,10 +1574,12 @@ impl<'a, 'tcx> LifetimeContext<'a, 'tcx> { break None; } - Scope::Binder { - ref lifetimes, s, .. - } => { - if let Some(&def) = lifetimes.get(&lifetime_ref.name) { + Scope::Binder { ref lifetimes, s, .. } => { + let name = match lifetime_ref.name { + LifetimeName::Param(param_name) => param_name, + _ => bug!("expected LifetimeName::Param"), + }; + if let Some(&def) = lifetimes.get(&name) { break Some(def.shifted(late_depth)); } else { late_depth += 1; @@ -2235,13 +2238,14 @@ impl<'a, 'tcx> LifetimeContext<'a, 'tcx> { fn check_lifetime_params(&mut self, old_scope: ScopeRef, params: &'tcx [hir::GenericParam]) { let lifetimes: Vec<_> = params.iter().filter_map(|param| match param.kind { - GenericParamKind::Lifetime { lt_name, .. } => Some((param, lt_name)), + GenericParamKind::Lifetime { .. } => Some((param, param.name)), _ => None, }).collect(); for (i, (lifetime_i, lifetime_i_name)) in lifetimes.iter().enumerate() { - match lifetime_i_name { - hir::LifetimeName::Static | hir::LifetimeName::Underscore => { - let name = lifetime_i.name; + if let hir::ParamName::Plain(_) = lifetime_i_name { + let name = lifetime_i_name.name(); + if name == keywords::UnderscoreLifetime.name() || + name == keywords::StaticLifetime.name() { let mut err = struct_span_err!( self.tcx.sess, lifetime_i.span, @@ -2255,9 +2259,6 @@ impl<'a, 'tcx> LifetimeContext<'a, 'tcx> { ); err.emit(); } - hir::LifetimeName::Fresh(_) - | hir::LifetimeName::Implicit - | hir::LifetimeName::Name(_) => {} } // It is a hard error to shadow a lifetime within the same scope. @@ -2268,10 +2269,10 @@ impl<'a, 'tcx> LifetimeContext<'a, 'tcx> { lifetime_j.span, E0263, "lifetime name `{}` declared twice in the same scope", - lifetime_j.name + lifetime_j.name.name() ).span_label(lifetime_j.span, "declared twice") - .span_label(lifetime_i.span, "previous declaration here") - .emit(); + .span_label(lifetime_i.span, "previous declaration here") + .emit(); } } @@ -2293,25 +2294,20 @@ impl<'a, 'tcx> LifetimeContext<'a, 'tcx> { } hir::LifetimeName::Static => { self.insert_lifetime(lt, Region::Static); - self.tcx - .sess - .struct_span_warn( - lifetime_i.span.to(lt.span), - &format!( - "unnecessary lifetime parameter `{}`", - lifetime_i.name - ), - ) - .help(&format!( - "you can use the `'static` lifetime directly, in place \ - of `{}`", - lifetime_i.name - )) - .emit(); + self.tcx.sess.struct_span_warn( + lifetime_i.span.to(lt.span), + &format!( + "unnecessary lifetime parameter `{}`", + lifetime_i.name.name(), + ), + ).help(&format!( + "you can use the `'static` lifetime directly, in place \ + of `{}`", + lifetime_i.name.name(), + )).emit(); } - hir::LifetimeName::Fresh(_) - | hir::LifetimeName::Implicit - | hir::LifetimeName::Name(_) => { + hir::LifetimeName::Param(_) + | hir::LifetimeName::Implicit => { self.resolve_lifetime_ref(lt); } } @@ -2328,7 +2324,7 @@ impl<'a, 'tcx> LifetimeContext<'a, 'tcx> { ) { for &(label, label_span) in &self.labels_in_fn { // FIXME (#24278): non-hygienic comparison - if param.name == label { + if param.name.name() == label { signal_shadowing_problem( self.tcx, label, @@ -2339,11 +2335,6 @@ impl<'a, 'tcx> LifetimeContext<'a, 'tcx> { } } - let name = match param.kind { - GenericParamKind::Lifetime { lt_name, .. } => lt_name, - _ => bug!("expected lifetime param"), - }; - loop { match *old_scope { Scope::Body { s, .. } @@ -2359,12 +2350,12 @@ impl<'a, 'tcx> LifetimeContext<'a, 'tcx> { Scope::Binder { ref lifetimes, s, .. } => { - if let Some(&def) = lifetimes.get(&name) { + if let Some(&def) = lifetimes.get(¶m.name) { let node_id = self.tcx.hir.as_local_node_id(def.id().unwrap()).unwrap(); signal_shadowing_problem( self.tcx, - param.name, + param.name.name(), original_lifetime(self.tcx.hir.span(node_id)), shadower_lifetime(¶m), ); @@ -2515,10 +2506,10 @@ fn insert_late_bound_lifetimes( for param in &generics.params { match param.kind { - hir::GenericParamKind::Lifetime { lt_name, .. } => { + hir::GenericParamKind::Lifetime { .. } => { if !param.bounds.is_empty() { // `'a: 'b` means both `'a` and `'b` are referenced - appears_in_where_clause.regions.insert(lt_name); + appears_in_where_clause.regions.insert(hir::LifetimeName::Param(param.name)); } } hir::GenericParamKind::Type { .. } => {} @@ -2535,25 +2526,21 @@ fn insert_late_bound_lifetimes( // - do not appear in the where-clauses // - are not implicitly captured by `impl Trait` for param in &generics.params { - let name = match param.kind { - GenericParamKind::Lifetime { lt_name, .. } => lt_name, - _ => continue, - }; - + let lt_name = hir::LifetimeName::Param(param.name); // appears in the where clauses? early-bound. - if appears_in_where_clause.regions.contains(&name) { + 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", - name, + param.name.name(), param.id); let inserted = map.late_bound.insert(param.id); diff --git a/src/librustc_lint/bad_style.rs b/src/librustc_lint/bad_style.rs index aeeb812dd77d4..8f8fe04fd8e01 100644 --- a/src/librustc_lint/bad_style.rs +++ b/src/librustc_lint/bad_style.rs @@ -151,7 +151,7 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for NonCamelCaseTypes { GenericParamKind::Lifetime { .. } => {} GenericParamKind::Type { synthetic, .. } => { if synthetic.is_none() { - self.check_case(cx, "type parameter", param.name, param.span); + self.check_case(cx, "type parameter", param.name.name(), param.span); } } } @@ -258,7 +258,8 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for NonSnakeCase { fn check_generic_param(&mut self, cx: &LateContext, param: &hir::GenericParam) { match param.kind { GenericParamKind::Lifetime { .. } => { - self.check_snake_case(cx, "lifetime", ¶m.name.as_str(), Some(param.span)); + let name = param.name.name().as_str(); + self.check_snake_case(cx, "lifetime", &name, Some(param.span)); } GenericParamKind::Type { .. } => {} } diff --git a/src/librustc_typeck/check/mod.rs b/src/librustc_typeck/check/mod.rs index 9ff400d013bf8..003c6c4fb74d2 100644 --- a/src/librustc_typeck/check/mod.rs +++ b/src/librustc_typeck/check/mod.rs @@ -5195,7 +5195,7 @@ pub fn check_bounds_are_used<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, for (&used, param) in types_used.iter().zip(types) { if !used { struct_span_err!(tcx.sess, param.span, E0091, "type parameter `{}` is unused", - param.name) + param.name.name()) .span_label(param.span, "unused type parameter") .emit(); } diff --git a/src/librustc_typeck/check/wfcheck.rs b/src/librustc_typeck/check/wfcheck.rs index 9df8502461cc0..c4b20699cee58 100644 --- a/src/librustc_typeck/check/wfcheck.rs +++ b/src/librustc_typeck/check/wfcheck.rs @@ -632,7 +632,7 @@ fn check_variances_for_type_defn<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, } let param = &ast_generics.params[index]; - report_bivariance(tcx, param.span, param.name); + report_bivariance(tcx, param.span, param.name.name()); } } diff --git a/src/librustc_typeck/collect.rs b/src/librustc_typeck/collect.rs index d53efe1460004..eb18916e78153 100644 --- a/src/librustc_typeck/collect.rs +++ b/src/librustc_typeck/collect.rs @@ -898,7 +898,7 @@ fn generics_of<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, let early_lifetimes = early_bound_lifetimes_from_generics(tcx, ast_generics); params.extend(early_lifetimes.enumerate().map(|(i, param)| { ty::GenericParamDef { - name: param.name.as_interned_str(), + name: param.name.name().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, @@ -914,7 +914,7 @@ fn generics_of<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, let mut i = 0; params.extend(ast_generics.params.iter().filter_map(|param| match param.kind { GenericParamKind::Type { ref default, synthetic, .. } => { - if param.name == keywords::SelfType.name() { + if param.name.name() == keywords::SelfType.name() { span_bug!(param.span, "`Self` should not be the name of a regular parameter"); } @@ -931,7 +931,7 @@ fn generics_of<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, let ty_param = ty::GenericParamDef { index: type_start + i as u32, - name: param.name.as_interned_str(), + name: param.name.name().as_interned_str(), def_id: tcx.hir.local_def_id(param.id), pure_wrt_drop: param.pure_wrt_drop, kind: ty::GenericParamDefKind::Type { @@ -1437,7 +1437,7 @@ pub fn explicit_predicates_of<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, let region = tcx.mk_region(ty::ReEarlyBound(ty::EarlyBoundRegion { def_id: tcx.hir.local_def_id(param.id), index, - name: param.name.as_interned_str(), + name: param.name.name().as_interned_str(), })); index += 1; @@ -1461,7 +1461,8 @@ pub fn explicit_predicates_of<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, for param in &ast_generics.params { match param.kind { GenericParamKind::Type { .. } => { - let param_ty = ty::ParamTy::new(index, param.name.as_interned_str()).to_ty(tcx); + let name = param.name.name().as_interned_str(); + let param_ty = ty::ParamTy::new(index, name).to_ty(tcx); index += 1; let sized = SizedByDefault::Yes; diff --git a/src/librustdoc/clean/auto_trait.rs b/src/librustdoc/clean/auto_trait.rs index 9671007a06b9f..0874e921f4173 100644 --- a/src/librustdoc/clean/auto_trait.rs +++ b/src/librustdoc/clean/auto_trait.rs @@ -251,15 +251,15 @@ impl<'a, 'tcx, 'rcx> AutoTraitFinder<'a, 'tcx, 'rcx> { match param.kind { ty::GenericParamDefKind::Lifetime => { let name = if param.name == "" { - hir::LifetimeName::Static + hir::ParamName::Plain(keywords::StaticLifetime.name()) } else { - hir::LifetimeName::Name(param.name.as_symbol()) + hir::ParamName::Plain(param.name.as_symbol()) }; args.push(hir::GenericArg::Lifetime(hir::Lifetime { id: ast::DUMMY_NODE_ID, span: DUMMY_SP, - name, + name: hir::LifetimeName::Param(name), })); } ty::GenericParamDefKind::Type {..} => { diff --git a/src/librustdoc/clean/mod.rs b/src/librustdoc/clean/mod.rs index cea29ab30dfe7..2b02c639b954a 100644 --- a/src/librustdoc/clean/mod.rs +++ b/src/librustdoc/clean/mod.rs @@ -1678,13 +1678,13 @@ impl Clean for hir::GenericParam { _ => panic!(), }); let name = bounds.next().unwrap().name.name(); - let mut s = format!("{}: {}", self.name, name); + let mut s = format!("{}: {}", self.name.name(), name); for bound in bounds { s.push_str(&format!(" + {}", bound.name.name())); } Lifetime(s) } else { - Lifetime(self.name.to_string()) + Lifetime(self.name.name().to_string()) } } _ => panic!(), @@ -1897,18 +1897,18 @@ impl Clean for hir::GenericParam { _ => panic!(), }); let name = bounds.next().unwrap().name.name(); - let mut s = format!("{}: {}", self.name, name); + let mut s = format!("{}: {}", self.name.name(), name); for bound in bounds { s.push_str(&format!(" + {}", bound.name.name())); } s } else { - self.name.to_string() + self.name.name().to_string() }; (name, GenericParamDefKind::Lifetime) } hir::GenericParamKind::Type { ref default, synthetic, .. } => { - (self.name.clean(cx), GenericParamDefKind::Type { + (self.name.name().clean(cx), GenericParamDefKind::Type { did: cx.tcx.hir.local_def_id(self.id), bounds: self.bounds.clean(cx), default: default.clean(cx), From 8bc3a35576dd4e2f02b9d34fe5ed241288b5bfbe Mon Sep 17 00:00:00 2001 From: varkor Date: Wed, 13 Jun 2018 13:29:40 +0100 Subject: [PATCH 28/41] Fix HasAttrs support for GenericParam --- src/libsyntax/attr.rs | 15 +++++---------- src/libsyntax/parse/parser.rs | 2 +- 2 files changed, 6 insertions(+), 11 deletions(-) diff --git a/src/libsyntax/attr.rs b/src/libsyntax/attr.rs index 2389ed799cfcc..ded493fe3958c 100644 --- a/src/libsyntax/attr.rs +++ b/src/libsyntax/attr.rs @@ -1446,17 +1446,12 @@ impl HasAttrs for Stmt { impl HasAttrs for GenericParam { fn attrs(&self) -> &[ast::Attribute] { - match self { - GenericParam::Lifetime(lifetime) => lifetime.attrs(), - GenericParam::Type(ty) => ty.attrs(), - } + &self.attrs } - fn map_attrs) -> Vec>(self, f: F) -> Self { - match self { - GenericParam::Lifetime(lifetime) => GenericParam::Lifetime(lifetime.map_attrs(f)), - GenericParam::Type(ty) => GenericParam::Type(ty.map_attrs(f)), - } + fn map_attrs) -> Vec>(mut self, f: F) -> Self { + self.attrs = self.attrs.map_attrs(f); + self } } @@ -1479,5 +1474,5 @@ macro_rules! derive_has_attrs { derive_has_attrs! { Item, Expr, Local, ast::ForeignItem, ast::StructField, ast::ImplItem, ast::TraitItem, ast::Arm, - ast::Field, ast::FieldPat, ast::Variant_, ast::LifetimeDef, ast::TyParam + ast::Field, ast::FieldPat, ast::Variant_ } diff --git a/src/libsyntax/parse/parser.rs b/src/libsyntax/parse/parser.rs index b2cfb459c359a..f69361c28ad00 100644 --- a/src/libsyntax/parse/parser.rs +++ b/src/libsyntax/parse/parser.rs @@ -4752,7 +4752,7 @@ impl<'a> Parser<'a> { self.span_err(question_span, "`?` may only modify trait bounds, not lifetime bounds"); } - bounds.push(Outlives(RegionTyParamBound(self.expect_lifetime()))); + bounds.push(Outlives(self.expect_lifetime())); if has_parens { self.expect(&token::CloseDelim(token::Paren))?; self.span_err(self.prev_span, From 7de6ed06a528db8f34ca3e75ded9d77ab9ba8b9a Mon Sep 17 00:00:00 2001 From: varkor Date: Thu, 14 Jun 2018 11:25:14 +0100 Subject: [PATCH 29/41] Rename TraitTyParamBound to ParamBound::Trait --- src/librustc/hir/intravisit.rs | 4 ++-- src/librustc/hir/lowering.rs | 14 ++++++------ src/librustc/hir/mod.rs | 7 +++--- src/librustc/hir/print.rs | 14 ++++++------ src/librustc/ich/impls_hir.rs | 2 +- src/librustc/middle/resolve_lifetime.rs | 2 +- src/librustc_passes/ast_validation.rs | 4 ++-- src/librustc_privacy/lib.rs | 2 +- src/librustc_save_analysis/dump_visitor.rs | 4 ++-- src/librustc_typeck/collect.rs | 26 ++++++++-------------- src/librustdoc/clean/mod.rs | 12 +++++----- src/libsyntax/ast.rs | 6 ++--- src/libsyntax/ext/build.rs | 2 +- src/libsyntax/fold.rs | 4 ++-- src/libsyntax/parse/parser.rs | 8 +++---- src/libsyntax/print/pprust.rs | 8 +++---- src/libsyntax/visit.rs | 2 +- 17 files changed, 57 insertions(+), 64 deletions(-) diff --git a/src/librustc/hir/intravisit.rs b/src/librustc/hir/intravisit.rs index 9c154d2e4af12..a66650aa161f2 100644 --- a/src/librustc/hir/intravisit.rs +++ b/src/librustc/hir/intravisit.rs @@ -733,10 +733,10 @@ pub fn walk_foreign_item<'v, V: Visitor<'v>>(visitor: &mut V, foreign_item: &'v pub fn walk_param_bound<'v, V: Visitor<'v>>(visitor: &mut V, bound: &'v ParamBound) { match *bound { - TraitTyParamBound(ref typ, modifier) => { + ParamBound::Trait(ref typ, modifier) => { visitor.visit_poly_trait_ref(typ, modifier); } - Outlives(ref lifetime) => visitor.visit_lifetime(lifetime), + ParamBound::Outlives(ref lifetime) => visitor.visit_lifetime(lifetime), } } diff --git a/src/librustc/hir/lowering.rs b/src/librustc/hir/lowering.rs index 7ef72fd75423a..2a23144849003 100644 --- a/src/librustc/hir/lowering.rs +++ b/src/librustc/hir/lowering.rs @@ -1108,10 +1108,10 @@ impl<'a> LoweringContext<'a> { let bounds = bounds .iter() .filter_map(|bound| match *bound { - TraitTyParamBound(ref ty, TraitBoundModifier::None) => { + Trait(ref ty, TraitBoundModifier::None) => { Some(self.lower_poly_trait_ref(ty, itctx)) } - TraitTyParamBound(_, TraitBoundModifier::Maybe) => None, + Trait(_, TraitBoundModifier::Maybe) => None, Outlives(ref lifetime) => { if lifetime_bound.is_none() { lifetime_bound = Some(self.lower_lifetime(lifetime)); @@ -1875,12 +1875,12 @@ impl<'a> LoweringContext<'a> { itctx: ImplTraitContext, ) -> hir::ParamBound { match *tpb { - TraitTyParamBound(ref ty, modifier) => hir::TraitTyParamBound( + ParamBound::Trait(ref ty, modifier) => hir::ParamBound::Trait( self.lower_poly_trait_ref(ty, itctx), self.lower_trait_bound_modifier(modifier), ), - Outlives(ref lifetime) => { - hir::Outlives(self.lower_lifetime(lifetime)) + ParamBound::Outlives(ref lifetime) => { + hir::ParamBound::Outlives(self.lower_lifetime(lifetime)) } } } @@ -2010,7 +2010,7 @@ impl<'a> LoweringContext<'a> { for pred in &generics.where_clause.predicates { if let WherePredicate::BoundPredicate(ref bound_pred) = *pred { 'next_bound: for bound in &bound_pred.bounds { - if let TraitTyParamBound(_, TraitBoundModifier::Maybe) = *bound { + if let ParamBound::Trait(_, TraitBoundModifier::Maybe) = *bound { let report_error = |this: &mut Self| { this.diagnostic().span_err( bound_pred.bounded_ty.span, @@ -2095,7 +2095,7 @@ impl<'a> LoweringContext<'a> { .filter_map(|bound| match *bound { // Ignore `?Trait` bounds. // Tthey were copied into type parameters already. - TraitTyParamBound(_, TraitBoundModifier::Maybe) => None, + ParamBound::Trait(_, TraitBoundModifier::Maybe) => None, _ => Some(this.lower_param_bound( bound, ImplTraitContext::Disallowed, diff --git a/src/librustc/hir/mod.rs b/src/librustc/hir/mod.rs index ab7e8c4e81341..974d287cd9731 100644 --- a/src/librustc/hir/mod.rs +++ b/src/librustc/hir/mod.rs @@ -22,7 +22,6 @@ pub use self::Mutability::*; pub use self::PrimTy::*; pub use self::Stmt_::*; pub use self::Ty_::*; -pub use self::ParamBound::*; pub use self::UnOp::*; pub use self::UnsafeSource::*; pub use self::Visibility::{Public, Inherited}; @@ -445,15 +444,15 @@ pub enum TraitBoundModifier { /// detects Copy, Send and Sync. #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)] pub enum ParamBound { - TraitTyParamBound(PolyTraitRef, TraitBoundModifier), + Trait(PolyTraitRef, TraitBoundModifier), Outlives(Lifetime), } impl ParamBound { pub fn span(&self) -> Span { match self { - &TraitTyParamBound(ref t, ..) => t.span, - &Outlives(ref l) => l.span, + &ParamBound::Trait(ref t, ..) => t.span, + &ParamBound::Outlives(ref l) => l.span, } } } diff --git a/src/librustc/hir/print.rs b/src/librustc/hir/print.rs index 56a4c2d3cb567..b6fd136255421 100644 --- a/src/librustc/hir/print.rs +++ b/src/librustc/hir/print.rs @@ -24,7 +24,7 @@ use syntax::util::parser::{self, AssocOp, Fixity}; use syntax_pos::{self, BytePos, FileName}; use hir; -use hir::{PatKind, Outlives, TraitTyParamBound, TraitBoundModifier, RangeEnd}; +use hir::{PatKind, ParamBound, TraitBoundModifier, RangeEnd}; use hir::{GenericParam, GenericParamKind, GenericArg}; use std::cell::Cell; @@ -740,7 +740,7 @@ impl<'a> State<'a> { self.print_generic_params(&generics.params)?; let mut real_bounds = Vec::with_capacity(bounds.len()); for b in bounds.iter() { - if let TraitTyParamBound(ref ptr, hir::TraitBoundModifier::Maybe) = *b { + if let ParamBound::Trait(ref ptr, hir::TraitBoundModifier::Maybe) = *b { self.s.space()?; self.word_space("for ?")?; self.print_trait_ref(&ptr.trait_ref)?; @@ -766,7 +766,7 @@ impl<'a> State<'a> { let mut real_bounds = Vec::with_capacity(bounds.len()); // FIXME(durka) this seems to be some quite outdated syntax for b in bounds.iter() { - if let TraitTyParamBound(ref ptr, hir::TraitBoundModifier::Maybe) = *b { + if let ParamBound::Trait(ref ptr, hir::TraitBoundModifier::Maybe) = *b { self.s.space()?; self.word_space("for ?")?; self.print_trait_ref(&ptr.trait_ref)?; @@ -2086,13 +2086,13 @@ impl<'a> State<'a> { } match bound { - TraitTyParamBound(tref, modifier) => { + ParamBound::Trait(tref, modifier) => { if modifier == &TraitBoundModifier::Maybe { self.s.word("?")?; } self.print_poly_trait_ref(tref)?; } - Outlives(lt) => { + ParamBound::Outlives(lt) => { self.print_lifetime(lt)?; } } @@ -2121,7 +2121,7 @@ impl<'a> State<'a> { let mut sep = ":"; for bound in ¶m.bounds { match bound { - hir::ParamBound::Outlives(lt) => { + ParamBound::Outlives(lt) => { self.s.word(sep)?; self.print_lifetime(lt)?; sep = "+"; @@ -2181,7 +2181,7 @@ impl<'a> State<'a> { for (i, bound) in bounds.iter().enumerate() { match bound { - hir::ParamBound::Outlives(lt) => { + ParamBound::Outlives(lt) => { self.print_lifetime(lt)?; } _ => bug!(), diff --git a/src/librustc/ich/impls_hir.rs b/src/librustc/ich/impls_hir.rs index 51934ad8e6a8c..ec55a05822cac 100644 --- a/src/librustc/ich/impls_hir.rs +++ b/src/librustc/ich/impls_hir.rs @@ -189,7 +189,7 @@ impl_stable_hash_for!(struct hir::GenericArgs { }); impl_stable_hash_for!(enum hir::ParamBound { - TraitTyParamBound(poly_trait_ref, trait_bound_modifier), + Trait(poly_trait_ref, trait_bound_modifier), Outlives(lifetime) }); diff --git a/src/librustc/middle/resolve_lifetime.rs b/src/librustc/middle/resolve_lifetime.rs index 2461a1436bced..14c782308a801 100644 --- a/src/librustc/middle/resolve_lifetime.rs +++ b/src/librustc/middle/resolve_lifetime.rs @@ -1256,7 +1256,7 @@ fn object_lifetime_defaults_for_item( ) -> Vec { fn add_bounds(set: &mut Set1, bounds: &[hir::ParamBound]) { for bound in bounds { - if let hir::Outlives(ref lifetime) = *bound { + if let hir::ParamBound::Outlives(ref lifetime) = *bound { set.insert(lifetime.name); } } diff --git a/src/librustc_passes/ast_validation.rs b/src/librustc_passes/ast_validation.rs index 3411c28f35bca..bdfe1d50e2686 100644 --- a/src/librustc_passes/ast_validation.rs +++ b/src/librustc_passes/ast_validation.rs @@ -101,7 +101,7 @@ impl<'a> AstValidator<'a> { fn no_questions_in_bounds(&self, bounds: &ParamBounds, where_: &str, is_trait: bool) { for bound in bounds { - if let TraitTyParamBound(ref poly, TraitBoundModifier::Maybe) = *bound { + if let Trait(ref poly, TraitBoundModifier::Maybe) = *bound { let mut err = self.err_handler().struct_span_err(poly.span, &format!("`?Trait` is not permitted in {}", where_)); if is_trait { @@ -203,7 +203,7 @@ impl<'a> Visitor<'a> for AstValidator<'a> { } TyKind::ImplTrait(ref bounds) => { if !bounds.iter() - .any(|b| if let TraitTyParamBound(..) = *b { true } else { false }) { + .any(|b| if let Trait(..) = *b { true } else { false }) { self.err_handler().span_err(ty.span, "at least one trait must be specified"); } } diff --git a/src/librustc_privacy/lib.rs b/src/librustc_privacy/lib.rs index 2667f68b26095..68b5a925ef3a0 100644 --- a/src/librustc_privacy/lib.rs +++ b/src/librustc_privacy/lib.rs @@ -1039,7 +1039,7 @@ impl<'a, 'tcx> ObsoleteVisiblePrivateTypesVisitor<'a, 'tcx> { fn check_ty_param_bound(&mut self, ty_param_bound: &hir::ParamBound) { - if let hir::TraitTyParamBound(ref trait_ref, _) = *ty_param_bound { + if let hir::ParamBound::Trait(ref trait_ref, _) = *ty_param_bound { if self.path_is_private_type(&trait_ref.trait_ref.path) { self.old_error_set.insert(trait_ref.trait_ref.ref_id); } diff --git a/src/librustc_save_analysis/dump_visitor.rs b/src/librustc_save_analysis/dump_visitor.rs index cbae6c1ab1ab8..1373ee94587a5 100644 --- a/src/librustc_save_analysis/dump_visitor.rs +++ b/src/librustc_save_analysis/dump_visitor.rs @@ -761,7 +761,7 @@ impl<'l, 'tcx: 'l, 'll, O: DumpOutput + 'll> DumpVisitor<'l, 'tcx, 'll, O> { // super-traits for super_bound in trait_refs.iter() { let trait_ref = match *super_bound { - ast::TraitTyParamBound(ref trait_ref, _) => trait_ref, + ast::Trait(ref trait_ref, _) => trait_ref, ast::Outlives(..) => { continue; } @@ -1489,7 +1489,7 @@ impl<'l, 'tcx: 'l, 'll, O: DumpOutput + 'll> Visitor<'l> for DumpVisitor<'l, 'tc ast::GenericParamKind::Lifetime { .. } => {} ast::GenericParamKind::Type { ref default, .. } => { for bound in ¶m.bounds { - if let ast::TraitTyParamBound(ref trait_ref, _) = *bound { + if let ast::Trait(ref trait_ref, _) = *bound { self.process_path(trait_ref.trait_ref.ref_id, &trait_ref.trait_ref.path) } } diff --git a/src/librustc_typeck/collect.rs b/src/librustc_typeck/collect.rs index eb18916e78153..f578d4f1ae6ab 100644 --- a/src/librustc_typeck/collect.rs +++ b/src/librustc_typeck/collect.rs @@ -1257,7 +1257,7 @@ fn is_unsized<'gcx: 'tcx, 'tcx>(astconv: &AstConv<'gcx, 'tcx>, // Try to find an unbound in bounds. let mut unbound = None; for ab in ast_bounds { - if let &hir::TraitTyParamBound(ref ptr, hir::TraitBoundModifier::Maybe) = ab { + if let &hir::ParamBound::Trait(ref ptr, hir::TraitBoundModifier::Maybe) = ab { if unbound.is_none() { unbound = Some(ptr.trait_ref.clone()); } else { @@ -1482,7 +1482,7 @@ pub fn explicit_predicates_of<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, for bound in bound_pred.bounds.iter() { match bound { - &hir::ParamBound::TraitTyParamBound(ref poly_trait_ref, _) => { + &hir::ParamBound::Trait(ref poly_trait_ref, _) => { let mut projections = Vec::new(); let trait_ref = @@ -1591,22 +1591,16 @@ pub fn compute_bounds<'gcx: 'tcx, 'tcx>(astconv: &AstConv<'gcx, 'tcx>, let mut trait_bounds = vec![]; for ast_bound in ast_bounds { match *ast_bound { - hir::TraitTyParamBound(ref b, hir::TraitBoundModifier::None) => { - trait_bounds.push(b); - } - hir::TraitTyParamBound(_, hir::TraitBoundModifier::Maybe) => {} - hir::Outlives(ref l) => { - region_bounds.push(l); - } + hir::ParamBound::Trait(ref b, hir::TraitBoundModifier::None) => trait_bounds.push(b), + hir::ParamBound::Trait(_, hir::TraitBoundModifier::Maybe) => {} + hir::ParamBound::Outlives(ref l) => region_bounds.push(l), } } 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) + astconv.instantiate_poly_trait_ref(bound, param_ty, &mut projection_bounds) }).collect(); let region_bounds = region_bounds.into_iter().map(|r| { @@ -1640,7 +1634,7 @@ fn predicates_from_bound<'tcx>(astconv: &AstConv<'tcx, 'tcx>, -> Vec> { match *bound { - hir::TraitTyParamBound(ref tr, hir::TraitBoundModifier::None) => { + hir::ParamBound::Trait(ref tr, hir::TraitBoundModifier::None) => { let mut projections = Vec::new(); let pred = astconv.instantiate_poly_trait_ref(tr, param_ty, @@ -1650,14 +1644,12 @@ fn predicates_from_bound<'tcx>(astconv: &AstConv<'tcx, 'tcx>, .chain(Some(pred.to_predicate())) .collect() } - hir::Outlives(ref lifetime) => { + hir::ParamBound::Outlives(ref lifetime) => { let region = astconv.ast_region_to_region(lifetime, None); let pred = ty::Binder::bind(ty::OutlivesPredicate(param_ty, region)); vec![ty::Predicate::TypeOutlives(pred)] } - hir::TraitTyParamBound(_, hir::TraitBoundModifier::Maybe) => { - Vec::new() - } + hir::ParamBound::Trait(_, hir::TraitBoundModifier::Maybe) => vec![], } } diff --git a/src/librustdoc/clean/mod.rs b/src/librustdoc/clean/mod.rs index 2b02c639b954a..7f9500d21f018 100644 --- a/src/librustdoc/clean/mod.rs +++ b/src/librustdoc/clean/mod.rs @@ -1510,8 +1510,8 @@ impl ParamBound { impl Clean for hir::ParamBound { fn clean(&self, cx: &DocContext) -> ParamBound { match *self { - hir::Outlives(lt) => Outlives(lt.clean(cx)), - hir::TraitTyParamBound(ref t, modifier) => TraitBound(t.clean(cx), modifier), + hir::ParamBound::Outlives(lt) => Outlives(lt.clean(cx)), + hir::ParamBound::Trait(ref t, modifier) => TraitBound(t.clean(cx), modifier), } } } @@ -1624,7 +1624,7 @@ impl<'tcx> Clean>> for Substs<'tcx> { fn clean(&self, cx: &DocContext) -> Option> { let mut v = Vec::new(); v.extend(self.regions().filter_map(|r| r.clean(cx)) - .map(Outlives)); + .map(ParamBound::Outlives)); v.extend(self.types().map(|t| TraitBound(PolyTrait { trait_: t.clean(cx), generic_params: Vec::new(), @@ -3080,7 +3080,7 @@ impl<'tcx> Clean for Ty<'tcx> { inline::record_extern_fqn(cx, did, TypeKind::Trait); let mut typarams = vec![]; - reg.clean(cx).map(|b| typarams.push(Outlives(b))); + reg.clean(cx).map(|b| typarams.push(ParamBound::Outlives(b))); for did in obj.auto_traits() { let empty = cx.tcx.intern_substs(&[]); let path = external_path(cx, &cx.tcx.item_name(did).as_str(), @@ -3137,7 +3137,9 @@ impl<'tcx> Clean for Ty<'tcx> { tr } else if let ty::Predicate::TypeOutlives(pred) = *predicate { // these should turn up at the end - pred.skip_binder().1.clean(cx).map(|r| regions.push(Outlives(r))); + pred.skip_binder().1.clean(cx).map(|r| { + regions.push(ParamBound::Outlives(r)) + }); return None; } else { return None; diff --git a/src/libsyntax/ast.rs b/src/libsyntax/ast.rs index 389afa96ea026..6fe90025ff8e5 100644 --- a/src/libsyntax/ast.rs +++ b/src/libsyntax/ast.rs @@ -283,14 +283,14 @@ pub enum TraitBoundModifier { /// detects Copy, Send and Sync. #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)] pub enum ParamBound { - TraitTyParamBound(PolyTraitRef, TraitBoundModifier), + Trait(PolyTraitRef, TraitBoundModifier), Outlives(Lifetime) } impl ParamBound { pub fn span(&self) -> Span { match self { - &TraitTyParamBound(ref t, ..) => t.span, + &Trait(ref t, ..) => t.span, &Outlives(ref l) => l.ident.span, } } @@ -930,7 +930,7 @@ impl Expr { fn to_bound(&self) -> Option { match &self.node { ExprKind::Path(None, path) => - Some(TraitTyParamBound(PolyTraitRef::new(Vec::new(), path.clone(), self.span), + Some(Trait(PolyTraitRef::new(Vec::new(), path.clone(), self.span), TraitBoundModifier::None)), _ => None, } diff --git a/src/libsyntax/ext/build.rs b/src/libsyntax/ext/build.rs index cc0bc7f0c745f..28bfb1ff81110 100644 --- a/src/libsyntax/ext/build.rs +++ b/src/libsyntax/ext/build.rs @@ -465,7 +465,7 @@ impl<'a> AstBuilder for ExtCtxt<'a> { } fn ty_param_bound(&self, path: ast::Path) -> ast::ParamBound { - ast::TraitTyParamBound(self.poly_trait_ref(path.span, path), ast::TraitBoundModifier::None) + ast::Trait(self.poly_trait_ref(path.span, path), ast::TraitBoundModifier::None) } fn lifetime(&self, span: Span, ident: ast::Ident) -> ast::Lifetime { diff --git a/src/libsyntax/fold.rs b/src/libsyntax/fold.rs index 804b1410b0786..290607a702b17 100644 --- a/src/libsyntax/fold.rs +++ b/src/libsyntax/fold.rs @@ -678,8 +678,8 @@ pub fn noop_fold_fn_decl(decl: P, fld: &mut T) -> P { pub fn noop_fold_param_bound(pb: ParamBound, fld: &mut T) -> ParamBound where T: Folder { match pb { - TraitTyParamBound(ty, modifier) => { - TraitTyParamBound(fld.fold_poly_trait_ref(ty), modifier) + Trait(ty, modifier) => { + Trait(fld.fold_poly_trait_ref(ty), modifier) } Outlives(lifetime) => Outlives(noop_fold_lifetime(lifetime, fld)), } diff --git a/src/libsyntax/parse/parser.rs b/src/libsyntax/parse/parser.rs index f69361c28ad00..75eefb844321c 100644 --- a/src/libsyntax/parse/parser.rs +++ b/src/libsyntax/parse/parser.rs @@ -10,7 +10,7 @@ use rustc_target::spec::abi::{self, Abi}; use ast::{AngleBracketedArgs, ParenthesizedArgData, AttrStyle, BareFnTy}; -use ast::{Outlives, TraitTyParamBound, TraitBoundModifier}; +use ast::{Outlives, Trait, TraitBoundModifier}; use ast::Unsafety; use ast::{Mod, AnonConst, Arg, Arm, Attribute, BindingMode, TraitItemKind}; use ast::Block; @@ -1444,7 +1444,7 @@ impl<'a> Parser<'a> { TyKind::TraitObject(ref bounds, TraitObjectSyntax::None) if maybe_bounds && bounds.len() == 1 && !trailing_plus => { let path = match bounds[0] { - TraitTyParamBound(ref pt, ..) => pt.trait_ref.path.clone(), + Trait(ref pt, ..) => pt.trait_ref.path.clone(), _ => self.bug("unexpected lifetime bound"), }; self.parse_remaining_bounds(Vec::new(), path, lo, true)? @@ -1566,7 +1566,7 @@ impl<'a> Parser<'a> { fn parse_remaining_bounds(&mut self, generic_params: Vec, path: ast::Path, lo: Span, parse_plus: bool) -> PResult<'a, TyKind> { let poly_trait_ref = PolyTraitRef::new(generic_params, path, lo.to(self.prev_span)); - let mut bounds = vec![TraitTyParamBound(poly_trait_ref, TraitBoundModifier::None)]; + let mut bounds = vec![Trait(poly_trait_ref, TraitBoundModifier::None)]; if parse_plus { self.eat_plus(); // `+`, or `+=` gets split and `+` is discarded bounds.append(&mut self.parse_ty_param_bounds()?); @@ -4770,7 +4770,7 @@ impl<'a> Parser<'a> { } else { TraitBoundModifier::None }; - bounds.push(TraitTyParamBound(poly_trait, modifier)); + bounds.push(Trait(poly_trait, modifier)); } } else { break diff --git a/src/libsyntax/print/pprust.rs b/src/libsyntax/print/pprust.rs index 5d39367f4b0d4..38229fa499876 100644 --- a/src/libsyntax/print/pprust.rs +++ b/src/libsyntax/print/pprust.rs @@ -12,7 +12,7 @@ pub use self::AnnNode::*; use rustc_target::spec::abi::{self, Abi}; use ast::{self, BlockCheckMode, PatKind, RangeEnd, RangeSyntax}; -use ast::{SelfKind, Outlives, TraitTyParamBound, TraitBoundModifier}; +use ast::{SelfKind, Outlives, Trait, TraitBoundModifier}; use ast::{Attribute, MacDelimiter, GenericArg}; use util::parser::{self, AssocOp, Fixity}; use attr; @@ -1364,7 +1364,7 @@ impl<'a> State<'a> { self.print_generic_params(&generics.params)?; let mut real_bounds = Vec::with_capacity(bounds.len()); for b in bounds.iter() { - if let TraitTyParamBound(ref ptr, ast::TraitBoundModifier::Maybe) = *b { + if let Trait(ref ptr, ast::TraitBoundModifier::Maybe) = *b { self.s.space()?; self.word_space("for ?")?; self.print_trait_ref(&ptr.trait_ref)?; @@ -1390,7 +1390,7 @@ impl<'a> State<'a> { let mut real_bounds = Vec::with_capacity(bounds.len()); // FIXME(durka) this seems to be some quite outdated syntax for b in bounds.iter() { - if let TraitTyParamBound(ref ptr, ast::TraitBoundModifier::Maybe) = *b { + if let Trait(ref ptr, ast::TraitBoundModifier::Maybe) = *b { self.s.space()?; self.word_space("for ?")?; self.print_trait_ref(&ptr.trait_ref)?; @@ -2826,7 +2826,7 @@ impl<'a> State<'a> { } match bound { - TraitTyParamBound(tref, modifier) => { + Trait(tref, modifier) => { if modifier == &TraitBoundModifier::Maybe { self.s.word("?")?; } diff --git a/src/libsyntax/visit.rs b/src/libsyntax/visit.rs index f63b474f450aa..6beaabd03de71 100644 --- a/src/libsyntax/visit.rs +++ b/src/libsyntax/visit.rs @@ -481,7 +481,7 @@ pub fn walk_global_asm<'a, V: Visitor<'a>>(_: &mut V, _: &'a GlobalAsm) { pub fn walk_param_bound<'a, V: Visitor<'a>>(visitor: &mut V, bound: &'a ParamBound) { match *bound { - TraitTyParamBound(ref typ, ref modifier) => { + Trait(ref typ, ref modifier) => { visitor.visit_poly_trait_ref(typ, modifier); } Outlives(ref lifetime) => { From 91712bc665d82019c5238dcd43280c9b8e2192cb Mon Sep 17 00:00:00 2001 From: varkor Date: Thu, 14 Jun 2018 11:42:12 +0100 Subject: [PATCH 30/41] Lift attrs into hir::GenericParam --- src/librustc/hir/intravisit.rs | 6 ++---- src/librustc/hir/lowering.rs | 11 +++++++---- src/librustc/hir/map/mod.rs | 5 +---- src/librustc/hir/mod.rs | 2 +- src/librustc/ich/impls_hir.rs | 4 ++-- 5 files changed, 13 insertions(+), 15 deletions(-) diff --git a/src/librustc/hir/intravisit.rs b/src/librustc/hir/intravisit.rs index a66650aa161f2..a778ea12552be 100644 --- a/src/librustc/hir/intravisit.rs +++ b/src/librustc/hir/intravisit.rs @@ -748,11 +748,9 @@ pub fn walk_generic_param<'v, V: Visitor<'v>>(visitor: &mut V, param: &'v Generi } match param.kind { GenericParamKind::Lifetime { .. } => {} - GenericParamKind::Type { ref default, ref attrs, .. } => { - walk_list!(visitor, visit_ty, default); - walk_list!(visitor, visit_attribute, attrs.iter()); - } + GenericParamKind::Type { ref default, .. } => walk_list!(visitor, visit_ty, default), } + walk_list!(visitor, visit_attribute, ¶m.attrs); walk_list!(visitor, visit_param_bound, ¶m.bounds); } diff --git a/src/librustc/hir/lowering.rs b/src/librustc/hir/lowering.rs index 2a23144849003..320d7d4cf3651 100644 --- a/src/librustc/hir/lowering.rs +++ b/src/librustc/hir/lowering.rs @@ -695,9 +695,10 @@ impl<'a> LoweringContext<'a> { hir::GenericParam { id: def_node_id, name: hir_name, + attrs: hir_vec![], + bounds: hir_vec![], span, pure_wrt_drop: false, - bounds: vec![].into(), kind: hir::GenericParamKind::Lifetime { in_band: true } } }) @@ -1239,11 +1240,11 @@ impl<'a> LoweringContext<'a> { name: ParamName::Plain(name), span, pure_wrt_drop: false, + attrs: hir_vec![], bounds: hir_bounds, kind: hir::GenericParamKind::Type { default: None, synthetic: Some(hir::SyntheticTyParamKind::ImplTrait), - attrs: P::new(), } }); @@ -1413,7 +1414,8 @@ impl<'a> LoweringContext<'a> { name, span: lifetime.span, pure_wrt_drop: false, - bounds: vec![].into(), + attrs: hir_vec![], + bounds: hir_vec![], kind: hir::GenericParamKind::Lifetime { in_band: false, } @@ -1950,6 +1952,7 @@ impl<'a> LoweringContext<'a> { name: param_name, span: lt.span, pure_wrt_drop: attr::contains_name(¶m.attrs, "may_dangle"), + attrs: self.lower_attrs(¶m.attrs), bounds, kind: hir::GenericParamKind::Lifetime { in_band: false } }; @@ -1980,6 +1983,7 @@ impl<'a> LoweringContext<'a> { name: hir::ParamName::Plain(name), span: param.ident.span, pure_wrt_drop: attr::contains_name(¶m.attrs, "may_dangle"), + attrs: self.lower_attrs(¶m.attrs), bounds, kind: hir::GenericParamKind::Type { default: default.as_ref().map(|x| { @@ -1989,7 +1993,6 @@ impl<'a> LoweringContext<'a> { .filter(|attr| attr.check_name("rustc_synthetic")) .map(|_| hir::SyntheticTyParamKind::ImplTrait) .next(), - attrs: self.lower_attrs(¶m.attrs), } } } diff --git a/src/librustc/hir/map/mod.rs b/src/librustc/hir/map/mod.rs index 5ea9348403a94..c2c8c7a391b9c 100644 --- a/src/librustc/hir/map/mod.rs +++ b/src/librustc/hir/map/mod.rs @@ -974,10 +974,7 @@ impl<'hir> Map<'hir> { Some(NodeField(ref f)) => Some(&f.attrs[..]), Some(NodeExpr(ref e)) => Some(&*e.attrs), Some(NodeStmt(ref s)) => Some(s.node.attrs()), - Some(NodeGenericParam(param)) => match param.kind { - GenericParamKind::Lifetime { .. } => None, - GenericParamKind::Type { ref attrs, .. } => Some(&attrs[..]), - } + Some(NodeGenericParam(param)) => Some(¶m.attrs[..]), // unit/tuple structs take the attributes straight from // the struct definition. Some(NodeStructCtor(_)) => { diff --git a/src/librustc/hir/mod.rs b/src/librustc/hir/mod.rs index 974d287cd9731..63b4614ef5d21 100644 --- a/src/librustc/hir/mod.rs +++ b/src/librustc/hir/mod.rs @@ -471,7 +471,6 @@ pub enum GenericParamKind { Type { default: Option>, synthetic: Option, - attrs: HirVec, } } @@ -479,6 +478,7 @@ pub enum GenericParamKind { pub struct GenericParam { pub id: NodeId, pub name: ParamName, + pub attrs: HirVec, pub bounds: ParamBounds, pub span: Span, pub pure_wrt_drop: bool, diff --git a/src/librustc/ich/impls_hir.rs b/src/librustc/ich/impls_hir.rs index ec55a05822cac..fbe2fdae87706 100644 --- a/src/librustc/ich/impls_hir.rs +++ b/src/librustc/ich/impls_hir.rs @@ -203,6 +203,7 @@ impl_stable_hash_for!(struct hir::GenericParam { name, span, pure_wrt_drop, + attrs, bounds, kind }); @@ -216,10 +217,9 @@ impl<'a> HashStable> for hir::GenericParamKind { hir::GenericParamKind::Lifetime { in_band } => { in_band.hash_stable(hcx, hasher); } - hir::GenericParamKind::Type { ref default, synthetic, attrs } => { + hir::GenericParamKind::Type { ref default, synthetic } => { default.hash_stable(hcx, hasher); synthetic.hash_stable(hcx, hasher); - attrs.hash_stable(hcx, hasher); } } } From 991efa4284c6ee01c36ab24a14b1c7779b92e17e Mon Sep 17 00:00:00 2001 From: varkor Date: Thu, 14 Jun 2018 12:05:47 +0100 Subject: [PATCH 31/41] Address various comments --- src/librustc/hir/lowering.rs | 4 +- src/librustc/middle/resolve_lifetime.rs | 43 +++++++------ src/librustc_lint/types.rs | 81 ++++++++++++++----------- src/librustc_resolve/lib.rs | 38 ++++++------ src/librustc_typeck/astconv.rs | 24 ++++---- src/librustc_typeck/check/mod.rs | 2 +- src/librustc_typeck/check/wfcheck.rs | 6 +- src/librustc_typeck/collect.rs | 2 +- 8 files changed, 103 insertions(+), 97 deletions(-) diff --git a/src/librustc/hir/lowering.rs b/src/librustc/hir/lowering.rs index 320d7d4cf3651..aec94d60f9430 100644 --- a/src/librustc/hir/lowering.rs +++ b/src/librustc/hir/lowering.rs @@ -379,7 +379,7 @@ impl<'a> LoweringContext<'a> { }); if item_lowered { - let item_lifetimes = match self.lctx.items.get(&item.id).unwrap().node { + let item_generics = match self.lctx.items.get(&item.id).unwrap().node { hir::Item_::ItemImpl(_, _, _, ref generics, ..) | hir::Item_::ItemTrait(_, _, ref generics, ..) => { generics.params.clone() @@ -387,7 +387,7 @@ impl<'a> LoweringContext<'a> { _ => HirVec::new(), }; - self.lctx.with_parent_impl_lifetime_defs(&item_lifetimes, |this| { + self.lctx.with_parent_impl_lifetime_defs(&item_generics, |this| { let this = &mut ItemLowerer { lctx: this }; if let ItemKind::Impl(_, _, _, _, ref opt_trait_ref, _, _) = item.node { this.with_trait_impl_ref(opt_trait_ref, |this| { diff --git a/src/librustc/middle/resolve_lifetime.rs b/src/librustc/middle/resolve_lifetime.rs index 14c782308a801..178b9b1f45af1 100644 --- a/src/librustc/middle/resolve_lifetime.rs +++ b/src/librustc/middle/resolve_lifetime.rs @@ -49,11 +49,16 @@ pub enum LifetimeDefOrigin { } impl LifetimeDefOrigin { - fn from_is_in_band(is_in_band: bool) -> Self { - if is_in_band { - LifetimeDefOrigin::InBand - } else { - LifetimeDefOrigin::Explicit + fn from_param(param: &GenericParam) -> Self { + match param.kind { + GenericParamKind::Lifetime { in_band } => { + if in_band { + LifetimeDefOrigin::InBand + } else { + LifetimeDefOrigin::Explicit + } + } + _ => bug!("expected a lifetime param"), } } } @@ -82,29 +87,20 @@ pub enum Region { Free(DefId, /* lifetime decl */ DefId), } -fn new_region(hir_map: &Map, param: &GenericParam) -> (DefId, LifetimeDefOrigin) { - let def_id = hir_map.local_def_id(param.id); - let origin = match param.kind { - GenericParamKind::Lifetime { in_band, .. } => { - LifetimeDefOrigin::from_is_in_band(in_band) - } - _ => bug!("expected a lifetime param"), - }; - (def_id, origin) -} - impl Region { fn early(hir_map: &Map, index: &mut u32, param: &GenericParam) -> (ParamName, Region) { let i = *index; *index += 1; - let (def_id, origin) = new_region(hir_map, param); + let def_id = hir_map.local_def_id(param.id); + let origin = LifetimeDefOrigin::from_param(param); debug!("Region::early: index={} def_id={:?}", i, def_id); (param.name, Region::EarlyBound(i, def_id, origin)) } fn late(hir_map: &Map, param: &GenericParam) -> (ParamName, Region) { let depth = ty::INNERMOST; - let (def_id, origin) = new_region(hir_map, param); + let def_id = hir_map.local_def_id(param.id); + let origin = LifetimeDefOrigin::from_param(param); debug!( "Region::late: param={:?} depth={:?} def_id={:?} origin={:?}", param, @@ -1300,16 +1296,19 @@ fn object_lifetime_defaults_for_item( Set1::One(Region::Static) } else { generics.params.iter().filter_map(|param| match param.kind { - GenericParamKind::Lifetime { in_band } => { - Some((param.id, hir::LifetimeName::Param(param.name), in_band)) + GenericParamKind::Lifetime { .. } => { + Some(( + param.id, + hir::LifetimeName::Param(param.name), + LifetimeDefOrigin::from_param(param), + )) } _ => None, }) .enumerate() .find(|&(_, (_, lt_name, _))| lt_name == name) - .map_or(Set1::Many, |(i, (id, _, in_band))| { + .map_or(Set1::Many, |(i, (id, _, origin))| { let def_id = tcx.hir.local_def_id(id); - let origin = LifetimeDefOrigin::from_is_in_band(in_band); Set1::One(Region::EarlyBound(i as u32, def_id, origin)) }) } diff --git a/src/librustc_lint/types.rs b/src/librustc_lint/types.rs index 2d96c01a6dfe4..804000faa370e 100644 --- a/src/librustc_lint/types.rs +++ b/src/librustc_lint/types.rs @@ -821,43 +821,50 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for VariantSizeDifferences { let item_def_id = cx.tcx.hir.local_def_id(it.id); let t = cx.tcx.type_of(item_def_id); let ty = cx.tcx.erase_regions(&t); - let layout = cx.layout_of(ty).unwrap_or_else(|e| { - bug!("failed to get layout for `{}`: {}", t, e) - }); - - if let layout::Variants::Tagged { ref variants, ref tag, .. } = layout.variants { - let discr_size = tag.value.size(cx.tcx).bytes(); - - debug!("enum `{}` is {} bytes large with layout:\n{:#?}", - t, layout.size.bytes(), layout); - - let (largest, slargest, largest_index) = enum_definition.variants - .iter() - .zip(variants) - .map(|(variant, variant_layout)| { - // Subtract the size of the enum discriminant. - let bytes = variant_layout.size.bytes().saturating_sub(discr_size); - - debug!("- variant `{}` is {} bytes large", variant.node.name, bytes); - bytes - }) - .enumerate() - .fold((0, 0, 0), |(l, s, li), (idx, size)| if size > l { - (size, l, idx) - } else if size > s { - (l, size, li) - } else { - (l, s, li) - }); - - // We only warn if the largest variant is at least thrice as large as - // the second-largest. - if largest > slargest * 3 && slargest > 0 { - cx.span_lint(VARIANT_SIZE_DIFFERENCES, - enum_definition.variants[largest_index].span, - &format!("enum variant is more than three times larger \ - ({} bytes) than the next largest", - largest)); + match cx.layout_of(ty) { + Ok(layout) => { + let variants = &layout.variants; + if let layout::Variants::Tagged { ref variants, ref tag, .. } = variants { + let discr_size = tag.value.size(cx.tcx).bytes(); + + debug!("enum `{}` is {} bytes large with layout:\n{:#?}", + t, layout.size.bytes(), layout); + + let (largest, slargest, largest_index) = enum_definition.variants + .iter() + .zip(variants) + .map(|(variant, variant_layout)| { + // Subtract the size of the enum discriminant. + let bytes = variant_layout.size.bytes().saturating_sub(discr_size); + + debug!("- variant `{}` is {} bytes large", + variant.node.name, + bytes); + bytes + }) + .enumerate() + .fold((0, 0, 0), |(l, s, li), (idx, size)| if size > l { + (size, l, idx) + } else if size > s { + (l, size, li) + } else { + (l, s, li) + }); + + // We only warn if the largest variant is at least thrice as large as + // the second-largest. + if largest > slargest * 3 && slargest > 0 { + cx.span_lint(VARIANT_SIZE_DIFFERENCES, + enum_definition.variants[largest_index].span, + &format!("enum variant is more than three times \ + larger ({} bytes) than the next largest", + largest)); + } + } + } + Err(ty::layout::LayoutError::Unknown(_)) => return, + Err(err @ ty::layout::LayoutError::SizeOverflow(_)) => { + bug!("failed to get layout for `{}`: {}", t, err); } } } diff --git a/src/librustc_resolve/lib.rs b/src/librustc_resolve/lib.rs index 731c6e2ef8295..e311701ac0589 100644 --- a/src/librustc_resolve/lib.rs +++ b/src/librustc_resolve/lib.rs @@ -2208,26 +2208,26 @@ impl<'a> Resolver<'a> { let mut function_type_rib = Rib::new(rib_kind); let mut seen_bindings = FxHashMap(); generics.params.iter().for_each(|param| match param.kind { - GenericParamKind::Type { .. } => { - let ident = param.ident.modern(); - debug!("with_type_parameter_rib: {}", param.id); - - if seen_bindings.contains_key(&ident) { - let span = seen_bindings.get(&ident).unwrap(); - let err = ResolutionError::NameAlreadyUsedInTypeParameterList( - ident.name, - span, - ); - resolve_error(self, param.ident.span, err); - } - seen_bindings.entry(ident).or_insert(param.ident.span); - - // Plain insert (no renaming). - let def = Def::TyParam(self.definitions.local_def_id(param.id)); - function_type_rib.bindings.insert(ident, def); - self.record_def(param.id, PathResolution::new(def)); + GenericParamKind::Lifetime { .. } => {} + GenericParamKind::Type { .. } => { + let ident = param.ident.modern(); + debug!("with_type_parameter_rib: {}", param.id); + + if seen_bindings.contains_key(&ident) { + let span = seen_bindings.get(&ident).unwrap(); + let err = ResolutionError::NameAlreadyUsedInTypeParameterList( + ident.name, + span, + ); + resolve_error(self, param.ident.span, err); } - _ => {} + seen_bindings.entry(ident).or_insert(param.ident.span); + + // Plain insert (no renaming). + let def = Def::TyParam(self.definitions.local_def_id(param.id)); + function_type_rib.bindings.insert(ident, def); + self.record_def(param.id, PathResolution::new(def)); + } }); self.ribs[TypeNS].push(function_type_rib); } diff --git a/src/librustc_typeck/astconv.rs b/src/librustc_typeck/astconv.rs index 7cd71518bed52..48c5353a40001 100644 --- a/src/librustc_typeck/astconv.rs +++ b/src/librustc_typeck/astconv.rs @@ -379,7 +379,7 @@ impl<'o, 'gcx: 'tcx, 'tcx> AstConv<'gcx, 'tcx>+'o { self_ty: Ty<'tcx>) -> ty::TraitRef<'tcx> { - self.prohibit_type_params(trait_ref.path.segments.split_last().unwrap().1); + self.prohibit_generics(trait_ref.path.segments.split_last().unwrap().1); let trait_def_id = self.trait_def_id(trait_ref); self.ast_path_to_mono_trait_ref(trait_ref.path.span, @@ -413,7 +413,7 @@ impl<'o, 'gcx: 'tcx, 'tcx> AstConv<'gcx, 'tcx>+'o { debug!("ast_path_to_poly_trait_ref({:?}, def_id={:?})", trait_ref, trait_def_id); - self.prohibit_type_params(trait_ref.path.segments.split_last().unwrap().1); + self.prohibit_generics(trait_ref.path.segments.split_last().unwrap().1); let (substs, assoc_bindings) = self.create_substs_for_ast_trait_ref(trait_ref.path.span, @@ -891,7 +891,7 @@ impl<'o, 'gcx: 'tcx, 'tcx> AstConv<'gcx, 'tcx>+'o { debug!("associated_path_def_to_ty: {:?}::{}", ty, assoc_name); - self.prohibit_type_params(slice::from_ref(item_segment)); + self.prohibit_generics(slice::from_ref(item_segment)); // Find the type of the associated item, and the trait where the associated // item is declared. @@ -968,7 +968,7 @@ impl<'o, 'gcx: 'tcx, 'tcx> AstConv<'gcx, 'tcx>+'o { let tcx = self.tcx(); let trait_def_id = tcx.parent_def_id(item_def_id).unwrap(); - self.prohibit_type_params(slice::from_ref(item_segment)); + self.prohibit_generics(slice::from_ref(item_segment)); let self_ty = if let Some(ty) = opt_self_ty { ty @@ -993,7 +993,7 @@ impl<'o, 'gcx: 'tcx, 'tcx> AstConv<'gcx, 'tcx>+'o { self.normalize_ty(span, tcx.mk_projection(item_def_id, trait_ref.substs)) } - pub fn prohibit_type_params(&self, segments: &[hir::PathSegment]) { + pub fn prohibit_generics(&self, segments: &[hir::PathSegment]) { for segment in segments { segment.with_generic_args(|generic_args| { let (mut err_for_lt, mut err_for_ty) = (false, false); @@ -1053,21 +1053,21 @@ impl<'o, 'gcx: 'tcx, 'tcx> AstConv<'gcx, 'tcx>+'o { Def::Enum(did) | Def::TyAlias(did) | Def::Struct(did) | Def::Union(did) | Def::TyForeign(did) => { assert_eq!(opt_self_ty, None); - self.prohibit_type_params(path.segments.split_last().unwrap().1); + self.prohibit_generics(path.segments.split_last().unwrap().1); self.ast_path_to_ty(span, did, path.segments.last().unwrap()) } Def::Variant(did) if permit_variants => { // Convert "variant type" as if it were a real type. // The resulting `Ty` is type of the variant's enum for now. assert_eq!(opt_self_ty, None); - self.prohibit_type_params(path.segments.split_last().unwrap().1); + self.prohibit_generics(path.segments.split_last().unwrap().1); self.ast_path_to_ty(span, tcx.parent_def_id(did).unwrap(), path.segments.last().unwrap()) } Def::TyParam(did) => { assert_eq!(opt_self_ty, None); - self.prohibit_type_params(&path.segments); + self.prohibit_generics(&path.segments); let node_id = tcx.hir.as_local_node_id(did).unwrap(); let item_id = tcx.hir.get_parent_node(node_id); @@ -1080,18 +1080,18 @@ impl<'o, 'gcx: 'tcx, 'tcx> AstConv<'gcx, 'tcx>+'o { // Self in impl (we know the concrete type). assert_eq!(opt_self_ty, None); - self.prohibit_type_params(&path.segments); + self.prohibit_generics(&path.segments); tcx.at(span).type_of(def_id) } Def::SelfTy(Some(_), None) => { // Self in trait. assert_eq!(opt_self_ty, None); - self.prohibit_type_params(&path.segments); + self.prohibit_generics(&path.segments); tcx.mk_self_type() } Def::AssociatedTy(def_id) => { - self.prohibit_type_params(&path.segments[..path.segments.len()-2]); + self.prohibit_generics(&path.segments[..path.segments.len()-2]); self.qpath_to_ty(span, opt_self_ty, def_id, @@ -1100,7 +1100,7 @@ impl<'o, 'gcx: 'tcx, 'tcx> AstConv<'gcx, 'tcx>+'o { } Def::PrimTy(prim_ty) => { assert_eq!(opt_self_ty, None); - self.prohibit_type_params(&path.segments); + self.prohibit_generics(&path.segments); match prim_ty { hir::TyBool => tcx.types.bool, hir::TyChar => tcx.types.char, diff --git a/src/librustc_typeck/check/mod.rs b/src/librustc_typeck/check/mod.rs index 003c6c4fb74d2..bececfc08ac0e 100644 --- a/src/librustc_typeck/check/mod.rs +++ b/src/librustc_typeck/check/mod.rs @@ -4782,7 +4782,7 @@ impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> { // errors if type parameters are provided in an inappropriate place. let poly_segments = type_segment.is_some() as usize + fn_segment.is_some() as usize; - AstConv::prohibit_type_params(self, &segments[..segments.len() - poly_segments]); + AstConv::prohibit_generics(self, &segments[..segments.len() - poly_segments]); match def { Def::Local(nid) | Def::Upvar(nid, ..) => { diff --git a/src/librustc_typeck/check/wfcheck.rs b/src/librustc_typeck/check/wfcheck.rs index c4b20699cee58..b61f09cbaea6d 100644 --- a/src/librustc_typeck/check/wfcheck.rs +++ b/src/librustc_typeck/check/wfcheck.rs @@ -602,8 +602,8 @@ fn check_method_receiver<'fcx, 'gcx, 'tcx>(fcx: &FnCtxt<'fcx, 'gcx, 'tcx>, } fn check_variances_for_type_defn<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, - item: &hir::Item, - ast_generics: &hir::Generics) + item: &hir::Item, + hir_generics: &hir::Generics) { let item_def_id = tcx.hir.local_def_id(item.id); let ty = tcx.type_of(item_def_id); @@ -631,7 +631,7 @@ fn check_variances_for_type_defn<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, continue; } - let param = &ast_generics.params[index]; + let param = &hir_generics.params[index]; report_bivariance(tcx, param.span, param.name.name()); } } diff --git a/src/librustc_typeck/collect.rs b/src/librustc_typeck/collect.rs index f578d4f1ae6ab..6e154819c4c4e 100644 --- a/src/librustc_typeck/collect.rs +++ b/src/librustc_typeck/collect.rs @@ -117,7 +117,7 @@ impl<'a, 'tcx> Visitor<'tcx> for CollectItemTypesVisitor<'a, 'tcx> { for param in &generics.params { match param.kind { hir::GenericParamKind::Lifetime { .. } => {} - hir::GenericParamKind::Type { ref default, .. } if default.is_some() => { + hir::GenericParamKind::Type { default: Some(_), .. } => { let def_id = self.tcx.hir.local_def_id(param.id); self.tcx.type_of(def_id); } From c5f16e0e180f4f76187e55aecb5913a1cf7fab2a Mon Sep 17 00:00:00 2001 From: varkor Date: Thu, 14 Jun 2018 12:08:58 +0100 Subject: [PATCH 32/41] Rename ParamBound(s) to GenericBound(s) --- src/librustc/hir/intravisit.rs | 8 +-- src/librustc/hir/lowering.rs | 24 +++---- src/librustc/hir/mod.rs | 24 +++---- src/librustc/hir/print.rs | 18 ++--- src/librustc/ich/impls_hir.rs | 2 +- src/librustc/middle/resolve_lifetime.rs | 6 +- src/librustc_passes/ast_validation.rs | 2 +- src/librustc_passes/hir_stats.rs | 8 +-- src/librustc_privacy/lib.rs | 4 +- src/librustc_save_analysis/dump_visitor.rs | 2 +- src/librustc_save_analysis/sig.rs | 6 +- src/librustc_typeck/collect.rs | 30 ++++---- src/librustdoc/clean/auto_trait.rs | 24 +++---- src/librustdoc/clean/inline.rs | 4 +- src/librustdoc/clean/mod.rs | 82 +++++++++++----------- src/librustdoc/clean/simplify.rs | 2 +- src/librustdoc/core.rs | 2 +- src/librustdoc/doctree.rs | 2 +- src/librustdoc/html/format.rs | 20 +++--- src/librustdoc/html/render.rs | 6 +- src/libsyntax/ast.rs | 26 +++---- src/libsyntax/ext/build.rs | 12 ++-- src/libsyntax/fold.rs | 16 ++--- src/libsyntax/parse/parser.rs | 12 ++-- src/libsyntax/print/pprust.rs | 10 +-- src/libsyntax/util/node_count.rs | 2 +- src/libsyntax/visit.rs | 4 +- src/libsyntax_ext/deriving/generic/mod.rs | 2 +- src/libsyntax_ext/deriving/generic/ty.rs | 2 +- 29 files changed, 181 insertions(+), 181 deletions(-) diff --git a/src/librustc/hir/intravisit.rs b/src/librustc/hir/intravisit.rs index a778ea12552be..e49a5e4ee6ae9 100644 --- a/src/librustc/hir/intravisit.rs +++ b/src/librustc/hir/intravisit.rs @@ -314,7 +314,7 @@ pub trait Visitor<'v> : Sized { fn visit_trait_ref(&mut self, t: &'v TraitRef) { walk_trait_ref(self, t) } - fn visit_param_bound(&mut self, bounds: &'v ParamBound) { + fn visit_param_bound(&mut self, bounds: &'v GenericBound) { walk_param_bound(self, bounds) } fn visit_poly_trait_ref(&mut self, t: &'v PolyTraitRef, m: TraitBoundModifier) { @@ -731,12 +731,12 @@ pub fn walk_foreign_item<'v, V: Visitor<'v>>(visitor: &mut V, foreign_item: &'v walk_list!(visitor, visit_attribute, &foreign_item.attrs); } -pub fn walk_param_bound<'v, V: Visitor<'v>>(visitor: &mut V, bound: &'v ParamBound) { +pub fn walk_param_bound<'v, V: Visitor<'v>>(visitor: &mut V, bound: &'v GenericBound) { match *bound { - ParamBound::Trait(ref typ, modifier) => { + GenericBound::Trait(ref typ, modifier) => { visitor.visit_poly_trait_ref(typ, modifier); } - ParamBound::Outlives(ref lifetime) => visitor.visit_lifetime(lifetime), + GenericBound::Outlives(ref lifetime) => visitor.visit_lifetime(lifetime), } } diff --git a/src/librustc/hir/lowering.rs b/src/librustc/hir/lowering.rs index aec94d60f9430..b725432eb5ca3 100644 --- a/src/librustc/hir/lowering.rs +++ b/src/librustc/hir/lowering.rs @@ -1285,7 +1285,7 @@ impl<'a> LoweringContext<'a> { &mut self, exist_ty_id: NodeId, parent_index: DefIndex, - bounds: &hir::ParamBounds, + bounds: &hir::GenericBounds, ) -> (HirVec, HirVec) { // This visitor walks over impl trait bounds and creates defs for all lifetimes which // appear in the bounds, excluding lifetimes that are created within the bounds. @@ -1873,16 +1873,16 @@ impl<'a> LoweringContext<'a> { fn lower_param_bound( &mut self, - tpb: &ParamBound, + tpb: &GenericBound, itctx: ImplTraitContext, - ) -> hir::ParamBound { + ) -> hir::GenericBound { match *tpb { - ParamBound::Trait(ref ty, modifier) => hir::ParamBound::Trait( + GenericBound::Trait(ref ty, modifier) => hir::GenericBound::Trait( self.lower_poly_trait_ref(ty, itctx), self.lower_trait_bound_modifier(modifier), ), - ParamBound::Outlives(ref lifetime) => { - hir::ParamBound::Outlives(self.lower_lifetime(lifetime)) + GenericBound::Outlives(ref lifetime) => { + hir::GenericBound::Outlives(self.lower_lifetime(lifetime)) } } } @@ -1925,7 +1925,7 @@ impl<'a> LoweringContext<'a> { fn lower_generic_params( &mut self, params: &Vec, - add_bounds: &NodeMap>, + add_bounds: &NodeMap>, itctx: ImplTraitContext, ) -> hir::HirVec { params.iter().map(|param| self.lower_generic_param(param, add_bounds, itctx)).collect() @@ -1933,7 +1933,7 @@ impl<'a> LoweringContext<'a> { fn lower_generic_param(&mut self, param: &GenericParam, - add_bounds: &NodeMap>, + add_bounds: &NodeMap>, itctx: ImplTraitContext) -> hir::GenericParam { let mut bounds = self.lower_param_bounds(¶m.bounds, itctx); @@ -2013,7 +2013,7 @@ impl<'a> LoweringContext<'a> { for pred in &generics.where_clause.predicates { if let WherePredicate::BoundPredicate(ref bound_pred) = *pred { 'next_bound: for bound in &bound_pred.bounds { - if let ParamBound::Trait(_, TraitBoundModifier::Maybe) = *bound { + if let GenericBound::Trait(_, TraitBoundModifier::Maybe) = *bound { let report_error = |this: &mut Self| { this.diagnostic().span_err( bound_pred.bounded_ty.span, @@ -2098,7 +2098,7 @@ impl<'a> LoweringContext<'a> { .filter_map(|bound| match *bound { // Ignore `?Trait` bounds. // Tthey were copied into type parameters already. - ParamBound::Trait(_, TraitBoundModifier::Maybe) => None, + GenericBound::Trait(_, TraitBoundModifier::Maybe) => None, _ => Some(this.lower_param_bound( bound, ImplTraitContext::Disallowed, @@ -2217,8 +2217,8 @@ impl<'a> LoweringContext<'a> { } } - fn lower_param_bounds(&mut self, bounds: &[ParamBound], itctx: ImplTraitContext) - -> hir::ParamBounds { + fn lower_param_bounds(&mut self, bounds: &[GenericBound], itctx: ImplTraitContext) + -> hir::GenericBounds { bounds.iter().map(|bound| self.lower_param_bound(bound, itctx)).collect() } diff --git a/src/librustc/hir/mod.rs b/src/librustc/hir/mod.rs index 63b4614ef5d21..f6876113c1176 100644 --- a/src/librustc/hir/mod.rs +++ b/src/librustc/hir/mod.rs @@ -443,21 +443,21 @@ pub enum TraitBoundModifier { /// the "special" built-in traits (see middle::lang_items) and /// detects Copy, Send and Sync. #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)] -pub enum ParamBound { +pub enum GenericBound { Trait(PolyTraitRef, TraitBoundModifier), Outlives(Lifetime), } -impl ParamBound { +impl GenericBound { pub fn span(&self) -> Span { match self { - &ParamBound::Trait(ref t, ..) => t.span, - &ParamBound::Outlives(ref l) => l.span, + &GenericBound::Trait(ref t, ..) => t.span, + &GenericBound::Outlives(ref l) => l.span, } } } -pub type ParamBounds = HirVec; +pub type GenericBounds = HirVec; #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)] pub enum GenericParamKind { @@ -479,7 +479,7 @@ pub struct GenericParam { pub id: NodeId, pub name: ParamName, pub attrs: HirVec, - pub bounds: ParamBounds, + pub bounds: GenericBounds, pub span: Span, pub pure_wrt_drop: bool, @@ -588,7 +588,7 @@ pub struct WhereBoundPredicate { /// The type being bounded pub bounded_ty: P, /// Trait and lifetime bounds (`Clone+Send+'static`) - pub bounds: ParamBounds, + pub bounds: GenericBounds, } /// A lifetime predicate, e.g. `'a: 'b+'c` @@ -596,7 +596,7 @@ pub struct WhereBoundPredicate { pub struct WhereRegionPredicate { pub span: Span, pub lifetime: Lifetime, - pub bounds: ParamBounds, + pub bounds: GenericBounds, } /// An equality predicate (unsupported), e.g. `T=int` @@ -1555,7 +1555,7 @@ pub enum TraitItemKind { Method(MethodSig, TraitMethod), /// An associated type with (possibly empty) bounds and optional concrete /// type - Type(ParamBounds, Option>), + Type(GenericBounds, Option>), } // The bodies for items are stored "out of line", in a separate @@ -1640,7 +1640,7 @@ pub struct BareFnTy { #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)] pub struct ExistTy { pub generics: Generics, - pub bounds: ParamBounds, + pub bounds: GenericBounds, pub impl_trait_fn: Option, } @@ -2049,9 +2049,9 @@ pub enum Item_ { /// A union definition, e.g. `union Foo {x: A, y: B}` ItemUnion(VariantData, Generics), /// Represents a Trait Declaration - ItemTrait(IsAuto, Unsafety, Generics, ParamBounds, HirVec), + ItemTrait(IsAuto, Unsafety, Generics, GenericBounds, HirVec), /// Represents a Trait Alias Declaration - ItemTraitAlias(Generics, ParamBounds), + ItemTraitAlias(Generics, GenericBounds), /// An implementation, eg `impl Trait for Foo { .. }` ItemImpl(Unsafety, diff --git a/src/librustc/hir/print.rs b/src/librustc/hir/print.rs index b6fd136255421..229a4da465a27 100644 --- a/src/librustc/hir/print.rs +++ b/src/librustc/hir/print.rs @@ -24,7 +24,7 @@ use syntax::util::parser::{self, AssocOp, Fixity}; use syntax_pos::{self, BytePos, FileName}; use hir; -use hir::{PatKind, ParamBound, TraitBoundModifier, RangeEnd}; +use hir::{PatKind, GenericBound, TraitBoundModifier, RangeEnd}; use hir::{GenericParam, GenericParamKind, GenericArg}; use std::cell::Cell; @@ -514,7 +514,7 @@ impl<'a> State<'a> { fn print_associated_type(&mut self, name: ast::Name, - bounds: Option<&hir::ParamBounds>, + bounds: Option<&hir::GenericBounds>, ty: Option<&hir::Ty>) -> io::Result<()> { self.word_space("type")?; @@ -740,7 +740,7 @@ impl<'a> State<'a> { self.print_generic_params(&generics.params)?; let mut real_bounds = Vec::with_capacity(bounds.len()); for b in bounds.iter() { - if let ParamBound::Trait(ref ptr, hir::TraitBoundModifier::Maybe) = *b { + if let GenericBound::Trait(ref ptr, hir::TraitBoundModifier::Maybe) = *b { self.s.space()?; self.word_space("for ?")?; self.print_trait_ref(&ptr.trait_ref)?; @@ -766,7 +766,7 @@ impl<'a> State<'a> { let mut real_bounds = Vec::with_capacity(bounds.len()); // FIXME(durka) this seems to be some quite outdated syntax for b in bounds.iter() { - if let ParamBound::Trait(ref ptr, hir::TraitBoundModifier::Maybe) = *b { + if let GenericBound::Trait(ref ptr, hir::TraitBoundModifier::Maybe) = *b { self.s.space()?; self.word_space("for ?")?; self.print_trait_ref(&ptr.trait_ref)?; @@ -2071,7 +2071,7 @@ impl<'a> State<'a> { } } - pub fn print_bounds(&mut self, prefix: &str, bounds: &[hir::ParamBound]) -> io::Result<()> { + pub fn print_bounds(&mut self, prefix: &str, bounds: &[hir::GenericBound]) -> io::Result<()> { if !bounds.is_empty() { self.s.word(prefix)?; let mut first = true; @@ -2086,13 +2086,13 @@ impl<'a> State<'a> { } match bound { - ParamBound::Trait(tref, modifier) => { + GenericBound::Trait(tref, modifier) => { if modifier == &TraitBoundModifier::Maybe { self.s.word("?")?; } self.print_poly_trait_ref(tref)?; } - ParamBound::Outlives(lt) => { + GenericBound::Outlives(lt) => { self.print_lifetime(lt)?; } } @@ -2121,7 +2121,7 @@ impl<'a> State<'a> { let mut sep = ":"; for bound in ¶m.bounds { match bound { - ParamBound::Outlives(lt) => { + GenericBound::Outlives(lt) => { self.s.word(sep)?; self.print_lifetime(lt)?; sep = "+"; @@ -2181,7 +2181,7 @@ impl<'a> State<'a> { for (i, bound) in bounds.iter().enumerate() { match bound { - ParamBound::Outlives(lt) => { + GenericBound::Outlives(lt) => { self.print_lifetime(lt)?; } _ => bug!(), diff --git a/src/librustc/ich/impls_hir.rs b/src/librustc/ich/impls_hir.rs index fbe2fdae87706..882194ae64e79 100644 --- a/src/librustc/ich/impls_hir.rs +++ b/src/librustc/ich/impls_hir.rs @@ -188,7 +188,7 @@ impl_stable_hash_for!(struct hir::GenericArgs { parenthesized }); -impl_stable_hash_for!(enum hir::ParamBound { +impl_stable_hash_for!(enum hir::GenericBound { Trait(poly_trait_ref, trait_bound_modifier), Outlives(lifetime) }); diff --git a/src/librustc/middle/resolve_lifetime.rs b/src/librustc/middle/resolve_lifetime.rs index 178b9b1f45af1..091662966ea8f 100644 --- a/src/librustc/middle/resolve_lifetime.rs +++ b/src/librustc/middle/resolve_lifetime.rs @@ -1250,9 +1250,9 @@ fn object_lifetime_defaults_for_item( tcx: TyCtxt<'_, '_, '_>, generics: &hir::Generics, ) -> Vec { - fn add_bounds(set: &mut Set1, bounds: &[hir::ParamBound]) { + fn add_bounds(set: &mut Set1, bounds: &[hir::GenericBound]) { for bound in bounds { - if let hir::ParamBound::Outlives(ref lifetime) = *bound { + if let hir::GenericBound::Outlives(ref lifetime) = *bound { set.insert(lifetime.name); } } @@ -2280,7 +2280,7 @@ impl<'a, 'tcx> LifetimeContext<'a, 'tcx> { for bound in &lifetime_i.bounds { match bound { - hir::ParamBound::Outlives(lt) => match lt.name { + hir::GenericBound::Outlives(lt) => match lt.name { hir::LifetimeName::Underscore => { let mut err = struct_span_err!( self.tcx.sess, diff --git a/src/librustc_passes/ast_validation.rs b/src/librustc_passes/ast_validation.rs index bdfe1d50e2686..4f04ad896983d 100644 --- a/src/librustc_passes/ast_validation.rs +++ b/src/librustc_passes/ast_validation.rs @@ -99,7 +99,7 @@ impl<'a> AstValidator<'a> { } } - fn no_questions_in_bounds(&self, bounds: &ParamBounds, where_: &str, is_trait: bool) { + fn no_questions_in_bounds(&self, bounds: &GenericBounds, where_: &str, is_trait: bool) { for bound in bounds { if let Trait(ref poly, TraitBoundModifier::Maybe) = *bound { let mut err = self.err_handler().struct_span_err(poly.span, diff --git a/src/librustc_passes/hir_stats.rs b/src/librustc_passes/hir_stats.rs index 879adebf7ea95..e7b2869dfe61e 100644 --- a/src/librustc_passes/hir_stats.rs +++ b/src/librustc_passes/hir_stats.rs @@ -203,8 +203,8 @@ impl<'v> hir_visit::Visitor<'v> for StatCollector<'v> { hir_visit::walk_impl_item(self, ii) } - fn visit_param_bound(&mut self, bounds: &'v hir::ParamBound) { - self.record("ParamBound", Id::None, bounds); + fn visit_param_bound(&mut self, bounds: &'v hir::GenericBound) { + self.record("GenericBound", Id::None, bounds); hir_visit::walk_param_bound(self, bounds) } @@ -322,8 +322,8 @@ impl<'v> ast_visit::Visitor<'v> for StatCollector<'v> { ast_visit::walk_impl_item(self, ii) } - fn visit_param_bound(&mut self, bounds: &'v ast::ParamBound) { - self.record("ParamBound", Id::None, bounds); + fn visit_param_bound(&mut self, bounds: &'v ast::GenericBound) { + self.record("GenericBound", Id::None, bounds); ast_visit::walk_param_bound(self, bounds) } diff --git a/src/librustc_privacy/lib.rs b/src/librustc_privacy/lib.rs index 68b5a925ef3a0..809f5a06952ad 100644 --- a/src/librustc_privacy/lib.rs +++ b/src/librustc_privacy/lib.rs @@ -1038,8 +1038,8 @@ impl<'a, 'tcx> ObsoleteVisiblePrivateTypesVisitor<'a, 'tcx> { } fn check_ty_param_bound(&mut self, - ty_param_bound: &hir::ParamBound) { - if let hir::ParamBound::Trait(ref trait_ref, _) = *ty_param_bound { + ty_param_bound: &hir::GenericBound) { + if let hir::GenericBound::Trait(ref trait_ref, _) = *ty_param_bound { if self.path_is_private_type(&trait_ref.trait_ref.path) { self.old_error_set.insert(trait_ref.trait_ref.ref_id); } diff --git a/src/librustc_save_analysis/dump_visitor.rs b/src/librustc_save_analysis/dump_visitor.rs index 1373ee94587a5..0f0f3f6e7892b 100644 --- a/src/librustc_save_analysis/dump_visitor.rs +++ b/src/librustc_save_analysis/dump_visitor.rs @@ -718,7 +718,7 @@ impl<'l, 'tcx: 'l, 'll, O: DumpOutput + 'll> DumpVisitor<'l, 'tcx, 'll, O> { &mut self, item: &'l ast::Item, generics: &'l ast::Generics, - trait_refs: &'l ast::ParamBounds, + trait_refs: &'l ast::GenericBounds, methods: &'l [ast::TraitItem], ) { let name = item.ident.to_string(); diff --git a/src/librustc_save_analysis/sig.rs b/src/librustc_save_analysis/sig.rs index 58e2e9b225829..7f2f0b0c83716 100644 --- a/src/librustc_save_analysis/sig.rs +++ b/src/librustc_save_analysis/sig.rs @@ -104,7 +104,7 @@ pub fn assoc_const_signature( pub fn assoc_type_signature( id: NodeId, ident: ast::Ident, - bounds: Option<&ast::ParamBounds>, + bounds: Option<&ast::GenericBounds>, default: Option<&ast::Ty>, scx: &SaveContext, ) -> Option { @@ -629,7 +629,7 @@ impl Sig for ast::Generics { ast::GenericParamKind::Lifetime { .. } => { let bounds = param.bounds.iter() .map(|bound| match bound { - ast::ParamBound::Outlives(lt) => lt.ident.to_string(), + ast::GenericBound::Outlives(lt) => lt.ident.to_string(), _ => panic!(), }) .collect::>() @@ -841,7 +841,7 @@ fn name_and_generics( fn make_assoc_type_signature( id: NodeId, ident: ast::Ident, - bounds: Option<&ast::ParamBounds>, + bounds: Option<&ast::GenericBounds>, default: Option<&ast::Ty>, scx: &SaveContext, ) -> Result { diff --git a/src/librustc_typeck/collect.rs b/src/librustc_typeck/collect.rs index 6e154819c4c4e..7a4fbc73c2e7d 100644 --- a/src/librustc_typeck/collect.rs +++ b/src/librustc_typeck/collect.rs @@ -1249,7 +1249,7 @@ fn impl_polarity<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, // Is it marked with ?Sized fn is_unsized<'gcx: 'tcx, 'tcx>(astconv: &AstConv<'gcx, 'tcx>, - ast_bounds: &[hir::ParamBound], + ast_bounds: &[hir::GenericBound], span: Span) -> bool { let tcx = astconv.tcx(); @@ -1257,7 +1257,7 @@ fn is_unsized<'gcx: 'tcx, 'tcx>(astconv: &AstConv<'gcx, 'tcx>, // Try to find an unbound in bounds. let mut unbound = None; for ab in ast_bounds { - if let &hir::ParamBound::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 { @@ -1444,7 +1444,7 @@ pub fn explicit_predicates_of<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, match param.kind { GenericParamKind::Lifetime { .. } => { param.bounds.iter().for_each(|bound| match bound { - hir::ParamBound::Outlives(lt) => { + hir::GenericBound::Outlives(lt) => { let bound = AstConv::ast_region_to_region(&icx, <, None); let outlives = ty::Binder::bind(ty::OutlivesPredicate(region, bound)); predicates.push(outlives.to_predicate()); @@ -1482,7 +1482,7 @@ pub fn explicit_predicates_of<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, for bound in bound_pred.bounds.iter() { match bound { - &hir::ParamBound::Trait(ref poly_trait_ref, _) => { + &hir::GenericBound::Trait(ref poly_trait_ref, _) => { let mut projections = Vec::new(); let trait_ref = @@ -1498,7 +1498,7 @@ pub fn explicit_predicates_of<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, } } - &hir::ParamBound::Outlives(ref lifetime) => { + &hir::GenericBound::Outlives(ref lifetime) => { let region = AstConv::ast_region_to_region(&icx, lifetime, None); @@ -1513,7 +1513,7 @@ pub fn explicit_predicates_of<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, let r1 = AstConv::ast_region_to_region(&icx, ®ion_pred.lifetime, None); for bound in ®ion_pred.bounds { let r2 = match bound { - hir::ParamBound::Outlives(lt) => { + hir::GenericBound::Outlives(lt) => { AstConv::ast_region_to_region(&icx, lt, None) } _ => bug!(), @@ -1582,7 +1582,7 @@ pub enum SizedByDefault { Yes, No, } /// built-in trait (formerly known as kind): Send. pub fn compute_bounds<'gcx: 'tcx, 'tcx>(astconv: &AstConv<'gcx, 'tcx>, param_ty: Ty<'tcx>, - ast_bounds: &[hir::ParamBound], + ast_bounds: &[hir::GenericBound], sized_by_default: SizedByDefault, span: Span) -> Bounds<'tcx> @@ -1591,9 +1591,9 @@ pub fn compute_bounds<'gcx: 'tcx, 'tcx>(astconv: &AstConv<'gcx, 'tcx>, let mut trait_bounds = vec![]; for ast_bound in ast_bounds { match *ast_bound { - hir::ParamBound::Trait(ref b, hir::TraitBoundModifier::None) => trait_bounds.push(b), - hir::ParamBound::Trait(_, hir::TraitBoundModifier::Maybe) => {} - hir::ParamBound::Outlives(ref l) => region_bounds.push(l), + hir::GenericBound::Trait(ref b, hir::TraitBoundModifier::None) => trait_bounds.push(b), + hir::GenericBound::Trait(_, hir::TraitBoundModifier::Maybe) => {} + hir::GenericBound::Outlives(ref l) => region_bounds.push(l), } } @@ -1623,18 +1623,18 @@ pub fn compute_bounds<'gcx: 'tcx, 'tcx>(astconv: &AstConv<'gcx, 'tcx>, } } -/// Converts a specific ParamBound from the AST into a set of +/// Converts a specific GenericBound from the AST into a set of /// predicates that apply to the self-type. A vector is returned /// 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: &AstConv<'tcx, 'tcx>, param_ty: Ty<'tcx>, - bound: &hir::ParamBound) + bound: &hir::GenericBound) -> Vec> { match *bound { - hir::ParamBound::Trait(ref tr, hir::TraitBoundModifier::None) => { + hir::GenericBound::Trait(ref tr, hir::TraitBoundModifier::None) => { let mut projections = Vec::new(); let pred = astconv.instantiate_poly_trait_ref(tr, param_ty, @@ -1644,12 +1644,12 @@ fn predicates_from_bound<'tcx>(astconv: &AstConv<'tcx, 'tcx>, .chain(Some(pred.to_predicate())) .collect() } - hir::ParamBound::Outlives(ref lifetime) => { + hir::GenericBound::Outlives(ref lifetime) => { let region = astconv.ast_region_to_region(lifetime, None); let pred = ty::Binder::bind(ty::OutlivesPredicate(param_ty, region)); vec![ty::Predicate::TypeOutlives(pred)] } - hir::ParamBound::Trait(_, hir::TraitBoundModifier::Maybe) => vec![], + hir::GenericBound::Trait(_, hir::TraitBoundModifier::Maybe) => vec![], } } diff --git a/src/librustdoc/clean/auto_trait.rs b/src/librustdoc/clean/auto_trait.rs index 0874e921f4173..5c09da90491d0 100644 --- a/src/librustdoc/clean/auto_trait.rs +++ b/src/librustdoc/clean/auto_trait.rs @@ -486,8 +486,8 @@ impl<'a, 'tcx, 'rcx> AutoTraitFinder<'a, 'tcx, 'rcx> { .iter() .flat_map(|(name, lifetime)| { let empty = Vec::new(); - let bounds: FxHashSet = finished.get(name).unwrap_or(&empty).iter() - .map(|region| ParamBound::Outlives(self.get_lifetime(region, names_map))) + let bounds: FxHashSet = finished.get(name).unwrap_or(&empty).iter() + .map(|region| GenericBound::Outlives(self.get_lifetime(region, names_map))) .collect(); if bounds.is_empty() { @@ -533,9 +533,9 @@ impl<'a, 'tcx, 'rcx> AutoTraitFinder<'a, 'tcx, 'rcx> { fn make_final_bounds<'b, 'c, 'cx>( &self, - ty_to_bounds: FxHashMap>, + ty_to_bounds: FxHashMap>, ty_to_fn: FxHashMap, Option)>, - lifetime_to_bounds: FxHashMap>, + lifetime_to_bounds: FxHashMap>, ) -> Vec { ty_to_bounds .into_iter() @@ -586,7 +586,7 @@ impl<'a, 'tcx, 'rcx> AutoTraitFinder<'a, 'tcx, 'rcx> { } _ => panic!("Unexpected data: {:?}, {:?}", ty, data), }; - bounds.insert(ParamBound::TraitBound( + bounds.insert(GenericBound::TraitBound( PolyTrait { trait_: new_ty, generic_params: poly_trait.generic_params, @@ -729,7 +729,7 @@ impl<'a, 'tcx, 'rcx> AutoTraitFinder<'a, 'tcx, 'rcx> { // later let is_fn = match &mut b { - &mut ParamBound::TraitBound(ref mut p, _) => { + &mut GenericBound::TraitBound(ref mut p, _) => { // Insert regions into the for_generics hash map first, to ensure // that we don't end up with duplicate bounds (e.g. for<'b, 'b>) for_generics.extend(p.generic_params.clone()); @@ -823,7 +823,7 @@ impl<'a, 'tcx, 'rcx> AutoTraitFinder<'a, 'tcx, 'rcx> { .entry(*ty.clone()) .or_insert_with(|| FxHashSet()); - bounds.insert(ParamBound::TraitBound( + bounds.insert(GenericBound::TraitBound( PolyTrait { trait_: Type::ResolvedPath { path: new_trait_path, @@ -840,7 +840,7 @@ impl<'a, 'tcx, 'rcx> AutoTraitFinder<'a, 'tcx, 'rcx> { // that we don't see a // duplicate bound like `T: Iterator + Iterator` // on the docs page. - bounds.remove(&ParamBound::TraitBound( + bounds.remove(&GenericBound::TraitBound( PolyTrait { trait_: *trait_.clone(), generic_params: Vec::new(), @@ -874,7 +874,7 @@ impl<'a, 'tcx, 'rcx> AutoTraitFinder<'a, 'tcx, 'rcx> { default.take(); let generic_ty = Type::Generic(param.name.clone()); if !has_sized.contains(&generic_ty) { - bounds.insert(0, ParamBound::maybe_sized(self.cx)); + bounds.insert(0, GenericBound::maybe_sized(self.cx)); } } GenericParamDefKind::Lifetime => {} @@ -908,7 +908,7 @@ impl<'a, 'tcx, 'rcx> AutoTraitFinder<'a, 'tcx, 'rcx> { // both for visual consistency between 'rustdoc' runs, and to // make writing tests much easier #[inline] - fn sort_where_bounds(&self, mut bounds: &mut Vec) { + fn sort_where_bounds(&self, mut bounds: &mut Vec) { // We should never have identical bounds - and if we do, // they're visually identical as well. Therefore, using // an unstable sort is fine. @@ -928,7 +928,7 @@ impl<'a, 'tcx, 'rcx> AutoTraitFinder<'a, 'tcx, 'rcx> { // to end users, it makes writing tests much more difficult, as predicates // can appear in any order in the final result. // - // To solve this problem, we sort WherePredicates and ParamBounds + // To solve this problem, we sort WherePredicates and GenericBounds // by their Debug string. The thing to keep in mind is that we don't really // care what the final order is - we're synthesizing an impl or bound // ourselves, so any order can be considered equally valid. By sorting the @@ -938,7 +938,7 @@ impl<'a, 'tcx, 'rcx> AutoTraitFinder<'a, 'tcx, 'rcx> { // Using the Debug impementation for sorting prevents us from needing to // write quite a bit of almost entirely useless code (e.g. how should two // Types be sorted relative to each other). It also allows us to solve the - // problem for both WherePredicates and ParamBounds at the same time. This + // problem for both WherePredicates and GenericBounds at the same time. This // approach is probably somewhat slower, but the small number of items // involved (impls rarely have more than a few bounds) means that it // shouldn't matter in practice. diff --git a/src/librustdoc/clean/inline.rs b/src/librustdoc/clean/inline.rs index c85178961c16a..f3a833bad8f78 100644 --- a/src/librustdoc/clean/inline.rs +++ b/src/librustdoc/clean/inline.rs @@ -474,7 +474,7 @@ fn filter_non_trait_generics(trait_did: DefId, mut g: clean::Generics) -> clean: } if *s == "Self" => { bounds.retain(|bound| { match *bound { - clean::ParamBound::TraitBound(clean::PolyTrait { + clean::GenericBound::TraitBound(clean::PolyTrait { trait_: clean::ResolvedPath { did, .. }, .. }, _) => did != trait_did, @@ -505,7 +505,7 @@ fn filter_non_trait_generics(trait_did: DefId, mut g: clean::Generics) -> clean: /// the metadata for a crate, so we want to separate those out and create a new /// list of explicit supertrait bounds to render nicely. fn separate_supertrait_bounds(mut g: clean::Generics) - -> (clean::Generics, Vec) { + -> (clean::Generics, Vec) { let mut ty_bounds = Vec::new(); g.where_predicates.retain(|pred| { match *pred { diff --git a/src/librustdoc/clean/mod.rs b/src/librustdoc/clean/mod.rs index 7f9500d21f018..031a948fe80d1 100644 --- a/src/librustdoc/clean/mod.rs +++ b/src/librustdoc/clean/mod.rs @@ -14,7 +14,7 @@ pub use self::Type::*; pub use self::Mutability::*; pub use self::ItemEnum::*; -pub use self::ParamBound::*; +pub use self::GenericBound::*; pub use self::SelfTy::*; pub use self::FunctionRetTy::*; pub use self::Visibility::{Public, Inherited}; @@ -532,7 +532,7 @@ pub enum ItemEnum { MacroItem(Macro), PrimitiveItem(PrimitiveType), AssociatedConstItem(Type, Option), - AssociatedTypeItem(Vec, Option), + AssociatedTypeItem(Vec, Option), /// An item that has been stripped by a rustdoc pass StrippedItem(Box), KeywordItem(String), @@ -1458,13 +1458,13 @@ impl Clean for [ast::Attribute] { } #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Eq, Debug, Hash)] -pub enum ParamBound { +pub enum GenericBound { TraitBound(PolyTrait, hir::TraitBoundModifier), Outlives(Lifetime), } -impl ParamBound { - fn maybe_sized(cx: &DocContext) -> ParamBound { +impl GenericBound { + fn maybe_sized(cx: &DocContext) -> GenericBound { let did = cx.tcx.require_lang_item(lang_items::SizedTraitLangItem); let empty = cx.tcx.intern_substs(&[]); let path = external_path(cx, &cx.tcx.item_name(did).as_str(), @@ -1483,7 +1483,7 @@ impl ParamBound { fn is_sized_bound(&self, cx: &DocContext) -> bool { use rustc::hir::TraitBoundModifier as TBM; - if let ParamBound::TraitBound(PolyTrait { ref trait_, .. }, TBM::None) = *self { + if let GenericBound::TraitBound(PolyTrait { ref trait_, .. }, TBM::None) = *self { if trait_.def_id() == cx.tcx.lang_items().sized_trait() { return true; } @@ -1492,7 +1492,7 @@ impl ParamBound { } fn get_poly_trait(&self) -> Option { - if let ParamBound::TraitBound(ref p, _) = *self { + if let GenericBound::TraitBound(ref p, _) = *self { return Some(p.clone()) } None @@ -1500,18 +1500,18 @@ impl ParamBound { fn get_trait_type(&self) -> Option { - if let ParamBound::TraitBound(PolyTrait { ref trait_, .. }, _) = *self { + if let GenericBound::TraitBound(PolyTrait { ref trait_, .. }, _) = *self { return Some(trait_.clone()); } None } } -impl Clean for hir::ParamBound { - fn clean(&self, cx: &DocContext) -> ParamBound { +impl Clean for hir::GenericBound { + fn clean(&self, cx: &DocContext) -> GenericBound { match *self { - hir::ParamBound::Outlives(lt) => Outlives(lt.clean(cx)), - hir::ParamBound::Trait(ref t, modifier) => TraitBound(t.clean(cx), modifier), + hir::GenericBound::Outlives(lt) => Outlives(lt.clean(cx)), + hir::GenericBound::Trait(ref t, modifier) => TraitBound(t.clean(cx), modifier), } } } @@ -1570,8 +1570,8 @@ fn external_path(cx: &DocContext, name: &str, trait_did: Option, has_self } } -impl<'a, 'tcx> Clean for (&'a ty::TraitRef<'tcx>, Vec) { - fn clean(&self, cx: &DocContext) -> ParamBound { +impl<'a, 'tcx> Clean for (&'a ty::TraitRef<'tcx>, Vec) { + fn clean(&self, cx: &DocContext) -> GenericBound { let (trait_ref, ref bounds) = *self; inline::record_extern_fqn(cx, trait_ref.def_id, TypeKind::Trait); let path = external_path(cx, &cx.tcx.item_name(trait_ref.def_id).as_str(), @@ -1614,17 +1614,17 @@ impl<'a, 'tcx> Clean for (&'a ty::TraitRef<'tcx>, Vec) } } -impl<'tcx> Clean for ty::TraitRef<'tcx> { - fn clean(&self, cx: &DocContext) -> ParamBound { +impl<'tcx> Clean for ty::TraitRef<'tcx> { + fn clean(&self, cx: &DocContext) -> GenericBound { (self, vec![]).clean(cx) } } -impl<'tcx> Clean>> for Substs<'tcx> { - fn clean(&self, cx: &DocContext) -> Option> { +impl<'tcx> Clean>> for Substs<'tcx> { + fn clean(&self, cx: &DocContext) -> Option> { let mut v = Vec::new(); v.extend(self.regions().filter_map(|r| r.clean(cx)) - .map(ParamBound::Outlives)); + .map(GenericBound::Outlives)); v.extend(self.types().map(|t| TraitBound(PolyTrait { trait_: t.clean(cx), generic_params: Vec::new(), @@ -1674,7 +1674,7 @@ impl Clean for hir::GenericParam { hir::GenericParamKind::Lifetime { .. } => { if self.bounds.len() > 0 { let mut bounds = self.bounds.iter().map(|bound| match bound { - hir::ParamBound::Outlives(lt) => lt, + hir::GenericBound::Outlives(lt) => lt, _ => panic!(), }); let name = bounds.next().unwrap().name.name(); @@ -1720,8 +1720,8 @@ impl Clean> for ty::RegionKind { #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Eq, Debug, Hash)] pub enum WherePredicate { - BoundPredicate { ty: Type, bounds: Vec }, - RegionPredicate { lifetime: Lifetime, bounds: Vec }, + BoundPredicate { ty: Type, bounds: Vec }, + RegionPredicate { lifetime: Lifetime, bounds: Vec }, EqPredicate { lhs: Type, rhs: Type }, } @@ -1791,7 +1791,7 @@ impl<'tcx> Clean for ty::OutlivesPredicate, ty: let ty::OutlivesPredicate(ref a, ref b) = *self; WherePredicate::RegionPredicate { lifetime: a.clean(cx).unwrap(), - bounds: vec![ParamBound::Outlives(b.clean(cx).unwrap())] + bounds: vec![GenericBound::Outlives(b.clean(cx).unwrap())] } } } @@ -1802,7 +1802,7 @@ impl<'tcx> Clean for ty::OutlivesPredicate, ty::Region< WherePredicate::BoundPredicate { ty: ty.clean(cx), - bounds: vec![ParamBound::Outlives(lt.clean(cx).unwrap())] + bounds: vec![GenericBound::Outlives(lt.clean(cx).unwrap())] } } } @@ -1819,8 +1819,8 @@ impl<'tcx> Clean for ty::ProjectionPredicate<'tcx> { impl<'tcx> Clean for ty::ProjectionTy<'tcx> { fn clean(&self, cx: &DocContext) -> Type { let trait_ = match self.trait_ref(cx.tcx).clean(cx) { - ParamBound::TraitBound(t, _) => t.trait_, - ParamBound::Outlives(_) => panic!("cleaning a trait got a lifetime"), + GenericBound::TraitBound(t, _) => t.trait_, + GenericBound::Outlives(_) => panic!("cleaning a trait got a lifetime"), }; Type::QPath { name: cx.tcx.associated_item(self.item_def_id).name.clean(cx), @@ -1835,7 +1835,7 @@ pub enum GenericParamDefKind { Lifetime, Type { did: DefId, - bounds: Vec, + bounds: Vec, default: Option, synthetic: Option, }, @@ -1893,7 +1893,7 @@ impl Clean for hir::GenericParam { hir::GenericParamKind::Lifetime { .. } => { let name = if self.bounds.len() > 0 { let mut bounds = self.bounds.iter().map(|bound| match bound { - hir::ParamBound::Outlives(lt) => lt, + hir::GenericBound::Outlives(lt) => lt, _ => panic!(), }); let name = bounds.next().unwrap().name.name(); @@ -2049,7 +2049,7 @@ impl<'a, 'tcx> Clean for (&'a ty::Generics, if !sized_params.contains(&tp.name) { where_predicates.push(WP::BoundPredicate { ty: Type::Generic(tp.name.clone()), - bounds: vec![ParamBound::maybe_sized(cx)], + bounds: vec![GenericBound::maybe_sized(cx)], }) } } @@ -2290,7 +2290,7 @@ pub struct Trait { pub unsafety: hir::Unsafety, pub items: Vec, pub generics: Generics, - pub bounds: Vec, + pub bounds: Vec, pub is_spotlight: bool, pub is_auto: bool, } @@ -2512,7 +2512,7 @@ impl<'tcx> Clean for ty::AssociatedItem { // at the end. match bounds.iter().position(|b| b.is_sized_bound(cx)) { Some(i) => { bounds.remove(i); } - None => bounds.push(ParamBound::maybe_sized(cx)), + None => bounds.push(GenericBound::maybe_sized(cx)), } let ty = if self.defaultness.has_value() { @@ -2567,7 +2567,7 @@ pub enum Type { /// structs/enums/traits (most that'd be an hir::TyPath) ResolvedPath { path: Path, - typarams: Option>, + typarams: Option>, did: DefId, /// true if is a `T::Name` path for associated types is_generic: bool, @@ -2603,7 +2603,7 @@ pub enum Type { Infer, // impl TraitA+TraitB - ImplTrait(Vec), + ImplTrait(Vec), } #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Eq, Hash, Copy, Debug)] @@ -2977,7 +2977,7 @@ impl Clean for hir::Ty { TyTraitObject(ref bounds, ref lifetime) => { match bounds[0].clean(cx).trait_ { ResolvedPath { path, typarams: None, did, is_generic } => { - let mut bounds: Vec = bounds[1..].iter().map(|bound| { + let mut bounds: Vec = bounds[1..].iter().map(|bound| { TraitBound(bound.clean(cx), hir::TraitBoundModifier::None) }).collect(); if !lifetime.is_elided() { @@ -3080,7 +3080,7 @@ impl<'tcx> Clean for Ty<'tcx> { inline::record_extern_fqn(cx, did, TypeKind::Trait); let mut typarams = vec![]; - reg.clean(cx).map(|b| typarams.push(ParamBound::Outlives(b))); + reg.clean(cx).map(|b| typarams.push(GenericBound::Outlives(b))); for did in obj.auto_traits() { let empty = cx.tcx.intern_substs(&[]); let path = external_path(cx, &cx.tcx.item_name(did).as_str(), @@ -3138,7 +3138,7 @@ impl<'tcx> Clean for Ty<'tcx> { } else if let ty::Predicate::TypeOutlives(pred) = *predicate { // these should turn up at the end pred.skip_binder().1.clean(cx).map(|r| { - regions.push(ParamBound::Outlives(r)) + regions.push(GenericBound::Outlives(r)) }); return None; } else { @@ -3173,7 +3173,7 @@ impl<'tcx> Clean for Ty<'tcx> { }).collect::>(); bounds.extend(regions); if !has_sized && !bounds.is_empty() { - bounds.insert(0, ParamBound::maybe_sized(cx)); + bounds.insert(0, GenericBound::maybe_sized(cx)); } ImplTrait(bounds) } @@ -4469,11 +4469,11 @@ impl AutoTraitResult { } } -impl From for SimpleBound { - fn from(bound: ParamBound) -> Self { +impl From for SimpleBound { + fn from(bound: GenericBound) -> Self { match bound.clone() { - ParamBound::Outlives(l) => SimpleBound::Outlives(l), - ParamBound::TraitBound(t, mod_) => match t.trait_ { + GenericBound::Outlives(l) => SimpleBound::Outlives(l), + GenericBound::TraitBound(t, mod_) => match t.trait_ { Type::ResolvedPath { path, typarams, .. } => { SimpleBound::TraitBound(path.segments, typarams diff --git a/src/librustdoc/clean/simplify.rs b/src/librustdoc/clean/simplify.rs index c7477645d6a2e..a54eb64443bef 100644 --- a/src/librustdoc/clean/simplify.rs +++ b/src/librustdoc/clean/simplify.rs @@ -147,7 +147,7 @@ pub fn ty_params(mut params: Vec) -> Vec) -> Vec { +fn ty_bounds(bounds: Vec) -> Vec { bounds } diff --git a/src/librustdoc/core.rs b/src/librustdoc/core.rs index 7147e13805f8b..53ebb3a12f527 100644 --- a/src/librustdoc/core.rs +++ b/src/librustdoc/core.rs @@ -77,7 +77,7 @@ pub struct DocContext<'a, 'tcx: 'a, 'rcx: 'a> { /// Table node id of lifetime parameter definition -> substituted lifetime pub lt_substs: RefCell>, /// Table DefId of `impl Trait` in argument position -> bounds - pub impl_trait_bounds: RefCell>>, + pub impl_trait_bounds: RefCell>>, pub send_trait: Option, pub fake_def_ids: RefCell>, pub all_fake_def_ids: RefCell>, diff --git a/src/librustdoc/doctree.rs b/src/librustdoc/doctree.rs index 542d753c4f0dc..16d14bc56d695 100644 --- a/src/librustdoc/doctree.rs +++ b/src/librustdoc/doctree.rs @@ -201,7 +201,7 @@ pub struct Trait { pub name: Name, pub items: hir::HirVec, pub generics: hir::Generics, - pub bounds: hir::HirVec, + pub bounds: hir::HirVec, pub attrs: hir::HirVec, pub id: ast::NodeId, pub whence: Span, diff --git a/src/librustdoc/html/format.rs b/src/librustdoc/html/format.rs index bd9194a8669f2..987821d2e3002 100644 --- a/src/librustdoc/html/format.rs +++ b/src/librustdoc/html/format.rs @@ -46,7 +46,7 @@ pub struct MutableSpace(pub clean::Mutability); #[derive(Copy, Clone)] pub struct RawMutableSpace(pub clean::Mutability); /// Wrapper struct for emitting type parameter bounds. -pub struct ParamBounds<'a>(pub &'a [clean::ParamBound]); +pub struct GenericBounds<'a>(pub &'a [clean::GenericBound]); /// Wrapper struct for emitting a comma-separated list of items pub struct CommaSep<'a, T: 'a>(pub &'a [T]); pub struct AbiSpace(pub Abi); @@ -104,9 +104,9 @@ impl<'a, T: fmt::Display> fmt::Display for CommaSep<'a, T> { } } -impl<'a> fmt::Display for ParamBounds<'a> { +impl<'a> fmt::Display for GenericBounds<'a> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - let &ParamBounds(bounds) = self; + let &GenericBounds(bounds) = self; for (i, bound) in bounds.iter().enumerate() { if i > 0 { f.write_str(" + ")?; @@ -126,9 +126,9 @@ impl fmt::Display for clean::GenericParamDef { if !bounds.is_empty() { if f.alternate() { - write!(f, ": {:#}", ParamBounds(bounds))?; + write!(f, ": {:#}", GenericBounds(bounds))?; } else { - write!(f, ": {}", ParamBounds(bounds))?; + write!(f, ": {}", GenericBounds(bounds))?; } } @@ -190,9 +190,9 @@ impl<'a> fmt::Display for WhereClause<'a> { &clean::WherePredicate::BoundPredicate { ref ty, ref bounds } => { let bounds = bounds; if f.alternate() { - clause.push_str(&format!("{:#}: {:#}", ty, ParamBounds(bounds))); + clause.push_str(&format!("{:#}: {:#}", ty, GenericBounds(bounds))); } else { - clause.push_str(&format!("{}: {}", ty, ParamBounds(bounds))); + clause.push_str(&format!("{}: {}", ty, GenericBounds(bounds))); } } &clean::WherePredicate::RegionPredicate { ref lifetime, @@ -267,7 +267,7 @@ impl fmt::Display for clean::PolyTrait { } } -impl fmt::Display for clean::ParamBound { +impl fmt::Display for clean::GenericBound { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { clean::Outlives(ref lt) => { @@ -512,7 +512,7 @@ fn primitive_link(f: &mut fmt::Formatter, /// Helper to render type parameters fn tybounds(w: &mut fmt::Formatter, - typarams: &Option>) -> fmt::Result { + typarams: &Option>) -> fmt::Result { match *typarams { Some(ref params) => { for param in params { @@ -667,7 +667,7 @@ fn fmt_type(t: &clean::Type, f: &mut fmt::Formatter, use_absolute: bool) -> fmt: } } clean::ImplTrait(ref bounds) => { - write!(f, "impl {}", ParamBounds(bounds)) + write!(f, "impl {}", GenericBounds(bounds)) } clean::QPath { ref name, ref self_type, ref trait_ } => { let should_show_cast = match *trait_ { diff --git a/src/librustdoc/html/render.rs b/src/librustdoc/html/render.rs index 21724c2d730ef..180591b353260 100644 --- a/src/librustdoc/html/render.rs +++ b/src/librustdoc/html/render.rs @@ -69,7 +69,7 @@ use doctree; use fold::DocFolder; use html::escape::Escape; use html::format::{ConstnessSpace}; -use html::format::{ParamBounds, WhereClause, href, AbiSpace}; +use html::format::{GenericBounds, WhereClause, href, AbiSpace}; use html::format::{VisSpace, Method, UnsafetySpace, MutableSpace}; use html::format::fmt_impl_for_trait_page; use html::item_type::ItemType; @@ -2960,14 +2960,14 @@ fn assoc_const(w: &mut fmt::Formatter, } fn assoc_type(w: &mut W, it: &clean::Item, - bounds: &Vec, + bounds: &Vec, default: Option<&clean::Type>, link: AssocItemLink) -> fmt::Result { write!(w, "type {}", naive_assoc_href(it, link), it.name.as_ref().unwrap())?; if !bounds.is_empty() { - write!(w, ": {}", ParamBounds(bounds))? + write!(w, ": {}", GenericBounds(bounds))? } if let Some(default) = default { write!(w, " = {}", default)?; diff --git a/src/libsyntax/ast.rs b/src/libsyntax/ast.rs index 6fe90025ff8e5..9dc13fab2d65d 100644 --- a/src/libsyntax/ast.rs +++ b/src/libsyntax/ast.rs @@ -10,7 +10,7 @@ // The Rust abstract syntax tree. -pub use self::ParamBound::*; +pub use self::GenericBound::*; pub use self::UnsafeSource::*; pub use self::GenericArgs::*; pub use symbol::{Ident, Symbol as Name}; @@ -282,12 +282,12 @@ pub enum TraitBoundModifier { /// the "special" built-in traits (see middle::lang_items) and /// detects Copy, Send and Sync. #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)] -pub enum ParamBound { +pub enum GenericBound { Trait(PolyTraitRef, TraitBoundModifier), Outlives(Lifetime) } -impl ParamBound { +impl GenericBound { pub fn span(&self) -> Span { match self { &Trait(ref t, ..) => t.span, @@ -296,7 +296,7 @@ impl ParamBound { } } -pub type ParamBounds = Vec; +pub type GenericBounds = Vec; #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)] pub enum GenericParamKind { @@ -312,7 +312,7 @@ pub struct GenericParam { pub id: NodeId, pub ident: Ident, pub attrs: ThinVec, - pub bounds: ParamBounds, + pub bounds: GenericBounds, pub kind: GenericParamKind, } @@ -381,7 +381,7 @@ pub struct WhereBoundPredicate { /// The type being bounded pub bounded_ty: P, /// Trait and lifetime bounds (`Clone+Send+'static`) - pub bounds: ParamBounds, + pub bounds: GenericBounds, } /// A lifetime predicate. @@ -391,7 +391,7 @@ pub struct WhereBoundPredicate { pub struct WhereRegionPredicate { pub span: Span, pub lifetime: Lifetime, - pub bounds: ParamBounds, + pub bounds: GenericBounds, } /// An equality predicate (unsupported). @@ -927,7 +927,7 @@ impl Expr { } } - fn to_bound(&self) -> Option { + fn to_bound(&self) -> Option { match &self.node { ExprKind::Path(None, path) => Some(Trait(PolyTraitRef::new(Vec::new(), path.clone(), self.span), @@ -1352,7 +1352,7 @@ pub struct TraitItem { pub enum TraitItemKind { Const(P, Option>), Method(MethodSig, Option>), - Type(ParamBounds, Option>), + Type(GenericBounds, Option>), Macro(Mac), } @@ -1537,10 +1537,10 @@ pub enum TyKind { Path(Option, Path), /// A trait object type `Bound1 + Bound2 + Bound3` /// where `Bound` is a trait or a lifetime. - TraitObject(ParamBounds, TraitObjectSyntax), + TraitObject(GenericBounds, TraitObjectSyntax), /// An `impl Bound1 + Bound2 + Bound3` type /// where `Bound` is a trait or a lifetime. - ImplTrait(ParamBounds), + ImplTrait(GenericBounds), /// No-op; kept solely so that we can pretty-print faithfully Paren(P), /// Unused for now @@ -2061,11 +2061,11 @@ pub enum ItemKind { /// A Trait declaration (`trait` or `pub trait`). /// /// E.g. `trait Foo { .. }`, `trait Foo { .. }` or `auto trait Foo {}` - Trait(IsAuto, Unsafety, Generics, ParamBounds, Vec), + Trait(IsAuto, Unsafety, Generics, GenericBounds, Vec), /// Trait alias /// /// E.g. `trait Foo = Bar + Quux;` - TraitAlias(Generics, ParamBounds), + TraitAlias(Generics, GenericBounds), /// An implementation. /// /// E.g. `impl Foo { .. }` or `impl Trait for Foo { .. }` diff --git a/src/libsyntax/ext/build.rs b/src/libsyntax/ext/build.rs index 28bfb1ff81110..9de6e14fbebdc 100644 --- a/src/libsyntax/ext/build.rs +++ b/src/libsyntax/ext/build.rs @@ -68,18 +68,18 @@ pub trait AstBuilder { span: Span, id: ast::Ident, attrs: Vec, - bounds: ast::ParamBounds, + bounds: ast::GenericBounds, default: Option>) -> ast::GenericParam; fn trait_ref(&self, path: ast::Path) -> ast::TraitRef; fn poly_trait_ref(&self, span: Span, path: ast::Path) -> ast::PolyTraitRef; - fn ty_param_bound(&self, path: ast::Path) -> ast::ParamBound; + fn ty_param_bound(&self, path: ast::Path) -> ast::GenericBound; fn lifetime(&self, span: Span, ident: ast::Ident) -> ast::Lifetime; fn lifetime_def(&self, span: Span, ident: ast::Ident, attrs: Vec, - bounds: ast::ParamBounds) + bounds: ast::GenericBounds) -> ast::GenericParam; // statements @@ -436,7 +436,7 @@ impl<'a> AstBuilder for ExtCtxt<'a> { span: Span, ident: ast::Ident, attrs: Vec, - bounds: ast::ParamBounds, + bounds: ast::GenericBounds, default: Option>) -> ast::GenericParam { ast::GenericParam { ident: ident.with_span_pos(span), @@ -464,7 +464,7 @@ impl<'a> AstBuilder for ExtCtxt<'a> { } } - fn ty_param_bound(&self, path: ast::Path) -> ast::ParamBound { + fn ty_param_bound(&self, path: ast::Path) -> ast::GenericBound { ast::Trait(self.poly_trait_ref(path.span, path), ast::TraitBoundModifier::None) } @@ -476,7 +476,7 @@ impl<'a> AstBuilder for ExtCtxt<'a> { span: Span, ident: ast::Ident, attrs: Vec, - bounds: ast::ParamBounds) + bounds: ast::GenericBounds) -> ast::GenericParam { let lifetime = self.lifetime(span, ident); ast::GenericParam { diff --git a/src/libsyntax/fold.rs b/src/libsyntax/fold.rs index 290607a702b17..5db5d0781eae1 100644 --- a/src/libsyntax/fold.rs +++ b/src/libsyntax/fold.rs @@ -268,15 +268,15 @@ pub trait Folder : Sized { noop_fold_interpolated(nt, self) } - fn fold_opt_bounds(&mut self, b: Option) -> Option { + fn fold_opt_bounds(&mut self, b: Option) -> Option { noop_fold_opt_bounds(b, self) } - fn fold_bounds(&mut self, b: ParamBounds) -> ParamBounds { + fn fold_bounds(&mut self, b: GenericBounds) -> GenericBounds { noop_fold_bounds(b, self) } - fn fold_param_bound(&mut self, tpb: ParamBound) -> ParamBound { + fn fold_param_bound(&mut self, tpb: GenericBound) -> GenericBound { noop_fold_param_bound(tpb, self) } @@ -676,7 +676,7 @@ pub fn noop_fold_fn_decl(decl: P, fld: &mut T) -> P { }) } -pub fn noop_fold_param_bound(pb: ParamBound, fld: &mut T) -> ParamBound where T: Folder { +pub fn noop_fold_param_bound(pb: GenericBound, fld: &mut T) -> GenericBound where T: Folder { match pb { Trait(ty, modifier) => { Trait(fld.fold_poly_trait_ref(ty), modifier) @@ -847,13 +847,13 @@ pub fn noop_fold_mt(MutTy {ty, mutbl}: MutTy, folder: &mut T) -> MutT } } -pub fn noop_fold_opt_bounds(b: Option, folder: &mut T) - -> Option { +pub fn noop_fold_opt_bounds(b: Option, folder: &mut T) + -> Option { b.map(|bounds| folder.fold_bounds(bounds)) } -fn noop_fold_bounds(bounds: ParamBounds, folder: &mut T) - -> ParamBounds { +fn noop_fold_bounds(bounds: GenericBounds, folder: &mut T) + -> GenericBounds { bounds.move_map(|bound| folder.fold_param_bound(bound)) } diff --git a/src/libsyntax/parse/parser.rs b/src/libsyntax/parse/parser.rs index 75eefb844321c..8588f4c492f94 100644 --- a/src/libsyntax/parse/parser.rs +++ b/src/libsyntax/parse/parser.rs @@ -36,7 +36,7 @@ use ast::{VariantData, StructField}; use ast::StrStyle; use ast::SelfKind; use ast::{TraitItem, TraitRef, TraitObjectSyntax}; -use ast::{Ty, TyKind, TypeBinding, ParamBounds}; +use ast::{Ty, TyKind, TypeBinding, GenericBounds}; use ast::{Visibility, VisibilityKind, WhereClause, CrateSugar}; use ast::{UseTree, UseTreeKind}; use ast::{BinOpKind, UnOp}; @@ -4735,7 +4735,7 @@ impl<'a> Parser<'a> { // LT_BOUND = LIFETIME (e.g. `'a`) // TY_BOUND = TY_BOUND_NOPAREN | (TY_BOUND_NOPAREN) // TY_BOUND_NOPAREN = [?] [for] SIMPLE_PATH (e.g. `?for<'a: 'b> m::Trait<'a>`) - fn parse_ty_param_bounds_common(&mut self, allow_plus: bool) -> PResult<'a, ParamBounds> { + fn parse_ty_param_bounds_common(&mut self, allow_plus: bool) -> PResult<'a, GenericBounds> { let mut bounds = Vec::new(); loop { // This needs to be syncronized with `Token::can_begin_bound`. @@ -4784,16 +4784,16 @@ impl<'a> Parser<'a> { return Ok(bounds); } - fn parse_ty_param_bounds(&mut self) -> PResult<'a, ParamBounds> { + fn parse_ty_param_bounds(&mut self) -> PResult<'a, GenericBounds> { self.parse_ty_param_bounds_common(true) } // Parse bounds of a lifetime parameter `BOUND + BOUND + BOUND`, possibly with trailing `+`. // BOUND = LT_BOUND (e.g. `'a`) - fn parse_lt_param_bounds(&mut self) -> ParamBounds { + fn parse_lt_param_bounds(&mut self) -> GenericBounds { let mut lifetimes = Vec::new(); while self.check_lifetime() { - lifetimes.push(ast::ParamBound::Outlives(self.expect_lifetime())); + lifetimes.push(ast::GenericBound::Outlives(self.expect_lifetime())); if !self.eat_plus() { break @@ -4833,7 +4833,7 @@ impl<'a> Parser<'a> { } /// Parses the following grammar: - /// TraitItemAssocTy = Ident ["<"...">"] [":" [ParamBounds]] ["where" ...] ["=" Ty] + /// TraitItemAssocTy = Ident ["<"...">"] [":" [GenericBounds]] ["where" ...] ["=" Ty] fn parse_trait_item_assoc_ty(&mut self) -> PResult<'a, (Ident, TraitItemKind, ast::Generics)> { let ident = self.parse_ident()?; diff --git a/src/libsyntax/print/pprust.rs b/src/libsyntax/print/pprust.rs index 38229fa499876..1e0b107ef6ead 100644 --- a/src/libsyntax/print/pprust.rs +++ b/src/libsyntax/print/pprust.rs @@ -292,7 +292,7 @@ pub fn ty_to_string(ty: &ast::Ty) -> String { to_string(|s| s.print_type(ty)) } -pub fn bounds_to_string(bounds: &[ast::ParamBound]) -> String { +pub fn bounds_to_string(bounds: &[ast::GenericBound]) -> String { to_string(|s| s.print_type_bounds("", bounds)) } @@ -1177,7 +1177,7 @@ impl<'a> State<'a> { fn print_associated_type(&mut self, ident: ast::Ident, - bounds: Option<&ast::ParamBounds>, + bounds: Option<&ast::GenericBounds>, ty: Option<&ast::Ty>) -> io::Result<()> { self.word_space("type")?; @@ -2810,7 +2810,7 @@ impl<'a> State<'a> { pub fn print_type_bounds(&mut self, prefix: &str, - bounds: &[ast::ParamBound]) + bounds: &[ast::GenericBound]) -> io::Result<()> { if !bounds.is_empty() { self.s.word(prefix)?; @@ -2843,7 +2843,7 @@ impl<'a> State<'a> { self.print_name(lifetime.ident.name) } - pub fn print_lifetime_bounds(&mut self, lifetime: ast::Lifetime, bounds: &ast::ParamBounds) + pub fn print_lifetime_bounds(&mut self, lifetime: ast::Lifetime, bounds: &ast::GenericBounds) -> io::Result<()> { self.print_lifetime(lifetime)?; @@ -2854,7 +2854,7 @@ impl<'a> State<'a> { self.s.word(" + ")?; } match bound { - ast::ParamBound::Outlives(lt) => self.print_lifetime(*lt)?, + ast::GenericBound::Outlives(lt) => self.print_lifetime(*lt)?, _ => panic!(), } } diff --git a/src/libsyntax/util/node_count.rs b/src/libsyntax/util/node_count.rs index 2d92f4b9531ad..ebb3081c1fde5 100644 --- a/src/libsyntax/util/node_count.rs +++ b/src/libsyntax/util/node_count.rs @@ -95,7 +95,7 @@ impl<'ast> Visitor<'ast> for NodeCounter { self.count += 1; walk_trait_ref(self, t) } - fn visit_param_bound(&mut self, bounds: &ParamBound) { + fn visit_param_bound(&mut self, bounds: &GenericBound) { self.count += 1; walk_param_bound(self, bounds) } diff --git a/src/libsyntax/visit.rs b/src/libsyntax/visit.rs index 6beaabd03de71..71b606f08a5a0 100644 --- a/src/libsyntax/visit.rs +++ b/src/libsyntax/visit.rs @@ -86,7 +86,7 @@ pub trait Visitor<'ast>: Sized { fn visit_trait_item(&mut self, ti: &'ast TraitItem) { walk_trait_item(self, ti) } fn visit_impl_item(&mut self, ii: &'ast ImplItem) { walk_impl_item(self, ii) } fn visit_trait_ref(&mut self, t: &'ast TraitRef) { walk_trait_ref(self, t) } - fn visit_param_bound(&mut self, bounds: &'ast ParamBound) { + fn visit_param_bound(&mut self, bounds: &'ast GenericBound) { walk_param_bound(self, bounds) } fn visit_poly_trait_ref(&mut self, t: &'ast PolyTraitRef, m: &'ast TraitBoundModifier) { @@ -479,7 +479,7 @@ pub fn walk_global_asm<'a, V: Visitor<'a>>(_: &mut V, _: &'a GlobalAsm) { // Empty! } -pub fn walk_param_bound<'a, V: Visitor<'a>>(visitor: &mut V, bound: &'a ParamBound) { +pub fn walk_param_bound<'a, V: Visitor<'a>>(visitor: &mut V, bound: &'a GenericBound) { match *bound { Trait(ref typ, ref modifier) => { visitor.visit_poly_trait_ref(typ, modifier); diff --git a/src/libsyntax_ext/deriving/generic/mod.rs b/src/libsyntax_ext/deriving/generic/mod.rs index 89b500441292d..0922e7cd800e4 100644 --- a/src/libsyntax_ext/deriving/generic/mod.rs +++ b/src/libsyntax_ext/deriving/generic/mod.rs @@ -553,7 +553,7 @@ impl<'a> TraitDef<'a> { GenericParamKind::Lifetime { .. } => param.clone(), GenericParamKind::Type { .. } => { // I don't think this can be moved out of the loop, since - // a ParamBound requires an ast id + // a GenericBound requires an ast id let mut bounds: Vec<_> = // extra restrictions on the generics parameters to the // type being derived upon diff --git a/src/libsyntax_ext/deriving/generic/ty.rs b/src/libsyntax_ext/deriving/generic/ty.rs index 99b6398160e5f..edb901e1f3c42 100644 --- a/src/libsyntax_ext/deriving/generic/ty.rs +++ b/src/libsyntax_ext/deriving/generic/ty.rs @@ -261,7 +261,7 @@ impl<'a> LifetimeBounds<'a> { .iter() .map(|&(lt, ref bounds)| { let bounds = bounds.iter() - .map(|b| ast::ParamBound::Outlives(cx.lifetime(span, Ident::from_str(b)))); + .map(|b| ast::GenericBound::Outlives(cx.lifetime(span, Ident::from_str(b)))); cx.lifetime_def(span, Ident::from_str(lt), vec![], bounds.collect()) }) .chain(self.bounds From 95f1866a4df85e815886901a7b64d8dd64709872 Mon Sep 17 00:00:00 2001 From: varkor Date: Thu, 14 Jun 2018 12:23:46 +0100 Subject: [PATCH 33/41] Make GenericBound explicit --- src/librustc/hir/lowering.rs | 6 +++--- src/librustc_passes/ast_validation.rs | 6 +++--- src/librustc_save_analysis/dump_visitor.rs | 8 +++----- src/librustdoc/clean/inline.rs | 10 +++++----- src/librustdoc/clean/mod.rs | 23 +++++++++++----------- src/librustdoc/clean/simplify.rs | 4 ++-- src/librustdoc/html/format.rs | 4 ++-- src/libsyntax/ast.rs | 9 ++++----- src/libsyntax/ext/build.rs | 3 ++- src/libsyntax/fold.rs | 8 +++++--- src/libsyntax/parse/parser.rs | 10 +++++----- src/libsyntax/print/pprust.rs | 10 +++++----- src/libsyntax/visit.rs | 8 ++------ 13 files changed, 53 insertions(+), 56 deletions(-) diff --git a/src/librustc/hir/lowering.rs b/src/librustc/hir/lowering.rs index b725432eb5ca3..7628504ba0dc1 100644 --- a/src/librustc/hir/lowering.rs +++ b/src/librustc/hir/lowering.rs @@ -1109,11 +1109,11 @@ impl<'a> LoweringContext<'a> { let bounds = bounds .iter() .filter_map(|bound| match *bound { - Trait(ref ty, TraitBoundModifier::None) => { + GenericBound::Trait(ref ty, TraitBoundModifier::None) => { Some(self.lower_poly_trait_ref(ty, itctx)) } - Trait(_, TraitBoundModifier::Maybe) => None, - Outlives(ref lifetime) => { + GenericBound::Trait(_, TraitBoundModifier::Maybe) => None, + GenericBound::Outlives(ref lifetime) => { if lifetime_bound.is_none() { lifetime_bound = Some(self.lower_lifetime(lifetime)); } diff --git a/src/librustc_passes/ast_validation.rs b/src/librustc_passes/ast_validation.rs index 4f04ad896983d..fc54d323b0f96 100644 --- a/src/librustc_passes/ast_validation.rs +++ b/src/librustc_passes/ast_validation.rs @@ -101,7 +101,7 @@ impl<'a> AstValidator<'a> { fn no_questions_in_bounds(&self, bounds: &GenericBounds, where_: &str, is_trait: bool) { for bound in bounds { - if let Trait(ref poly, TraitBoundModifier::Maybe) = *bound { + if let GenericBound::Trait(ref poly, TraitBoundModifier::Maybe) = *bound { let mut err = self.err_handler().struct_span_err(poly.span, &format!("`?Trait` is not permitted in {}", where_)); if is_trait { @@ -190,7 +190,7 @@ impl<'a> Visitor<'a> for AstValidator<'a> { TyKind::TraitObject(ref bounds, ..) => { let mut any_lifetime_bounds = false; for bound in bounds { - if let Outlives(ref lifetime) = *bound { + if let GenericBound::Outlives(ref lifetime) = *bound { if any_lifetime_bounds { span_err!(self.session, lifetime.ident.span, E0226, "only a single explicit lifetime bound is permitted"); @@ -203,7 +203,7 @@ impl<'a> Visitor<'a> for AstValidator<'a> { } TyKind::ImplTrait(ref bounds) => { if !bounds.iter() - .any(|b| if let Trait(..) = *b { true } else { false }) { + .any(|b| if let GenericBound::Trait(..) = *b { true } else { false }) { self.err_handler().span_err(ty.span, "at least one trait must be specified"); } } diff --git a/src/librustc_save_analysis/dump_visitor.rs b/src/librustc_save_analysis/dump_visitor.rs index 0f0f3f6e7892b..7da5b1668b3d8 100644 --- a/src/librustc_save_analysis/dump_visitor.rs +++ b/src/librustc_save_analysis/dump_visitor.rs @@ -761,10 +761,8 @@ impl<'l, 'tcx: 'l, 'll, O: DumpOutput + 'll> DumpVisitor<'l, 'tcx, 'll, O> { // super-traits for super_bound in trait_refs.iter() { let trait_ref = match *super_bound { - ast::Trait(ref trait_ref, _) => trait_ref, - ast::Outlives(..) => { - continue; - } + ast::GenericBound::Trait(ref trait_ref, _) => trait_ref, + ast::GenericBound::Outlives(..) => continue, }; let trait_ref = &trait_ref.trait_ref; @@ -1489,7 +1487,7 @@ impl<'l, 'tcx: 'l, 'll, O: DumpOutput + 'll> Visitor<'l> for DumpVisitor<'l, 'tc ast::GenericParamKind::Lifetime { .. } => {} ast::GenericParamKind::Type { ref default, .. } => { for bound in ¶m.bounds { - if let ast::Trait(ref trait_ref, _) = *bound { + if let ast::GenericBound::Trait(ref trait_ref, _) = *bound { self.process_path(trait_ref.trait_ref.ref_id, &trait_ref.trait_ref.path) } } diff --git a/src/librustdoc/clean/inline.rs b/src/librustdoc/clean/inline.rs index f3a833bad8f78..114cb0e455d9a 100644 --- a/src/librustdoc/clean/inline.rs +++ b/src/librustdoc/clean/inline.rs @@ -374,8 +374,8 @@ pub fn build_impl(cx: &DocContext, did: DefId, ret: &mut Vec) { let polarity = tcx.impl_polarity(did); let trait_ = associated_trait.clean(cx).map(|bound| { match bound { - clean::TraitBound(polyt, _) => polyt.trait_, - clean::Outlives(..) => unreachable!(), + clean::GenericBound::TraitBound(polyt, _) => polyt.trait_, + clean::GenericBound::Outlives(..) => unreachable!(), } }); if trait_.def_id() == tcx.lang_items().deref_trait() { @@ -387,9 +387,9 @@ pub fn build_impl(cx: &DocContext, did: DefId, ret: &mut Vec) { let provided = trait_.def_id().map(|did| { tcx.provided_trait_methods(did) - .into_iter() - .map(|meth| meth.name.to_string()) - .collect() + .into_iter() + .map(|meth| meth.name.to_string()) + .collect() }).unwrap_or(FxHashSet()); ret.push(clean::Item { diff --git a/src/librustdoc/clean/mod.rs b/src/librustdoc/clean/mod.rs index 031a948fe80d1..0979c3d85587d 100644 --- a/src/librustdoc/clean/mod.rs +++ b/src/librustdoc/clean/mod.rs @@ -14,7 +14,6 @@ pub use self::Type::*; pub use self::Mutability::*; pub use self::ItemEnum::*; -pub use self::GenericBound::*; pub use self::SelfTy::*; pub use self::FunctionRetTy::*; pub use self::Visibility::{Public, Inherited}; @@ -1470,7 +1469,7 @@ impl GenericBound { let path = external_path(cx, &cx.tcx.item_name(did).as_str(), Some(did), false, vec![], empty); inline::record_extern_fqn(cx, did, TypeKind::Trait); - TraitBound(PolyTrait { + GenericBound::TraitBound(PolyTrait { trait_: ResolvedPath { path, typarams: None, @@ -1510,8 +1509,10 @@ impl GenericBound { impl Clean for hir::GenericBound { fn clean(&self, cx: &DocContext) -> GenericBound { match *self { - hir::GenericBound::Outlives(lt) => Outlives(lt.clean(cx)), - hir::GenericBound::Trait(ref t, modifier) => TraitBound(t.clean(cx), modifier), + hir::GenericBound::Outlives(lt) => GenericBound::Outlives(lt.clean(cx)), + hir::GenericBound::Trait(ref t, modifier) => { + GenericBound::TraitBound(t.clean(cx), modifier) + } } } } @@ -1599,7 +1600,7 @@ impl<'a, 'tcx> Clean for (&'a ty::TraitRef<'tcx>, Vec } } - TraitBound( + GenericBound::TraitBound( PolyTrait { trait_: ResolvedPath { path, @@ -1623,9 +1624,8 @@ impl<'tcx> Clean for ty::TraitRef<'tcx> { impl<'tcx> Clean>> for Substs<'tcx> { fn clean(&self, cx: &DocContext) -> Option> { let mut v = Vec::new(); - v.extend(self.regions().filter_map(|r| r.clean(cx)) - .map(GenericBound::Outlives)); - v.extend(self.types().map(|t| TraitBound(PolyTrait { + v.extend(self.regions().filter_map(|r| r.clean(cx)).map(GenericBound::Outlives)); + v.extend(self.types().map(|t| GenericBound::TraitBound(PolyTrait { trait_: t.clean(cx), generic_params: Vec::new(), }, hir::TraitBoundModifier::None))); @@ -2978,10 +2978,11 @@ impl Clean for hir::Ty { match bounds[0].clean(cx).trait_ { ResolvedPath { path, typarams: None, did, is_generic } => { let mut bounds: Vec = bounds[1..].iter().map(|bound| { - TraitBound(bound.clean(cx), hir::TraitBoundModifier::None) + self::GenericBound::TraitBound(bound.clean(cx), + hir::TraitBoundModifier::None) }).collect(); if !lifetime.is_elided() { - bounds.push(self::Outlives(lifetime.clean(cx))); + bounds.push(self::GenericBound::Outlives(lifetime.clean(cx))); } ResolvedPath { path, typarams: Some(bounds), did, is_generic, } } @@ -3086,7 +3087,7 @@ impl<'tcx> Clean for Ty<'tcx> { let path = external_path(cx, &cx.tcx.item_name(did).as_str(), Some(did), false, vec![], empty); inline::record_extern_fqn(cx, did, TypeKind::Trait); - let bound = TraitBound(PolyTrait { + let bound = GenericBound::TraitBound(PolyTrait { trait_: ResolvedPath { path, typarams: None, diff --git a/src/librustdoc/clean/simplify.rs b/src/librustdoc/clean/simplify.rs index a54eb64443bef..30a55bf0d1809 100644 --- a/src/librustdoc/clean/simplify.rs +++ b/src/librustdoc/clean/simplify.rs @@ -83,8 +83,8 @@ pub fn where_clauses(cx: &DocContext, clauses: Vec) -> Vec { }; !bounds.iter_mut().any(|b| { let trait_ref = match *b { - clean::TraitBound(ref mut tr, _) => tr, - clean::Outlives(..) => return false, + clean::GenericBound::TraitBound(ref mut tr, _) => tr, + clean::GenericBound::Outlives(..) => return false, }; let (did, path) = match trait_ref.trait_ { clean::ResolvedPath { did, ref mut path, ..} => (did, path), diff --git a/src/librustdoc/html/format.rs b/src/librustdoc/html/format.rs index 987821d2e3002..3d360f2f344b6 100644 --- a/src/librustdoc/html/format.rs +++ b/src/librustdoc/html/format.rs @@ -270,10 +270,10 @@ impl fmt::Display for clean::PolyTrait { impl fmt::Display for clean::GenericBound { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { - clean::Outlives(ref lt) => { + clean::GenericBound::Outlives(ref lt) => { write!(f, "{}", *lt) } - clean::TraitBound(ref ty, modifier) => { + clean::GenericBound::TraitBound(ref ty, modifier) => { let modifier_str = match modifier { hir::TraitBoundModifier::None => "", hir::TraitBoundModifier::Maybe => "?", diff --git a/src/libsyntax/ast.rs b/src/libsyntax/ast.rs index 9dc13fab2d65d..76d19ce0ac5b2 100644 --- a/src/libsyntax/ast.rs +++ b/src/libsyntax/ast.rs @@ -10,7 +10,6 @@ // The Rust abstract syntax tree. -pub use self::GenericBound::*; pub use self::UnsafeSource::*; pub use self::GenericArgs::*; pub use symbol::{Ident, Symbol as Name}; @@ -290,8 +289,8 @@ pub enum GenericBound { impl GenericBound { pub fn span(&self) -> Span { match self { - &Trait(ref t, ..) => t.span, - &Outlives(ref l) => l.ident.span, + &GenericBound::Trait(ref t, ..) => t.span, + &GenericBound::Outlives(ref l) => l.ident.span, } } } @@ -930,8 +929,8 @@ impl Expr { fn to_bound(&self) -> Option { match &self.node { ExprKind::Path(None, path) => - Some(Trait(PolyTraitRef::new(Vec::new(), path.clone(), self.span), - TraitBoundModifier::None)), + Some(GenericBound::Trait(PolyTraitRef::new(Vec::new(), path.clone(), self.span), + TraitBoundModifier::None)), _ => None, } } diff --git a/src/libsyntax/ext/build.rs b/src/libsyntax/ext/build.rs index 9de6e14fbebdc..40d453061497a 100644 --- a/src/libsyntax/ext/build.rs +++ b/src/libsyntax/ext/build.rs @@ -465,7 +465,8 @@ impl<'a> AstBuilder for ExtCtxt<'a> { } fn ty_param_bound(&self, path: ast::Path) -> ast::GenericBound { - ast::Trait(self.poly_trait_ref(path.span, path), ast::TraitBoundModifier::None) + ast::GenericBound::Trait(self.poly_trait_ref(path.span, path), + ast::TraitBoundModifier::None) } fn lifetime(&self, span: Span, ident: ast::Ident) -> ast::Lifetime { diff --git a/src/libsyntax/fold.rs b/src/libsyntax/fold.rs index 5db5d0781eae1..03668cc279a2c 100644 --- a/src/libsyntax/fold.rs +++ b/src/libsyntax/fold.rs @@ -678,10 +678,12 @@ pub fn noop_fold_fn_decl(decl: P, fld: &mut T) -> P { pub fn noop_fold_param_bound(pb: GenericBound, fld: &mut T) -> GenericBound where T: Folder { match pb { - Trait(ty, modifier) => { - Trait(fld.fold_poly_trait_ref(ty), modifier) + GenericBound::Trait(ty, modifier) => { + GenericBound::Trait(fld.fold_poly_trait_ref(ty), modifier) + } + GenericBound::Outlives(lifetime) => { + GenericBound::Outlives(noop_fold_lifetime(lifetime, fld)) } - Outlives(lifetime) => Outlives(noop_fold_lifetime(lifetime, fld)), } } diff --git a/src/libsyntax/parse/parser.rs b/src/libsyntax/parse/parser.rs index 8588f4c492f94..675849c8a5c4d 100644 --- a/src/libsyntax/parse/parser.rs +++ b/src/libsyntax/parse/parser.rs @@ -10,7 +10,7 @@ use rustc_target::spec::abi::{self, Abi}; use ast::{AngleBracketedArgs, ParenthesizedArgData, AttrStyle, BareFnTy}; -use ast::{Outlives, Trait, TraitBoundModifier}; +use ast::{GenericBound, TraitBoundModifier}; use ast::Unsafety; use ast::{Mod, AnonConst, Arg, Arm, Attribute, BindingMode, TraitItemKind}; use ast::Block; @@ -1444,7 +1444,7 @@ impl<'a> Parser<'a> { TyKind::TraitObject(ref bounds, TraitObjectSyntax::None) if maybe_bounds && bounds.len() == 1 && !trailing_plus => { let path = match bounds[0] { - Trait(ref pt, ..) => pt.trait_ref.path.clone(), + GenericBound::Trait(ref pt, ..) => pt.trait_ref.path.clone(), _ => self.bug("unexpected lifetime bound"), }; self.parse_remaining_bounds(Vec::new(), path, lo, true)? @@ -1566,7 +1566,7 @@ impl<'a> Parser<'a> { fn parse_remaining_bounds(&mut self, generic_params: Vec, path: ast::Path, lo: Span, parse_plus: bool) -> PResult<'a, TyKind> { let poly_trait_ref = PolyTraitRef::new(generic_params, path, lo.to(self.prev_span)); - let mut bounds = vec![Trait(poly_trait_ref, TraitBoundModifier::None)]; + let mut bounds = vec![GenericBound::Trait(poly_trait_ref, TraitBoundModifier::None)]; if parse_plus { self.eat_plus(); // `+`, or `+=` gets split and `+` is discarded bounds.append(&mut self.parse_ty_param_bounds()?); @@ -4752,7 +4752,7 @@ impl<'a> Parser<'a> { self.span_err(question_span, "`?` may only modify trait bounds, not lifetime bounds"); } - bounds.push(Outlives(self.expect_lifetime())); + bounds.push(GenericBound::Outlives(self.expect_lifetime())); if has_parens { self.expect(&token::CloseDelim(token::Paren))?; self.span_err(self.prev_span, @@ -4770,7 +4770,7 @@ impl<'a> Parser<'a> { } else { TraitBoundModifier::None }; - bounds.push(Trait(poly_trait, modifier)); + bounds.push(GenericBound::Trait(poly_trait, modifier)); } } else { break diff --git a/src/libsyntax/print/pprust.rs b/src/libsyntax/print/pprust.rs index 1e0b107ef6ead..7a55919f422b8 100644 --- a/src/libsyntax/print/pprust.rs +++ b/src/libsyntax/print/pprust.rs @@ -12,7 +12,7 @@ pub use self::AnnNode::*; use rustc_target::spec::abi::{self, Abi}; use ast::{self, BlockCheckMode, PatKind, RangeEnd, RangeSyntax}; -use ast::{SelfKind, Outlives, Trait, TraitBoundModifier}; +use ast::{SelfKind, GenericBound, TraitBoundModifier}; use ast::{Attribute, MacDelimiter, GenericArg}; use util::parser::{self, AssocOp, Fixity}; use attr; @@ -1364,7 +1364,7 @@ impl<'a> State<'a> { self.print_generic_params(&generics.params)?; let mut real_bounds = Vec::with_capacity(bounds.len()); for b in bounds.iter() { - if let Trait(ref ptr, ast::TraitBoundModifier::Maybe) = *b { + if let GenericBound::Trait(ref ptr, ast::TraitBoundModifier::Maybe) = *b { self.s.space()?; self.word_space("for ?")?; self.print_trait_ref(&ptr.trait_ref)?; @@ -1390,7 +1390,7 @@ impl<'a> State<'a> { let mut real_bounds = Vec::with_capacity(bounds.len()); // FIXME(durka) this seems to be some quite outdated syntax for b in bounds.iter() { - if let Trait(ref ptr, ast::TraitBoundModifier::Maybe) = *b { + if let GenericBound::Trait(ref ptr, ast::TraitBoundModifier::Maybe) = *b { self.s.space()?; self.word_space("for ?")?; self.print_trait_ref(&ptr.trait_ref)?; @@ -2826,13 +2826,13 @@ impl<'a> State<'a> { } match bound { - Trait(tref, modifier) => { + GenericBound::Trait(tref, modifier) => { if modifier == &TraitBoundModifier::Maybe { self.s.word("?")?; } self.print_poly_trait_ref(tref)?; } - Outlives(lt) => self.print_lifetime(*lt)?, + GenericBound::Outlives(lt) => self.print_lifetime(*lt)?, } } } diff --git a/src/libsyntax/visit.rs b/src/libsyntax/visit.rs index 71b606f08a5a0..5476a3f0d2a72 100644 --- a/src/libsyntax/visit.rs +++ b/src/libsyntax/visit.rs @@ -481,12 +481,8 @@ pub fn walk_global_asm<'a, V: Visitor<'a>>(_: &mut V, _: &'a GlobalAsm) { pub fn walk_param_bound<'a, V: Visitor<'a>>(visitor: &mut V, bound: &'a GenericBound) { match *bound { - Trait(ref typ, ref modifier) => { - visitor.visit_poly_trait_ref(typ, modifier); - } - Outlives(ref lifetime) => { - visitor.visit_lifetime(lifetime); - } + GenericBound::Trait(ref typ, ref modifier) => visitor.visit_poly_trait_ref(typ, modifier), + GenericBound::Outlives(ref lifetime) => visitor.visit_lifetime(lifetime), } } From 37204027b609f9bd218641c764e692335597ff26 Mon Sep 17 00:00:00 2001 From: varkor Date: Thu, 14 Jun 2018 15:00:21 +0100 Subject: [PATCH 34/41] Rename ty_param_bound to trait_bound --- src/librustc_privacy/lib.rs | 5 ++--- src/libsyntax/ext/build.rs | 4 ++-- src/libsyntax_ext/deriving/generic/mod.rs | 8 ++++---- src/libsyntax_ext/deriving/generic/ty.rs | 2 +- 4 files changed, 9 insertions(+), 10 deletions(-) diff --git a/src/librustc_privacy/lib.rs b/src/librustc_privacy/lib.rs index 809f5a06952ad..3b865e6ce0ff8 100644 --- a/src/librustc_privacy/lib.rs +++ b/src/librustc_privacy/lib.rs @@ -1037,9 +1037,8 @@ impl<'a, 'tcx> ObsoleteVisiblePrivateTypesVisitor<'a, 'tcx> { self.access_levels.is_public(trait_id) } - fn check_ty_param_bound(&mut self, - ty_param_bound: &hir::GenericBound) { - if let hir::GenericBound::Trait(ref trait_ref, _) = *ty_param_bound { + fn check_ty_param_bound(&mut self, bound: &hir::GenericBound) { + if let hir::GenericBound::Trait(ref trait_ref, _) = *bound { if self.path_is_private_type(&trait_ref.trait_ref.path) { self.old_error_set.insert(trait_ref.trait_ref.ref_id); } diff --git a/src/libsyntax/ext/build.rs b/src/libsyntax/ext/build.rs index 40d453061497a..9044cab05d667 100644 --- a/src/libsyntax/ext/build.rs +++ b/src/libsyntax/ext/build.rs @@ -73,7 +73,7 @@ pub trait AstBuilder { fn trait_ref(&self, path: ast::Path) -> ast::TraitRef; fn poly_trait_ref(&self, span: Span, path: ast::Path) -> ast::PolyTraitRef; - fn ty_param_bound(&self, path: ast::Path) -> ast::GenericBound; + fn trait_bound(&self, path: ast::Path) -> ast::GenericBound; fn lifetime(&self, span: Span, ident: ast::Ident) -> ast::Lifetime; fn lifetime_def(&self, span: Span, @@ -464,7 +464,7 @@ impl<'a> AstBuilder for ExtCtxt<'a> { } } - fn ty_param_bound(&self, path: ast::Path) -> ast::GenericBound { + fn trait_bound(&self, path: ast::Path) -> ast::GenericBound { ast::GenericBound::Trait(self.poly_trait_ref(path.span, path), ast::TraitBoundModifier::None) } diff --git a/src/libsyntax_ext/deriving/generic/mod.rs b/src/libsyntax_ext/deriving/generic/mod.rs index 0922e7cd800e4..44a07f532a78a 100644 --- a/src/libsyntax_ext/deriving/generic/mod.rs +++ b/src/libsyntax_ext/deriving/generic/mod.rs @@ -558,11 +558,11 @@ impl<'a> TraitDef<'a> { // extra restrictions on the generics parameters to the // type being derived upon self.additional_bounds.iter().map(|p| { - cx.ty_param_bound(p.to_path(cx, self.span, type_ident, generics)) + cx.trait_bound(p.to_path(cx, self.span, type_ident, generics)) }).collect(); // require the current trait - bounds.push(cx.ty_param_bound(trait_path.clone())); + bounds.push(cx.trait_bound(trait_path.clone())); // also add in any bounds from the declaration for declared_bound in ¶m.bounds { @@ -634,12 +634,12 @@ impl<'a> TraitDef<'a> { let mut bounds: Vec<_> = self.additional_bounds .iter() .map(|p| { - cx.ty_param_bound(p.to_path(cx, self.span, type_ident, generics)) + cx.trait_bound(p.to_path(cx, self.span, type_ident, generics)) }) .collect(); // require the current trait - bounds.push(cx.ty_param_bound(trait_path.clone())); + bounds.push(cx.trait_bound(trait_path.clone())); let predicate = ast::WhereBoundPredicate { span: self.span, diff --git a/src/libsyntax_ext/deriving/generic/ty.rs b/src/libsyntax_ext/deriving/generic/ty.rs index edb901e1f3c42..0b809ab585cdc 100644 --- a/src/libsyntax_ext/deriving/generic/ty.rs +++ b/src/libsyntax_ext/deriving/generic/ty.rs @@ -219,7 +219,7 @@ fn mk_ty_param(cx: &ExtCtxt, let bounds = bounds.iter() .map(|b| { let path = b.to_path(cx, span, self_ident, self_generics); - cx.ty_param_bound(path) + cx.trait_bound(path) }) .collect(); cx.typaram(span, cx.ident_of(name), attrs.to_owned(), bounds, None) From a65a9d77f3c4e0a573f9c43b51f9076e96201edc Mon Sep 17 00:00:00 2001 From: varkor Date: Fri, 15 Jun 2018 10:51:44 +0100 Subject: [PATCH 35/41] Fix accidental quadratic loops --- src/librustc_typeck/astconv.rs | 41 +++++++++------------- src/librustc_typeck/check/mod.rs | 59 +++++++++++++++++++------------- 2 files changed, 52 insertions(+), 48 deletions(-) diff --git a/src/librustc_typeck/astconv.rs b/src/librustc_typeck/astconv.rs index 48c5353a40001..d0cd1cf61ff10 100644 --- a/src/librustc_typeck/astconv.rs +++ b/src/librustc_typeck/astconv.rs @@ -271,22 +271,24 @@ impl<'o, 'gcx: 'tcx, 'tcx> AstConv<'gcx, 'tcx>+'o { }; let own_self = self_ty.is_some() as usize; + // FIXME(varkor): Separating out the parameters is messy. + let lifetimes: Vec<_> = generic_args.args.iter().filter_map(|arg| match arg { + GenericArg::Lifetime(lt) => Some(lt), + _ => None, + }).collect(); + let types: Vec<_> = generic_args.args.iter().filter_map(|arg| match arg { + GenericArg::Type(ty) => Some(ty), + _ => None, + }).collect(); let substs = Substs::for_item(tcx, def_id, |param, substs| { match param.kind { GenericParamDefKind::Lifetime => { - let mut i = param.index as usize - own_self; - for arg in &generic_args.args { - match arg { - GenericArg::Lifetime(lt) => { - if i == 0 { - return self.ast_region_to_region(lt, Some(param)).into(); - } - i -= 1; - } - _ => {} - } + let i = param.index as usize - own_self; + if let Some(lt) = lifetimes.get(i) { + self.ast_region_to_region(lt, Some(param)).into() + } else { + tcx.types.re_static.into() } - tcx.types.re_static.into() } GenericParamDefKind::Type { has_default, .. } => { let i = param.index as usize; @@ -296,21 +298,10 @@ impl<'o, 'gcx: 'tcx, 'tcx> AstConv<'gcx, 'tcx>+'o { return ty.into(); } - let mut i = i - (lt_accepted + own_self); + let i = i - (lt_accepted + own_self); if i < ty_provided { // A provided type parameter. - for arg in &generic_args.args { - match arg { - GenericArg::Type(ty) => { - if i == 0 { - return self.ast_ty_to_ty(ty).into(); - } - i -= 1; - } - _ => {} - } - } - bug!() + self.ast_ty_to_ty(&types[i]).into() } else if infer_types { // No type parameters were provided, we can infer all. if !default_needs_object_self(param) { diff --git a/src/librustc_typeck/check/mod.rs b/src/librustc_typeck/check/mod.rs index bececfc08ac0e..93739fbada2f1 100644 --- a/src/librustc_typeck/check/mod.rs +++ b/src/librustc_typeck/check/mod.rs @@ -4813,11 +4813,42 @@ impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> { } (None, None) => (0, false) }; + // FIXME(varkor): Separating out the parameters is messy. + let mut lifetimes_type_seg = vec![]; + let mut types_type_seg = vec![]; + let mut infer_types_type_seg = true; + if let Some((seg, _)) = type_segment { + if let Some(ref data) = seg.args { + for arg in &data.args { + match arg { + GenericArg::Lifetime(lt) => lifetimes_type_seg.push(lt), + GenericArg::Type(ty) => types_type_seg.push(ty), + } + } + } + infer_types_type_seg = seg.infer_types; + } + + let mut lifetimes_fn_seg = vec![]; + let mut types_fn_seg = vec![]; + let mut infer_types_fn_seg = true; + if let Some((seg, _)) = fn_segment { + if let Some(ref data) = seg.args { + for arg in &data.args { + match arg { + GenericArg::Lifetime(lt) => lifetimes_fn_seg.push(lt), + GenericArg::Type(ty) => types_fn_seg.push(ty), + } + } + } + infer_types_fn_seg = seg.infer_types; + } + let substs = Substs::for_item(self.tcx, def.def_id(), |param, substs| { let mut i = param.index as usize; - let segment = if i < fn_start { - if let GenericParamDefKind::Type {..} = param.kind { + let (segment, lifetimes, types, infer_types) = if i < fn_start { + if let GenericParamDefKind::Type { .. } = param.kind { // Handle Self first, so we can adjust the index to match the AST. if has_self && i == 0 { return opt_self_ty.map(|ty| ty.into()).unwrap_or_else(|| { @@ -4826,39 +4857,21 @@ impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> { } } i -= has_self as usize; - type_segment + (type_segment, &lifetimes_type_seg, &types_type_seg, infer_types_type_seg) } else { i -= fn_start; - fn_segment + (fn_segment, &lifetimes_fn_seg, &types_fn_seg, infer_types_fn_seg) }; match param.kind { GenericParamDefKind::Lifetime => { - let lifetimes = segment.map_or(vec![], |(s, _)| { - s.args.as_ref().map_or(vec![], |data| { - data.args.iter().filter_map(|arg| match arg { - GenericArg::Lifetime(lt) => Some(lt), - _ => None, - }).collect() - }) - }); - if let Some(lifetime) = lifetimes.get(i) { AstConv::ast_region_to_region(self, lifetime, Some(param)).into() } else { self.re_infer(span, Some(param)).unwrap().into() } } - GenericParamDefKind::Type {..} => { - let (types, infer_types) = segment.map_or((vec![], true), |(s, _)| { - (s.args.as_ref().map_or(vec![], |data| { - data.args.iter().filter_map(|arg| match arg { - GenericArg::Type(ty) => Some(ty), - _ => None, - }).collect() - }), s.infer_types) - }); - + GenericParamDefKind::Type { .. } => { // Skip over the lifetimes in the same segment. if let Some((_, generics)) = segment { i -= generics.own_counts().lifetimes; From dde942bb646b07e6cf3cddf9bf379e42a6c79ed8 Mon Sep 17 00:00:00 2001 From: varkor Date: Fri, 15 Jun 2018 10:52:46 +0100 Subject: [PATCH 36/41] Fix additional comments --- src/librustc/hir/intravisit.rs | 2 +- src/libsyntax/visit.rs | 2 +- src/libsyntax_ext/deriving/generic/mod.rs | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/librustc/hir/intravisit.rs b/src/librustc/hir/intravisit.rs index e49a5e4ee6ae9..de53262490bba 100644 --- a/src/librustc/hir/intravisit.rs +++ b/src/librustc/hir/intravisit.rs @@ -742,6 +742,7 @@ pub fn walk_param_bound<'v, V: Visitor<'v>>(visitor: &mut V, bound: &'v GenericB pub fn walk_generic_param<'v, V: Visitor<'v>>(visitor: &mut V, param: &'v GenericParam) { visitor.visit_id(param.id); + walk_list!(visitor, visit_attribute, ¶m.attrs); match param.name { ParamName::Plain(name) => visitor.visit_name(param.span, name), ParamName::Fresh(_) => {} @@ -750,7 +751,6 @@ pub fn walk_generic_param<'v, V: Visitor<'v>>(visitor: &mut V, param: &'v Generi GenericParamKind::Lifetime { .. } => {} GenericParamKind::Type { ref default, .. } => walk_list!(visitor, visit_ty, default), } - walk_list!(visitor, visit_attribute, ¶m.attrs); walk_list!(visitor, visit_param_bound, ¶m.bounds); } diff --git a/src/libsyntax/visit.rs b/src/libsyntax/visit.rs index 5476a3f0d2a72..613f1a4f113bd 100644 --- a/src/libsyntax/visit.rs +++ b/src/libsyntax/visit.rs @@ -488,12 +488,12 @@ pub fn walk_param_bound<'a, V: Visitor<'a>>(visitor: &mut V, bound: &'a GenericB pub fn walk_generic_param<'a, V: Visitor<'a>>(visitor: &mut V, param: &'a GenericParam) { visitor.visit_ident(param.ident); + walk_list!(visitor, visit_attribute, param.attrs.iter()); walk_list!(visitor, visit_param_bound, ¶m.bounds); match param.kind { GenericParamKind::Lifetime => {} GenericParamKind::Type { ref default } => walk_list!(visitor, visit_ty, default), } - walk_list!(visitor, visit_attribute, param.attrs.iter()); } pub fn walk_generics<'a, V: Visitor<'a>>(visitor: &mut V, generics: &'a Generics) { diff --git a/src/libsyntax_ext/deriving/generic/mod.rs b/src/libsyntax_ext/deriving/generic/mod.rs index 44a07f532a78a..672726d147579 100644 --- a/src/libsyntax_ext/deriving/generic/mod.rs +++ b/src/libsyntax_ext/deriving/generic/mod.rs @@ -666,7 +666,7 @@ impl<'a> TraitDef<'a> { let self_params: Vec<_> = generics.params.iter().map(|param| match param.kind { GenericParamKind::Lifetime { .. } => { - GenericArg::Lifetime(ast::Lifetime { id: param.id, ident: param.ident }) + GenericArg::Lifetime(cx.lifetime(self.span, param.ident)) } GenericParamKind::Type { .. } => { GenericArg::Type(cx.ty_ident(self.span, param.ident)) From 4343c20819f1129924d2657322442d66672f213d Mon Sep 17 00:00:00 2001 From: varkor Date: Fri, 15 Jun 2018 11:45:12 +0100 Subject: [PATCH 37/41] Use ty::Generics instead of hir::Generics for various checks --- src/librustc/middle/reachable.rs | 39 +++++++++++++++++++------------- src/librustc_lint/types.rs | 9 ++++---- src/librustc_metadata/encoder.rs | 5 ++-- src/librustc_typeck/check/mod.rs | 16 +++++++------ 4 files changed, 40 insertions(+), 29 deletions(-) diff --git a/src/librustc/middle/reachable.rs b/src/librustc/middle/reachable.rs index 9637b376b0e43..7f81af7e46c7d 100644 --- a/src/librustc/middle/reachable.rs +++ b/src/librustc/middle/reachable.rs @@ -20,7 +20,7 @@ use hir::map as hir_map; use hir::def::Def; use hir::def_id::{DefId, CrateNum}; use rustc_data_structures::sync::Lrc; -use ty::{self, TyCtxt}; +use ty::{self, TyCtxt, GenericParamDefKind}; use ty::query::Providers; use middle::privacy; use session::config; @@ -29,7 +29,7 @@ use util::nodemap::{NodeSet, FxHashSet}; use rustc_target::spec::abi::Abi; use syntax::ast; use syntax::attr; -use hir::{self, GenericParamKind}; +use hir; use hir::def_id::LOCAL_CRATE; use hir::intravisit::{Visitor, NestedVisitorMap}; use hir::itemlikevisit::ItemLikeVisitor; @@ -37,11 +37,11 @@ use hir::intravisit; // Returns true if the given set of generics implies that the item it's // associated with must be inlined. -fn generics_require_inlining(generics: &hir::Generics) -> bool { +fn generics_require_inlining(generics: &ty::Generics) -> bool { for param in &generics.params { match param.kind { - GenericParamKind::Lifetime { .. } => {} - GenericParamKind::Type { .. } => return true, + GenericParamDefKind::Lifetime { .. } => {} + GenericParamDefKind::Type { .. } => return true, } } false @@ -50,14 +50,17 @@ fn generics_require_inlining(generics: &hir::Generics) -> bool { // Returns true if the given item must be inlined because it may be // monomorphized or it was marked with `#[inline]`. This will only return // true for functions. -fn item_might_be_inlined(item: &hir::Item, attrs: CodegenFnAttrs) -> bool { +fn item_might_be_inlined(tcx: TyCtxt<'a, 'tcx, 'tcx>, + item: &hir::Item, + attrs: CodegenFnAttrs) -> bool { if attrs.requests_inline() { return true } match item.node { - hir::ItemImpl(_, _, _, ref generics, ..) | - hir::ItemFn(.., ref generics, _) => { + hir::ItemImpl(..) | + hir::ItemFn(..) => { + let generics = tcx.generics_of(tcx.hir.local_def_id(item.id)); generics_require_inlining(generics) } _ => false, @@ -68,14 +71,14 @@ fn method_might_be_inlined<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, impl_item: &hir::ImplItem, impl_src: DefId) -> bool { let codegen_fn_attrs = tcx.codegen_fn_attrs(impl_item.hir_id.owner_def_id()); - if codegen_fn_attrs.requests_inline() || - generics_require_inlining(&impl_item.generics) { + let generics = tcx.generics_of(tcx.hir.local_def_id(impl_item.id)); + if codegen_fn_attrs.requests_inline() || generics_require_inlining(generics) { return true } if let Some(impl_node_id) = tcx.hir.as_local_node_id(impl_src) { match tcx.hir.find(impl_node_id) { Some(hir_map::NodeItem(item)) => - item_might_be_inlined(&item, codegen_fn_attrs), + item_might_be_inlined(tcx, &item, codegen_fn_attrs), Some(..) | None => span_bug!(impl_item.span, "impl did is not an item") } @@ -169,7 +172,7 @@ impl<'a, 'tcx> ReachableContext<'a, 'tcx> { Some(hir_map::NodeItem(item)) => { match item.node { hir::ItemFn(..) => - item_might_be_inlined(&item, self.tcx.codegen_fn_attrs(def_id)), + item_might_be_inlined(self.tcx, &item, self.tcx.codegen_fn_attrs(def_id)), _ => false, } } @@ -186,7 +189,8 @@ impl<'a, 'tcx> ReachableContext<'a, 'tcx> { hir::ImplItemKind::Const(..) => true, hir::ImplItemKind::Method(..) => { let attrs = self.tcx.codegen_fn_attrs(def_id); - if generics_require_inlining(&impl_item.generics) || + let generics = self.tcx.generics_of(def_id); + if generics_require_inlining(&generics) || attrs.requests_inline() { true } else { @@ -198,8 +202,9 @@ impl<'a, 'tcx> ReachableContext<'a, 'tcx> { // does too. let impl_node_id = self.tcx.hir.as_local_node_id(impl_did).unwrap(); match self.tcx.hir.expect_item(impl_node_id).node { - hir::ItemImpl(_, _, _, ref generics, ..) => { - generics_require_inlining(generics) + hir::ItemImpl(..) => { + let generics = self.tcx.generics_of(impl_did); + generics_require_inlining(&generics) } _ => false } @@ -257,7 +262,9 @@ impl<'a, 'tcx> ReachableContext<'a, 'tcx> { match item.node { hir::ItemFn(.., body) => { let def_id = self.tcx.hir.local_def_id(item.id); - if item_might_be_inlined(&item, self.tcx.codegen_fn_attrs(def_id)) { + if item_might_be_inlined(self.tcx, + &item, + self.tcx.codegen_fn_attrs(def_id)) { self.visit_nested_body(body); } } diff --git a/src/librustc_lint/types.rs b/src/librustc_lint/types.rs index 804000faa370e..50492ae073720 100644 --- a/src/librustc_lint/types.rs +++ b/src/librustc_lint/types.rs @@ -810,15 +810,16 @@ impl LintPass for VariantSizeDifferences { impl<'a, 'tcx> LateLintPass<'a, 'tcx> for VariantSizeDifferences { fn check_item(&mut self, cx: &LateContext, it: &hir::Item) { - if let hir::ItemEnum(ref enum_definition, ref generics) = it.node { + if let hir::ItemEnum(ref enum_definition, _) = it.node { + let item_def_id = cx.tcx.hir.local_def_id(it.id); + let generics = cx.tcx.generics_of(item_def_id); for param in &generics.params { match param.kind { - hir::GenericParamKind::Lifetime { .. } => {}, - hir::GenericParamKind::Type { .. } => return, + ty::GenericParamDefKind::Lifetime { .. } => {}, + ty::GenericParamDefKind::Type { .. } => return, } } // Sizes only make sense for non-generic types. - let item_def_id = cx.tcx.hir.local_def_id(it.id); let t = cx.tcx.type_of(item_def_id); let ty = cx.tcx.erase_regions(&t); match cx.layout_of(ty) { diff --git a/src/librustc_metadata/encoder.rs b/src/librustc_metadata/encoder.rs index ed3dab09df91e..cbe9615c69397 100644 --- a/src/librustc_metadata/encoder.rs +++ b/src/librustc_metadata/encoder.rs @@ -1235,9 +1235,10 @@ impl<'a, 'b: 'a, 'tcx: 'b> IsolatedEncoder<'a, 'b, 'tcx> { self.encode_optimized_mir(def_id) } hir::ItemConst(..) => self.encode_optimized_mir(def_id), - hir::ItemFn(_, _, constness, _, ref generics, _) => { + hir::ItemFn(_, _, constness, ..) => { + let generics = tcx.generics_of(def_id); let has_types = generics.params.iter().any(|param| match param.kind { - hir::GenericParamKind::Type { .. } => true, + ty::GenericParamDefKind::Type { .. } => true, _ => false, }); let needs_inline = diff --git a/src/librustc_typeck/check/mod.rs b/src/librustc_typeck/check/mod.rs index 93739fbada2f1..0a16cbeccd103 100644 --- a/src/librustc_typeck/check/mod.rs +++ b/src/librustc_typeck/check/mod.rs @@ -1261,10 +1261,11 @@ pub fn check_item_type<'a,'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, it: &'tcx hir::Item hir::ItemUnion(..) => { check_union(tcx, it.id, it.span); } - hir::ItemTy(_, ref generics) => { + hir::ItemTy(..) => { let def_id = tcx.hir.local_def_id(it.id); let pty_ty = tcx.type_of(def_id); - check_bounds_are_used(tcx, generics, pty_ty); + let generics = tcx.generics_of(def_id); + check_bounds_are_used(tcx, &generics, pty_ty); } hir::ItemForeignMod(ref m) => { check_abi(tcx, it.span, m.abi); @@ -5178,7 +5179,7 @@ impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> { } pub fn check_bounds_are_used<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, - generics: &hir::Generics, + generics: &ty::Generics, ty: Ty<'tcx>) { let own_counts = generics.own_counts(); debug!("check_bounds_are_used(n_tps={}, ty={:?})", own_counts.types, ty); @@ -5202,14 +5203,15 @@ pub fn check_bounds_are_used<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, } let types = generics.params.iter().filter(|param| match param.kind { - hir::GenericParamKind::Type { .. } => true, + ty::GenericParamDefKind::Type { .. } => true, _ => false, }); for (&used, param) in types_used.iter().zip(types) { if !used { - struct_span_err!(tcx.sess, param.span, E0091, "type parameter `{}` is unused", - param.name.name()) - .span_label(param.span, "unused type parameter") + let id = tcx.hir.as_local_node_id(param.def_id).unwrap(); + let span = tcx.hir.span(id); + struct_span_err!(tcx.sess, span, E0091, "type parameter `{}` is unused", param.name) + .span_label(span, "unused type parameter") .emit(); } } From 7a829273bf67999838cb14e6ff9ce6fd3a14a5e7 Mon Sep 17 00:00:00 2001 From: varkor Date: Sat, 16 Jun 2018 11:14:07 +0100 Subject: [PATCH 38/41] Rename ty_param_bound to generic_bound --- src/librustc_privacy/lib.rs | 8 ++++---- src/libsyntax/parse/parser.rs | 26 +++++++++++++------------- 2 files changed, 17 insertions(+), 17 deletions(-) diff --git a/src/librustc_privacy/lib.rs b/src/librustc_privacy/lib.rs index 3b865e6ce0ff8..de087049267b1 100644 --- a/src/librustc_privacy/lib.rs +++ b/src/librustc_privacy/lib.rs @@ -1037,7 +1037,7 @@ impl<'a, 'tcx> ObsoleteVisiblePrivateTypesVisitor<'a, 'tcx> { self.access_levels.is_public(trait_id) } - fn check_ty_param_bound(&mut self, bound: &hir::GenericBound) { + fn check_generic_bound(&mut self, bound: &hir::GenericBound) { if let hir::GenericBound::Trait(ref trait_ref, _) = *bound { if self.path_is_private_type(&trait_ref.trait_ref.path) { self.old_error_set.insert(trait_ref.trait_ref.ref_id); @@ -1100,7 +1100,7 @@ impl<'a, 'tcx> Visitor<'tcx> for ObsoleteVisiblePrivateTypesVisitor<'a, 'tcx> { } for bound in bounds.iter() { - self.check_ty_param_bound(bound) + self.check_generic_bound(bound) } } @@ -1271,7 +1271,7 @@ impl<'a, 'tcx> Visitor<'tcx> for ObsoleteVisiblePrivateTypesVisitor<'a, 'tcx> { GenericParamKind::Lifetime { .. } => {} GenericParamKind::Type { .. } => { for bound in ¶m.bounds { - self.check_ty_param_bound(bound); + self.check_generic_bound(bound); } } }); @@ -1279,7 +1279,7 @@ impl<'a, 'tcx> Visitor<'tcx> for ObsoleteVisiblePrivateTypesVisitor<'a, 'tcx> { match predicate { &hir::WherePredicate::BoundPredicate(ref bound_pred) => { for bound in bound_pred.bounds.iter() { - self.check_ty_param_bound(bound) + self.check_generic_bound(bound) } } &hir::WherePredicate::RegionPredicate(_) => {} diff --git a/src/libsyntax/parse/parser.rs b/src/libsyntax/parse/parser.rs index 675849c8a5c4d..2bb8fff40370e 100644 --- a/src/libsyntax/parse/parser.rs +++ b/src/libsyntax/parse/parser.rs @@ -1509,7 +1509,7 @@ impl<'a> Parser<'a> { } } else if self.eat_keyword(keywords::Impl) { // Always parse bounds greedily for better error recovery. - let bounds = self.parse_ty_param_bounds()?; + let bounds = self.parse_generic_bounds()?; impl_dyn_multi = bounds.len() > 1 || self.prev_token_kind == PrevTokenKind::Plus; TyKind::ImplTrait(bounds) } else if self.check_keyword(keywords::Dyn) && @@ -1517,13 +1517,13 @@ impl<'a> Parser<'a> { !can_continue_type_after_non_fn_ident(t)) { self.bump(); // `dyn` // Always parse bounds greedily for better error recovery. - let bounds = self.parse_ty_param_bounds()?; + let bounds = self.parse_generic_bounds()?; impl_dyn_multi = bounds.len() > 1 || self.prev_token_kind == PrevTokenKind::Plus; TyKind::TraitObject(bounds, TraitObjectSyntax::Dyn) } else if self.check(&token::Question) || self.check_lifetime() && self.look_ahead(1, |t| t.is_like_plus()) { // Bound list (trait object type) - TyKind::TraitObject(self.parse_ty_param_bounds_common(allow_plus)?, + TyKind::TraitObject(self.parse_generic_bounds_common(allow_plus)?, TraitObjectSyntax::None) } else if self.eat_lt() { // Qualified path @@ -1569,7 +1569,7 @@ impl<'a> Parser<'a> { let mut bounds = vec![GenericBound::Trait(poly_trait_ref, TraitBoundModifier::None)]; if parse_plus { self.eat_plus(); // `+`, or `+=` gets split and `+` is discarded - bounds.append(&mut self.parse_ty_param_bounds()?); + bounds.append(&mut self.parse_generic_bounds()?); } Ok(TyKind::TraitObject(bounds, TraitObjectSyntax::None)) } @@ -1594,7 +1594,7 @@ impl<'a> Parser<'a> { } self.bump(); // `+` - let bounds = self.parse_ty_param_bounds()?; + let bounds = self.parse_generic_bounds()?; let sum_span = ty.span.to(self.prev_span); let mut err = struct_span_err!(self.sess.span_diagnostic, sum_span, E0178, @@ -4735,7 +4735,7 @@ impl<'a> Parser<'a> { // LT_BOUND = LIFETIME (e.g. `'a`) // TY_BOUND = TY_BOUND_NOPAREN | (TY_BOUND_NOPAREN) // TY_BOUND_NOPAREN = [?] [for] SIMPLE_PATH (e.g. `?for<'a: 'b> m::Trait<'a>`) - fn parse_ty_param_bounds_common(&mut self, allow_plus: bool) -> PResult<'a, GenericBounds> { + fn parse_generic_bounds_common(&mut self, allow_plus: bool) -> PResult<'a, GenericBounds> { let mut bounds = Vec::new(); loop { // This needs to be syncronized with `Token::can_begin_bound`. @@ -4784,8 +4784,8 @@ impl<'a> Parser<'a> { return Ok(bounds); } - fn parse_ty_param_bounds(&mut self) -> PResult<'a, GenericBounds> { - self.parse_ty_param_bounds_common(true) + fn parse_generic_bounds(&mut self) -> PResult<'a, GenericBounds> { + self.parse_generic_bounds_common(true) } // Parse bounds of a lifetime parameter `BOUND + BOUND + BOUND`, possibly with trailing `+`. @@ -4810,7 +4810,7 @@ impl<'a> Parser<'a> { // Parse optional colon and param bounds. let bounds = if self.eat(&token::Colon) { - self.parse_ty_param_bounds()? + self.parse_generic_bounds()? } else { Vec::new() }; @@ -4841,7 +4841,7 @@ impl<'a> Parser<'a> { // Parse optional colon and param bounds. let bounds = if self.eat(&token::Colon) { - self.parse_ty_param_bounds()? + self.parse_generic_bounds()? } else { Vec::new() }; @@ -5036,7 +5036,7 @@ impl<'a> Parser<'a> { // or with mandatory equality sign and the second type. let ty = self.parse_ty()?; if self.eat(&token::Colon) { - let bounds = self.parse_ty_param_bounds()?; + let bounds = self.parse_generic_bounds()?; where_clause.predicates.push(ast::WherePredicate::BoundPredicate( ast::WhereBoundPredicate { span: lo.to(self.prev_span), @@ -5536,14 +5536,14 @@ impl<'a> Parser<'a> { // Parse optional colon and supertrait bounds. let bounds = if self.eat(&token::Colon) { - self.parse_ty_param_bounds()? + self.parse_generic_bounds()? } else { Vec::new() }; if self.eat(&token::Eq) { // it's a trait alias - let bounds = self.parse_ty_param_bounds()?; + let bounds = self.parse_generic_bounds()?; tps.where_clause = self.parse_where_clause()?; self.expect(&token::Semi)?; if unsafety != Unsafety::Normal { From 95ce05c586b8d8c97238ca4bedc5b06909bb7090 Mon Sep 17 00:00:00 2001 From: varkor Date: Sat, 16 Jun 2018 11:30:31 +0100 Subject: [PATCH 39/41] Simplify some counting --- src/librustc_typeck/astconv.rs | 29 ++++++++++++----------------- src/librustc_typeck/check/mod.rs | 3 +-- 2 files changed, 13 insertions(+), 19 deletions(-) diff --git a/src/librustc_typeck/astconv.rs b/src/librustc_typeck/astconv.rs index d0cd1cf61ff10..f3912c3042d7f 100644 --- a/src/librustc_typeck/astconv.rs +++ b/src/librustc_typeck/astconv.rs @@ -213,14 +213,18 @@ impl<'o, 'gcx: 'tcx, 'tcx> AstConv<'gcx, 'tcx>+'o { // If the type is parameterized by this region, then replace this // region with the current anon region binding (in other words, // whatever & would get replaced with). - let mut lt_provided = 0; - let mut ty_provided = 0; - for arg in &generic_args.args { - match arg { - GenericArg::Lifetime(_) => lt_provided += 1, - GenericArg::Type(_) => ty_provided += 1, - } - } + + // FIXME(varkor): Separating out the parameters is messy. + let lifetimes: Vec<_> = generic_args.args.iter().filter_map(|arg| match arg { + GenericArg::Lifetime(lt) => Some(lt), + _ => None, + }).collect(); + let types: Vec<_> = generic_args.args.iter().filter_map(|arg| match arg { + GenericArg::Type(ty) => Some(ty), + _ => None, + }).collect(); + let lt_provided = lifetimes.len(); + let ty_provided = types.len(); let decl_generics = tcx.generics_of(def_id); let mut lt_accepted = 0; @@ -271,15 +275,6 @@ impl<'o, 'gcx: 'tcx, 'tcx> AstConv<'gcx, 'tcx>+'o { }; let own_self = self_ty.is_some() as usize; - // FIXME(varkor): Separating out the parameters is messy. - let lifetimes: Vec<_> = generic_args.args.iter().filter_map(|arg| match arg { - GenericArg::Lifetime(lt) => Some(lt), - _ => None, - }).collect(); - let types: Vec<_> = generic_args.args.iter().filter_map(|arg| match arg { - GenericArg::Type(ty) => Some(ty), - _ => None, - }).collect(); let substs = Substs::for_item(tcx, def_id, |param, substs| { match param.kind { GenericParamDefKind::Lifetime => { diff --git a/src/librustc_typeck/check/mod.rs b/src/librustc_typeck/check/mod.rs index 0a16cbeccd103..366420cfcabb1 100644 --- a/src/librustc_typeck/check/mod.rs +++ b/src/librustc_typeck/check/mod.rs @@ -4742,8 +4742,7 @@ impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> { Def::Fn(def_id) | Def::Const(def_id) | Def::Static(def_id, _) => { - fn_segment = Some((segments.last().unwrap(), - self.tcx.generics_of(def_id))); + fn_segment = Some((segments.last().unwrap(), self.tcx.generics_of(def_id))); } // Case 3. Reference to a method or associated const. From 21136b8ab408a71c9f275f6ddcb9838a74c43a0c Mon Sep 17 00:00:00 2001 From: varkor Date: Sun, 17 Jun 2018 16:04:10 +0100 Subject: [PATCH 40/41] Rename ParenthesizedArgData to ParenthesisedArgs --- src/librustc/hir/lowering.rs | 4 ++-- src/libsyntax/ast.rs | 6 +++--- src/libsyntax/fold.rs | 12 ++++++------ src/libsyntax/parse/parser.rs | 4 ++-- 4 files changed, 13 insertions(+), 13 deletions(-) diff --git a/src/librustc/hir/lowering.rs b/src/librustc/hir/lowering.rs index 7628504ba0dc1..4e9bf8047e9e8 100644 --- a/src/librustc/hir/lowering.rs +++ b/src/librustc/hir/lowering.rs @@ -1747,7 +1747,7 @@ impl<'a> LoweringContext<'a> { fn lower_parenthesized_parameter_data( &mut self, - data: &ParenthesizedArgData, + data: &ParenthesisedArgs, ) -> (hir::GenericArgs, bool) { // Switch to `PassThrough` mode for anonymous lifetimes: this // means that we permit things like `&Ref`, where `Ref` has @@ -1758,7 +1758,7 @@ impl<'a> LoweringContext<'a> { AnonymousLifetimeMode::PassThrough, |this| { const DISALLOWED: ImplTraitContext = ImplTraitContext::Disallowed; - let &ParenthesizedArgData { ref inputs, ref output, span } = data; + let &ParenthesisedArgs { ref inputs, ref output, span } = data; let inputs = inputs.iter().map(|ty| this.lower_ty(ty, DISALLOWED)).collect(); let mk_tup = |this: &mut Self, tys, span| { let LoweredNodeId { node_id, hir_id } = this.next_id(); diff --git a/src/libsyntax/ast.rs b/src/libsyntax/ast.rs index 76d19ce0ac5b2..c6de2c4da39cf 100644 --- a/src/libsyntax/ast.rs +++ b/src/libsyntax/ast.rs @@ -146,7 +146,7 @@ pub enum GenericArgs { /// The `<'a, A,B,C>` in `foo::bar::baz::<'a, A,B,C>` AngleBracketed(AngleBracketedArgs), /// The `(A,B)` and `C` in `Foo(A,B) -> C` - Parenthesized(ParenthesizedArgData), + Parenthesized(ParenthesisedArgs), } impl GenericArgs { @@ -183,7 +183,7 @@ impl Into>> for AngleBracketedArgs { } } -impl Into>> for ParenthesizedArgData { +impl Into>> for ParenthesisedArgs { fn into(self) -> Option> { Some(P(GenericArgs::Parenthesized(self))) } @@ -191,7 +191,7 @@ impl Into>> for ParenthesizedArgData { /// A path like `Foo(A,B) -> C` #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)] -pub struct ParenthesizedArgData { +pub struct ParenthesisedArgs { /// Overall span pub span: Span, diff --git a/src/libsyntax/fold.rs b/src/libsyntax/fold.rs index 03668cc279a2c..93248fe3bfab0 100644 --- a/src/libsyntax/fold.rs +++ b/src/libsyntax/fold.rs @@ -193,8 +193,8 @@ pub trait Folder : Sized { noop_fold_angle_bracketed_parameter_data(p, self) } - fn fold_parenthesized_parameter_data(&mut self, p: ParenthesizedArgData) - -> ParenthesizedArgData + fn fold_parenthesized_parameter_data(&mut self, p: ParenthesisedArgs) + -> ParenthesisedArgs { noop_fold_parenthesized_parameter_data(p, self) } @@ -483,12 +483,12 @@ pub fn noop_fold_angle_bracketed_parameter_data(data: AngleBracketedA } } -pub fn noop_fold_parenthesized_parameter_data(data: ParenthesizedArgData, +pub fn noop_fold_parenthesized_parameter_data(data: ParenthesisedArgs, fld: &mut T) - -> ParenthesizedArgData + -> ParenthesisedArgs { - let ParenthesizedArgData { inputs, output, span } = data; - ParenthesizedArgData { + let ParenthesisedArgs { inputs, output, span } = data; + ParenthesisedArgs { inputs: inputs.move_map(|ty| fld.fold_ty(ty)), output: output.map(|ty| fld.fold_ty(ty)), span: fld.new_span(span) diff --git a/src/libsyntax/parse/parser.rs b/src/libsyntax/parse/parser.rs index 2bb8fff40370e..6f78ae9ebca5d 100644 --- a/src/libsyntax/parse/parser.rs +++ b/src/libsyntax/parse/parser.rs @@ -9,7 +9,7 @@ // except according to those terms. use rustc_target::spec::abi::{self, Abi}; -use ast::{AngleBracketedArgs, ParenthesizedArgData, AttrStyle, BareFnTy}; +use ast::{AngleBracketedArgs, ParenthesisedArgs, AttrStyle, BareFnTy}; use ast::{GenericBound, TraitBoundModifier}; use ast::Unsafety; use ast::{Mod, AnonConst, Arg, Arm, Attribute, BindingMode, TraitItemKind}; @@ -1988,7 +1988,7 @@ impl<'a> Parser<'a> { None }; let span = lo.to(self.prev_span); - ParenthesizedArgData { inputs, output, span }.into() + ParenthesisedArgs { inputs, output, span }.into() }; PathSegment { ident, args } From daf7e359a10306c004bdffd06b6432998d70b858 Mon Sep 17 00:00:00 2001 From: varkor Date: Wed, 20 Jun 2018 12:34:39 +0100 Subject: [PATCH 41/41] Fix rebase issues with existential types --- src/librustc/hir/intravisit.rs | 2 +- src/librustc/hir/lowering.rs | 2 +- src/librustc/hir/print.rs | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/librustc/hir/intravisit.rs b/src/librustc/hir/intravisit.rs index de53262490bba..ed86ef705649b 100644 --- a/src/librustc/hir/intravisit.rs +++ b/src/librustc/hir/intravisit.rs @@ -511,7 +511,7 @@ pub fn walk_item<'v, V: Visitor<'v>>(visitor: &mut V, item: &'v Item) { ItemExistential(ExistTy {ref generics, ref bounds, impl_trait_fn}) => { visitor.visit_id(item.id); walk_generics(visitor, generics); - walk_list!(visitor, visit_ty_param_bound, bounds); + walk_list!(visitor, visit_param_bound, bounds); if let Some(impl_trait_fn) = impl_trait_fn { visitor.visit_def_mention(Def::Fn(impl_trait_fn)) } diff --git a/src/librustc/hir/lowering.rs b/src/librustc/hir/lowering.rs index 4e9bf8047e9e8..6291e0eb11372 100644 --- a/src/librustc/hir/lowering.rs +++ b/src/librustc/hir/lowering.rs @@ -1165,7 +1165,7 @@ impl<'a> LoweringContext<'a> { self.allocate_hir_id_counter(exist_ty_node_id, t); let hir_bounds = self.with_hir_id_owner(exist_ty_node_id, |lctx| { - lctx.lower_bounds(bounds, itctx) + lctx.lower_param_bounds(bounds, itctx) }); let (lifetimes, lifetime_defs) = self.lifetimes_from_impl_trait_bounds( diff --git a/src/librustc/hir/print.rs b/src/librustc/hir/print.rs index 229a4da465a27..14f780fab7f2e 100644 --- a/src/librustc/hir/print.rs +++ b/src/librustc/hir/print.rs @@ -662,7 +662,7 @@ impl<'a> State<'a> { self.word_space(":")?; let mut real_bounds = Vec::with_capacity(exist.bounds.len()); for b in exist.bounds.iter() { - if let TraitTyParamBound(ref ptr, hir::TraitBoundModifier::Maybe) = *b { + if let GenericBound::Trait(ref ptr, hir::TraitBoundModifier::Maybe) = *b { self.s.space()?; self.word_space("for ?")?; self.print_trait_ref(&ptr.trait_ref)?;