]> git.lizzy.rs Git - rust.git/blob - src/librustc_typeck/impl_wf_check.rs
Enclose type in backticks for "reached the recursion limit while auto-dereferencing...
[rust.git] / src / librustc_typeck / impl_wf_check.rs
1 // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 //! This pass enforces various "well-formedness constraints" on impls.
12 //! Logically, it is part of wfcheck -- but we do it early so that we
13 //! can stop compilation afterwards, since part of the trait matching
14 //! infrastructure gets very grumpy if these conditions don't hold. In
15 //! particular, if there are type parameters that are not part of the
16 //! impl, then coherence will report strange inference ambiguity
17 //! errors; if impls have duplicate items, we get misleading
18 //! specialization errors. These things can (and probably should) be
19 //! fixed, but for the moment it's easier to do these checks early.
20
21 use constrained_type_params as ctp;
22 use rustc::hir;
23 use rustc::hir::itemlikevisit::ItemLikeVisitor;
24 use rustc::hir::def_id::DefId;
25 use rustc::ty::{self, TyCtxt};
26 use rustc::util::nodemap::{FxHashMap, FxHashSet};
27 use std::collections::hash_map::Entry::{Occupied, Vacant};
28
29 use syntax_pos::Span;
30
31 /// Checks that all the type/lifetime parameters on an impl also
32 /// appear in the trait ref or self-type (or are constrained by a
33 /// where-clause). These rules are needed to ensure that, given a
34 /// trait ref like `<T as Trait<U>>`, we can derive the values of all
35 /// parameters on the impl (which is needed to make specialization
36 /// possible).
37 ///
38 /// However, in the case of lifetimes, we only enforce these rules if
39 /// the lifetime parameter is used in an associated type.  This is a
40 /// concession to backwards compatibility; see comment at the end of
41 /// the fn for details.
42 ///
43 /// Example:
44 ///
45 /// ```rust,ignore (pseudo-Rust)
46 /// impl<T> Trait<Foo> for Bar { ... }
47 /// //   ^ T does not appear in `Foo` or `Bar`, error!
48 ///
49 /// impl<T> Trait<Foo<T>> for Bar { ... }
50 /// //   ^ T appears in `Foo<T>`, ok.
51 ///
52 /// impl<T> Trait<Foo> for Bar where Bar: Iterator<Item=T> { ... }
53 /// //   ^ T is bound to `<Bar as Iterator>::Item`, ok.
54 ///
55 /// impl<'a> Trait<Foo> for Bar { }
56 /// //   ^ 'a is unused, but for back-compat we allow it
57 ///
58 /// impl<'a> Trait<Foo> for Bar { type X = &'a i32; }
59 /// //   ^ 'a is unused and appears in assoc type, error
60 /// ```
61 pub fn impl_wf_check<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>) {
62     // We will tag this as part of the WF check -- logically, it is,
63     // but it's one that we must perform earlier than the rest of
64     // WfCheck.
65     tcx.hir.krate().visit_all_item_likes(&mut ImplWfCheck { tcx });
66 }
67
68 struct ImplWfCheck<'a, 'tcx: 'a> {
69     tcx: TyCtxt<'a, 'tcx, 'tcx>,
70 }
71
72 impl<'a, 'tcx> ItemLikeVisitor<'tcx> for ImplWfCheck<'a, 'tcx> {
73     fn visit_item(&mut self, item: &'tcx hir::Item) {
74         if let hir::ItemKind::Impl(.., ref impl_item_refs) = item.node {
75             let impl_def_id = self.tcx.hir.local_def_id(item.id);
76             enforce_impl_params_are_constrained(self.tcx,
77                                                 impl_def_id,
78                                                 impl_item_refs);
79             enforce_impl_items_are_distinct(self.tcx, impl_item_refs);
80         }
81     }
82
83     fn visit_trait_item(&mut self, _trait_item: &'tcx hir::TraitItem) { }
84
85     fn visit_impl_item(&mut self, _impl_item: &'tcx hir::ImplItem) { }
86 }
87
88 fn enforce_impl_params_are_constrained<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
89                                                  impl_def_id: DefId,
90                                                  impl_item_refs: &[hir::ImplItemRef])
91 {
92     // Every lifetime used in an associated type must be constrained.
93     let impl_self_ty = tcx.type_of(impl_def_id);
94     let impl_generics = tcx.generics_of(impl_def_id);
95     let impl_predicates = tcx.predicates_of(impl_def_id);
96     let impl_trait_ref = tcx.impl_trait_ref(impl_def_id);
97
98     let mut input_parameters = ctp::parameters_for_impl(impl_self_ty, impl_trait_ref);
99     ctp::identify_constrained_type_params(
100         tcx, &impl_predicates, impl_trait_ref, &mut input_parameters);
101
102     // Disallow unconstrained lifetimes, but only if they appear in assoc types.
103     let lifetimes_in_associated_types: FxHashSet<_> = impl_item_refs.iter()
104         .map(|item_ref| tcx.hir.local_def_id(item_ref.id.node_id))
105         .filter(|&def_id| {
106             let item = tcx.associated_item(def_id);
107             item.kind == ty::AssociatedKind::Type && item.defaultness.has_value()
108         })
109         .flat_map(|def_id| {
110             ctp::parameters_for(&tcx.type_of(def_id), true)
111         }).collect();
112
113     for param in &impl_generics.params {
114         match param.kind {
115             // Disallow ANY unconstrained type parameters.
116             ty::GenericParamDefKind::Type {..} => {
117                 let param_ty = ty::ParamTy::for_def(param);
118                 if !input_parameters.contains(&ctp::Parameter::from(param_ty)) {
119                     report_unused_parameter(tcx,
120                                             tcx.def_span(param.def_id),
121                                             "type",
122                                             &param_ty.to_string());
123                 }
124             }
125             ty::GenericParamDefKind::Lifetime => {
126                 let param_lt = ctp::Parameter::from(param.to_early_bound_region_data());
127                 if lifetimes_in_associated_types.contains(&param_lt) && // (*)
128                     !input_parameters.contains(&param_lt) {
129                     report_unused_parameter(tcx,
130                                             tcx.def_span(param.def_id),
131                                             "lifetime",
132                                             &param.name.to_string());
133                 }
134             }
135         }
136     }
137
138     // (*) This is a horrible concession to reality. I think it'd be
139     // better to just ban unconstrianed lifetimes outright, but in
140     // practice people do non-hygenic macros like:
141     //
142     // ```
143     // macro_rules! __impl_slice_eq1 {
144     //     ($Lhs: ty, $Rhs: ty, $Bound: ident) => {
145     //         impl<'a, 'b, A: $Bound, B> PartialEq<$Rhs> for $Lhs where A: PartialEq<B> {
146     //            ....
147     //         }
148     //     }
149     // }
150     // ```
151     //
152     // In a concession to backwards compatibility, we continue to
153     // permit those, so long as the lifetimes aren't used in
154     // associated types. I believe this is sound, because lifetimes
155     // used elsewhere are not projected back out.
156 }
157
158 fn report_unused_parameter(tcx: TyCtxt,
159                            span: Span,
160                            kind: &str,
161                            name: &str)
162 {
163     struct_span_err!(
164         tcx.sess, span, E0207,
165         "the {} parameter `{}` is not constrained by the \
166         impl trait, self type, or predicates",
167         kind, name)
168         .span_label(span, format!("unconstrained {} parameter", kind))
169         .emit();
170 }
171
172 /// Enforce that we do not have two items in an impl with the same name.
173 fn enforce_impl_items_are_distinct<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
174                                              impl_item_refs: &[hir::ImplItemRef])
175 {
176     let mut seen_type_items = FxHashMap::default();
177     let mut seen_value_items = FxHashMap::default();
178     for impl_item_ref in impl_item_refs {
179         let impl_item = tcx.hir.impl_item(impl_item_ref.id);
180         let seen_items = match impl_item.node {
181             hir::ImplItemKind::Type(_) => &mut seen_type_items,
182             _                          => &mut seen_value_items,
183         };
184         match seen_items.entry(impl_item.ident.modern()) {
185             Occupied(entry) => {
186                 let mut err = struct_span_err!(tcx.sess, impl_item.span, E0201,
187                                                "duplicate definitions with name `{}`:",
188                                                impl_item.ident);
189                 err.span_label(*entry.get(),
190                                format!("previous definition of `{}` here",
191                                        impl_item.ident));
192                 err.span_label(impl_item.span, "duplicate definition");
193                 err.emit();
194             }
195             Vacant(entry) => {
196                 entry.insert(impl_item.span);
197             }
198         }
199     }
200 }