]> git.lizzy.rs Git - rust.git/blob - src/librustc_typeck/check/wfcheck.rs
Check WF of defaults even when there are no bounds.
[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         
281         self.for_item(item).with_fcx(|fcx, _| {
282             self.check_where_clauses(fcx, item.span, trait_def_id);
283             vec![]
284         });
285     }
286
287     fn check_item_fn(&mut self, item: &hir::Item) {
288         self.for_item(item).with_fcx(|fcx, this| {
289             let def_id = fcx.tcx.hir.local_def_id(item.id);
290             let sig = fcx.tcx.fn_sig(def_id);
291             let sig = fcx.normalize_associated_types_in(item.span, &sig);
292             let mut implied_bounds = vec![];
293             this.check_fn_or_method(fcx, item.span, sig,
294                                     def_id, &mut implied_bounds);
295             implied_bounds
296         })
297     }
298
299     fn check_item_type(&mut self,
300                        item: &hir::Item)
301     {
302         debug!("check_item_type: {:?}", item);
303
304         self.for_item(item).with_fcx(|fcx, this| {
305             let ty = fcx.tcx.type_of(fcx.tcx.hir.local_def_id(item.id));
306             let item_ty = fcx.normalize_associated_types_in(item.span, &ty);
307
308             fcx.register_wf_obligation(item_ty, item.span, this.code.clone());
309
310             vec![] // no implied bounds in a const etc
311         });
312     }
313
314     fn check_impl(&mut self,
315                   item: &hir::Item,
316                   ast_self_ty: &hir::Ty,
317                   ast_trait_ref: &Option<hir::TraitRef>)
318     {
319         debug!("check_impl: {:?}", item);
320
321         self.for_item(item).with_fcx(|fcx, this| {
322             let item_def_id = fcx.tcx.hir.local_def_id(item.id);
323
324             match *ast_trait_ref {
325                 Some(ref ast_trait_ref) => {
326                     let trait_ref = fcx.tcx.impl_trait_ref(item_def_id).unwrap();
327                     let trait_ref =
328                         fcx.normalize_associated_types_in(
329                             ast_trait_ref.path.span, &trait_ref);
330                     let obligations =
331                         ty::wf::trait_obligations(fcx,
332                                                   fcx.param_env,
333                                                   fcx.body_id,
334                                                   &trait_ref,
335                                                   ast_trait_ref.path.span);
336                     for obligation in obligations {
337                         fcx.register_predicate(obligation);
338                     }
339                 }
340                 None => {
341                     let self_ty = fcx.tcx.type_of(item_def_id);
342                     let self_ty = fcx.normalize_associated_types_in(item.span, &self_ty);
343                     fcx.register_wf_obligation(self_ty, ast_self_ty.span, this.code.clone());
344                 }
345             }
346
347             this.check_where_clauses(fcx, item.span, item_def_id);
348
349             fcx.impl_implied_bounds(item_def_id, item.span)
350         });
351     }
352
353     /// Checks where clauses and inline bounds.
354     fn check_where_clauses<'fcx, 'tcx>(&mut self,
355                                        fcx: &FnCtxt<'fcx, 'gcx, 'tcx>,
356                                        span: Span,
357                                        def_id: DefId)
358     {
359         use ty::subst::Subst;
360         use ty::Predicate;
361
362         let generics = self.tcx.generics_of(def_id);
363         let defaults = generics.types.iter().filter_map(|p| match p.has_default {
364                                                                 true => Some(p.def_id),
365                                                                 false => None,
366                                                         });
367         // Defaults must be well-formed.
368         for d in defaults {
369             fcx.register_wf_obligation(fcx.tcx.type_of(d), fcx.tcx.def_span(d), self.code.clone());
370         }
371
372         // Check that each default fulfills the bounds on it's parameter.
373         // We go over each predicate and duplicate it, substituting defaults in the self type.
374         let mut predicates = fcx.tcx.predicates_of(def_id);
375         let mut default_predicates = Vec::new();
376         for pred in &predicates.predicates {
377             let mut self_ty = match pred {
378                 Predicate::Trait(trait_pred) => trait_pred.skip_binder().self_ty(),
379                 Predicate::TypeOutlives(outlives_pred) => (outlives_pred.0).0,
380                 Predicate::Projection(proj_pred) => {
381                     fcx.tcx.mk_ty(ty::TyProjection(proj_pred.skip_binder().projection_ty))
382                 }
383                 // Lifetime params can't have defaults.
384                 Predicate::RegionOutlives(..) => continue,
385                 _ => bug!("Predicate {:?} not supported in where clauses.", pred)
386             };
387
388             let mut skip = false;
389             let mut no_default = true;
390             let substs = ty::subst::Substs::for_item(fcx.tcx, def_id, |def, _| {
391                 // All regions are identity.
392                 fcx.tcx.mk_region(ty::ReEarlyBound(def.to_early_bound_region_data()))
393             }, |def, _| {
394                 // No default or generic comes from parent, identity substitution.
395                 if !def.has_default || (def.index as usize) < generics.parent_count() {
396                     fcx.tcx.mk_param_from_def(def)
397                 } else {
398                     no_default = false;
399                     // Has a default, use it in the substitution.
400                     let default_ty = fcx.tcx.type_of(def.def_id);
401                     // Skip `Self : Self` in traits, it's problematic.
402                     // This means we probably check less than we could.
403                     let should_skip = match self_ty.sty {
404                         ty::TyParam(ref p) => {
405                             // lhs is Self && rhs is Self
406                             p.is_self() && match pred {
407                                 Predicate::Trait(p) => p.def_id() == def_id,
408                                 Predicate::TypeOutlives(_) => false,
409                                 _ => bug!("Unexpected predicate {:?}", pred)
410                             }
411                         }
412                         ty::TyProjection(ref proj) => {
413                             let mut projection = proj;
414                             let mut next_typ = &projection.substs[0].as_type().unwrap().sty;
415                             // Dig through projections.
416                             while let ty::TyProjection(ref proj) = next_typ {
417                                 projection = proj;
418                                 next_typ = &projection.substs[0].as_type().unwrap().sty;
419                             }
420                             let lhs_is_self = match next_typ {
421                                 ty::TyParam(ref p) => p.is_self(),
422                                 _ => false
423                             };
424                             let rhs = fcx.tcx.associated_item(projection.item_def_id)
425                                                      .container
426                                                      .assert_trait();
427                             lhs_is_self && rhs == def_id
428                         }
429                         _ => false
430                     };
431                     skip = skip || should_skip;
432
433                    match default_ty.sty {
434                         // Skip `Self: Sized` when `Self` is the default. Needed in traits.
435                         ty::TyParam(ref p) if p.is_self() => {
436                             if let Predicate::Trait(p) = pred {
437                                 if Some(p.def_id()) == fcx.tcx.lang_items().sized_trait() {
438                                     skip = true;
439                                 }
440                             }
441                         }
442                         _ => ()
443                     }
444                     default_ty
445                 }
446             });
447
448             if skip || no_default {
449                 continue;
450             }
451
452             self_ty = self_ty.subst(fcx.tcx, substs);
453             default_predicates.push(match pred {
454                 Predicate::Trait(trait_pred) => {
455                     let mut substs = trait_pred.skip_binder().trait_ref.substs.to_vec();
456                     substs[0] = self_ty.into();
457                     let substs = fcx.tcx.intern_substs(&substs);
458                     let trait_ref = ty::Binder(ty::TraitRef::new(trait_pred.def_id(), substs));
459                     Predicate::Trait(trait_ref.to_poly_trait_predicate())
460                 }
461                 Predicate::TypeOutlives(pred) => {
462                     Predicate::TypeOutlives(ty::Binder(ty::OutlivesPredicate(self_ty, (pred.0).1)))
463                 }
464                 Predicate::Projection(proj_pred) => {
465                     let projection_ty = match self_ty.sty {
466                         ty::TyProjection(proj_ty) => proj_ty,
467                         _ => bug!("self_ty not projection for projection predicate.")
468                     };
469                     Predicate::Projection(ty::Binder(ty::ProjectionPredicate {
470                                                         projection_ty,
471                                                         ty: proj_pred.ty().skip_binder()
472                                                     }))
473                 }
474                 _ => bug!("Predicate {:?} not supported for type params.", pred)
475             });
476         }
477
478         predicates.predicates.extend(default_predicates);
479         let predicates = predicates.instantiate_identity(fcx.tcx);
480         let predicates = fcx.normalize_associated_types_in(span, &predicates);
481
482         let obligations =
483             predicates.predicates
484                       .iter()
485                       .flat_map(|p| ty::wf::predicate_obligations(fcx,
486                                                                   fcx.param_env,
487                                                                   fcx.body_id,
488                                                                   p,
489                                                                   span));
490
491         for obligation in obligations {
492             fcx.register_predicate(obligation);
493         }
494     }
495
496     fn check_fn_or_method<'fcx, 'tcx>(&mut self,
497                                       fcx: &FnCtxt<'fcx, 'gcx, 'tcx>,
498                                       span: Span,
499                                       sig: ty::PolyFnSig<'tcx>,
500                                       def_id: DefId,
501                                       implied_bounds: &mut Vec<Ty<'tcx>>)
502     {
503         let sig = fcx.normalize_associated_types_in(span, &sig);
504         let sig = fcx.tcx.liberate_late_bound_regions(def_id, &sig);
505
506         for input_ty in sig.inputs() {
507             fcx.register_wf_obligation(&input_ty, span, self.code.clone());
508         }
509         implied_bounds.extend(sig.inputs());
510
511         fcx.register_wf_obligation(sig.output(), span, self.code.clone());
512
513         // FIXME(#25759) return types should not be implied bounds
514         implied_bounds.push(sig.output());
515
516         self.check_where_clauses(fcx, span, def_id);
517     }
518
519     fn check_method_receiver<'fcx, 'tcx>(&mut self,
520                                          fcx: &FnCtxt<'fcx, 'gcx, 'tcx>,
521                                          method_sig: &hir::MethodSig,
522                                          method: &ty::AssociatedItem,
523                                          self_ty: Ty<'tcx>)
524     {
525         // check that the method has a valid receiver type, given the type `Self`
526         debug!("check_method_receiver({:?}, self_ty={:?})",
527                method, self_ty);
528
529         if !method.method_has_self_argument {
530             return;
531         }
532
533         let span = method_sig.decl.inputs[0].span;
534
535         let sig = fcx.tcx.fn_sig(method.def_id);
536         let sig = fcx.normalize_associated_types_in(span, &sig);
537         let sig = fcx.tcx.liberate_late_bound_regions(method.def_id, &sig);
538
539         debug!("check_method_receiver: sig={:?}", sig);
540
541         let self_ty = fcx.normalize_associated_types_in(span, &self_ty);
542         let self_ty = fcx.tcx.liberate_late_bound_regions(
543             method.def_id,
544             &ty::Binder(self_ty)
545         );
546
547         let self_arg_ty = sig.inputs()[0];
548
549         let cause = fcx.cause(span, ObligationCauseCode::MethodReceiver);
550         let self_arg_ty = fcx.normalize_associated_types_in(span, &self_arg_ty);
551         let self_arg_ty = fcx.tcx.liberate_late_bound_regions(
552             method.def_id,
553             &ty::Binder(self_arg_ty)
554         );
555
556         let mut autoderef = fcx.autoderef(span, self_arg_ty).include_raw_pointers();
557
558         loop {
559             if let Some((potential_self_ty, _)) = autoderef.next() {
560                 debug!("check_method_receiver: potential self type `{:?}` to match `{:?}`",
561                     potential_self_ty, self_ty);
562
563                 if fcx.infcx.can_eq(fcx.param_env, self_ty, potential_self_ty).is_ok() {
564                     autoderef.finalize();
565                     if let Some(mut err) = fcx.demand_eqtype_with_origin(
566                         &cause, self_ty, potential_self_ty) {
567                         err.emit();
568                     }
569                     break
570                 }
571             } else {
572                 fcx.tcx.sess.diagnostic().mut_span_err(
573                     span, &format!("invalid `self` type: {:?}", self_arg_ty))
574                 .note(&format!("type must be `{:?}` or a type that dereferences to it`", self_ty))
575                 .help("consider changing to `self`, `&self`, `&mut self`, or `self: Box<Self>`")
576                 .code(DiagnosticId::Error("E0307".into()))
577                 .emit();
578                 return
579             }
580         }
581
582         let is_self_ty = |ty| fcx.infcx.can_eq(fcx.param_env, self_ty, ty).is_ok();
583         let self_kind = ExplicitSelf::determine(self_arg_ty, is_self_ty);
584
585         if !fcx.tcx.sess.features.borrow().arbitrary_self_types {
586             match self_kind {
587                 ExplicitSelf::ByValue |
588                 ExplicitSelf::ByReference(_, _) |
589                 ExplicitSelf::ByBox => (),
590
591                 ExplicitSelf::ByRawPointer(_) => {
592                     feature_gate::feature_err(
593                         &fcx.tcx.sess.parse_sess,
594                         "arbitrary_self_types",
595                         span,
596                         GateIssue::Language,
597                         "raw pointer `self` is unstable")
598                     .help("consider changing to `self`, `&self`, `&mut self`, or `self: Box<Self>`")
599                     .emit();
600                 }
601
602                 ExplicitSelf::Other => {
603                     feature_gate::feature_err(
604                         &fcx.tcx.sess.parse_sess,
605                         "arbitrary_self_types",
606                         span,
607                         GateIssue::Language,"arbitrary `self` types are unstable")
608                     .help("consider changing to `self`, `&self`, `&mut self`, or `self: Box<Self>`")
609                     .emit();
610                 }
611             }
612         }
613     }
614
615     fn check_variances_for_type_defn(&self,
616                                      item: &hir::Item,
617                                      ast_generics: &hir::Generics)
618     {
619         let item_def_id = self.tcx.hir.local_def_id(item.id);
620         let ty = self.tcx.type_of(item_def_id);
621         if self.tcx.has_error_field(ty) {
622             return;
623         }
624
625         let ty_predicates = self.tcx.predicates_of(item_def_id);
626         assert_eq!(ty_predicates.parent, None);
627         let variances = self.tcx.variances_of(item_def_id);
628
629         let mut constrained_parameters: FxHashSet<_> =
630             variances.iter().enumerate()
631                      .filter(|&(_, &variance)| variance != ty::Bivariant)
632                      .map(|(index, _)| Parameter(index as u32))
633                      .collect();
634
635         identify_constrained_type_params(self.tcx,
636                                          ty_predicates.predicates.as_slice(),
637                                          None,
638                                          &mut constrained_parameters);
639
640         for (index, _) in variances.iter().enumerate() {
641             if constrained_parameters.contains(&Parameter(index as u32)) {
642                 continue;
643             }
644
645             let (span, name) = match ast_generics.params[index] {
646                 hir::GenericParam::Lifetime(ref ld) => (ld.lifetime.span, ld.lifetime.name.name()),
647                 hir::GenericParam::Type(ref tp) => (tp.span, tp.name),
648             };
649             self.report_bivariance(span, name);
650         }
651     }
652
653     fn report_bivariance(&self,
654                          span: Span,
655                          param_name: ast::Name)
656     {
657         let mut err = error_392(self.tcx, span, param_name);
658
659         let suggested_marker_id = self.tcx.lang_items().phantom_data();
660         match suggested_marker_id {
661             Some(def_id) => {
662                 err.help(
663                     &format!("consider removing `{}` or using a marker such as `{}`",
664                              param_name,
665                              self.tcx.item_path_str(def_id)));
666             }
667             None => {
668                 // no lang items, no help!
669             }
670         }
671         err.emit();
672     }
673 }
674
675 fn reject_shadowing_type_parameters(tcx: TyCtxt, def_id: DefId) {
676     let generics = tcx.generics_of(def_id);
677     let parent = tcx.generics_of(generics.parent.unwrap());
678     let impl_params: FxHashMap<_, _> = parent.types
679                                        .iter()
680                                        .map(|tp| (tp.name, tp.def_id))
681                                        .collect();
682
683     for method_param in &generics.types {
684         if impl_params.contains_key(&method_param.name) {
685             // Tighten up the span to focus on only the shadowing type
686             let type_span = tcx.def_span(method_param.def_id);
687
688             // The expectation here is that the original trait declaration is
689             // local so it should be okay to just unwrap everything.
690             let trait_def_id = impl_params[&method_param.name];
691             let trait_decl_span = tcx.def_span(trait_def_id);
692             error_194(tcx, type_span, trait_decl_span, method_param.name);
693         }
694     }
695 }
696
697 impl<'a, 'tcx, 'v> Visitor<'v> for CheckTypeWellFormedVisitor<'a, 'tcx> {
698     fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'v> {
699         NestedVisitorMap::None
700     }
701
702     fn visit_item(&mut self, i: &hir::Item) {
703         debug!("visit_item: {:?}", i);
704         self.check_item_well_formed(i);
705         intravisit::walk_item(self, i);
706     }
707
708     fn visit_trait_item(&mut self, trait_item: &'v hir::TraitItem) {
709         debug!("visit_trait_item: {:?}", trait_item);
710         let method_sig = match trait_item.node {
711             hir::TraitItemKind::Method(ref sig, _) => Some(sig),
712             _ => None
713         };
714         self.check_associated_item(trait_item.id, trait_item.span, method_sig);
715         intravisit::walk_trait_item(self, trait_item)
716     }
717
718     fn visit_impl_item(&mut self, impl_item: &'v hir::ImplItem) {
719         debug!("visit_impl_item: {:?}", impl_item);
720         let method_sig = match impl_item.node {
721             hir::ImplItemKind::Method(ref sig, _) => Some(sig),
722             _ => None
723         };
724         self.check_associated_item(impl_item.id, impl_item.span, method_sig);
725         intravisit::walk_impl_item(self, impl_item)
726     }
727 }
728
729 ///////////////////////////////////////////////////////////////////////////
730 // ADT
731
732 struct AdtVariant<'tcx> {
733     fields: Vec<AdtField<'tcx>>,
734 }
735
736 struct AdtField<'tcx> {
737     ty: Ty<'tcx>,
738     span: Span,
739 }
740
741 impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> {
742     fn non_enum_variant(&self, struct_def: &hir::VariantData) -> AdtVariant<'tcx> {
743         let fields =
744             struct_def.fields().iter()
745             .map(|field| {
746                 let field_ty = self.tcx.type_of(self.tcx.hir.local_def_id(field.id));
747                 let field_ty = self.normalize_associated_types_in(field.span,
748                                                                   &field_ty);
749                 AdtField { ty: field_ty, span: field.span }
750             })
751             .collect();
752         AdtVariant { fields: fields }
753     }
754
755     fn enum_variants(&self, enum_def: &hir::EnumDef) -> Vec<AdtVariant<'tcx>> {
756         enum_def.variants.iter()
757             .map(|variant| self.non_enum_variant(&variant.node.data))
758             .collect()
759     }
760
761     fn impl_implied_bounds(&self, impl_def_id: DefId, span: Span) -> Vec<Ty<'tcx>> {
762         match self.tcx.impl_trait_ref(impl_def_id) {
763             Some(ref trait_ref) => {
764                 // Trait impl: take implied bounds from all types that
765                 // appear in the trait reference.
766                 let trait_ref = self.normalize_associated_types_in(span, trait_ref);
767                 trait_ref.substs.types().collect()
768             }
769
770             None => {
771                 // Inherent impl: take implied bounds from the self type.
772                 let self_ty = self.tcx.type_of(impl_def_id);
773                 let self_ty = self.normalize_associated_types_in(span, &self_ty);
774                 vec![self_ty]
775             }
776         }
777     }
778 }
779
780 fn error_392<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, span: Span, param_name: ast::Name)
781                        -> DiagnosticBuilder<'tcx> {
782     let mut err = struct_span_err!(tcx.sess, span, E0392,
783                   "parameter `{}` is never used", param_name);
784     err.span_label(span, "unused type parameter");
785     err
786 }
787
788 fn error_194(tcx: TyCtxt, span: Span, trait_decl_span: Span, name: ast::Name) {
789     struct_span_err!(tcx.sess, span, E0194,
790               "type parameter `{}` shadows another type parameter of the same name",
791               name)
792         .span_label(span, "shadows another type parameter")
793         .span_label(trait_decl_span, format!("first `{}` declared here", name))
794         .emit();
795 }