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.
11 use crate::constrained_generic_params as cgp;
12 use min_specialization::check_min_specialization;
14 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
15 use rustc_errors::struct_span_err;
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};
23 use std::collections::hash_map::Entry::{Occupied, Vacant};
25 mod min_specialization;
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
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.
41 /// ```rust,ignore (pseudo-Rust)
42 /// impl<T> Trait<Foo> for Bar { ... }
43 /// // ^ T does not appear in `Foo` or `Bar`, error!
45 /// impl<T> Trait<Foo<T>> for Bar { ... }
46 /// // ^ T appears in `Foo<T>`, ok.
48 /// impl<T> Trait<Foo> for Bar where Bar: Iterator<Item = T> { ... }
49 /// // ^ T is bound to `<Bar as Iterator>::Item`, ok.
51 /// impl<'a> Trait<Foo> for Bar { }
52 /// // ^ 'a is unused, but for back-compat we allow it
54 /// impl<'a> Trait<Foo> for Bar { type X = &'a i32; }
55 /// // ^ 'a is unused and appears in assoc type, error
57 fn check_mod_impl_wf(tcx: TyCtxt<'_>, module_def_id: LocalDefId) {
58 let min_specialization = tcx.features().min_specialization;
59 let module = tcx.hir_module_items(module_def_id);
60 for id in module.items() {
61 if matches!(tcx.def_kind(id.def_id), DefKind::Impl) {
62 let item = tcx.hir().item(id);
63 if let hir::ItemKind::Impl(ref impl_) = item.kind {
64 enforce_impl_params_are_constrained(tcx, item.def_id, impl_.items);
65 enforce_impl_items_are_distinct(tcx, impl_.items);
66 if min_specialization {
67 check_min_specialization(tcx, item.def_id.to_def_id(), item.span);
74 pub fn provide(providers: &mut Providers) {
75 *providers = Providers { check_mod_impl_wf, ..*providers };
78 fn enforce_impl_params_are_constrained(
80 impl_def_id: LocalDefId,
81 impl_item_refs: &[hir::ImplItemRef],
83 // Every lifetime used in an associated type must be constrained.
84 let impl_self_ty = tcx.type_of(impl_def_id);
85 if impl_self_ty.references_error() {
86 // Don't complain about unconstrained type params when self ty isn't known due to errors.
88 tcx.sess.delay_span_bug(
89 tcx.def_span(impl_def_id),
91 "potentially unconstrained type parameters weren't evaluated: {:?}",
97 let impl_generics = tcx.generics_of(impl_def_id);
98 let impl_predicates = tcx.predicates_of(impl_def_id);
99 let impl_trait_ref = tcx.impl_trait_ref(impl_def_id);
101 let mut input_parameters = cgp::parameters_for_impl(impl_self_ty, impl_trait_ref);
102 cgp::identify_constrained_generic_params(
106 &mut input_parameters,
109 // Disallow unconstrained lifetimes, but only if they appear in assoc types.
110 let lifetimes_in_associated_types: FxHashSet<_> = impl_item_refs
112 .map(|item_ref| item_ref.id.def_id)
114 let item = tcx.associated_item(def_id);
116 ty::AssocKind::Type => {
117 if item.defaultness.has_value() {
118 cgp::parameters_for(&tcx.type_of(def_id), true)
123 ty::AssocKind::Fn | ty::AssocKind::Const => Vec::new(),
128 for param in &impl_generics.params {
130 // Disallow ANY unconstrained type parameters.
131 ty::GenericParamDefKind::Type { .. } => {
132 let param_ty = ty::ParamTy::for_def(param);
133 if !input_parameters.contains(&cgp::Parameter::from(param_ty)) {
134 report_unused_parameter(
136 tcx.def_span(param.def_id),
138 ¶m_ty.to_string(),
142 ty::GenericParamDefKind::Lifetime => {
143 let param_lt = cgp::Parameter::from(param.to_early_bound_region_data());
144 if lifetimes_in_associated_types.contains(¶m_lt) && // (*)
145 !input_parameters.contains(¶m_lt)
147 report_unused_parameter(
149 tcx.def_span(param.def_id),
151 ¶m.name.to_string(),
155 ty::GenericParamDefKind::Const { .. } => {
156 let param_ct = ty::ParamConst::for_def(param);
157 if !input_parameters.contains(&cgp::Parameter::from(param_ct)) {
158 report_unused_parameter(
160 tcx.def_span(param.def_id),
162 ¶m_ct.to_string(),
169 // (*) This is a horrible concession to reality. I think it'd be
170 // better to just ban unconstrained lifetimes outright, but in
171 // practice people do non-hygienic macros like:
174 // macro_rules! __impl_slice_eq1 {
175 // ($Lhs: ty, $Rhs: ty, $Bound: ident) => {
176 // impl<'a, 'b, A: $Bound, B> PartialEq<$Rhs> for $Lhs where A: PartialEq<B> {
183 // In a concession to backwards compatibility, we continue to
184 // permit those, so long as the lifetimes aren't used in
185 // associated types. I believe this is sound, because lifetimes
186 // used elsewhere are not projected back out.
189 fn report_unused_parameter(tcx: TyCtxt<'_>, span: Span, kind: &str, name: &str) {
190 let mut err = struct_span_err!(
194 "the {} parameter `{}` is not constrained by the \
195 impl trait, self type, or predicates",
199 err.span_label(span, format!("unconstrained {} parameter", kind));
202 "expressions using a const parameter must map each value to a distinct output value",
205 "proving the result of expressions other than the parameter are unique is not supported",
211 /// Enforce that we do not have two items in an impl with the same name.
212 fn enforce_impl_items_are_distinct(tcx: TyCtxt<'_>, impl_item_refs: &[hir::ImplItemRef]) {
213 let mut seen_type_items = FxHashMap::default();
214 let mut seen_value_items = FxHashMap::default();
215 for impl_item_ref in impl_item_refs {
216 let impl_item = tcx.hir().impl_item(impl_item_ref.id);
217 let seen_items = match impl_item.kind {
218 hir::ImplItemKind::TyAlias(_) => &mut seen_type_items,
219 _ => &mut seen_value_items,
221 match seen_items.entry(impl_item.ident.normalize_to_macros_2_0()) {
223 let mut err = struct_span_err!(
227 "duplicate definitions with name `{}`:",
232 format!("previous definition of `{}` here", impl_item.ident),
234 err.span_label(impl_item.span, "duplicate definition");
238 entry.insert(impl_item.span);