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
;
13 use rustc
::hir
::itemlikevisit
::ItemLikeVisitor
;
14 use rustc
::hir
::def_id
::DefId
;
15 use rustc
::ty
::{self, TyCtxt, TypeFoldable}
;
16 use rustc
::ty
::query
::Providers
;
17 use rustc
::util
::nodemap
::{FxHashMap, FxHashSet}
;
18 use std
::collections
::hash_map
::Entry
::{Occupied, Vacant}
;
22 use rustc_error_codes
::*;
24 /// Checks that all the type/lifetime parameters on an impl also
25 /// appear in the trait ref or self type (or are constrained by a
26 /// where-clause). These rules are needed to ensure that, given a
27 /// trait ref like `<T as Trait<U>>`, we can derive the values of all
28 /// parameters on the impl (which is needed to make specialization
31 /// However, in the case of lifetimes, we only enforce these rules if
32 /// the lifetime parameter is used in an associated type. This is a
33 /// concession to backwards compatibility; see comment at the end of
34 /// the fn for details.
38 /// ```rust,ignore (pseudo-Rust)
39 /// impl<T> Trait<Foo> for Bar { ... }
40 /// // ^ T does not appear in `Foo` or `Bar`, error!
42 /// impl<T> Trait<Foo<T>> for Bar { ... }
43 /// // ^ T appears in `Foo<T>`, ok.
45 /// impl<T> Trait<Foo> for Bar where Bar: Iterator<Item = T> { ... }
46 /// // ^ T is bound to `<Bar as Iterator>::Item`, ok.
48 /// impl<'a> Trait<Foo> for Bar { }
49 /// // ^ 'a is unused, but for back-compat we allow it
51 /// impl<'a> Trait<Foo> for Bar { type X = &'a i32; }
52 /// // ^ 'a is unused and appears in assoc type, error
54 pub fn impl_wf_check(tcx
: TyCtxt
<'_
>) {
55 // We will tag this as part of the WF check -- logically, it is,
56 // but it's one that we must perform earlier than the rest of
58 for &module
in tcx
.hir().krate().modules
.keys() {
59 tcx
.ensure().check_mod_impl_wf(tcx
.hir().local_def_id(module
));
63 fn check_mod_impl_wf(tcx
: TyCtxt
<'_
>, module_def_id
: DefId
) {
64 tcx
.hir().visit_item_likes_in_module(
66 &mut ImplWfCheck { tcx }
70 pub fn provide(providers
: &mut Providers
<'_
>) {
71 *providers
= Providers
{
77 struct ImplWfCheck
<'tcx
> {
81 impl ItemLikeVisitor
<'tcx
> for ImplWfCheck
<'tcx
> {
82 fn visit_item(&mut self, item
: &'tcx hir
::Item
) {
83 if let hir
::ItemKind
::Impl(.., ref impl_item_refs
) = item
.kind
{
84 let impl_def_id
= self.tcx
.hir().local_def_id(item
.hir_id
);
85 enforce_impl_params_are_constrained(self.tcx
,
88 enforce_impl_items_are_distinct(self.tcx
, impl_item_refs
);
92 fn visit_trait_item(&mut self, _trait_item
: &'tcx hir
::TraitItem
) { }
94 fn visit_impl_item(&mut self, _impl_item
: &'tcx hir
::ImplItem
) { }
97 fn enforce_impl_params_are_constrained(
100 impl_item_refs
: &[hir
::ImplItemRef
],
102 // Every lifetime used in an associated type must be constrained.
103 let impl_self_ty
= tcx
.type_of(impl_def_id
);
104 if impl_self_ty
.references_error() {
105 // Don't complain about unconstrained type params when self ty isn't known due to errors.
107 tcx
.sess
.delay_span_bug(
108 tcx
.def_span(impl_def_id
),
109 "potentially unconstrained type parameters weren't evaluated",
113 let impl_generics
= tcx
.generics_of(impl_def_id
);
114 let impl_predicates
= tcx
.predicates_of(impl_def_id
);
115 let impl_trait_ref
= tcx
.impl_trait_ref(impl_def_id
);
117 let mut input_parameters
= cgp
::parameters_for_impl(impl_self_ty
, impl_trait_ref
);
118 cgp
::identify_constrained_generic_params(
119 tcx
, impl_predicates
, impl_trait_ref
, &mut input_parameters
);
121 // Disallow unconstrained lifetimes, but only if they appear in assoc types.
122 let lifetimes_in_associated_types
: FxHashSet
<_
> = impl_item_refs
.iter()
123 .map(|item_ref
| tcx
.hir().local_def_id(item_ref
.id
.hir_id
))
125 let item
= tcx
.associated_item(def_id
);
126 item
.kind
== ty
::AssocKind
::Type
&& item
.defaultness
.has_value()
129 cgp
::parameters_for(&tcx
.type_of(def_id
), true)
132 for param
in &impl_generics
.params
{
134 // Disallow ANY unconstrained type parameters.
135 ty
::GenericParamDefKind
::Type { .. }
=> {
136 let param_ty
= ty
::ParamTy
::for_def(param
);
137 if !input_parameters
.contains(&cgp
::Parameter
::from(param_ty
)) {
138 report_unused_parameter(tcx
,
139 tcx
.def_span(param
.def_id
),
141 ¶m_ty
.to_string());
144 ty
::GenericParamDefKind
::Lifetime
=> {
145 let param_lt
= cgp
::Parameter
::from(param
.to_early_bound_region_data());
146 if lifetimes_in_associated_types
.contains(¶m_lt
) && // (*)
147 !input_parameters
.contains(¶m_lt
) {
148 report_unused_parameter(tcx
,
149 tcx
.def_span(param
.def_id
),
151 ¶m
.name
.to_string());
154 ty
::GenericParamDefKind
::Const
=> {
155 let param_ct
= ty
::ParamConst
::for_def(param
);
156 if !input_parameters
.contains(&cgp
::Parameter
::from(param_ct
)) {
157 report_unused_parameter(tcx
,
158 tcx
.def_span(param
.def_id
),
160 ¶m_ct
.to_string());
166 // (*) This is a horrible concession to reality. I think it'd be
167 // better to just ban unconstrianed lifetimes outright, but in
168 // practice people do non-hygenic macros like:
171 // macro_rules! __impl_slice_eq1 {
172 // ($Lhs: ty, $Rhs: ty, $Bound: ident) => {
173 // impl<'a, 'b, A: $Bound, B> PartialEq<$Rhs> for $Lhs where A: PartialEq<B> {
180 // In a concession to backwards compatibility, we continue to
181 // permit those, so long as the lifetimes aren't used in
182 // associated types. I believe this is sound, because lifetimes
183 // used elsewhere are not projected back out.
186 fn report_unused_parameter(tcx
: TyCtxt
<'_
>, span
: Span
, kind
: &str, name
: &str) {
188 tcx
.sess
, span
, E0207
,
189 "the {} parameter `{}` is not constrained by the \
190 impl trait, self type, or predicates",
192 .span_label(span
, format
!("unconstrained {} parameter", kind
))
196 /// Enforce that we do not have two items in an impl with the same name.
197 fn enforce_impl_items_are_distinct(tcx
: TyCtxt
<'_
>, impl_item_refs
: &[hir
::ImplItemRef
]) {
198 let mut seen_type_items
= FxHashMap
::default();
199 let mut seen_value_items
= FxHashMap
::default();
200 for impl_item_ref
in impl_item_refs
{
201 let impl_item
= tcx
.hir().impl_item(impl_item_ref
.id
);
202 let seen_items
= match impl_item
.kind
{
203 hir
::ImplItemKind
::TyAlias(_
) => &mut seen_type_items
,
204 _
=> &mut seen_value_items
,
206 match seen_items
.entry(impl_item
.ident
.modern()) {
208 let mut err
= struct_span_err
!(tcx
.sess
, impl_item
.span
, E0201
,
209 "duplicate definitions with name `{}`:",
211 err
.span_label(*entry
.get(),
212 format
!("previous definition of `{}` here",
214 err
.span_label(impl_item
.span
, "duplicate definition");
218 entry
.insert(impl_item
.span
);