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