]> git.lizzy.rs Git - rust.git/blob - src/librustc_typeck/check/wfcheck.rs
Check WF of predicate with defaults only if all in LHS have default
[rust.git] / src / librustc_typeck / check / wfcheck.rs
1 // Copyright 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 use check::{Inherited, FnCtxt};
12 use constrained_type_params::{identify_constrained_type_params, Parameter};
13
14 use hir::def_id::DefId;
15 use rustc::traits::{self, ObligationCauseCode};
16 use rustc::ty::{self, Lift, Ty, TyCtxt};
17 use rustc::ty::util::ExplicitSelf;
18 use rustc::util::nodemap::{FxHashSet, FxHashMap};
19 use rustc::middle::lang_items;
20
21 use syntax::ast;
22 use syntax::feature_gate::{self, GateIssue};
23 use syntax_pos::Span;
24 use errors::{DiagnosticBuilder, DiagnosticId};
25
26 use rustc::hir::intravisit::{self, Visitor, NestedVisitorMap};
27 use rustc::hir;
28
29 pub struct CheckTypeWellFormedVisitor<'a, 'tcx:'a> {
30     tcx: TyCtxt<'a, 'tcx, 'tcx>,
31     code: ObligationCauseCode<'tcx>,
32 }
33
34 /// Helper type of a temporary returned by .for_item(...).
35 /// Necessary because we can't write the following bound:
36 /// F: for<'b, 'tcx> where 'gcx: 'tcx FnOnce(FnCtxt<'b, 'gcx, 'tcx>).
37 struct CheckWfFcxBuilder<'a, 'gcx: 'a+'tcx, 'tcx: 'a> {
38     inherited: super::InheritedBuilder<'a, 'gcx, 'tcx>,
39     code: ObligationCauseCode<'gcx>,
40     id: ast::NodeId,
41     span: Span,
42     param_env: ty::ParamEnv<'tcx>,
43 }
44
45 impl<'a, 'gcx, 'tcx> CheckWfFcxBuilder<'a, 'gcx, 'tcx> {
46     fn with_fcx<F>(&'tcx mut self, f: F) where
47         F: for<'b> FnOnce(&FnCtxt<'b, 'gcx, 'tcx>,
48                           &mut CheckTypeWellFormedVisitor<'b, 'gcx>) -> Vec<Ty<'tcx>>
49     {
50         let code = self.code.clone();
51         let id = self.id;
52         let span = self.span;
53         let param_env = self.param_env;
54         self.inherited.enter(|inh| {
55             let fcx = FnCtxt::new(&inh, param_env, id);
56             let wf_tys = f(&fcx, &mut CheckTypeWellFormedVisitor {
57                 tcx: fcx.tcx.global_tcx(),
58                 code,
59             });
60             fcx.select_all_obligations_or_error();
61             fcx.regionck_item(id, span, &wf_tys);
62         });
63     }
64 }
65
66 impl<'a, 'gcx> CheckTypeWellFormedVisitor<'a, 'gcx> {
67     pub fn new(tcx: TyCtxt<'a, 'gcx, 'gcx>)
68                -> CheckTypeWellFormedVisitor<'a, 'gcx> {
69         CheckTypeWellFormedVisitor {
70             tcx,
71             code: ObligationCauseCode::MiscObligation
72         }
73     }
74
75     /// Checks that the field types (in a struct def'n) or argument types (in an enum def'n) are
76     /// well-formed, meaning that they do not require any constraints not declared in the struct
77     /// definition itself. For example, this definition would be illegal:
78     ///
79     ///     struct Ref<'a, T> { x: &'a T }
80     ///
81     /// because the type did not declare that `T:'a`.
82     ///
83     /// We do this check as a pre-pass before checking fn bodies because if these constraints are
84     /// not included it frequently leads to confusing errors in fn bodies. So it's better to check
85     /// the types first.
86     fn check_item_well_formed(&mut self, item: &hir::Item) {
87         let tcx = self.tcx;
88         debug!("check_item_well_formed(it.id={}, it.name={})",
89                item.id,
90                tcx.item_path_str(tcx.hir.local_def_id(item.id)));
91
92         match item.node {
93             // Right now we check that every default trait implementation
94             // has an implementation of itself. Basically, a case like:
95             //
96             // `impl Trait for T {}`
97             //
98             // has a requirement of `T: Trait` which was required for default
99             // method implementations. Although this could be improved now that
100             // there's a better infrastructure in place for this, it's being left
101             // for a follow-up work.
102             //
103             // Since there's such a requirement, we need to check *just* positive
104             // implementations, otherwise things like:
105             //
106             // impl !Send for T {}
107             //
108             // won't be allowed unless there's an *explicit* implementation of `Send`
109             // for `T`
110             hir::ItemImpl(_, polarity, defaultness, _, ref trait_ref, ref self_ty, _) => {
111                 let is_auto = tcx.impl_trait_ref(tcx.hir.local_def_id(item.id))
112                                  .map_or(false, |trait_ref| tcx.trait_is_auto(trait_ref.def_id));
113                 if let (hir::Defaultness::Default { .. }, true) = (defaultness, is_auto) {
114                     tcx.sess.span_err(item.span, "impls of auto traits cannot be default");
115                 }
116                 if polarity == hir::ImplPolarity::Positive {
117                     self.check_impl(item, self_ty, trait_ref);
118                 } else {
119                     // FIXME(#27579) what amount of WF checking do we need for neg impls?
120                     if trait_ref.is_some() && !is_auto {
121                         span_err!(tcx.sess, item.span, E0192,
122                                   "negative impls are only allowed for \
123                                    auto traits (e.g., `Send` and `Sync`)")
124                     }
125                 }
126             }
127             hir::ItemFn(..) => {
128                 self.check_item_fn(item);
129             }
130             hir::ItemStatic(..) => {
131                 self.check_item_type(item);
132             }
133             hir::ItemConst(..) => {
134                 self.check_item_type(item);
135             }
136             hir::ItemStruct(ref struct_def, ref ast_generics) => {
137                 self.check_type_defn(item, false, |fcx| {
138                     vec![fcx.non_enum_variant(struct_def)]
139                 });
140
141                 self.check_variances_for_type_defn(item, ast_generics);
142             }
143             hir::ItemUnion(ref struct_def, ref ast_generics) => {
144                 self.check_type_defn(item, true, |fcx| {
145                     vec![fcx.non_enum_variant(struct_def)]
146                 });
147
148                 self.check_variances_for_type_defn(item, ast_generics);
149             }
150             hir::ItemEnum(ref enum_def, ref ast_generics) => {
151                 self.check_type_defn(item, true, |fcx| {
152                     fcx.enum_variants(enum_def)
153                 });
154
155                 self.check_variances_for_type_defn(item, ast_generics);
156             }
157             hir::ItemTrait(..) => {
158                 self.check_trait(item);
159             }
160             _ => {}
161         }
162     }
163
164     fn check_associated_item(&mut self,
165                              item_id: ast::NodeId,
166                              span: Span,
167                              sig_if_method: Option<&hir::MethodSig>) {
168         let code = self.code.clone();
169         self.for_id(item_id, span).with_fcx(|fcx, this| {
170             let item = fcx.tcx.associated_item(fcx.tcx.hir.local_def_id(item_id));
171
172             let (mut implied_bounds, self_ty) = match item.container {
173                 ty::TraitContainer(_) => (vec![], fcx.tcx.mk_self_type()),
174                 ty::ImplContainer(def_id) => (fcx.impl_implied_bounds(def_id, span),
175                                               fcx.tcx.type_of(def_id))
176             };
177
178             match item.kind {
179                 ty::AssociatedKind::Const => {
180                     let ty = fcx.tcx.type_of(item.def_id);
181                     let ty = fcx.normalize_associated_types_in(span, &ty);
182                     fcx.register_wf_obligation(ty, span, code.clone());
183                 }
184                 ty::AssociatedKind::Method => {
185                     reject_shadowing_type_parameters(fcx.tcx, item.def_id);
186                     let sig = fcx.tcx.fn_sig(item.def_id);
187                     let sig = fcx.normalize_associated_types_in(span, &sig);
188                     this.check_fn_or_method(fcx, span, sig,
189                                             item.def_id, &mut implied_bounds);
190                     let sig_if_method = sig_if_method.expect("bad signature for method");
191                     this.check_method_receiver(fcx, sig_if_method, &item, self_ty);
192                 }
193                 ty::AssociatedKind::Type => {
194                     if item.defaultness.has_value() {
195                         let ty = fcx.tcx.type_of(item.def_id);
196                         let ty = fcx.normalize_associated_types_in(span, &ty);
197                         fcx.register_wf_obligation(ty, span, code.clone());
198                     }
199                 }
200             }
201
202             implied_bounds
203         })
204     }
205
206     fn for_item<'tcx>(&self, item: &hir::Item)
207                       -> CheckWfFcxBuilder<'a, 'gcx, 'tcx> {
208         self.for_id(item.id, item.span)
209     }
210
211     fn for_id<'tcx>(&self, id: ast::NodeId, span: Span)
212                     -> CheckWfFcxBuilder<'a, 'gcx, 'tcx> {
213         let def_id = self.tcx.hir.local_def_id(id);
214         CheckWfFcxBuilder {
215             inherited: Inherited::build(self.tcx, def_id),
216             code: self.code.clone(),
217             id,
218             span,
219             param_env: self.tcx.param_env(def_id),
220         }
221     }
222
223     /// In a type definition, we check that to ensure that the types of the fields are well-formed.
224     fn check_type_defn<F>(&mut self, item: &hir::Item, all_sized: bool, mut lookup_fields: F)
225         where F: for<'fcx, 'tcx> FnMut(&FnCtxt<'fcx, 'gcx, 'tcx>) -> Vec<AdtVariant<'tcx>>
226     {
227         self.for_item(item).with_fcx(|fcx, this| {
228             let variants = lookup_fields(fcx);
229             let def_id = fcx.tcx.hir.local_def_id(item.id);
230             let packed = fcx.tcx.adt_def(def_id).repr.packed();
231
232             for variant in &variants {
233                 // For DST, or when drop needs to copy things around, all
234                 // intermediate types must be sized.
235                 let needs_drop_copy = || {
236                     packed && {
237                         let ty = variant.fields.last().unwrap().ty;
238                         let ty = fcx.tcx.erase_regions(&ty).lift_to_tcx(this.tcx)
239                             .unwrap_or_else(|| {
240                                 span_bug!(item.span, "inference variables in {:?}", ty)
241                             });
242                         ty.needs_drop(this.tcx, this.tcx.param_env(def_id))
243                     }
244                 };
245                 let unsized_len = if
246                     all_sized ||
247                     variant.fields.is_empty() ||
248                     needs_drop_copy()
249                 {
250                     0
251                 } else {
252                     1
253                 };
254                 for field in &variant.fields[..variant.fields.len() - unsized_len] {
255                     fcx.register_bound(
256                         field.ty,
257                         fcx.tcx.require_lang_item(lang_items::SizedTraitLangItem),
258                         traits::ObligationCause::new(field.span,
259                                                      fcx.body_id,
260                                                      traits::FieldSized(match item.node.adt_kind() {
261                                                         Some(i) => i,
262                                                         None => bug!(),
263                                                      })));
264                 }
265
266                 // All field types must be well-formed.
267                 for field in &variant.fields {
268                     fcx.register_wf_obligation(field.ty, field.span, this.code.clone())
269                 }
270             }
271
272             self.check_where_clauses(fcx, item.span, def_id);
273
274             vec![] // no implied bounds in a struct def'n
275         });
276     }
277
278     fn check_trait(&mut self, item: &hir::Item) {
279         let trait_def_id = self.tcx.hir.local_def_id(item.id);
280         self.for_item(item).with_fcx(|fcx, _| {
281             self.check_trait_where_clauses(fcx, item.span, trait_def_id);
282             vec![]
283         });
284     }
285
286     fn check_item_fn(&mut self, item: &hir::Item) {
287         self.for_item(item).with_fcx(|fcx, this| {
288             let def_id = fcx.tcx.hir.local_def_id(item.id);
289             let sig = fcx.tcx.fn_sig(def_id);
290             let sig = fcx.normalize_associated_types_in(item.span, &sig);
291             let mut implied_bounds = vec![];
292             this.check_fn_or_method(fcx, item.span, sig,
293                                     def_id, &mut implied_bounds);
294             implied_bounds
295         })
296     }
297
298     fn check_item_type(&mut self,
299                        item: &hir::Item)
300     {
301         debug!("check_item_type: {:?}", item);
302
303         self.for_item(item).with_fcx(|fcx, this| {
304             let ty = fcx.tcx.type_of(fcx.tcx.hir.local_def_id(item.id));
305             let item_ty = fcx.normalize_associated_types_in(item.span, &ty);
306
307             fcx.register_wf_obligation(item_ty, item.span, this.code.clone());
308
309             vec![] // no implied bounds in a const etc
310         });
311     }
312
313     fn check_impl(&mut self,
314                   item: &hir::Item,
315                   ast_self_ty: &hir::Ty,
316                   ast_trait_ref: &Option<hir::TraitRef>)
317     {
318         debug!("check_impl: {:?}", item);
319
320         self.for_item(item).with_fcx(|fcx, this| {
321             let item_def_id = fcx.tcx.hir.local_def_id(item.id);
322
323             match *ast_trait_ref {
324                 Some(ref ast_trait_ref) => {
325                     let trait_ref = fcx.tcx.impl_trait_ref(item_def_id).unwrap();
326                     let trait_ref =
327                         fcx.normalize_associated_types_in(
328                             ast_trait_ref.path.span, &trait_ref);
329                     let obligations =
330                         ty::wf::trait_obligations(fcx,
331                                                   fcx.param_env,
332                                                   fcx.body_id,
333                                                   &trait_ref,
334                                                   ast_trait_ref.path.span);
335                     for obligation in obligations {
336                         fcx.register_predicate(obligation);
337                     }
338                 }
339                 None => {
340                     let self_ty = fcx.tcx.type_of(item_def_id);
341                     let self_ty = fcx.normalize_associated_types_in(item.span, &self_ty);
342                     fcx.register_wf_obligation(self_ty, ast_self_ty.span, this.code.clone());
343                 }
344             }
345
346             this.check_where_clauses(fcx, item.span, item_def_id);
347
348             fcx.impl_implied_bounds(item_def_id, item.span)
349         });
350     }
351
352     /// Checks where clauses and inline bounds that are declared on def_id.
353     fn check_where_clauses<'fcx, 'tcx>(&mut self,
354                                        fcx: &FnCtxt<'fcx, 'gcx, 'tcx>,
355                                        span: Span,
356                                        def_id: DefId) {
357         self.inner_check_where_clauses(fcx, span, def_id, false)
358     }
359
360     fn check_trait_where_clauses<'fcx, 'tcx>(&mut self,
361                                        fcx: &FnCtxt<'fcx, 'gcx, 'tcx>,
362                                        span: Span,
363                                        def_id: DefId) {
364         self.inner_check_where_clauses(fcx, span, def_id, true)
365     }
366
367     /// Checks where clauses and inline bounds that are declared on def_id.
368     fn inner_check_where_clauses<'fcx, 'tcx>(&mut self,
369                                        fcx: &FnCtxt<'fcx, 'gcx, 'tcx>,
370                                        span: Span,
371                                        def_id: DefId,
372                                        is_trait: bool)
373     {
374         use ty::subst::Subst;
375         use rustc::ty::TypeFoldable;
376
377         let mut predicates = fcx.tcx.predicates_of(def_id);
378         let mut substituted_predicates = Vec::new();
379
380         let generics = self.tcx.generics_of(def_id);
381         let is_our_default = |def: &ty::TypeParameterDef|
382                                 def.has_default && def.index >= generics.parent_count() as u32;
383         let defaulted_params = generics.types.iter().cloned().filter(&is_our_default);
384         // Check that defaults are well-formed. See test `type-check-defaults.rs`.
385         // For example this forbids the declaration:
386         // struct Foo<T = Vec<[u32]>> { .. }
387         // Here the default `Vec<[u32]>` is not WF because `[u32]: Sized` does not hold.
388         for d in defaulted_params.map(|p| p.def_id) {
389             fcx.register_wf_obligation(fcx.tcx.type_of(d), fcx.tcx.def_span(d), self.code.clone());
390         }
391
392         // Check that trait predicates are WF when params are substituted by their defaults.
393         // We don't want to overly constrain the predicates that may be written but we
394         // want to catch obviously wrong cases such as `struct Foo<T: Copy = String>`
395         // or cases that may cause backwards incompatibility such as a library going from
396         // `pub struct Foo<T>` to `pub struct Foo<T, U = i32>` where U: Trait<T>`
397         // which may break existing uses of Foo<T>.
398         // Therefore the check we do is: If if all params appearing in the LHS of the predicate
399         // have defaults then we verify that it is WF with all defaults substituted simultaneously.
400         // For more examples see tests `defaults-well-formedness.rs` and `type-check-defaults.rs`.
401         //
402         // First, we build the defaulted substitution.
403         let mut defaulted_params = Vec::new();
404         let substs = ty::subst::Substs::for_item(fcx.tcx, def_id, |def, _| {
405                 // All regions are identity.
406                 fcx.tcx.mk_region(ty::ReEarlyBound(def.to_early_bound_region_data()))
407             }, |def, _| {
408                 if !is_our_default(def) {
409                     // Identity substitution.
410                     fcx.tcx.mk_param_from_def(def)
411                 } else  {
412                     // Substitute with default.
413                     defaulted_params.push(def.index);
414                     fcx.tcx.type_of(def.def_id)
415                 }
416             });
417         // In `trait Trait: Super`, checking `Self: Trait` or `Self: Super` is problematic.
418         // We avoid those by skipping any predicates in trait declarations that contain `Self`,
419         // which is excessive so we end up checking less than we could.
420         for pred in predicates.predicates.iter()
421                                          .filter_map(ty::Predicate::as_poly_trait_predicate)
422                                          .filter(|p| !(is_trait && p.has_self_ty())) {
423             let is_defaulted_param = |ty: ty::Ty| match ty.sty {
424                                             ty::TyParam(p) => defaulted_params.contains(&p.idx),
425                                             _ => false
426                                           };
427             // If there is a non-defaulted param in the LHS, don't check the substituted predicate.
428             // `skip_binder()` is ok, we're only inspecting the type params.
429             if !pred.skip_binder().self_ty().walk().all(is_defaulted_param) {
430                 continue;
431             }
432             let substituted_pred = pred.subst(fcx.tcx, substs);
433             // `skip_binder()` is ok, we're only inspecting for `has_self_ty()`.
434             let substituted_lhs = substituted_pred.skip_binder().self_ty();
435             // In trait defs, don't check `Self: Sized` when `Self` is the default.
436             let pred_is_sized = Some(pred.def_id()) == fcx.tcx.lang_items().sized_trait();
437             if is_trait && substituted_lhs.has_self_ty() && pred_is_sized {
438                 continue;
439             }
440             let pred = ty::Predicate::Trait(pred.subst(fcx.tcx, substs));
441             // Avoid duplicates.
442             if !predicates.predicates.contains(&pred) {
443                 substituted_predicates.push(pred);
444             }
445         }
446
447         predicates.predicates.extend(substituted_predicates);
448         let predicates = predicates.instantiate_identity(fcx.tcx);
449         let predicates = fcx.normalize_associated_types_in(span, &predicates);
450
451         let obligations =
452             predicates.predicates
453                       .iter()
454                       .flat_map(|p| ty::wf::predicate_obligations(fcx,
455                                                                   fcx.param_env,
456                                                                   fcx.body_id,
457                                                                   p,
458                                                                   span));
459
460         for obligation in obligations {
461             fcx.register_predicate(obligation);
462         }
463     }
464
465     fn check_fn_or_method<'fcx, 'tcx>(&mut self,
466                                       fcx: &FnCtxt<'fcx, 'gcx, 'tcx>,
467                                       span: Span,
468                                       sig: ty::PolyFnSig<'tcx>,
469                                       def_id: DefId,
470                                       implied_bounds: &mut Vec<Ty<'tcx>>)
471     {
472         let sig = fcx.normalize_associated_types_in(span, &sig);
473         let sig = fcx.tcx.liberate_late_bound_regions(def_id, &sig);
474
475         for input_ty in sig.inputs() {
476             fcx.register_wf_obligation(&input_ty, span, self.code.clone());
477         }
478         implied_bounds.extend(sig.inputs());
479
480         fcx.register_wf_obligation(sig.output(), span, self.code.clone());
481
482         // FIXME(#25759) return types should not be implied bounds
483         implied_bounds.push(sig.output());
484
485         self.check_where_clauses(fcx, span, def_id);
486     }
487
488     fn check_method_receiver<'fcx, 'tcx>(&mut self,
489                                          fcx: &FnCtxt<'fcx, 'gcx, 'tcx>,
490                                          method_sig: &hir::MethodSig,
491                                          method: &ty::AssociatedItem,
492                                          self_ty: Ty<'tcx>)
493     {
494         // check that the method has a valid receiver type, given the type `Self`
495         debug!("check_method_receiver({:?}, self_ty={:?})",
496                method, self_ty);
497
498         if !method.method_has_self_argument {
499             return;
500         }
501
502         let span = method_sig.decl.inputs[0].span;
503
504         let sig = fcx.tcx.fn_sig(method.def_id);
505         let sig = fcx.normalize_associated_types_in(span, &sig);
506         let sig = fcx.tcx.liberate_late_bound_regions(method.def_id, &sig);
507
508         debug!("check_method_receiver: sig={:?}", sig);
509
510         let self_ty = fcx.normalize_associated_types_in(span, &self_ty);
511         let self_ty = fcx.tcx.liberate_late_bound_regions(
512             method.def_id,
513             &ty::Binder(self_ty)
514         );
515
516         let self_arg_ty = sig.inputs()[0];
517
518         let cause = fcx.cause(span, ObligationCauseCode::MethodReceiver);
519         let self_arg_ty = fcx.normalize_associated_types_in(span, &self_arg_ty);
520         let self_arg_ty = fcx.tcx.liberate_late_bound_regions(
521             method.def_id,
522             &ty::Binder(self_arg_ty)
523         );
524
525         let mut autoderef = fcx.autoderef(span, self_arg_ty).include_raw_pointers();
526
527         loop {
528             if let Some((potential_self_ty, _)) = autoderef.next() {
529                 debug!("check_method_receiver: potential self type `{:?}` to match `{:?}`",
530                     potential_self_ty, self_ty);
531
532                 if fcx.infcx.can_eq(fcx.param_env, self_ty, potential_self_ty).is_ok() {
533                     autoderef.finalize();
534                     if let Some(mut err) = fcx.demand_eqtype_with_origin(
535                         &cause, self_ty, potential_self_ty) {
536                         err.emit();
537                     }
538                     break
539                 }
540             } else {
541                 fcx.tcx.sess.diagnostic().mut_span_err(
542                     span, &format!("invalid `self` type: {:?}", self_arg_ty))
543                 .note(&format!("type must be `{:?}` or a type that dereferences to it`", self_ty))
544                 .help("consider changing to `self`, `&self`, `&mut self`, or `self: Box<Self>`")
545                 .code(DiagnosticId::Error("E0307".into()))
546                 .emit();
547                 return
548             }
549         }
550
551         let is_self_ty = |ty| fcx.infcx.can_eq(fcx.param_env, self_ty, ty).is_ok();
552         let self_kind = ExplicitSelf::determine(self_arg_ty, is_self_ty);
553
554         if !fcx.tcx.sess.features.borrow().arbitrary_self_types {
555             match self_kind {
556                 ExplicitSelf::ByValue |
557                 ExplicitSelf::ByReference(_, _) |
558                 ExplicitSelf::ByBox => (),
559
560                 ExplicitSelf::ByRawPointer(_) => {
561                     feature_gate::feature_err(
562                         &fcx.tcx.sess.parse_sess,
563                         "arbitrary_self_types",
564                         span,
565                         GateIssue::Language,
566                         "raw pointer `self` is unstable")
567                     .help("consider changing to `self`, `&self`, `&mut self`, or `self: Box<Self>`")
568                     .emit();
569                 }
570
571                 ExplicitSelf::Other => {
572                     feature_gate::feature_err(
573                         &fcx.tcx.sess.parse_sess,
574                         "arbitrary_self_types",
575                         span,
576                         GateIssue::Language,"arbitrary `self` types are unstable")
577                     .help("consider changing to `self`, `&self`, `&mut self`, or `self: Box<Self>`")
578                     .emit();
579                 }
580             }
581         }
582     }
583
584     fn check_variances_for_type_defn(&self,
585                                      item: &hir::Item,
586                                      ast_generics: &hir::Generics)
587     {
588         let item_def_id = self.tcx.hir.local_def_id(item.id);
589         let ty = self.tcx.type_of(item_def_id);
590         if self.tcx.has_error_field(ty) {
591             return;
592         }
593
594         let ty_predicates = self.tcx.predicates_of(item_def_id);
595         assert_eq!(ty_predicates.parent, None);
596         let variances = self.tcx.variances_of(item_def_id);
597
598         let mut constrained_parameters: FxHashSet<_> =
599             variances.iter().enumerate()
600                      .filter(|&(_, &variance)| variance != ty::Bivariant)
601                      .map(|(index, _)| Parameter(index as u32))
602                      .collect();
603
604         identify_constrained_type_params(self.tcx,
605                                          ty_predicates.predicates.as_slice(),
606                                          None,
607                                          &mut constrained_parameters);
608
609         for (index, _) in variances.iter().enumerate() {
610             if constrained_parameters.contains(&Parameter(index as u32)) {
611                 continue;
612             }
613
614             let (span, name) = match ast_generics.params[index] {
615                 hir::GenericParam::Lifetime(ref ld) => (ld.lifetime.span, ld.lifetime.name.name()),
616                 hir::GenericParam::Type(ref tp) => (tp.span, tp.name),
617             };
618             self.report_bivariance(span, name);
619         }
620     }
621
622     fn report_bivariance(&self,
623                          span: Span,
624                          param_name: ast::Name)
625     {
626         let mut err = error_392(self.tcx, span, param_name);
627
628         let suggested_marker_id = self.tcx.lang_items().phantom_data();
629         match suggested_marker_id {
630             Some(def_id) => {
631                 err.help(
632                     &format!("consider removing `{}` or using a marker such as `{}`",
633                              param_name,
634                              self.tcx.item_path_str(def_id)));
635             }
636             None => {
637                 // no lang items, no help!
638             }
639         }
640         err.emit();
641     }
642 }
643
644 fn reject_shadowing_type_parameters(tcx: TyCtxt, def_id: DefId) {
645     let generics = tcx.generics_of(def_id);
646     let parent = tcx.generics_of(generics.parent.unwrap());
647     let impl_params: FxHashMap<_, _> = parent.types
648                                        .iter()
649                                        .map(|tp| (tp.name, tp.def_id))
650                                        .collect();
651
652     for method_param in &generics.types {
653         if impl_params.contains_key(&method_param.name) {
654             // Tighten up the span to focus on only the shadowing type
655             let type_span = tcx.def_span(method_param.def_id);
656
657             // The expectation here is that the original trait declaration is
658             // local so it should be okay to just unwrap everything.
659             let trait_def_id = impl_params[&method_param.name];
660             let trait_decl_span = tcx.def_span(trait_def_id);
661             error_194(tcx, type_span, trait_decl_span, method_param.name);
662         }
663     }
664 }
665
666 impl<'a, 'tcx, 'v> Visitor<'v> for CheckTypeWellFormedVisitor<'a, 'tcx> {
667     fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'v> {
668         NestedVisitorMap::None
669     }
670
671     fn visit_item(&mut self, i: &hir::Item) {
672         debug!("visit_item: {:?}", i);
673         self.check_item_well_formed(i);
674         intravisit::walk_item(self, i);
675     }
676
677     fn visit_trait_item(&mut self, trait_item: &'v hir::TraitItem) {
678         debug!("visit_trait_item: {:?}", trait_item);
679         let method_sig = match trait_item.node {
680             hir::TraitItemKind::Method(ref sig, _) => Some(sig),
681             _ => None
682         };
683         self.check_associated_item(trait_item.id, trait_item.span, method_sig);
684         intravisit::walk_trait_item(self, trait_item)
685     }
686
687     fn visit_impl_item(&mut self, impl_item: &'v hir::ImplItem) {
688         debug!("visit_impl_item: {:?}", impl_item);
689         let method_sig = match impl_item.node {
690             hir::ImplItemKind::Method(ref sig, _) => Some(sig),
691             _ => None
692         };
693         self.check_associated_item(impl_item.id, impl_item.span, method_sig);
694         intravisit::walk_impl_item(self, impl_item)
695     }
696 }
697
698 ///////////////////////////////////////////////////////////////////////////
699 // ADT
700
701 struct AdtVariant<'tcx> {
702     fields: Vec<AdtField<'tcx>>,
703 }
704
705 struct AdtField<'tcx> {
706     ty: Ty<'tcx>,
707     span: Span,
708 }
709
710 impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> {
711     fn non_enum_variant(&self, struct_def: &hir::VariantData) -> AdtVariant<'tcx> {
712         let fields =
713             struct_def.fields().iter()
714             .map(|field| {
715                 let field_ty = self.tcx.type_of(self.tcx.hir.local_def_id(field.id));
716                 let field_ty = self.normalize_associated_types_in(field.span,
717                                                                   &field_ty);
718                 AdtField { ty: field_ty, span: field.span }
719             })
720             .collect();
721         AdtVariant { fields: fields }
722     }
723
724     fn enum_variants(&self, enum_def: &hir::EnumDef) -> Vec<AdtVariant<'tcx>> {
725         enum_def.variants.iter()
726             .map(|variant| self.non_enum_variant(&variant.node.data))
727             .collect()
728     }
729
730     fn impl_implied_bounds(&self, impl_def_id: DefId, span: Span) -> Vec<Ty<'tcx>> {
731         match self.tcx.impl_trait_ref(impl_def_id) {
732             Some(ref trait_ref) => {
733                 // Trait impl: take implied bounds from all types that
734                 // appear in the trait reference.
735                 let trait_ref = self.normalize_associated_types_in(span, trait_ref);
736                 trait_ref.substs.types().collect()
737             }
738
739             None => {
740                 // Inherent impl: take implied bounds from the self type.
741                 let self_ty = self.tcx.type_of(impl_def_id);
742                 let self_ty = self.normalize_associated_types_in(span, &self_ty);
743                 vec![self_ty]
744             }
745         }
746     }
747 }
748
749 fn error_392<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, span: Span, param_name: ast::Name)
750                        -> DiagnosticBuilder<'tcx> {
751     let mut err = struct_span_err!(tcx.sess, span, E0392,
752                   "parameter `{}` is never used", param_name);
753     err.span_label(span, "unused type parameter");
754     err
755 }
756
757 fn error_194(tcx: TyCtxt, span: Span, trait_decl_span: Span, name: ast::Name) {
758     struct_span_err!(tcx.sess, span, E0194,
759               "type parameter `{}` shadows another type parameter of the same name",
760               name)
761         .span_label(span, "shadows another type parameter")
762         .span_label(trait_decl_span, format!("first `{}` declared here", name))
763         .emit();
764 }