]> git.lizzy.rs Git - rust.git/blob - src/librustc_typeck/impl_wf_check.rs
Rollup merge of #61698 - davidtwco:ice-const-generic-length, r=varkor
[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 crate::constrained_generic_params as cgp;
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::ty::query::Providers;
17 use rustc::util::nodemap::{FxHashMap, FxHashSet};
18 use std::collections::hash_map::Entry::{Occupied, Vacant};
19
20 use syntax_pos::Span;
21
22 /// Checks that all the type/lifetime parameters on an impl also
23 /// appear in the trait ref or self type (or are constrained by a
24 /// where-clause). These rules are needed to ensure that, given a
25 /// trait ref like `<T as Trait<U>>`, we can derive the values of all
26 /// parameters on the impl (which is needed to make specialization
27 /// possible).
28 ///
29 /// However, in the case of lifetimes, we only enforce these rules if
30 /// the lifetime parameter is used in an associated type. This is a
31 /// concession to backwards compatibility; see comment at the end of
32 /// the fn for details.
33 ///
34 /// Example:
35 ///
36 /// ```rust,ignore (pseudo-Rust)
37 /// impl<T> Trait<Foo> for Bar { ... }
38 /// //   ^ T does not appear in `Foo` or `Bar`, error!
39 ///
40 /// impl<T> Trait<Foo<T>> for Bar { ... }
41 /// //   ^ T appears in `Foo<T>`, ok.
42 ///
43 /// impl<T> Trait<Foo> for Bar where Bar: Iterator<Item = T> { ... }
44 /// //   ^ T is bound to `<Bar as Iterator>::Item`, ok.
45 ///
46 /// impl<'a> Trait<Foo> for Bar { }
47 /// //   ^ 'a is unused, but for back-compat we allow it
48 ///
49 /// impl<'a> Trait<Foo> for Bar { type X = &'a i32; }
50 /// //   ^ 'a is unused and appears in assoc type, error
51 /// ```
52 pub fn impl_wf_check<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>) {
53     // We will tag this as part of the WF check -- logically, it is,
54     // but it's one that we must perform earlier than the rest of
55     // WfCheck.
56     for &module in tcx.hir().krate().modules.keys() {
57         tcx.ensure().check_mod_impl_wf(tcx.hir().local_def_id(module));
58     }
59 }
60
61 fn check_mod_impl_wf<'tcx>(tcx: TyCtxt<'_, 'tcx, 'tcx>, module_def_id: DefId) {
62     tcx.hir().visit_item_likes_in_module(
63         module_def_id,
64         &mut ImplWfCheck { tcx }
65     );
66 }
67
68 pub fn provide(providers: &mut Providers<'_>) {
69     *providers = Providers {
70         check_mod_impl_wf,
71         ..*providers
72     };
73 }
74
75 struct ImplWfCheck<'a, 'tcx: 'a> {
76     tcx: TyCtxt<'a, 'tcx, 'tcx>,
77 }
78
79 impl<'a, 'tcx> ItemLikeVisitor<'tcx> for ImplWfCheck<'a, 'tcx> {
80     fn visit_item(&mut self, item: &'tcx hir::Item) {
81         if let hir::ItemKind::Impl(.., ref impl_item_refs) = item.node {
82             let impl_def_id = self.tcx.hir().local_def_id_from_hir_id(item.hir_id);
83             enforce_impl_params_are_constrained(self.tcx,
84                                                 impl_def_id,
85                                                 impl_item_refs);
86             enforce_impl_items_are_distinct(self.tcx, impl_item_refs);
87         }
88     }
89
90     fn visit_trait_item(&mut self, _trait_item: &'tcx hir::TraitItem) { }
91
92     fn visit_impl_item(&mut self, _impl_item: &'tcx hir::ImplItem) { }
93 }
94
95 fn enforce_impl_params_are_constrained<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
96                                                  impl_def_id: DefId,
97                                                  impl_item_refs: &[hir::ImplItemRef])
98 {
99     // Every lifetime used in an associated type must be constrained.
100     let impl_self_ty = tcx.type_of(impl_def_id);
101     let impl_generics = tcx.generics_of(impl_def_id);
102     let impl_predicates = tcx.predicates_of(impl_def_id);
103     let impl_trait_ref = tcx.impl_trait_ref(impl_def_id);
104
105     let mut input_parameters = cgp::parameters_for_impl(impl_self_ty, impl_trait_ref);
106     cgp::identify_constrained_generic_params(
107         tcx, &impl_predicates, impl_trait_ref, &mut input_parameters);
108
109     // Disallow unconstrained lifetimes, but only if they appear in assoc types.
110     let lifetimes_in_associated_types: FxHashSet<_> = impl_item_refs.iter()
111         .map(|item_ref| tcx.hir().local_def_id_from_hir_id(item_ref.id.hir_id))
112         .filter(|&def_id| {
113             let item = tcx.associated_item(def_id);
114             item.kind == ty::AssocKind::Type && item.defaultness.has_value()
115         })
116         .flat_map(|def_id| {
117             cgp::parameters_for(&tcx.type_of(def_id), true)
118         }).collect();
119
120     for param in &impl_generics.params {
121         match param.kind {
122             // Disallow ANY unconstrained type parameters.
123             ty::GenericParamDefKind::Type { .. } => {
124                 let param_ty = ty::ParamTy::for_def(param);
125                 if !input_parameters.contains(&cgp::Parameter::from(param_ty)) {
126                     report_unused_parameter(tcx,
127                                             tcx.def_span(param.def_id),
128                                             "type",
129                                             &param_ty.to_string());
130                 }
131             }
132             ty::GenericParamDefKind::Lifetime => {
133                 let param_lt = cgp::Parameter::from(param.to_early_bound_region_data());
134                 if lifetimes_in_associated_types.contains(&param_lt) && // (*)
135                     !input_parameters.contains(&param_lt) {
136                     report_unused_parameter(tcx,
137                                             tcx.def_span(param.def_id),
138                                             "lifetime",
139                                             &param.name.to_string());
140                 }
141             }
142             ty::GenericParamDefKind::Const => {
143                 let param_ct = ty::ParamConst::for_def(param);
144                 if !input_parameters.contains(&cgp::Parameter::from(param_ct)) {
145                     report_unused_parameter(tcx,
146                                            tcx.def_span(param.def_id),
147                                            "const",
148                                            &param_ct.to_string());
149                 }
150             }
151         }
152     }
153
154     // (*) This is a horrible concession to reality. I think it'd be
155     // better to just ban unconstrianed lifetimes outright, but in
156     // practice people do non-hygenic macros like:
157     //
158     // ```
159     // macro_rules! __impl_slice_eq1 {
160     //     ($Lhs: ty, $Rhs: ty, $Bound: ident) => {
161     //         impl<'a, 'b, A: $Bound, B> PartialEq<$Rhs> for $Lhs where A: PartialEq<B> {
162     //            ....
163     //         }
164     //     }
165     // }
166     // ```
167     //
168     // In a concession to backwards compatibility, we continue to
169     // permit those, so long as the lifetimes aren't used in
170     // associated types. I believe this is sound, because lifetimes
171     // used elsewhere are not projected back out.
172 }
173
174 fn report_unused_parameter(tcx: TyCtxt<'_, '_, '_>,
175                            span: Span,
176                            kind: &str,
177                            name: &str)
178 {
179     struct_span_err!(
180         tcx.sess, span, E0207,
181         "the {} parameter `{}` is not constrained by the \
182         impl trait, self type, or predicates",
183         kind, name)
184         .span_label(span, format!("unconstrained {} parameter", kind))
185         .emit();
186 }
187
188 /// Enforce that we do not have two items in an impl with the same name.
189 fn enforce_impl_items_are_distinct<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
190                                              impl_item_refs: &[hir::ImplItemRef])
191 {
192     let mut seen_type_items = FxHashMap::default();
193     let mut seen_value_items = FxHashMap::default();
194     for impl_item_ref in impl_item_refs {
195         let impl_item = tcx.hir().impl_item(impl_item_ref.id);
196         let seen_items = match impl_item.node {
197             hir::ImplItemKind::Type(_) => &mut seen_type_items,
198             _                          => &mut seen_value_items,
199         };
200         match seen_items.entry(impl_item.ident.modern()) {
201             Occupied(entry) => {
202                 let mut err = struct_span_err!(tcx.sess, impl_item.span, E0201,
203                                                "duplicate definitions with name `{}`:",
204                                                impl_item.ident);
205                 err.span_label(*entry.get(),
206                                format!("previous definition of `{}` here",
207                                        impl_item.ident));
208                 err.span_label(impl_item.span, "duplicate definition");
209                 err.emit();
210             }
211             Vacant(entry) => {
212                 entry.insert(impl_item.span);
213             }
214         }
215     }
216 }