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