]> git.lizzy.rs Git - rust.git/blob - src/librustc_typeck/impl_wf_check.rs
Merge remote-tracking branch 'upstream/master'
[rust.git] / src / librustc_typeck / impl_wf_check.rs
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.
10
11 use constrained_type_params as ctp;
12 use rustc::hir;
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};
18
19 use syntax_pos::Span;
20
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
26 /// possible).
27 ///
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.
32 ///
33 /// Example:
34 ///
35 /// ```rust,ignore (pseudo-Rust)
36 /// impl<T> Trait<Foo> for Bar { ... }
37 /// //   ^ T does not appear in `Foo` or `Bar`, error!
38 ///
39 /// impl<T> Trait<Foo<T>> for Bar { ... }
40 /// //   ^ T appears in `Foo<T>`, ok.
41 ///
42 /// impl<T> Trait<Foo> for Bar where Bar: Iterator<Item=T> { ... }
43 /// //   ^ T is bound to `<Bar as Iterator>::Item`, ok.
44 ///
45 /// impl<'a> Trait<Foo> for Bar { }
46 /// //   ^ 'a is unused, but for back-compat we allow it
47 ///
48 /// impl<'a> Trait<Foo> for Bar { type X = &'a i32; }
49 /// //   ^ 'a is unused and appears in assoc type, error
50 /// ```
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
54     // WfCheck.
55     tcx.hir().krate().visit_all_item_likes(&mut ImplWfCheck { tcx });
56 }
57
58 struct ImplWfCheck<'a, 'tcx: 'a> {
59     tcx: TyCtxt<'a, 'tcx, 'tcx>,
60 }
61
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,
67                                                 impl_def_id,
68                                                 impl_item_refs);
69             enforce_impl_items_are_distinct(self.tcx, impl_item_refs);
70         }
71     }
72
73     fn visit_trait_item(&mut self, _trait_item: &'tcx hir::TraitItem) { }
74
75     fn visit_impl_item(&mut self, _impl_item: &'tcx hir::ImplItem) { }
76 }
77
78 fn enforce_impl_params_are_constrained<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
79                                                  impl_def_id: DefId,
80                                                  impl_item_refs: &[hir::ImplItemRef])
81 {
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);
87
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);
91
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))
95         .filter(|&def_id| {
96             let item = tcx.associated_item(def_id);
97             item.kind == ty::AssociatedKind::Type && item.defaultness.has_value()
98         })
99         .flat_map(|def_id| {
100             ctp::parameters_for(&tcx.type_of(def_id), true)
101         }).collect();
102
103     for param in &impl_generics.params {
104         match param.kind {
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),
111                                             "type",
112                                             &param_ty.to_string());
113                 }
114             }
115             ty::GenericParamDefKind::Lifetime => {
116                 let param_lt = ctp::Parameter::from(param.to_early_bound_region_data());
117                 if lifetimes_in_associated_types.contains(&param_lt) && // (*)
118                     !input_parameters.contains(&param_lt) {
119                     report_unused_parameter(tcx,
120                                             tcx.def_span(param.def_id),
121                                             "lifetime",
122                                             &param.name.to_string());
123                 }
124             }
125         }
126     }
127
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:
131     //
132     // ```
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> {
136     //            ....
137     //         }
138     //     }
139     // }
140     // ```
141     //
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.
146 }
147
148 fn report_unused_parameter(tcx: TyCtxt,
149                            span: Span,
150                            kind: &str,
151                            name: &str)
152 {
153     struct_span_err!(
154         tcx.sess, span, E0207,
155         "the {} parameter `{}` is not constrained by the \
156         impl trait, self type, or predicates",
157         kind, name)
158         .span_label(span, format!("unconstrained {} parameter", kind))
159         .emit();
160 }
161
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])
165 {
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,
173         };
174         match seen_items.entry(impl_item.ident.modern()) {
175             Occupied(entry) => {
176                 let mut err = struct_span_err!(tcx.sess, impl_item.span, E0201,
177                                                "duplicate definitions with name `{}`:",
178                                                impl_item.ident);
179                 err.span_label(*entry.get(),
180                                format!("previous definition of `{}` here",
181                                        impl_item.ident));
182                 err.span_label(impl_item.span, "duplicate definition");
183                 err.emit();
184             }
185             Vacant(entry) => {
186                 entry.insert(impl_item.span);
187             }
188         }
189     }
190 }