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