]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_typeck/src/impl_wf_check.rs
Rollup merge of #76366 - ayushmishra2005:arith_tests_in_library, r=jyn514
[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_id::LocalDefId;
18 use rustc_hir::itemlikevisit::ItemLikeVisitor;
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     for &module in tcx.hir().krate().modules.keys() {
62         tcx.ensure().check_mod_impl_wf(tcx.hir().local_def_id(module));
63     }
64 }
65
66 fn check_mod_impl_wf(tcx: TyCtxt<'_>, module_def_id: LocalDefId) {
67     let min_specialization = tcx.features().min_specialization;
68     tcx.hir()
69         .visit_item_likes_in_module(module_def_id, &mut ImplWfCheck { tcx, min_specialization });
70 }
71
72 pub fn provide(providers: &mut Providers) {
73     *providers = Providers { check_mod_impl_wf, ..*providers };
74 }
75
76 struct ImplWfCheck<'tcx> {
77     tcx: TyCtxt<'tcx>,
78     min_specialization: bool,
79 }
80
81 impl ItemLikeVisitor<'tcx> for ImplWfCheck<'tcx> {
82     fn visit_item(&mut self, item: &'tcx hir::Item<'tcx>) {
83         if let hir::ItemKind::Impl { ref items, .. } = item.kind {
84             let impl_def_id = self.tcx.hir().local_def_id(item.hir_id);
85             enforce_impl_params_are_constrained(self.tcx, impl_def_id, items);
86             enforce_impl_items_are_distinct(self.tcx, items);
87             if self.min_specialization {
88                 check_min_specialization(self.tcx, impl_def_id.to_def_id(), item.span);
89             }
90         }
91     }
92
93     fn visit_trait_item(&mut self, _trait_item: &'tcx hir::TraitItem<'tcx>) {}
94
95     fn visit_impl_item(&mut self, _impl_item: &'tcx hir::ImplItem<'tcx>) {}
96 }
97
98 fn enforce_impl_params_are_constrained(
99     tcx: TyCtxt<'_>,
100     impl_def_id: LocalDefId,
101     impl_item_refs: &[hir::ImplItemRef<'_>],
102 ) {
103     // Every lifetime used in an associated type must be constrained.
104     let impl_self_ty = tcx.type_of(impl_def_id);
105     if impl_self_ty.references_error() {
106         // Don't complain about unconstrained type params when self ty isn't known due to errors.
107         // (#36836)
108         tcx.sess.delay_span_bug(
109             tcx.def_span(impl_def_id),
110             &format!(
111                 "potentially unconstrained type parameters weren't evaluated: {:?}",
112                 impl_self_ty,
113             ),
114         );
115         return;
116     }
117     let impl_generics = tcx.generics_of(impl_def_id);
118     let impl_predicates = tcx.predicates_of(impl_def_id);
119     let impl_trait_ref = tcx.impl_trait_ref(impl_def_id);
120
121     let mut input_parameters = cgp::parameters_for_impl(impl_self_ty, impl_trait_ref);
122     cgp::identify_constrained_generic_params(
123         tcx,
124         impl_predicates,
125         impl_trait_ref,
126         &mut input_parameters,
127     );
128
129     // Disallow unconstrained lifetimes, but only if they appear in assoc types.
130     let lifetimes_in_associated_types: FxHashSet<_> = impl_item_refs
131         .iter()
132         .map(|item_ref| tcx.hir().local_def_id(item_ref.id.hir_id))
133         .flat_map(|def_id| {
134             let item = tcx.associated_item(def_id);
135             match item.kind {
136                 ty::AssocKind::Type => {
137                     if item.defaultness.has_value() {
138                         cgp::parameters_for(&tcx.type_of(def_id), true)
139                     } else {
140                         Vec::new()
141                     }
142                 }
143                 ty::AssocKind::Fn | ty::AssocKind::Const => Vec::new(),
144             }
145         })
146         .collect();
147
148     for param in &impl_generics.params {
149         match param.kind {
150             // Disallow ANY unconstrained type parameters.
151             ty::GenericParamDefKind::Type { .. } => {
152                 let param_ty = ty::ParamTy::for_def(param);
153                 if !input_parameters.contains(&cgp::Parameter::from(param_ty)) {
154                     report_unused_parameter(
155                         tcx,
156                         tcx.def_span(param.def_id),
157                         "type",
158                         &param_ty.to_string(),
159                     );
160                 }
161             }
162             ty::GenericParamDefKind::Lifetime => {
163                 let param_lt = cgp::Parameter::from(param.to_early_bound_region_data());
164                 if lifetimes_in_associated_types.contains(&param_lt) && // (*)
165                     !input_parameters.contains(&param_lt)
166                 {
167                     report_unused_parameter(
168                         tcx,
169                         tcx.def_span(param.def_id),
170                         "lifetime",
171                         &param.name.to_string(),
172                     );
173                 }
174             }
175             ty::GenericParamDefKind::Const => {
176                 let param_ct = ty::ParamConst::for_def(param);
177                 if !input_parameters.contains(&cgp::Parameter::from(param_ct)) {
178                     report_unused_parameter(
179                         tcx,
180                         tcx.def_span(param.def_id),
181                         "const",
182                         &param_ct.to_string(),
183                     );
184                 }
185             }
186         }
187     }
188
189     // (*) This is a horrible concession to reality. I think it'd be
190     // better to just ban unconstrained lifetimes outright, but in
191     // practice people do non-hygenic macros like:
192     //
193     // ```
194     // macro_rules! __impl_slice_eq1 {
195     //     ($Lhs: ty, $Rhs: ty, $Bound: ident) => {
196     //         impl<'a, 'b, A: $Bound, B> PartialEq<$Rhs> for $Lhs where A: PartialEq<B> {
197     //            ....
198     //         }
199     //     }
200     // }
201     // ```
202     //
203     // In a concession to backwards compatibility, we continue to
204     // permit those, so long as the lifetimes aren't used in
205     // associated types. I believe this is sound, because lifetimes
206     // used elsewhere are not projected back out.
207 }
208
209 fn report_unused_parameter(tcx: TyCtxt<'_>, span: Span, kind: &str, name: &str) {
210     let mut err = struct_span_err!(
211         tcx.sess,
212         span,
213         E0207,
214         "the {} parameter `{}` is not constrained by the \
215         impl trait, self type, or predicates",
216         kind,
217         name
218     );
219     err.span_label(span, format!("unconstrained {} parameter", kind));
220     if kind == "const" {
221         err.note(
222             "expressions using a const parameter must map each value to a distinct output value",
223         );
224         err.note(
225             "proving the result of expressions other than the parameter are unique is not supported",
226         );
227     }
228     err.emit();
229 }
230
231 /// Enforce that we do not have two items in an impl with the same name.
232 fn enforce_impl_items_are_distinct(tcx: TyCtxt<'_>, impl_item_refs: &[hir::ImplItemRef<'_>]) {
233     let mut seen_type_items = FxHashMap::default();
234     let mut seen_value_items = FxHashMap::default();
235     for impl_item_ref in impl_item_refs {
236         let impl_item = tcx.hir().impl_item(impl_item_ref.id);
237         let seen_items = match impl_item.kind {
238             hir::ImplItemKind::TyAlias(_) => &mut seen_type_items,
239             _ => &mut seen_value_items,
240         };
241         match seen_items.entry(impl_item.ident.normalize_to_macros_2_0()) {
242             Occupied(entry) => {
243                 let mut err = struct_span_err!(
244                     tcx.sess,
245                     impl_item.span,
246                     E0201,
247                     "duplicate definitions with name `{}`:",
248                     impl_item.ident
249                 );
250                 err.span_label(
251                     *entry.get(),
252                     format!("previous definition of `{}` here", impl_item.ident),
253                 );
254                 err.span_label(impl_item.span, "duplicate definition");
255                 err.emit();
256             }
257             Vacant(entry) => {
258                 entry.insert(impl_item.span);
259             }
260         }
261     }
262 }