]> git.lizzy.rs Git - rust.git/blob - src/librustc_typeck/check/wf.rs
Auto merge of #30286 - oli-obk:const_error_span, r=nikomatsakis
[rust.git] / src / librustc_typeck / check / wf.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::AstConv;
12 use check::{FnCtxt, Inherited, blank_fn_ctxt, regionck, wfcheck};
13 use constrained_type_params::{identify_constrained_type_params, Parameter};
14 use CrateCtxt;
15 use middle::region;
16 use middle::subst::{self, TypeSpace, FnSpace, ParamSpace, SelfSpace};
17 use middle::traits;
18 use middle::ty::{self, Ty};
19 use middle::ty::fold::{TypeFolder, TypeFoldable, super_fold_ty};
20
21 use std::cell::RefCell;
22 use std::collections::HashSet;
23 use syntax::ast;
24 use syntax::codemap::{DUMMY_SP, Span};
25 use syntax::parse::token::special_idents;
26
27 use rustc_front::intravisit::{self, Visitor, FnKind};
28 use rustc_front::hir;
29
30 pub struct CheckTypeWellFormedVisitor<'ccx, 'tcx:'ccx> {
31     ccx: &'ccx CrateCtxt<'ccx, 'tcx>,
32     cache: HashSet<Ty<'tcx>>
33 }
34
35 impl<'ccx, 'tcx> CheckTypeWellFormedVisitor<'ccx, 'tcx> {
36     pub fn new(ccx: &'ccx CrateCtxt<'ccx, 'tcx>) -> CheckTypeWellFormedVisitor<'ccx, 'tcx> {
37         CheckTypeWellFormedVisitor { ccx: ccx, cache: HashSet::new() }
38     }
39
40     fn tcx(&self) -> &ty::ctxt<'tcx> {
41         self.ccx.tcx
42     }
43
44     /// Checks that the field types (in a struct def'n) or argument types (in an enum def'n) are
45     /// well-formed, meaning that they do not require any constraints not declared in the struct
46     /// definition itself. For example, this definition would be illegal:
47     ///
48     ///     struct Ref<'a, T> { x: &'a T }
49     ///
50     /// because the type did not declare that `T:'a`.
51     ///
52     /// We do this check as a pre-pass before checking fn bodies because if these constraints are
53     /// not included it frequently leads to confusing errors in fn bodies. So it's better to check
54     /// the types first.
55     fn check_item_well_formed(&mut self, item: &hir::Item) {
56         let ccx = self.ccx;
57         debug!("check_item_well_formed(it.id={}, it.name={})",
58                item.id,
59                ccx.tcx.item_path_str(ccx.tcx.map.local_def_id(item.id)));
60
61         match item.node {
62             /// Right now we check that every default trait implementation
63             /// has an implementation of itself. Basically, a case like:
64             ///
65             /// `impl Trait for T {}`
66             ///
67             /// has a requirement of `T: Trait` which was required for default
68             /// method implementations. Although this could be improved now that
69             /// there's a better infrastructure in place for this, it's being left
70             /// for a follow-up work.
71             ///
72             /// Since there's such a requirement, we need to check *just* positive
73             /// implementations, otherwise things like:
74             ///
75             /// impl !Send for T {}
76             ///
77             /// won't be allowed unless there's an *explicit* implementation of `Send`
78             /// for `T`
79             hir::ItemImpl(_, hir::ImplPolarity::Positive, _, _, _, _) => {
80                 self.check_impl(item);
81             }
82             hir::ItemImpl(_, hir::ImplPolarity::Negative, _, Some(_), _, _) => {
83                 let item_def_id = ccx.tcx.map.local_def_id(item.id);
84                 let trait_ref = ccx.tcx.impl_trait_ref(item_def_id).unwrap();
85                 ccx.tcx.populate_implementations_for_trait_if_necessary(trait_ref.def_id);
86                 match ccx.tcx.lang_items.to_builtin_kind(trait_ref.def_id) {
87                     Some(ty::BoundSend) | Some(ty::BoundSync) => {}
88                     Some(_) | None => {
89                         if !ccx.tcx.trait_has_default_impl(trait_ref.def_id) {
90                             wfcheck::error_192(ccx, item.span);
91                         }
92                     }
93                 }
94             }
95             hir::ItemFn(..) => {
96                 self.check_item_type(item);
97             }
98             hir::ItemStatic(..) => {
99                 self.check_item_type(item);
100             }
101             hir::ItemConst(..) => {
102                 self.check_item_type(item);
103             }
104             hir::ItemStruct(ref struct_def, ref ast_generics) => {
105                 self.check_type_defn(item, |fcx| {
106                     vec![struct_variant(fcx, struct_def)]
107                 });
108
109                 self.check_variances_for_type_defn(item, ast_generics);
110             }
111             hir::ItemEnum(ref enum_def, ref ast_generics) => {
112                 self.check_type_defn(item, |fcx| {
113                     enum_variants(fcx, enum_def)
114                 });
115
116                 self.check_variances_for_type_defn(item, ast_generics);
117             }
118             hir::ItemTrait(_, _, _, ref items) => {
119                 let trait_predicates =
120                     ccx.tcx.lookup_predicates(ccx.tcx.map.local_def_id(item.id));
121                 reject_non_type_param_bounds(ccx.tcx, item.span, &trait_predicates);
122                 if ccx.tcx.trait_has_default_impl(ccx.tcx.map.local_def_id(item.id)) {
123                     if !items.is_empty() {
124                         wfcheck::error_380(ccx, item.span);
125                     }
126                 }
127             }
128             _ => {}
129         }
130     }
131
132     fn with_fcx<F>(&mut self, item: &hir::Item, mut f: F) where
133         F: for<'fcx> FnMut(&mut CheckTypeWellFormedVisitor<'ccx, 'tcx>, &FnCtxt<'fcx, 'tcx>),
134     {
135         let ccx = self.ccx;
136         let item_def_id = ccx.tcx.map.local_def_id(item.id);
137         let type_scheme = ccx.tcx.lookup_item_type(item_def_id);
138         let type_predicates = ccx.tcx.lookup_predicates(item_def_id);
139         reject_non_type_param_bounds(ccx.tcx, item.span, &type_predicates);
140         let free_id_outlive = ccx.tcx.region_maps.item_extent(item.id);
141         let param_env = ccx.tcx.construct_parameter_environment(item.span,
142                                                                 &type_scheme.generics,
143                                                                 &type_predicates,
144                                                                 free_id_outlive);
145         let tables = RefCell::new(ty::Tables::empty());
146         let inh = Inherited::new(ccx.tcx, &tables, param_env);
147         let fcx = blank_fn_ctxt(ccx, &inh, ty::FnConverging(type_scheme.ty), item.id);
148         f(self, &fcx);
149         fcx.select_all_obligations_or_error();
150         regionck::regionck_item(&fcx, item.id, item.span, &[]);
151     }
152
153     /// In a type definition, we check that to ensure that the types of the fields are well-formed.
154     fn check_type_defn<F>(&mut self, item: &hir::Item, mut lookup_fields: F) where
155         F: for<'fcx> FnMut(&FnCtxt<'fcx, 'tcx>) -> Vec<AdtVariant<'tcx>>,
156     {
157         self.with_fcx(item, |this, fcx| {
158             let variants = lookup_fields(fcx);
159             let mut bounds_checker = BoundsChecker::new(fcx,
160                                                         item.id,
161                                                         Some(&mut this.cache));
162             debug!("check_type_defn at bounds_checker.scope: {:?}", bounds_checker.scope);
163
164             for variant in &variants {
165                 for field in &variant.fields {
166                     // Regions are checked below.
167                     bounds_checker.check_traits_in_ty(field.ty, field.span);
168                 }
169
170                 // For DST, all intermediate types must be sized.
171                 if let Some((_, fields)) = variant.fields.split_last() {
172                     for field in fields {
173                         fcx.register_builtin_bound(
174                             field.ty,
175                             ty::BoundSized,
176                             traits::ObligationCause::new(field.span,
177                                                          fcx.body_id,
178                                                          traits::FieldSized));
179                     }
180                 }
181             }
182
183             for field in variants.iter().flat_map(|v| v.fields.iter()) {
184                 fcx.register_old_wf_obligation(field.ty, field.span, traits::MiscObligation);
185             }
186         });
187     }
188
189     fn check_item_type(&mut self,
190                        item: &hir::Item)
191     {
192         self.with_fcx(item, |this, fcx| {
193             let mut bounds_checker = BoundsChecker::new(fcx,
194                                                         item.id,
195                                                         Some(&mut this.cache));
196             debug!("check_item_type at bounds_checker.scope: {:?}", bounds_checker.scope);
197
198             let item_def_id = fcx.tcx().map.local_def_id(item.id);
199             let type_scheme = fcx.tcx().lookup_item_type(item_def_id);
200             let item_ty = fcx.instantiate_type_scheme(item.span,
201                                                       &fcx.inh
202                                                           .infcx
203                                                           .parameter_environment
204                                                           .free_substs,
205                                                       &type_scheme.ty);
206
207             bounds_checker.check_traits_in_ty(item_ty, item.span);
208         });
209     }
210
211     fn check_impl(&mut self,
212                   item: &hir::Item)
213     {
214         self.with_fcx(item, |this, fcx| {
215             let mut bounds_checker = BoundsChecker::new(fcx,
216                                                         item.id,
217                                                         Some(&mut this.cache));
218             debug!("check_impl at bounds_checker.scope: {:?}", bounds_checker.scope);
219
220             // Find the impl self type as seen from the "inside" --
221             // that is, with all type parameters converted from bound
222             // to free.
223             let self_ty = fcx.tcx().node_id_to_type(item.id);
224             let self_ty = fcx.instantiate_type_scheme(item.span,
225                                                       &fcx.inh
226                                                           .infcx
227                                                           .parameter_environment
228                                                           .free_substs,
229                                                       &self_ty);
230
231             bounds_checker.check_traits_in_ty(self_ty, item.span);
232
233             // Similarly, obtain an "inside" reference to the trait
234             // that the impl implements.
235             let trait_ref = match fcx.tcx().impl_trait_ref(fcx.tcx().map.local_def_id(item.id)) {
236                 None => { return; }
237                 Some(t) => { t }
238             };
239
240             let trait_ref = fcx.instantiate_type_scheme(item.span,
241                                                         &fcx.inh
242                                                             .infcx
243                                                             .parameter_environment
244                                                             .free_substs,
245                                                         &trait_ref);
246
247             // We are stricter on the trait-ref in an impl than the
248             // self-type.  In particular, we enforce region
249             // relationships. The reason for this is that (at least
250             // presently) "applying" an impl does not require that the
251             // application site check the well-formedness constraints on the
252             // trait reference. Instead, this is done at the impl site.
253             // Arguably this is wrong and we should treat the trait-reference
254             // the same way as we treat the self-type.
255             bounds_checker.check_trait_ref(&trait_ref, item.span);
256
257             let cause =
258                 traits::ObligationCause::new(
259                     item.span,
260                     fcx.body_id,
261                     traits::ItemObligation(trait_ref.def_id));
262
263             // Find the supertrait bounds. This will add `int:Bar`.
264             let poly_trait_ref = ty::Binder(trait_ref);
265             let predicates = fcx.tcx().lookup_super_predicates(poly_trait_ref.def_id());
266             let predicates = predicates.instantiate_supertrait(fcx.tcx(), &poly_trait_ref);
267             let predicates = {
268                 let selcx = &mut traits::SelectionContext::new(fcx.infcx());
269                 traits::normalize(selcx, cause.clone(), &predicates)
270             };
271             for predicate in predicates.value.predicates {
272                 fcx.register_predicate(traits::Obligation::new(cause.clone(), predicate));
273             }
274             for obligation in predicates.obligations {
275                 fcx.register_predicate(obligation);
276             }
277         });
278     }
279
280     fn check_variances_for_type_defn(&self,
281                                      item: &hir::Item,
282                                      ast_generics: &hir::Generics)
283     {
284         let item_def_id = self.tcx().map.local_def_id(item.id);
285         let ty_predicates = self.tcx().lookup_predicates(item_def_id);
286         let variances = self.tcx().item_variances(item_def_id);
287
288         let mut constrained_parameters: HashSet<_> =
289             variances.types
290                      .iter_enumerated()
291                      .filter(|&(_, _, &variance)| variance != ty::Bivariant)
292                      .map(|(space, index, _)| self.param_ty(ast_generics, space, index))
293                      .map(|p| Parameter::Type(p))
294                      .collect();
295
296         identify_constrained_type_params(self.tcx(),
297                                          ty_predicates.predicates.as_slice(),
298                                          None,
299                                          &mut constrained_parameters);
300
301         for (space, index, _) in variances.types.iter_enumerated() {
302             let param_ty = self.param_ty(ast_generics, space, index);
303             if constrained_parameters.contains(&Parameter::Type(param_ty)) {
304                 continue;
305             }
306             let span = self.ty_param_span(ast_generics, item, space, index);
307             self.report_bivariance(span, param_ty.name);
308         }
309
310         for (space, index, &variance) in variances.regions.iter_enumerated() {
311             if variance != ty::Bivariant {
312                 continue;
313             }
314
315             assert_eq!(space, TypeSpace);
316             let span = ast_generics.lifetimes[index].lifetime.span;
317             let name = ast_generics.lifetimes[index].lifetime.name;
318             self.report_bivariance(span, name);
319         }
320     }
321
322     fn param_ty(&self,
323                 ast_generics: &hir::Generics,
324                 space: ParamSpace,
325                 index: usize)
326                 -> ty::ParamTy
327     {
328         let name = match space {
329             TypeSpace => ast_generics.ty_params[index].name,
330             SelfSpace => special_idents::type_self.name,
331             FnSpace => self.tcx().sess.bug("Fn space occupied?"),
332         };
333
334         ty::ParamTy { space: space, idx: index as u32, name: name }
335     }
336
337     fn ty_param_span(&self,
338                      ast_generics: &hir::Generics,
339                      item: &hir::Item,
340                      space: ParamSpace,
341                      index: usize)
342                      -> Span
343     {
344         match space {
345             TypeSpace => ast_generics.ty_params[index].span,
346             SelfSpace => item.span,
347             FnSpace => self.tcx().sess.span_bug(item.span, "Fn space occupied?"),
348         }
349     }
350
351     fn report_bivariance(&self,
352                          span: Span,
353                          param_name: ast::Name)
354     {
355         wfcheck::error_392(self.tcx(), span, param_name);
356
357         let suggested_marker_id = self.tcx().lang_items.phantom_data();
358         match suggested_marker_id {
359             Some(def_id) => {
360                 self.tcx().sess.fileline_help(
361                     span,
362                     &format!("consider removing `{}` or using a marker such as `{}`",
363                              param_name,
364                              self.tcx().item_path_str(def_id)));
365             }
366             None => {
367                 // no lang items, no help!
368             }
369         }
370     }
371 }
372
373 // Reject any predicates that do not involve a type parameter.
374 fn reject_non_type_param_bounds<'tcx>(tcx: &ty::ctxt<'tcx>,
375                                       span: Span,
376                                       predicates: &ty::GenericPredicates<'tcx>) {
377     for predicate in &predicates.predicates {
378         match predicate {
379             &ty::Predicate::Trait(ty::Binder(ref tr)) => {
380                 let found_param = tr.input_types().iter()
381                                     .flat_map(|ty| ty.walk())
382                                     .any(is_ty_param);
383                 if !found_param { report_bound_error(tcx, span, tr.self_ty() )}
384             }
385             &ty::Predicate::TypeOutlives(ty::Binder(ty::OutlivesPredicate(ty, _))) => {
386                 let found_param = ty.walk().any(|t| is_ty_param(t));
387                 if !found_param { report_bound_error(tcx, span, ty) }
388             }
389             _ => {}
390         };
391     }
392
393     fn report_bound_error<'t>(tcx: &ty::ctxt<'t>,
394                           span: Span,
395                           bounded_ty: ty::Ty<'t>) {
396         span_err!(tcx.sess, span, E0193,
397             "cannot bound type `{}`, where clause \
398                 bounds may only be attached to types involving \
399                 type parameters",
400                 bounded_ty)
401     }
402
403     fn is_ty_param(ty: ty::Ty) -> bool {
404         match &ty.sty {
405             &ty::TyParam(_) => true,
406             _ => false
407         }
408     }
409 }
410
411 fn reject_shadowing_type_parameters<'tcx>(tcx: &ty::ctxt<'tcx>,
412                                           span: Span,
413                                           generics: &ty::Generics<'tcx>) {
414     let impl_params = generics.types.get_slice(subst::TypeSpace).iter()
415         .map(|tp| tp.name).collect::<HashSet<_>>();
416
417     for method_param in generics.types.get_slice(subst::FnSpace) {
418         if impl_params.contains(&method_param.name) {
419             wfcheck::error_194(tcx, span, method_param.name);
420         }
421     }
422 }
423
424 impl<'ccx, 'tcx, 'v> Visitor<'v> for CheckTypeWellFormedVisitor<'ccx, 'tcx> {
425     fn visit_item(&mut self, i: &hir::Item) {
426         self.check_item_well_formed(i);
427         intravisit::walk_item(self, i);
428     }
429
430     fn visit_fn(&mut self,
431                 fk: FnKind<'v>, fd: &'v hir::FnDecl,
432                 b: &'v hir::Block, span: Span, id: ast::NodeId) {
433         match fk {
434             FnKind::Closure | FnKind::ItemFn(..) => {}
435             FnKind::Method(..) => {
436                 match self.tcx().impl_or_trait_item(self.tcx().map.local_def_id(id)) {
437                     ty::ImplOrTraitItem::MethodTraitItem(ty_method) => {
438                         reject_shadowing_type_parameters(self.tcx(), span, &ty_method.generics)
439                     }
440                     _ => {}
441                 }
442             }
443         }
444         intravisit::walk_fn(self, fk, fd, b, span)
445     }
446
447     fn visit_trait_item(&mut self, trait_item: &'v hir::TraitItem) {
448         if let hir::MethodTraitItem(_, None) = trait_item.node {
449             match self.tcx().impl_or_trait_item(self.tcx().map.local_def_id(trait_item.id)) {
450                 ty::ImplOrTraitItem::MethodTraitItem(ty_method) => {
451                     reject_non_type_param_bounds(
452                         self.tcx(),
453                         trait_item.span,
454                         &ty_method.predicates);
455                     reject_shadowing_type_parameters(
456                         self.tcx(),
457                         trait_item.span,
458                         &ty_method.generics);
459                 }
460                 _ => {}
461             }
462         }
463
464         intravisit::walk_trait_item(self, trait_item)
465     }
466 }
467
468 pub struct BoundsChecker<'cx,'tcx:'cx> {
469     fcx: &'cx FnCtxt<'cx,'tcx>,
470     span: Span,
471
472     scope: region::CodeExtent,
473
474     binding_count: usize,
475     cache: Option<&'cx mut HashSet<Ty<'tcx>>>,
476 }
477
478 impl<'cx,'tcx> BoundsChecker<'cx,'tcx> {
479     pub fn new(fcx: &'cx FnCtxt<'cx,'tcx>,
480                scope: ast::NodeId,
481                cache: Option<&'cx mut HashSet<Ty<'tcx>>>)
482                -> BoundsChecker<'cx,'tcx> {
483         let scope = fcx.tcx().region_maps.item_extent(scope);
484         BoundsChecker { fcx: fcx, span: DUMMY_SP, scope: scope,
485                         cache: cache, binding_count: 0 }
486     }
487
488     /// Given a trait ref like `A : Trait<B>`, where `Trait` is defined as (say):
489     ///
490     ///     trait Trait<B:OtherTrait> : Copy { ... }
491     ///
492     /// This routine will check that `B : OtherTrait` and `A : Trait<B>`. It will also recursively
493     /// check that the types `A` and `B` are well-formed.
494     ///
495     /// Note that it does not (currently, at least) check that `A : Copy` (that check is delegated
496     /// to the point where impl `A : Trait<B>` is implemented).
497     pub fn check_trait_ref(&mut self, trait_ref: &ty::TraitRef<'tcx>, span: Span) {
498         let trait_predicates = self.fcx.tcx().lookup_predicates(trait_ref.def_id);
499
500         let bounds = self.fcx.instantiate_bounds(span,
501                                                  trait_ref.substs,
502                                                  &trait_predicates);
503
504         self.fcx.add_obligations_for_parameters(
505             traits::ObligationCause::new(
506                 span,
507                 self.fcx.body_id,
508                 traits::ItemObligation(trait_ref.def_id)),
509             &bounds);
510
511         for &ty in &trait_ref.substs.types {
512             self.check_traits_in_ty(ty, span);
513         }
514     }
515
516     fn check_traits_in_ty(&mut self, ty: Ty<'tcx>, span: Span) {
517         self.span = span;
518         // When checking types outside of a type def'n, we ignore
519         // region obligations. See discussion below in fold_ty().
520         self.binding_count += 1;
521         ty.fold_with(self);
522         self.binding_count -= 1;
523     }
524 }
525
526 impl<'cx,'tcx> TypeFolder<'tcx> for BoundsChecker<'cx,'tcx> {
527     fn tcx(&self) -> &ty::ctxt<'tcx> {
528         self.fcx.tcx()
529     }
530
531     fn fold_binder<T>(&mut self, binder: &ty::Binder<T>) -> ty::Binder<T>
532         where T : TypeFoldable<'tcx>
533     {
534         self.binding_count += 1;
535         let value = self.fcx.tcx().liberate_late_bound_regions(
536             self.scope,
537             binder);
538         debug!("BoundsChecker::fold_binder: late-bound regions replaced: {:?} at scope: {:?}",
539                value, self.scope);
540         let value = value.fold_with(self);
541         self.binding_count -= 1;
542         ty::Binder(value)
543     }
544
545     fn fold_ty(&mut self, t: Ty<'tcx>) -> Ty<'tcx> {
546         debug!("BoundsChecker t={:?}",
547                t);
548
549         match self.cache {
550             Some(ref mut cache) => {
551                 if !cache.insert(t) {
552                     // Already checked this type! Don't check again.
553                     debug!("cached");
554                     return t;
555                 }
556             }
557             None => { }
558         }
559
560         match t.sty{
561             ty::TyStruct(def, substs) |
562             ty::TyEnum(def, substs) => {
563                 let type_predicates = def.predicates(self.fcx.tcx());
564                 let bounds = self.fcx.instantiate_bounds(self.span, substs,
565                                                          &type_predicates);
566
567                 if self.binding_count == 0 {
568                     self.fcx.add_obligations_for_parameters(
569                         traits::ObligationCause::new(self.span,
570                                                      self.fcx.body_id,
571                                                      traits::ItemObligation(def.did)),
572                         &bounds);
573                 } else {
574                     // There are two circumstances in which we ignore
575                     // region obligations.
576                     //
577                     // The first is when we are inside of a closure
578                     // type. This is because in that case the region
579                     // obligations for the parameter types are things
580                     // that the closure body gets to assume and the
581                     // caller must prove at the time of call. In other
582                     // words, if there is a type like `<'a, 'b> | &'a
583                     // &'b int |`, it is well-formed, and caller will
584                     // have to show that `'b : 'a` at the time of
585                     // call.
586                     //
587                     // The second is when we are checking for
588                     // well-formedness outside of a type def'n or fn
589                     // body. This is for a similar reason: in general,
590                     // we only do WF checking for regions in the
591                     // result of expressions and type definitions, so
592                     // to as allow for implicit where clauses.
593                     //
594                     // (I believe we should do the same for traits, but
595                     // that will require an RFC. -nmatsakis)
596                     let bounds = filter_to_trait_obligations(bounds);
597                     self.fcx.add_obligations_for_parameters(
598                         traits::ObligationCause::new(self.span,
599                                                      self.fcx.body_id,
600                                                      traits::ItemObligation(def.did)),
601                         &bounds);
602                 }
603
604                 self.fold_substs(substs);
605             }
606             _ => {
607                 super_fold_ty(self, t);
608             }
609         }
610
611         t // we're not folding to produce a new type, so just return `t` here
612     }
613 }
614
615 ///////////////////////////////////////////////////////////////////////////
616 // ADT
617
618 struct AdtVariant<'tcx> {
619     fields: Vec<AdtField<'tcx>>,
620 }
621
622 struct AdtField<'tcx> {
623     ty: Ty<'tcx>,
624     span: Span,
625 }
626
627 fn struct_variant<'a, 'tcx>(fcx: &FnCtxt<'a, 'tcx>,
628                             struct_def: &hir::VariantData)
629                             -> AdtVariant<'tcx> {
630     let fields =
631         struct_def.fields().iter()
632         .map(|field| {
633             let field_ty = fcx.tcx().node_id_to_type(field.node.id);
634             let field_ty = fcx.instantiate_type_scheme(field.span,
635                                                        &fcx.inh
636                                                            .infcx
637                                                            .parameter_environment
638                                                            .free_substs,
639                                                        &field_ty);
640             AdtField { ty: field_ty, span: field.span }
641         })
642         .collect();
643     AdtVariant { fields: fields }
644 }
645
646 fn enum_variants<'a, 'tcx>(fcx: &FnCtxt<'a, 'tcx>,
647                            enum_def: &hir::EnumDef)
648                            -> Vec<AdtVariant<'tcx>> {
649     enum_def.variants.iter()
650         .map(|variant| struct_variant(fcx, &variant.node.data))
651         .collect()
652 }
653
654 fn filter_to_trait_obligations<'tcx>(bounds: ty::InstantiatedPredicates<'tcx>)
655                                      -> ty::InstantiatedPredicates<'tcx>
656 {
657     let mut result = ty::InstantiatedPredicates::empty();
658     for (space, _, predicate) in bounds.predicates.iter_enumerated() {
659         match *predicate {
660             ty::Predicate::Trait(..) |
661             ty::Predicate::Projection(..) => {
662                 result.predicates.push(space, predicate.clone())
663             }
664             ty::Predicate::WellFormed(..) |
665             ty::Predicate::ObjectSafe(..) |
666             ty::Predicate::Equate(..) |
667             ty::Predicate::TypeOutlives(..) |
668             ty::Predicate::RegionOutlives(..) => {
669             }
670         }
671     }
672     result
673 }