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