]> git.lizzy.rs Git - rust.git/blob - src/librustc_typeck/check/wfcheck.rs
Auto merge of #42394 - ollie27:rustdoc_deref_box, r=QuietMisdreavus
[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 astconv::ExplicitSelf;
12 use check::{Inherited, FnCtxt};
13 use constrained_type_params::{identify_constrained_type_params, Parameter};
14
15 use hir::def_id::DefId;
16 use rustc::traits::{self, ObligationCauseCode};
17 use rustc::ty::{self, Ty, TyCtxt};
18 use rustc::util::nodemap::{FxHashSet, FxHashMap};
19 use rustc::middle::lang_items;
20
21 use syntax::ast;
22 use syntax_pos::Span;
23 use errors::DiagnosticBuilder;
24
25 use rustc::hir::intravisit::{self, Visitor, NestedVisitorMap};
26 use rustc::hir;
27
28 pub struct CheckTypeWellFormedVisitor<'a, 'tcx:'a> {
29     tcx: TyCtxt<'a, 'tcx, 'tcx>,
30     code: ObligationCauseCode<'tcx>,
31 }
32
33 /// Helper type of a temporary returned by .for_item(...).
34 /// Necessary because we can't write the following bound:
35 /// F: for<'b, 'tcx> where 'gcx: 'tcx FnOnce(FnCtxt<'b, 'gcx, 'tcx>).
36 struct CheckWfFcxBuilder<'a, 'gcx: 'a+'tcx, 'tcx: 'a> {
37     inherited: super::InheritedBuilder<'a, 'gcx, 'tcx>,
38     code: ObligationCauseCode<'gcx>,
39     id: ast::NodeId,
40     span: Span,
41     param_env: ty::ParamEnv<'tcx>,
42 }
43
44 impl<'a, 'gcx, 'tcx> CheckWfFcxBuilder<'a, 'gcx, 'tcx> {
45     fn with_fcx<F>(&'tcx mut self, f: F) where
46         F: for<'b> FnOnce(&FnCtxt<'b, 'gcx, 'tcx>,
47                           &mut CheckTypeWellFormedVisitor<'b, 'gcx>) -> Vec<Ty<'tcx>>
48     {
49         let code = self.code.clone();
50         let id = self.id;
51         let span = self.span;
52         let param_env = self.param_env;
53         self.inherited.enter(|inh| {
54             let fcx = FnCtxt::new(&inh, param_env, id);
55             let wf_tys = f(&fcx, &mut CheckTypeWellFormedVisitor {
56                 tcx: fcx.tcx.global_tcx(),
57                 code: code
58             });
59             fcx.select_all_obligations_or_error();
60             fcx.regionck_item(id, span, &wf_tys);
61         });
62     }
63 }
64
65 impl<'a, 'gcx> CheckTypeWellFormedVisitor<'a, 'gcx> {
66     pub fn new(tcx: TyCtxt<'a, 'gcx, 'gcx>)
67                -> CheckTypeWellFormedVisitor<'a, 'gcx> {
68         CheckTypeWellFormedVisitor {
69             tcx: tcx,
70             code: ObligationCauseCode::MiscObligation
71         }
72     }
73
74     /// Checks that the field types (in a struct def'n) or argument types (in an enum def'n) are
75     /// well-formed, meaning that they do not require any constraints not declared in the struct
76     /// definition itself. For example, this definition would be illegal:
77     ///
78     ///     struct Ref<'a, T> { x: &'a T }
79     ///
80     /// because the type did not declare that `T:'a`.
81     ///
82     /// We do this check as a pre-pass before checking fn bodies because if these constraints are
83     /// not included it frequently leads to confusing errors in fn bodies. So it's better to check
84     /// the types first.
85     fn check_item_well_formed(&mut self, item: &hir::Item) {
86         let tcx = self.tcx;
87         debug!("check_item_well_formed(it.id={}, it.name={})",
88                item.id,
89                tcx.item_path_str(tcx.hir.local_def_id(item.id)));
90
91         match item.node {
92             /// Right now we check that every default trait implementation
93             /// has an implementation of itself. Basically, a case like:
94             ///
95             /// `impl Trait for T {}`
96             ///
97             /// has a requirement of `T: Trait` which was required for default
98             /// method implementations. Although this could be improved now that
99             /// there's a better infrastructure in place for this, it's being left
100             /// for a follow-up work.
101             ///
102             /// Since there's such a requirement, we need to check *just* positive
103             /// implementations, otherwise things like:
104             ///
105             /// impl !Send for T {}
106             ///
107             /// won't be allowed unless there's an *explicit* implementation of `Send`
108             /// for `T`
109             hir::ItemImpl(_, hir::ImplPolarity::Positive, _, _,
110                           ref trait_ref, ref self_ty, _) => {
111                 self.check_impl(item, self_ty, trait_ref);
112             }
113             hir::ItemImpl(_, hir::ImplPolarity::Negative, _, _, Some(_), ..) => {
114                 // FIXME(#27579) what amount of WF checking do we need for neg impls?
115
116                 let trait_ref = tcx.impl_trait_ref(tcx.hir.local_def_id(item.id)).unwrap();
117                 if !tcx.trait_has_default_impl(trait_ref.def_id) {
118                     error_192(tcx, item.span);
119                 }
120             }
121             hir::ItemFn(..) => {
122                 self.check_item_fn(item);
123             }
124             hir::ItemStatic(..) => {
125                 self.check_item_type(item);
126             }
127             hir::ItemConst(..) => {
128                 self.check_item_type(item);
129             }
130             hir::ItemStruct(ref struct_def, ref ast_generics) => {
131                 self.check_type_defn(item, false, |fcx| {
132                     vec![fcx.struct_variant(struct_def)]
133                 });
134
135                 self.check_variances_for_type_defn(item, ast_generics);
136             }
137             hir::ItemUnion(ref struct_def, ref ast_generics) => {
138                 self.check_type_defn(item, true, |fcx| {
139                     vec![fcx.struct_variant(struct_def)]
140                 });
141
142                 self.check_variances_for_type_defn(item, ast_generics);
143             }
144             hir::ItemEnum(ref enum_def, ref ast_generics) => {
145                 self.check_type_defn(item, true, |fcx| {
146                     fcx.enum_variants(enum_def)
147                 });
148
149                 self.check_variances_for_type_defn(item, ast_generics);
150             }
151             hir::ItemTrait(..) => {
152                 self.check_trait(item);
153             }
154             _ => {}
155         }
156     }
157
158     fn check_associated_item(&mut self,
159                              item_id: ast::NodeId,
160                              span: Span,
161                              sig_if_method: Option<&hir::MethodSig>) {
162         let code = self.code.clone();
163         self.for_id(item_id, span).with_fcx(|fcx, this| {
164             let item = fcx.tcx.associated_item(fcx.tcx.hir.local_def_id(item_id));
165
166             let (mut implied_bounds, self_ty) = match item.container {
167                 ty::TraitContainer(_) => (vec![], fcx.tcx.mk_self_type()),
168                 ty::ImplContainer(def_id) => (fcx.impl_implied_bounds(def_id, span),
169                                               fcx.tcx.type_of(def_id))
170             };
171
172             match item.kind {
173                 ty::AssociatedKind::Const => {
174                     let ty = fcx.tcx.type_of(item.def_id);
175                     let ty = fcx.normalize_associated_types_in(span, &ty);
176                     fcx.register_wf_obligation(ty, span, code.clone());
177                 }
178                 ty::AssociatedKind::Method => {
179                     reject_shadowing_type_parameters(fcx.tcx, item.def_id);
180                     let method_ty = fcx.tcx.type_of(item.def_id);
181                     let method_ty = fcx.normalize_associated_types_in(span, &method_ty);
182                     let predicates = fcx.tcx.predicates_of(item.def_id)
183                         .instantiate_identity(fcx.tcx);
184                     let predicates = fcx.normalize_associated_types_in(span, &predicates);
185                     let sig = method_ty.fn_sig();
186                     this.check_fn_or_method(fcx, span, sig, &predicates,
187                                             item.def_id, &mut implied_bounds);
188                     let sig_if_method = sig_if_method.expect("bad signature for method");
189                     this.check_method_receiver(fcx, sig_if_method, &item, self_ty);
190                 }
191                 ty::AssociatedKind::Type => {
192                     if item.defaultness.has_value() {
193                         let ty = fcx.tcx.type_of(item.def_id);
194                         let ty = fcx.normalize_associated_types_in(span, &ty);
195                         fcx.register_wf_obligation(ty, span, code.clone());
196                     }
197                 }
198             }
199
200             implied_bounds
201         })
202     }
203
204     fn for_item<'tcx>(&self, item: &hir::Item)
205                       -> CheckWfFcxBuilder<'a, 'gcx, 'tcx> {
206         self.for_id(item.id, item.span)
207     }
208
209     fn for_id<'tcx>(&self, id: ast::NodeId, span: Span)
210                     -> CheckWfFcxBuilder<'a, 'gcx, 'tcx> {
211         let def_id = self.tcx.hir.local_def_id(id);
212         CheckWfFcxBuilder {
213             inherited: Inherited::build(self.tcx, def_id),
214             code: self.code.clone(),
215             id: id,
216             span: span,
217             param_env: self.tcx.param_env(def_id),
218         }
219     }
220
221     /// In a type definition, we check that to ensure that the types of the fields are well-formed.
222     fn check_type_defn<F>(&mut self, item: &hir::Item, all_sized: bool, mut lookup_fields: F)
223         where F: for<'fcx, 'tcx> FnMut(&FnCtxt<'fcx, 'gcx, 'tcx>) -> Vec<AdtVariant<'tcx>>
224     {
225         self.for_item(item).with_fcx(|fcx, this| {
226             let variants = lookup_fields(fcx);
227
228             for variant in &variants {
229                 // For DST, all intermediate types must be sized.
230                 let unsized_len = if all_sized || variant.fields.is_empty() { 0 } else { 1 };
231                 for field in &variant.fields[..variant.fields.len() - unsized_len] {
232                     fcx.register_bound(
233                         field.ty,
234                         fcx.tcx.require_lang_item(lang_items::SizedTraitLangItem),
235                         traits::ObligationCause::new(field.span,
236                                                      fcx.body_id,
237                                                      traits::FieldSized));
238                 }
239
240                 // All field types must be well-formed.
241                 for field in &variant.fields {
242                     fcx.register_wf_obligation(field.ty, field.span, this.code.clone())
243                 }
244             }
245
246             let def_id = fcx.tcx.hir.local_def_id(item.id);
247             let predicates = fcx.tcx.predicates_of(def_id).instantiate_identity(fcx.tcx);
248             let predicates = fcx.normalize_associated_types_in(item.span, &predicates);
249             this.check_where_clauses(fcx, item.span, &predicates);
250
251             vec![] // no implied bounds in a struct def'n
252         });
253     }
254
255     fn check_auto_trait(&mut self, trait_def_id: DefId, span: Span) {
256         // We want to ensure:
257         //
258         // 1) that there are no items contained within
259         // the trait defintion
260         //
261         // 2) that the definition doesn't violate the no-super trait rule
262         // for auto traits.
263         //
264         // 3) that the trait definition does not have any type parameters
265
266         let predicates = self.tcx.predicates_of(trait_def_id);
267
268         // We must exclude the Self : Trait predicate contained by all
269         // traits.
270         let has_predicates =
271             predicates.predicates.iter().any(|predicate| {
272                 match predicate {
273                     &ty::Predicate::Trait(ref poly_trait_ref) => {
274                         let self_ty = poly_trait_ref.0.self_ty();
275                         !(self_ty.is_self() && poly_trait_ref.def_id() == trait_def_id)
276                     },
277                     _ => true,
278                 }
279             });
280
281         let has_ty_params = self.tcx.generics_of(trait_def_id).types.len() > 1;
282
283         // We use an if-else here, since the generics will also trigger
284         // an extraneous error message when we find predicates like
285         // `T : Sized` for a trait like: `trait Magic<T>`.
286         //
287         // We also put the check on the number of items here,
288         // as it seems confusing to report an error about
289         // extraneous predicates created by things like
290         // an associated type inside the trait.
291         let mut err = None;
292         if !self.tcx.associated_item_def_ids(trait_def_id).is_empty() {
293             error_380(self.tcx, span);
294         } else if has_ty_params {
295             err = Some(struct_span_err!(self.tcx.sess, span, E0567,
296                 "traits with auto impls (`e.g. impl \
297                     Trait for ..`) can not have type parameters"));
298         } else if has_predicates {
299             err = Some(struct_span_err!(self.tcx.sess, span, E0568,
300                 "traits with auto impls (`e.g. impl \
301                     Trait for ..`) cannot have predicates"));
302         }
303
304         // Finally if either of the above conditions apply we should add a note
305         // indicating that this error is the result of a recent soundness fix.
306         match err {
307             None => {},
308             Some(mut e) => {
309                 e.note("the new auto trait rules are the result of a \
310                           recent soundness fix; see #29859 for more details");
311                 e.emit();
312             }
313         }
314     }
315
316     fn check_trait(&mut self, item: &hir::Item) {
317         let trait_def_id = self.tcx.hir.local_def_id(item.id);
318
319         if self.tcx.trait_has_default_impl(trait_def_id) {
320             self.check_auto_trait(trait_def_id, item.span);
321         }
322
323         self.for_item(item).with_fcx(|fcx, this| {
324             let predicates = fcx.tcx.predicates_of(trait_def_id).instantiate_identity(fcx.tcx);
325             let predicates = fcx.normalize_associated_types_in(item.span, &predicates);
326             this.check_where_clauses(fcx, item.span, &predicates);
327             vec![]
328         });
329     }
330
331     fn check_item_fn(&mut self, item: &hir::Item) {
332         self.for_item(item).with_fcx(|fcx, this| {
333             let def_id = fcx.tcx.hir.local_def_id(item.id);
334             let ty = fcx.tcx.type_of(def_id);
335             let item_ty = fcx.normalize_associated_types_in(item.span, &ty);
336             let sig = item_ty.fn_sig();
337
338             let predicates = fcx.tcx.predicates_of(def_id).instantiate_identity(fcx.tcx);
339             let predicates = fcx.normalize_associated_types_in(item.span, &predicates);
340
341             let mut implied_bounds = vec![];
342             this.check_fn_or_method(fcx, item.span, sig, &predicates,
343                                     def_id, &mut implied_bounds);
344             implied_bounds
345         })
346     }
347
348     fn check_item_type(&mut self,
349                        item: &hir::Item)
350     {
351         debug!("check_item_type: {:?}", item);
352
353         self.for_item(item).with_fcx(|fcx, this| {
354             let ty = fcx.tcx.type_of(fcx.tcx.hir.local_def_id(item.id));
355             let item_ty = fcx.normalize_associated_types_in(item.span, &ty);
356
357             fcx.register_wf_obligation(item_ty, item.span, this.code.clone());
358
359             vec![] // no implied bounds in a const etc
360         });
361     }
362
363     fn check_impl(&mut self,
364                   item: &hir::Item,
365                   ast_self_ty: &hir::Ty,
366                   ast_trait_ref: &Option<hir::TraitRef>)
367     {
368         debug!("check_impl: {:?}", item);
369
370         self.for_item(item).with_fcx(|fcx, this| {
371             let item_def_id = fcx.tcx.hir.local_def_id(item.id);
372
373             match *ast_trait_ref {
374                 Some(ref ast_trait_ref) => {
375                     let trait_ref = fcx.tcx.impl_trait_ref(item_def_id).unwrap();
376                     let trait_ref =
377                         fcx.normalize_associated_types_in(
378                             ast_trait_ref.path.span, &trait_ref);
379                     let obligations =
380                         ty::wf::trait_obligations(fcx,
381                                                   fcx.param_env,
382                                                   fcx.body_id,
383                                                   &trait_ref,
384                                                   ast_trait_ref.path.span);
385                     for obligation in obligations {
386                         fcx.register_predicate(obligation);
387                     }
388                 }
389                 None => {
390                     let self_ty = fcx.tcx.type_of(item_def_id);
391                     let self_ty = fcx.normalize_associated_types_in(item.span, &self_ty);
392                     fcx.register_wf_obligation(self_ty, ast_self_ty.span, this.code.clone());
393                 }
394             }
395
396             let predicates = fcx.tcx.predicates_of(item_def_id).instantiate_identity(fcx.tcx);
397             let predicates = fcx.normalize_associated_types_in(item.span, &predicates);
398             this.check_where_clauses(fcx, item.span, &predicates);
399
400             fcx.impl_implied_bounds(item_def_id, item.span)
401         });
402     }
403
404     fn check_where_clauses<'fcx, 'tcx>(&mut self,
405                                        fcx: &FnCtxt<'fcx, 'gcx, 'tcx>,
406                                        span: Span,
407                                        predicates: &ty::InstantiatedPredicates<'tcx>)
408     {
409         let obligations =
410             predicates.predicates
411                       .iter()
412                       .flat_map(|p| ty::wf::predicate_obligations(fcx,
413                                                                   fcx.param_env,
414                                                                   fcx.body_id,
415                                                                   p,
416                                                                   span));
417
418         for obligation in obligations {
419             fcx.register_predicate(obligation);
420         }
421     }
422
423     fn check_fn_or_method<'fcx, 'tcx>(&mut self,
424                                       fcx: &FnCtxt<'fcx, 'gcx, 'tcx>,
425                                       span: Span,
426                                       sig: ty::PolyFnSig<'tcx>,
427                                       predicates: &ty::InstantiatedPredicates<'tcx>,
428                                       def_id: DefId,
429                                       implied_bounds: &mut Vec<Ty<'tcx>>)
430     {
431         let sig = fcx.normalize_associated_types_in(span, &sig);
432         let sig = fcx.liberate_late_bound_regions(def_id, &sig);
433
434         for input_ty in sig.inputs() {
435             fcx.register_wf_obligation(&input_ty, span, self.code.clone());
436         }
437         implied_bounds.extend(sig.inputs());
438
439         fcx.register_wf_obligation(sig.output(), span, self.code.clone());
440
441         // FIXME(#25759) return types should not be implied bounds
442         implied_bounds.push(sig.output());
443
444         self.check_where_clauses(fcx, span, predicates);
445     }
446
447     fn check_method_receiver<'fcx, 'tcx>(&mut self,
448                                          fcx: &FnCtxt<'fcx, 'gcx, 'tcx>,
449                                          method_sig: &hir::MethodSig,
450                                          method: &ty::AssociatedItem,
451                                          self_ty: ty::Ty<'tcx>)
452     {
453         // check that the type of the method's receiver matches the
454         // method's first parameter.
455         debug!("check_method_receiver({:?}, self_ty={:?})",
456                method, self_ty);
457
458         if !method.method_has_self_argument {
459             return;
460         }
461
462         let span = method_sig.decl.inputs[0].span;
463
464         let method_ty = fcx.tcx.type_of(method.def_id);
465         let fty = fcx.normalize_associated_types_in(span, &method_ty);
466         let sig = fcx.liberate_late_bound_regions(method.def_id, &fty.fn_sig());
467
468         debug!("check_method_receiver: sig={:?}", sig);
469
470         let self_arg_ty = sig.inputs()[0];
471         let rcvr_ty = match ExplicitSelf::determine(self_ty, self_arg_ty) {
472             ExplicitSelf::ByValue => self_ty,
473             ExplicitSelf::ByReference(region, mutbl) => {
474                 fcx.tcx.mk_ref(region, ty::TypeAndMut {
475                     ty: self_ty,
476                     mutbl: mutbl
477                 })
478             }
479             ExplicitSelf::ByBox => fcx.tcx.mk_box(self_ty)
480         };
481         let rcvr_ty = fcx.normalize_associated_types_in(span, &rcvr_ty);
482         let rcvr_ty = fcx.liberate_late_bound_regions(method.def_id,
483                                                       &ty::Binder(rcvr_ty));
484
485         debug!("check_method_receiver: receiver ty = {:?}", rcvr_ty);
486
487         let cause = fcx.cause(span, ObligationCauseCode::MethodReceiver);
488         if let Some(mut err) = fcx.demand_eqtype_with_origin(&cause, rcvr_ty, self_arg_ty) {
489             err.emit();
490         }
491     }
492
493     fn check_variances_for_type_defn(&self,
494                                      item: &hir::Item,
495                                      ast_generics: &hir::Generics)
496     {
497         let item_def_id = self.tcx.hir.local_def_id(item.id);
498         let ty = self.tcx.type_of(item_def_id);
499         if self.tcx.has_error_field(ty) {
500             return;
501         }
502
503         let ty_predicates = self.tcx.predicates_of(item_def_id);
504         assert_eq!(ty_predicates.parent, None);
505         let variances = self.tcx.variances_of(item_def_id);
506
507         let mut constrained_parameters: FxHashSet<_> =
508             variances.iter().enumerate()
509                      .filter(|&(_, &variance)| variance != ty::Bivariant)
510                      .map(|(index, _)| Parameter(index as u32))
511                      .collect();
512
513         identify_constrained_type_params(ty_predicates.predicates.as_slice(),
514                                          None,
515                                          &mut constrained_parameters);
516
517         for (index, _) in variances.iter().enumerate() {
518             if constrained_parameters.contains(&Parameter(index as u32)) {
519                 continue;
520             }
521
522             let (span, name) = if index < ast_generics.lifetimes.len() {
523                 (ast_generics.lifetimes[index].lifetime.span,
524                  ast_generics.lifetimes[index].lifetime.name)
525             } else {
526                 let index = index - ast_generics.lifetimes.len();
527                 (ast_generics.ty_params[index].span,
528                  ast_generics.ty_params[index].name)
529             };
530             self.report_bivariance(span, name);
531         }
532     }
533
534     fn report_bivariance(&self,
535                          span: Span,
536                          param_name: ast::Name)
537     {
538         let mut err = error_392(self.tcx, span, param_name);
539
540         let suggested_marker_id = self.tcx.lang_items.phantom_data();
541         match suggested_marker_id {
542             Some(def_id) => {
543                 err.help(
544                     &format!("consider removing `{}` or using a marker such as `{}`",
545                              param_name,
546                              self.tcx.item_path_str(def_id)));
547             }
548             None => {
549                 // no lang items, no help!
550             }
551         }
552         err.emit();
553     }
554 }
555
556 fn reject_shadowing_type_parameters(tcx: TyCtxt, def_id: DefId) {
557     let generics = tcx.generics_of(def_id);
558     let parent = tcx.generics_of(generics.parent.unwrap());
559     let impl_params: FxHashMap<_, _> = parent.types
560                                        .iter()
561                                        .map(|tp| (tp.name, tp.def_id))
562                                        .collect();
563
564     for method_param in &generics.types {
565         if impl_params.contains_key(&method_param.name) {
566             // Tighten up the span to focus on only the shadowing type
567             let type_span = tcx.def_span(method_param.def_id);
568
569             // The expectation here is that the original trait declaration is
570             // local so it should be okay to just unwrap everything.
571             let trait_def_id = impl_params[&method_param.name];
572             let trait_decl_span = tcx.def_span(trait_def_id);
573             error_194(tcx, type_span, trait_decl_span, method_param.name);
574         }
575     }
576 }
577
578 impl<'a, 'tcx, 'v> Visitor<'v> for CheckTypeWellFormedVisitor<'a, 'tcx> {
579     fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'v> {
580         NestedVisitorMap::None
581     }
582
583     fn visit_item(&mut self, i: &hir::Item) {
584         debug!("visit_item: {:?}", i);
585         self.check_item_well_formed(i);
586         intravisit::walk_item(self, i);
587     }
588
589     fn visit_trait_item(&mut self, trait_item: &'v hir::TraitItem) {
590         debug!("visit_trait_item: {:?}", trait_item);
591         let method_sig = match trait_item.node {
592             hir::TraitItemKind::Method(ref sig, _) => Some(sig),
593             _ => None
594         };
595         self.check_associated_item(trait_item.id, trait_item.span, method_sig);
596         intravisit::walk_trait_item(self, trait_item)
597     }
598
599     fn visit_impl_item(&mut self, impl_item: &'v hir::ImplItem) {
600         debug!("visit_impl_item: {:?}", impl_item);
601         let method_sig = match impl_item.node {
602             hir::ImplItemKind::Method(ref sig, _) => Some(sig),
603             _ => None
604         };
605         self.check_associated_item(impl_item.id, impl_item.span, method_sig);
606         intravisit::walk_impl_item(self, impl_item)
607     }
608 }
609
610 ///////////////////////////////////////////////////////////////////////////
611 // ADT
612
613 struct AdtVariant<'tcx> {
614     fields: Vec<AdtField<'tcx>>,
615 }
616
617 struct AdtField<'tcx> {
618     ty: Ty<'tcx>,
619     span: Span,
620 }
621
622 impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> {
623     fn struct_variant(&self, struct_def: &hir::VariantData) -> AdtVariant<'tcx> {
624         let fields =
625             struct_def.fields().iter()
626             .map(|field| {
627                 let field_ty = self.tcx.type_of(self.tcx.hir.local_def_id(field.id));
628                 let field_ty = self.normalize_associated_types_in(field.span,
629                                                                   &field_ty);
630                 AdtField { ty: field_ty, span: field.span }
631             })
632             .collect();
633         AdtVariant { fields: fields }
634     }
635
636     fn enum_variants(&self, enum_def: &hir::EnumDef) -> Vec<AdtVariant<'tcx>> {
637         enum_def.variants.iter()
638             .map(|variant| self.struct_variant(&variant.node.data))
639             .collect()
640     }
641
642     fn impl_implied_bounds(&self, impl_def_id: DefId, span: Span) -> Vec<Ty<'tcx>> {
643         match self.tcx.impl_trait_ref(impl_def_id) {
644             Some(ref trait_ref) => {
645                 // Trait impl: take implied bounds from all types that
646                 // appear in the trait reference.
647                 let trait_ref = self.normalize_associated_types_in(span, trait_ref);
648                 trait_ref.substs.types().collect()
649             }
650
651             None => {
652                 // Inherent impl: take implied bounds from the self type.
653                 let self_ty = self.tcx.type_of(impl_def_id);
654                 let self_ty = self.normalize_associated_types_in(span, &self_ty);
655                 vec![self_ty]
656             }
657         }
658     }
659 }
660
661 fn error_192(tcx: TyCtxt, span: Span) {
662     span_err!(tcx.sess, span, E0192,
663               "negative impls are only allowed for traits with \
664                default impls (e.g., `Send` and `Sync`)")
665 }
666
667 fn error_380(tcx: TyCtxt, span: Span) {
668     span_err!(tcx.sess, span, E0380,
669               "traits with default impls (`e.g. impl \
670                Trait for ..`) must have no methods or associated items")
671 }
672
673 fn error_392<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, span: Span, param_name: ast::Name)
674                        -> DiagnosticBuilder<'tcx> {
675     let mut err = struct_span_err!(tcx.sess, span, E0392,
676                   "parameter `{}` is never used", param_name);
677     err.span_label(span, "unused type parameter");
678     err
679 }
680
681 fn error_194(tcx: TyCtxt, span: Span, trait_decl_span: Span, name: ast::Name) {
682     struct_span_err!(tcx.sess, span, E0194,
683               "type parameter `{}` shadows another type parameter of the same name",
684               name)
685         .span_label(span, "shadows another type parameter")
686         .span_label(trait_decl_span, format!("first `{}` declared here", name))
687         .emit();
688 }