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