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