• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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::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::query::Providers;
19 use rustc_middle::ty::{self, TyCtxt, TypeVisitableExt};
20 use rustc_span::{Span, Symbol};
21 
22 mod min_specialization;
23 
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
29 /// possible).
30 ///
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.
35 ///
36 /// Example:
37 ///
38 /// ```rust,ignore (pseudo-Rust)
39 /// impl<T> Trait<Foo> for Bar { ... }
40 /// //   ^ T does not appear in `Foo` or `Bar`, error!
41 ///
42 /// impl<T> Trait<Foo<T>> for Bar { ... }
43 /// //   ^ T appears in `Foo<T>`, ok.
44 ///
45 /// impl<T> Trait<Foo> for Bar where Bar: Iterator<Item = T> { ... }
46 /// //   ^ T is bound to `<Bar as Iterator>::Item`, ok.
47 ///
48 /// impl<'a> Trait<Foo> for Bar { }
49 /// //   ^ 'a is unused, but for back-compat we allow it
50 ///
51 /// impl<'a> Trait<Foo> for Bar { type X = &'a i32; }
52 /// //   ^ 'a is unused and appears in assoc type, error
53 /// ```
check_mod_impl_wf(tcx: TyCtxt<'_>, module_def_id: LocalDefId)54 fn check_mod_impl_wf(tcx: TyCtxt<'_>, module_def_id: LocalDefId) {
55     let min_specialization = tcx.features().min_specialization;
56     let module = tcx.hir_module_items(module_def_id);
57     for id in module.items() {
58         if matches!(tcx.def_kind(id.owner_id), DefKind::Impl { .. }) {
59             enforce_impl_params_are_constrained(tcx, id.owner_id.def_id);
60             if min_specialization {
61                 check_min_specialization(tcx, id.owner_id.def_id);
62             }
63         }
64     }
65 }
66 
provide(providers: &mut Providers)67 pub fn provide(providers: &mut Providers) {
68     *providers = Providers { check_mod_impl_wf, ..*providers };
69 }
70 
enforce_impl_params_are_constrained(tcx: TyCtxt<'_>, impl_def_id: LocalDefId)71 fn enforce_impl_params_are_constrained(tcx: TyCtxt<'_>, impl_def_id: LocalDefId) {
72     // Every lifetime used in an associated type must be constrained.
73     let impl_self_ty = tcx.type_of(impl_def_id).subst_identity();
74     if impl_self_ty.references_error() {
75         // Don't complain about unconstrained type params when self ty isn't known due to errors.
76         // (#36836)
77         tcx.sess.delay_span_bug(
78             tcx.def_span(impl_def_id),
79             format!(
80                 "potentially unconstrained type parameters weren't evaluated: {:?}",
81                 impl_self_ty,
82             ),
83         );
84         return;
85     }
86     let impl_generics = tcx.generics_of(impl_def_id);
87     let impl_predicates = tcx.predicates_of(impl_def_id);
88     let impl_trait_ref = tcx.impl_trait_ref(impl_def_id).map(ty::EarlyBinder::subst_identity);
89 
90     let mut input_parameters = cgp::parameters_for_impl(impl_self_ty, impl_trait_ref);
91     cgp::identify_constrained_generic_params(
92         tcx,
93         impl_predicates,
94         impl_trait_ref,
95         &mut input_parameters,
96     );
97 
98     // Disallow unconstrained lifetimes, but only if they appear in assoc types.
99     let lifetimes_in_associated_types: FxHashSet<_> = tcx
100         .associated_item_def_ids(impl_def_id)
101         .iter()
102         .flat_map(|def_id| {
103             let item = tcx.associated_item(def_id);
104             match item.kind {
105                 ty::AssocKind::Type => {
106                     if item.defaultness(tcx).has_value() {
107                         cgp::parameters_for(&tcx.type_of(def_id).subst_identity(), true)
108                     } else {
109                         vec![]
110                     }
111                 }
112                 ty::AssocKind::Fn => {
113                     if !tcx.lower_impl_trait_in_trait_to_assoc_ty()
114                         && item.defaultness(tcx).has_value()
115                         && tcx.impl_method_has_trait_impl_trait_tys(item.def_id)
116                         && let Ok(table) = tcx.collect_return_position_impl_trait_in_trait_tys(def_id)
117                     {
118                         table.values().copied().flat_map(|ty| {
119                             cgp::parameters_for(&ty.subst_identity(), true)
120                         }).collect()
121                     } else {
122                         vec![]
123                     }
124                 }
125                 ty::AssocKind::Const => vec![],
126             }
127         })
128         .collect();
129 
130     for param in &impl_generics.params {
131         match param.kind {
132             // Disallow ANY unconstrained type parameters.
133             ty::GenericParamDefKind::Type { .. } => {
134                 let param_ty = ty::ParamTy::for_def(param);
135                 if !input_parameters.contains(&cgp::Parameter::from(param_ty)) {
136                     report_unused_parameter(tcx, tcx.def_span(param.def_id), "type", param_ty.name);
137                 }
138             }
139             ty::GenericParamDefKind::Lifetime => {
140                 let param_lt = cgp::Parameter::from(param.to_early_bound_region_data());
141                 if lifetimes_in_associated_types.contains(&param_lt) && // (*)
142                     !input_parameters.contains(&param_lt)
143                 {
144                     report_unused_parameter(
145                         tcx,
146                         tcx.def_span(param.def_id),
147                         "lifetime",
148                         param.name,
149                     );
150                 }
151             }
152             ty::GenericParamDefKind::Const { .. } => {
153                 let param_ct = ty::ParamConst::for_def(param);
154                 if !input_parameters.contains(&cgp::Parameter::from(param_ct)) {
155                     report_unused_parameter(
156                         tcx,
157                         tcx.def_span(param.def_id),
158                         "const",
159                         param_ct.name,
160                     );
161                 }
162             }
163         }
164     }
165 
166     // (*) This is a horrible concession to reality. I think it'd be
167     // better to just ban unconstrained lifetimes outright, but in
168     // practice people do non-hygienic macros like:
169     //
170     // ```
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> {
174     //            ....
175     //         }
176     //     }
177     // }
178     // ```
179     //
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.
184 }
185 
report_unused_parameter(tcx: TyCtxt<'_>, span: Span, kind: &str, name: Symbol)186 fn report_unused_parameter(tcx: TyCtxt<'_>, span: Span, kind: &str, name: Symbol) {
187     let mut err = struct_span_err!(
188         tcx.sess,
189         span,
190         E0207,
191         "the {} parameter `{}` is not constrained by the \
192         impl trait, self type, or predicates",
193         kind,
194         name
195     );
196     err.span_label(span, format!("unconstrained {} parameter", kind));
197     if kind == "const" {
198         err.note(
199             "expressions using a const parameter must map each value to a distinct output value",
200         );
201         err.note(
202             "proving the result of expressions other than the parameter are unique is not supported",
203         );
204     }
205     err.emit();
206 }
207