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