1 //! This pass enforces various "well-formedness constraints" on impls.
2 //! Logically, it is part of wfcheck -- but we do it early so that we
3 //! can stop compilation afterwards, since part of the trait matching
4 //! infrastructure gets very grumpy if these conditions don't hold. In
5 //! particular, if there are type parameters that are not part of the
6 //! impl, then coherence will report strange inference ambiguity
7 //! errors; if impls have duplicate items, we get misleading
8 //! specialization errors. These things can (and probably should) be
9 //! fixed, but for the moment it's easier to do these checks early.
11 use constrained_type_params as ctp;
13 use rustc::hir::itemlikevisit::ItemLikeVisitor;
14 use rustc::hir::def_id::DefId;
15 use rustc::ty::{self, TyCtxt};
16 use rustc::util::nodemap::{FxHashMap, FxHashSet};
17 use std::collections::hash_map::Entry::{Occupied, Vacant};
21 /// Checks that all the type/lifetime parameters on an impl also
22 /// appear in the trait ref or self-type (or are constrained by a
23 /// where-clause). These rules are needed to ensure that, given a
24 /// trait ref like `<T as Trait<U>>`, we can derive the values of all
25 /// parameters on the impl (which is needed to make specialization
28 /// However, in the case of lifetimes, we only enforce these rules if
29 /// the lifetime parameter is used in an associated type. This is a
30 /// concession to backwards compatibility; see comment at the end of
31 /// the fn for details.
35 /// ```rust,ignore (pseudo-Rust)
36 /// impl<T> Trait<Foo> for Bar { ... }
37 /// // ^ T does not appear in `Foo` or `Bar`, error!
39 /// impl<T> Trait<Foo<T>> for Bar { ... }
40 /// // ^ T appears in `Foo<T>`, ok.
42 /// impl<T> Trait<Foo> for Bar where Bar: Iterator<Item=T> { ... }
43 /// // ^ T is bound to `<Bar as Iterator>::Item`, ok.
45 /// impl<'a> Trait<Foo> for Bar { }
46 /// // ^ 'a is unused, but for back-compat we allow it
48 /// impl<'a> Trait<Foo> for Bar { type X = &'a i32; }
49 /// // ^ 'a is unused and appears in assoc type, error
51 pub fn impl_wf_check<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>) {
52 // We will tag this as part of the WF check -- logically, it is,
53 // but it's one that we must perform earlier than the rest of
55 tcx.hir().krate().visit_all_item_likes(&mut ImplWfCheck { tcx });
58 struct ImplWfCheck<'a, 'tcx: 'a> {
59 tcx: TyCtxt<'a, 'tcx, 'tcx>,
62 impl<'a, 'tcx> ItemLikeVisitor<'tcx> for ImplWfCheck<'a, 'tcx> {
63 fn visit_item(&mut self, item: &'tcx hir::Item) {
64 if let hir::ItemKind::Impl(.., ref impl_item_refs) = item.node {
65 let impl_def_id = self.tcx.hir().local_def_id(item.id);
66 enforce_impl_params_are_constrained(self.tcx,
69 enforce_impl_items_are_distinct(self.tcx, impl_item_refs);
73 fn visit_trait_item(&mut self, _trait_item: &'tcx hir::TraitItem) { }
75 fn visit_impl_item(&mut self, _impl_item: &'tcx hir::ImplItem) { }
78 fn enforce_impl_params_are_constrained<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
80 impl_item_refs: &[hir::ImplItemRef])
82 // Every lifetime used in an associated type must be constrained.
83 let impl_self_ty = tcx.type_of(impl_def_id);
84 let impl_generics = tcx.generics_of(impl_def_id);
85 let impl_predicates = tcx.predicates_of(impl_def_id);
86 let impl_trait_ref = tcx.impl_trait_ref(impl_def_id);
88 let mut input_parameters = ctp::parameters_for_impl(impl_self_ty, impl_trait_ref);
89 ctp::identify_constrained_type_params(
90 tcx, &impl_predicates, impl_trait_ref, &mut input_parameters);
92 // Disallow unconstrained lifetimes, but only if they appear in assoc types.
93 let lifetimes_in_associated_types: FxHashSet<_> = impl_item_refs.iter()
94 .map(|item_ref| tcx.hir().local_def_id(item_ref.id.node_id))
96 let item = tcx.associated_item(def_id);
97 item.kind == ty::AssociatedKind::Type && item.defaultness.has_value()
100 ctp::parameters_for(&tcx.type_of(def_id), true)
103 for param in &impl_generics.params {
105 // Disallow ANY unconstrained type parameters.
106 ty::GenericParamDefKind::Type {..} => {
107 let param_ty = ty::ParamTy::for_def(param);
108 if !input_parameters.contains(&ctp::Parameter::from(param_ty)) {
109 report_unused_parameter(tcx,
110 tcx.def_span(param.def_id),
112 ¶m_ty.to_string());
115 ty::GenericParamDefKind::Lifetime => {
116 let param_lt = ctp::Parameter::from(param.to_early_bound_region_data());
117 if lifetimes_in_associated_types.contains(¶m_lt) && // (*)
118 !input_parameters.contains(¶m_lt) {
119 report_unused_parameter(tcx,
120 tcx.def_span(param.def_id),
122 ¶m.name.to_string());
128 // (*) This is a horrible concession to reality. I think it'd be
129 // better to just ban unconstrianed lifetimes outright, but in
130 // practice people do non-hygenic macros like:
133 // macro_rules! __impl_slice_eq1 {
134 // ($Lhs: ty, $Rhs: ty, $Bound: ident) => {
135 // impl<'a, 'b, A: $Bound, B> PartialEq<$Rhs> for $Lhs where A: PartialEq<B> {
142 // In a concession to backwards compatibility, we continue to
143 // permit those, so long as the lifetimes aren't used in
144 // associated types. I believe this is sound, because lifetimes
145 // used elsewhere are not projected back out.
148 fn report_unused_parameter(tcx: TyCtxt,
154 tcx.sess, span, E0207,
155 "the {} parameter `{}` is not constrained by the \
156 impl trait, self type, or predicates",
158 .span_label(span, format!("unconstrained {} parameter", kind))
162 /// Enforce that we do not have two items in an impl with the same name.
163 fn enforce_impl_items_are_distinct<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
164 impl_item_refs: &[hir::ImplItemRef])
166 let mut seen_type_items = FxHashMap::default();
167 let mut seen_value_items = FxHashMap::default();
168 for impl_item_ref in impl_item_refs {
169 let impl_item = tcx.hir().impl_item(impl_item_ref.id);
170 let seen_items = match impl_item.node {
171 hir::ImplItemKind::Type(_) => &mut seen_type_items,
172 _ => &mut seen_value_items,
174 match seen_items.entry(impl_item.ident.modern()) {
176 let mut err = struct_span_err!(tcx.sess, impl_item.span, E0201,
177 "duplicate definitions with name `{}`:",
179 err.span_label(*entry.get(),
180 format!("previous definition of `{}` here",
182 err.span_label(impl_item.span, "duplicate definition");
186 entry.insert(impl_item.span);