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