]> git.lizzy.rs Git - rust.git/blob - src/librustc_typeck/check/wfcheck.rs
support `default impl` for specialization
[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                     let predicates = fcx.tcx.predicates_of(item.def_id)
189                         .instantiate_identity(fcx.tcx);
190                     let predicates = fcx.normalize_associated_types_in(span, &predicates);
191                     this.check_fn_or_method(fcx, span, sig, &predicates,
192                                             item.def_id, &mut implied_bounds);
193                     let sig_if_method = sig_if_method.expect("bad signature for method");
194                     this.check_method_receiver(fcx, sig_if_method, &item, self_ty);
195                 }
196                 ty::AssociatedKind::Type => {
197                     if item.defaultness.has_value() {
198                         let ty = fcx.tcx.type_of(item.def_id);
199                         let ty = fcx.normalize_associated_types_in(span, &ty);
200                         fcx.register_wf_obligation(ty, span, code.clone());
201                     }
202                 }
203             }
204
205             implied_bounds
206         })
207     }
208
209     fn for_item<'tcx>(&self, item: &hir::Item)
210                       -> CheckWfFcxBuilder<'a, 'gcx, 'tcx> {
211         self.for_id(item.id, item.span)
212     }
213
214     fn for_id<'tcx>(&self, id: ast::NodeId, span: Span)
215                     -> CheckWfFcxBuilder<'a, 'gcx, 'tcx> {
216         let def_id = self.tcx.hir.local_def_id(id);
217         CheckWfFcxBuilder {
218             inherited: Inherited::build(self.tcx, def_id),
219             code: self.code.clone(),
220             id,
221             span,
222             param_env: self.tcx.param_env(def_id),
223         }
224     }
225
226     /// In a type definition, we check that to ensure that the types of the fields are well-formed.
227     fn check_type_defn<F>(&mut self, item: &hir::Item, all_sized: bool, mut lookup_fields: F)
228         where F: for<'fcx, 'tcx> FnMut(&FnCtxt<'fcx, 'gcx, 'tcx>) -> Vec<AdtVariant<'tcx>>
229     {
230         self.for_item(item).with_fcx(|fcx, this| {
231             let variants = lookup_fields(fcx);
232             let def_id = fcx.tcx.hir.local_def_id(item.id);
233             let packed = fcx.tcx.adt_def(def_id).repr.packed();
234
235             for variant in &variants {
236                 // For DST, or when drop needs to copy things around, all
237                 // intermediate types must be sized.
238                 let needs_drop_copy = || {
239                     packed && {
240                         let ty = variant.fields.last().unwrap().ty;
241                         let ty = fcx.tcx.erase_regions(&ty).lift_to_tcx(this.tcx)
242                             .unwrap_or_else(|| {
243                                 span_bug!(item.span, "inference variables in {:?}", ty)
244                             });
245                         ty.needs_drop(this.tcx, this.tcx.param_env(def_id))
246                     }
247                 };
248                 let unsized_len = if
249                     all_sized ||
250                     variant.fields.is_empty() ||
251                     needs_drop_copy()
252                 {
253                     0
254                 } else {
255                     1
256                 };
257                 for field in &variant.fields[..variant.fields.len() - unsized_len] {
258                     fcx.register_bound(
259                         field.ty,
260                         fcx.tcx.require_lang_item(lang_items::SizedTraitLangItem),
261                         traits::ObligationCause::new(field.span,
262                                                      fcx.body_id,
263                                                      traits::FieldSized(match item.node.adt_kind() {
264                                                         Some(i) => i,
265                                                         None => bug!(),
266                                                      })));
267                 }
268
269                 // All field types must be well-formed.
270                 for field in &variant.fields {
271                     fcx.register_wf_obligation(field.ty, field.span, this.code.clone())
272                 }
273             }
274
275             let predicates = fcx.tcx.predicates_of(def_id).instantiate_identity(fcx.tcx);
276             let predicates = fcx.normalize_associated_types_in(item.span, &predicates);
277             this.check_where_clauses(fcx, item.span, &predicates);
278
279             vec![] // no implied bounds in a struct def'n
280         });
281     }
282
283     fn check_trait(&mut self, item: &hir::Item) {
284         let trait_def_id = self.tcx.hir.local_def_id(item.id);
285         self.for_item(item).with_fcx(|fcx, this| {
286             let predicates = fcx.tcx.predicates_of(trait_def_id).instantiate_identity(fcx.tcx);
287             let predicates = fcx.normalize_associated_types_in(item.span, &predicates);
288             this.check_where_clauses(fcx, item.span, &predicates);
289             vec![]
290         });
291     }
292
293     fn check_item_fn(&mut self, item: &hir::Item) {
294         self.for_item(item).with_fcx(|fcx, this| {
295             let def_id = fcx.tcx.hir.local_def_id(item.id);
296             let sig = fcx.tcx.fn_sig(def_id);
297             let sig = fcx.normalize_associated_types_in(item.span, &sig);
298
299             let predicates = fcx.tcx.predicates_of(def_id).instantiate_identity(fcx.tcx);
300             let predicates = fcx.normalize_associated_types_in(item.span, &predicates);
301
302             let mut implied_bounds = vec![];
303             this.check_fn_or_method(fcx, item.span, sig, &predicates,
304                                     def_id, &mut implied_bounds);
305             implied_bounds
306         })
307     }
308
309     fn check_item_type(&mut self,
310                        item: &hir::Item)
311     {
312         debug!("check_item_type: {:?}", item);
313
314         self.for_item(item).with_fcx(|fcx, this| {
315             let ty = fcx.tcx.type_of(fcx.tcx.hir.local_def_id(item.id));
316             let item_ty = fcx.normalize_associated_types_in(item.span, &ty);
317
318             fcx.register_wf_obligation(item_ty, item.span, this.code.clone());
319
320             vec![] // no implied bounds in a const etc
321         });
322     }
323
324     fn check_impl(&mut self,
325                   item: &hir::Item,
326                   ast_self_ty: &hir::Ty,
327                   ast_trait_ref: &Option<hir::TraitRef>)
328     {
329         debug!("check_impl: {:?}", item);
330
331         self.for_item(item).with_fcx(|fcx, this| {
332             let item_def_id = fcx.tcx.hir.local_def_id(item.id);
333
334             match *ast_trait_ref {
335                 Some(ref ast_trait_ref) => {
336                     let trait_ref = fcx.tcx.impl_trait_ref(item_def_id).unwrap();
337                     let trait_ref =
338                         fcx.normalize_associated_types_in(
339                             ast_trait_ref.path.span, &trait_ref);
340                     let obligations =
341                         ty::wf::trait_obligations(fcx,
342                                                   fcx.param_env,
343                                                   fcx.body_id,
344                                                   &trait_ref,
345                                                   ast_trait_ref.path.span);
346
347                     // not registering predicates associcated with a `default impl`
348                     let impl_is_default = fcx.tcx.impl_is_default(item_def_id);
349                     for obligation in obligations {
350                         let register = match obligation.predicate {
351                             ty::Predicate::Trait(..)  => !impl_is_default,
352                             _ => true
353                         };
354
355                         if register {
356                             fcx.register_predicate(obligation);
357                         }
358                     }
359                 }
360                 None => {
361                     let self_ty = fcx.tcx.type_of(item_def_id);
362                     let self_ty = fcx.normalize_associated_types_in(item.span, &self_ty);
363                     fcx.register_wf_obligation(self_ty, ast_self_ty.span, this.code.clone());
364                 }
365             }
366
367             let predicates = fcx.tcx.predicates_of(item_def_id).instantiate_identity(fcx.tcx);
368             let predicates = fcx.normalize_associated_types_in(item.span, &predicates);
369             this.check_where_clauses(fcx, item.span, &predicates);
370
371             fcx.impl_implied_bounds(item_def_id, item.span)
372         });
373     }
374
375     fn check_where_clauses<'fcx, 'tcx>(&mut self,
376                                        fcx: &FnCtxt<'fcx, 'gcx, 'tcx>,
377                                        span: Span,
378                                        predicates: &ty::InstantiatedPredicates<'tcx>)
379     {
380         let obligations =
381             predicates.predicates
382                       .iter()
383                       .flat_map(|p| ty::wf::predicate_obligations(fcx,
384                                                                   fcx.param_env,
385                                                                   fcx.body_id,
386                                                                   p,
387                                                                   span));
388
389         for obligation in obligations {
390             fcx.register_predicate(obligation);
391         }
392     }
393
394     fn check_fn_or_method<'fcx, 'tcx>(&mut self,
395                                       fcx: &FnCtxt<'fcx, 'gcx, 'tcx>,
396                                       span: Span,
397                                       sig: ty::PolyFnSig<'tcx>,
398                                       predicates: &ty::InstantiatedPredicates<'tcx>,
399                                       def_id: DefId,
400                                       implied_bounds: &mut Vec<Ty<'tcx>>)
401     {
402         let sig = fcx.normalize_associated_types_in(span, &sig);
403         let sig = fcx.tcx.liberate_late_bound_regions(def_id, &sig);
404
405         for input_ty in sig.inputs() {
406             fcx.register_wf_obligation(&input_ty, span, self.code.clone());
407         }
408         implied_bounds.extend(sig.inputs());
409
410         fcx.register_wf_obligation(sig.output(), span, self.code.clone());
411
412         // FIXME(#25759) return types should not be implied bounds
413         implied_bounds.push(sig.output());
414
415         self.check_where_clauses(fcx, span, predicates);
416     }
417
418     fn check_method_receiver<'fcx, 'tcx>(&mut self,
419                                          fcx: &FnCtxt<'fcx, 'gcx, 'tcx>,
420                                          method_sig: &hir::MethodSig,
421                                          method: &ty::AssociatedItem,
422                                          self_ty: Ty<'tcx>)
423     {
424         // check that the method has a valid receiver type, given the type `Self`
425         debug!("check_method_receiver({:?}, self_ty={:?})",
426                method, self_ty);
427
428         if !method.method_has_self_argument {
429             return;
430         }
431
432         let span = method_sig.decl.inputs[0].span;
433
434         let sig = fcx.tcx.fn_sig(method.def_id);
435         let sig = fcx.normalize_associated_types_in(span, &sig);
436         let sig = fcx.tcx.liberate_late_bound_regions(method.def_id, &sig);
437
438         debug!("check_method_receiver: sig={:?}", sig);
439
440         let self_ty = fcx.normalize_associated_types_in(span, &self_ty);
441         let self_ty = fcx.tcx.liberate_late_bound_regions(
442             method.def_id,
443             &ty::Binder(self_ty)
444         );
445
446         let self_arg_ty = sig.inputs()[0];
447
448         let cause = fcx.cause(span, ObligationCauseCode::MethodReceiver);
449         let self_arg_ty = fcx.normalize_associated_types_in(span, &self_arg_ty);
450         let self_arg_ty = fcx.tcx.liberate_late_bound_regions(
451             method.def_id,
452             &ty::Binder(self_arg_ty)
453         );
454
455         let mut autoderef = fcx.autoderef(span, self_arg_ty).include_raw_pointers();
456
457         loop {
458             if let Some((potential_self_ty, _)) = autoderef.next() {
459                 debug!("check_method_receiver: potential self type `{:?}` to match `{:?}`",
460                     potential_self_ty, self_ty);
461
462                 if fcx.infcx.can_eq(fcx.param_env, self_ty, potential_self_ty).is_ok() {
463                     autoderef.finalize();
464                     if let Some(mut err) = fcx.demand_eqtype_with_origin(
465                         &cause, self_ty, potential_self_ty) {
466                         err.emit();
467                     }
468                     break
469                 }
470             } else {
471                 fcx.tcx.sess.diagnostic().mut_span_err(
472                     span, &format!("invalid `self` type: {:?}", self_arg_ty))
473                 .note(&format!("type must be `{:?}` or a type that dereferences to it`", self_ty))
474                 .help("consider changing to `self`, `&self`, `&mut self`, or `self: Box<Self>`")
475                 .code(DiagnosticId::Error("E0307".into()))
476                 .emit();
477                 return
478             }
479         }
480
481         let is_self_ty = |ty| fcx.infcx.can_eq(fcx.param_env, self_ty, ty).is_ok();
482         let self_kind = ExplicitSelf::determine(self_arg_ty, is_self_ty);
483
484         if !fcx.tcx.sess.features.borrow().arbitrary_self_types {
485             match self_kind {
486                 ExplicitSelf::ByValue |
487                 ExplicitSelf::ByReference(_, _) |
488                 ExplicitSelf::ByBox => (),
489
490                 ExplicitSelf::ByRawPointer(_) => {
491                     feature_gate::feature_err(
492                         &fcx.tcx.sess.parse_sess,
493                         "arbitrary_self_types",
494                         span,
495                         GateIssue::Language,
496                         "raw pointer `self` is unstable")
497                     .help("consider changing to `self`, `&self`, `&mut self`, or `self: Box<Self>`")
498                     .emit();
499                 }
500
501                 ExplicitSelf::Other => {
502                     feature_gate::feature_err(
503                         &fcx.tcx.sess.parse_sess,
504                         "arbitrary_self_types",
505                         span,
506                         GateIssue::Language,"arbitrary `self` types are unstable")
507                     .help("consider changing to `self`, `&self`, `&mut self`, or `self: Box<Self>`")
508                     .emit();
509                 }
510             }
511         }
512     }
513
514     fn check_variances_for_type_defn(&self,
515                                      item: &hir::Item,
516                                      ast_generics: &hir::Generics)
517     {
518         let item_def_id = self.tcx.hir.local_def_id(item.id);
519         let ty = self.tcx.type_of(item_def_id);
520         if self.tcx.has_error_field(ty) {
521             return;
522         }
523
524         let ty_predicates = self.tcx.predicates_of(item_def_id);
525         assert_eq!(ty_predicates.parent, None);
526         let variances = self.tcx.variances_of(item_def_id);
527
528         let mut constrained_parameters: FxHashSet<_> =
529             variances.iter().enumerate()
530                      .filter(|&(_, &variance)| variance != ty::Bivariant)
531                      .map(|(index, _)| Parameter(index as u32))
532                      .collect();
533
534         identify_constrained_type_params(self.tcx,
535                                          ty_predicates.predicates.as_slice(),
536                                          None,
537                                          &mut constrained_parameters);
538
539         for (index, _) in variances.iter().enumerate() {
540             if constrained_parameters.contains(&Parameter(index as u32)) {
541                 continue;
542             }
543
544             let (span, name) = match ast_generics.params[index] {
545                 hir::GenericParam::Lifetime(ref ld) => (ld.lifetime.span, ld.lifetime.name.name()),
546                 hir::GenericParam::Type(ref tp) => (tp.span, tp.name),
547             };
548             self.report_bivariance(span, name);
549         }
550     }
551
552     fn report_bivariance(&self,
553                          span: Span,
554                          param_name: ast::Name)
555     {
556         let mut err = error_392(self.tcx, span, param_name);
557
558         let suggested_marker_id = self.tcx.lang_items().phantom_data();
559         match suggested_marker_id {
560             Some(def_id) => {
561                 err.help(
562                     &format!("consider removing `{}` or using a marker such as `{}`",
563                              param_name,
564                              self.tcx.item_path_str(def_id)));
565             }
566             None => {
567                 // no lang items, no help!
568             }
569         }
570         err.emit();
571     }
572 }
573
574 fn reject_shadowing_type_parameters(tcx: TyCtxt, def_id: DefId) {
575     let generics = tcx.generics_of(def_id);
576     let parent = tcx.generics_of(generics.parent.unwrap());
577     let impl_params: FxHashMap<_, _> = parent.types
578                                        .iter()
579                                        .map(|tp| (tp.name, tp.def_id))
580                                        .collect();
581
582     for method_param in &generics.types {
583         if impl_params.contains_key(&method_param.name) {
584             // Tighten up the span to focus on only the shadowing type
585             let type_span = tcx.def_span(method_param.def_id);
586
587             // The expectation here is that the original trait declaration is
588             // local so it should be okay to just unwrap everything.
589             let trait_def_id = impl_params[&method_param.name];
590             let trait_decl_span = tcx.def_span(trait_def_id);
591             error_194(tcx, type_span, trait_decl_span, method_param.name);
592         }
593     }
594 }
595
596 impl<'a, 'tcx, 'v> Visitor<'v> for CheckTypeWellFormedVisitor<'a, 'tcx> {
597     fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'v> {
598         NestedVisitorMap::None
599     }
600
601     fn visit_item(&mut self, i: &hir::Item) {
602         debug!("visit_item: {:?}", i);
603         self.check_item_well_formed(i);
604         intravisit::walk_item(self, i);
605     }
606
607     fn visit_trait_item(&mut self, trait_item: &'v hir::TraitItem) {
608         debug!("visit_trait_item: {:?}", trait_item);
609         let method_sig = match trait_item.node {
610             hir::TraitItemKind::Method(ref sig, _) => Some(sig),
611             _ => None
612         };
613         self.check_associated_item(trait_item.id, trait_item.span, method_sig);
614         intravisit::walk_trait_item(self, trait_item)
615     }
616
617     fn visit_impl_item(&mut self, impl_item: &'v hir::ImplItem) {
618         debug!("visit_impl_item: {:?}", impl_item);
619         let method_sig = match impl_item.node {
620             hir::ImplItemKind::Method(ref sig, _) => Some(sig),
621             _ => None
622         };
623         self.check_associated_item(impl_item.id, impl_item.span, method_sig);
624         intravisit::walk_impl_item(self, impl_item)
625     }
626 }
627
628 ///////////////////////////////////////////////////////////////////////////
629 // ADT
630
631 struct AdtVariant<'tcx> {
632     fields: Vec<AdtField<'tcx>>,
633 }
634
635 struct AdtField<'tcx> {
636     ty: Ty<'tcx>,
637     span: Span,
638 }
639
640 impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> {
641     fn non_enum_variant(&self, struct_def: &hir::VariantData) -> AdtVariant<'tcx> {
642         let fields =
643             struct_def.fields().iter()
644             .map(|field| {
645                 let field_ty = self.tcx.type_of(self.tcx.hir.local_def_id(field.id));
646                 let field_ty = self.normalize_associated_types_in(field.span,
647                                                                   &field_ty);
648                 AdtField { ty: field_ty, span: field.span }
649             })
650             .collect();
651         AdtVariant { fields: fields }
652     }
653
654     fn enum_variants(&self, enum_def: &hir::EnumDef) -> Vec<AdtVariant<'tcx>> {
655         enum_def.variants.iter()
656             .map(|variant| self.non_enum_variant(&variant.node.data))
657             .collect()
658     }
659
660     fn impl_implied_bounds(&self, impl_def_id: DefId, span: Span) -> Vec<Ty<'tcx>> {
661         match self.tcx.impl_trait_ref(impl_def_id) {
662             Some(ref trait_ref) => {
663                 // Trait impl: take implied bounds from all types that
664                 // appear in the trait reference.
665                 let trait_ref = self.normalize_associated_types_in(span, trait_ref);
666                 trait_ref.substs.types().collect()
667             }
668
669             None => {
670                 // Inherent impl: take implied bounds from the self type.
671                 let self_ty = self.tcx.type_of(impl_def_id);
672                 let self_ty = self.normalize_associated_types_in(span, &self_ty);
673                 vec![self_ty]
674             }
675         }
676     }
677 }
678
679 fn error_392<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, span: Span, param_name: ast::Name)
680                        -> DiagnosticBuilder<'tcx> {
681     let mut err = struct_span_err!(tcx.sess, span, E0392,
682                   "parameter `{}` is never used", param_name);
683     err.span_label(span, "unused type parameter");
684     err
685 }
686
687 fn error_194(tcx: TyCtxt, span: Span, trait_decl_span: Span, name: ast::Name) {
688     struct_span_err!(tcx.sess, span, E0194,
689               "type parameter `{}` shadows another type parameter of the same name",
690               name)
691         .span_label(span, "shadows another type parameter")
692         .span_label(trait_decl_span, format!("first `{}` declared here", name))
693         .emit();
694 }