]> git.lizzy.rs Git - rust.git/blob - src/librustc_typeck/check/wf.rs
Implement a new wfcheck to replace the old wf; this new code only issues
[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::ast_util::local_def;
25 use syntax::codemap::{DUMMY_SP, Span};
26 use syntax::parse::token::{special_idents};
27 use syntax::visit;
28 use syntax::visit::Visitor;
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: &ast::Item) {
56         let ccx = self.ccx;
57         debug!("check_item_well_formed(it.id={}, it.ident={})",
58                item.id,
59                ccx.tcx.item_path_str(local_def(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             ast::ItemImpl(_, ast::ImplPolarity::Positive, _, _, _, _) => {
80                 self.check_impl(item);
81             }
82             ast::ItemImpl(_, ast::ImplPolarity::Negative, _, Some(_), _, _) => {
83                 let trait_ref = ccx.tcx.impl_trait_ref(local_def(item.id)).unwrap();
84                 ccx.tcx.populate_implementations_for_trait_if_necessary(trait_ref.def_id);
85                 match ccx.tcx.lang_items.to_builtin_kind(trait_ref.def_id) {
86                     Some(ty::BoundSend) | Some(ty::BoundSync) => {}
87                     Some(_) | None => {
88                         if !ccx.tcx.trait_has_default_impl(trait_ref.def_id) {
89                             wfcheck::error_192(ccx, item.span);
90                         }
91                     }
92                 }
93             }
94             ast::ItemFn(..) => {
95                 self.check_item_type(item);
96             }
97             ast::ItemStatic(..) => {
98                 self.check_item_type(item);
99             }
100             ast::ItemConst(..) => {
101                 self.check_item_type(item);
102             }
103             ast::ItemStruct(ref struct_def, ref ast_generics) => {
104                 self.check_type_defn(item, |fcx| {
105                     vec![struct_variant(fcx, &**struct_def)]
106                 });
107
108                 self.check_variances_for_type_defn(item, ast_generics);
109             }
110             ast::ItemEnum(ref enum_def, ref ast_generics) => {
111                 self.check_type_defn(item, |fcx| {
112                     enum_variants(fcx, enum_def)
113                 });
114
115                 self.check_variances_for_type_defn(item, ast_generics);
116             }
117             ast::ItemTrait(_, _, _, ref items) => {
118                 let trait_predicates =
119                     ccx.tcx.lookup_predicates(local_def(item.id));
120                 reject_non_type_param_bounds(ccx.tcx, item.span, &trait_predicates);
121                 if ccx.tcx.trait_has_default_impl(local_def(item.id)) {
122                     if !items.is_empty() {
123                         wfcheck::error_380(ccx, item.span);
124                     }
125                 }
126             }
127             _ => {}
128         }
129     }
130
131     fn with_fcx<F>(&mut self, item: &ast::Item, mut f: F) where
132         F: for<'fcx> FnMut(&mut CheckTypeWellFormedVisitor<'ccx, 'tcx>, &FnCtxt<'fcx, 'tcx>),
133     {
134         let ccx = self.ccx;
135         let item_def_id = local_def(item.id);
136         let type_scheme = ccx.tcx.lookup_item_type(item_def_id);
137         let type_predicates = ccx.tcx.lookup_predicates(item_def_id);
138         reject_non_type_param_bounds(ccx.tcx, item.span, &type_predicates);
139         let param_env = ccx.tcx.construct_parameter_environment(item.span,
140                                                                 &type_scheme.generics,
141                                                                 &type_predicates,
142                                                                 item.id);
143         let tables = RefCell::new(ty::Tables::empty());
144         let inh = Inherited::new(ccx.tcx, &tables, param_env);
145         let fcx = blank_fn_ctxt(ccx, &inh, ty::FnConverging(type_scheme.ty), item.id);
146         f(self, &fcx);
147         fcx.select_all_obligations_or_error();
148         regionck::regionck_item(&fcx, item.id, item.span, &[]);
149     }
150
151     /// In a type definition, we check that to ensure that the types of the fields are well-formed.
152     fn check_type_defn<F>(&mut self, item: &ast::Item, mut lookup_fields: F) where
153         F: for<'fcx> FnMut(&FnCtxt<'fcx, 'tcx>) -> Vec<AdtVariant<'tcx>>,
154     {
155         self.with_fcx(item, |this, fcx| {
156             let variants = lookup_fields(fcx);
157             let mut bounds_checker = BoundsChecker::new(fcx,
158                                                         item.id,
159                                                         Some(&mut this.cache));
160             debug!("check_type_defn at bounds_checker.scope: {:?}", bounds_checker.scope);
161
162             for variant in &variants {
163                 for field in &variant.fields {
164                     // Regions are checked below.
165                     bounds_checker.check_traits_in_ty(field.ty, field.span);
166                 }
167
168                 // For DST, all intermediate types must be sized.
169                 if let Some((_, fields)) = variant.fields.split_last() {
170                     for field in fields {
171                         fcx.register_builtin_bound(
172                             field.ty,
173                             ty::BoundSized,
174                             traits::ObligationCause::new(field.span,
175                                                          fcx.body_id,
176                                                          traits::FieldSized));
177                     }
178                 }
179             }
180
181             let field_tys: Vec<Ty> =
182                 variants.iter().flat_map(|v| v.fields.iter().map(|f| f.ty)).collect();
183
184             for &field_ty in &field_tys {
185                 fcx.register_wf_obligation(field_ty, item.span, traits::MiscObligation);
186             }
187         });
188     }
189
190     fn check_item_type(&mut self,
191                        item: &ast::Item)
192     {
193         self.with_fcx(item, |this, fcx| {
194             let mut bounds_checker = BoundsChecker::new(fcx,
195                                                         item.id,
196                                                         Some(&mut this.cache));
197             debug!("check_item_type at bounds_checker.scope: {:?}", bounds_checker.scope);
198
199             let type_scheme = fcx.tcx().lookup_item_type(local_def(item.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: &ast::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(local_def(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: &ast::Item,
282                                      ast_generics: &ast::Generics)
283     {
284         let item_def_id = local_def(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: &ast::Generics,
324                 space: ParamSpace,
325                 index: usize)
326                 -> ty::ParamTy
327     {
328         let name = match space {
329             TypeSpace => ast_generics.ty_params[index].ident.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: &ast::Generics,
339                      item: &ast::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: &ast::Item) {
426         self.check_item_well_formed(i);
427         visit::walk_item(self, i);
428     }
429
430     fn visit_fn(&mut self,
431                 fk: visit::FnKind<'v>, fd: &'v ast::FnDecl,
432                 b: &'v ast::Block, span: Span, id: ast::NodeId) {
433         match fk {
434             visit::FkFnBlock | visit::FkItemFn(..) => {}
435             visit::FkMethod(..) => {
436                 match self.tcx().impl_or_trait_item(local_def(id)) {
437                     ty::ImplOrTraitItem::MethodTraitItem(ty_method) => {
438                         reject_shadowing_type_parameters(self.tcx(), span, &ty_method.generics)
439                     }
440                     _ => {}
441                 }
442             }
443         }
444         visit::walk_fn(self, fk, fd, b, span)
445     }
446
447     fn visit_trait_item(&mut self, trait_item: &'v ast::TraitItem) {
448         if let ast::MethodTraitItem(_, None) = trait_item.node {
449             match self.tcx().impl_or_trait_item(local_def(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         visit::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     // This field is often attached to item impls; it is not clear
473     // that `CodeExtent` is well-defined for such nodes, so pnkfelix
474     // has left it as a NodeId rather than porting to CodeExtent.
475     scope: ast::NodeId,
476
477     binding_count: usize,
478     cache: Option<&'cx mut HashSet<Ty<'tcx>>>,
479 }
480
481 impl<'cx,'tcx> BoundsChecker<'cx,'tcx> {
482     pub fn new(fcx: &'cx FnCtxt<'cx,'tcx>,
483                scope: ast::NodeId,
484                cache: Option<&'cx mut HashSet<Ty<'tcx>>>)
485                -> BoundsChecker<'cx,'tcx> {
486         BoundsChecker { fcx: fcx, span: DUMMY_SP, scope: scope,
487                         cache: cache, binding_count: 0 }
488     }
489
490     /// Given a trait ref like `A : Trait<B>`, where `Trait` is defined as (say):
491     ///
492     ///     trait Trait<B:OtherTrait> : Copy { ... }
493     ///
494     /// This routine will check that `B : OtherTrait` and `A : Trait<B>`. It will also recursively
495     /// check that the types `A` and `B` are well-formed.
496     ///
497     /// Note that it does not (currently, at least) check that `A : Copy` (that check is delegated
498     /// to the point where impl `A : Trait<B>` is implemented).
499     pub fn check_trait_ref(&mut self, trait_ref: &ty::TraitRef<'tcx>, span: Span) {
500         let trait_predicates = self.fcx.tcx().lookup_predicates(trait_ref.def_id);
501
502         let bounds = self.fcx.instantiate_bounds(span,
503                                                  trait_ref.substs,
504                                                  &trait_predicates);
505
506         self.fcx.add_obligations_for_parameters(
507             traits::ObligationCause::new(
508                 span,
509                 self.fcx.body_id,
510                 traits::ItemObligation(trait_ref.def_id)),
511             &bounds);
512
513         for &ty in &trait_ref.substs.types {
514             self.check_traits_in_ty(ty, span);
515         }
516     }
517
518     fn check_traits_in_ty(&mut self, ty: Ty<'tcx>, span: Span) {
519         self.span = span;
520         // When checking types outside of a type def'n, we ignore
521         // region obligations. See discussion below in fold_ty().
522         self.binding_count += 1;
523         ty.fold_with(self);
524         self.binding_count -= 1;
525     }
526 }
527
528 impl<'cx,'tcx> TypeFolder<'tcx> for BoundsChecker<'cx,'tcx> {
529     fn tcx(&self) -> &ty::ctxt<'tcx> {
530         self.fcx.tcx()
531     }
532
533     fn fold_binder<T>(&mut self, binder: &ty::Binder<T>) -> ty::Binder<T>
534         where T : TypeFoldable<'tcx>
535     {
536         self.binding_count += 1;
537         let value = self.fcx.tcx().liberate_late_bound_regions(
538             region::DestructionScopeData::new(self.scope),
539             binder);
540         debug!("BoundsChecker::fold_binder: late-bound regions replaced: {:?} at scope: {:?}",
541                value, self.scope);
542         let value = value.fold_with(self);
543         self.binding_count -= 1;
544         ty::Binder(value)
545     }
546
547     fn fold_ty(&mut self, t: Ty<'tcx>) -> Ty<'tcx> {
548         debug!("BoundsChecker t={:?}",
549                t);
550
551         match self.cache {
552             Some(ref mut cache) => {
553                 if !cache.insert(t) {
554                     // Already checked this type! Don't check again.
555                     debug!("cached");
556                     return t;
557                 }
558             }
559             None => { }
560         }
561
562         match t.sty{
563             ty::TyStruct(def, substs) |
564             ty::TyEnum(def, substs) => {
565                 let type_predicates = def.predicates(self.fcx.tcx());
566                 let bounds = self.fcx.instantiate_bounds(self.span, substs,
567                                                          &type_predicates);
568
569                 if self.binding_count == 0 {
570                     self.fcx.add_obligations_for_parameters(
571                         traits::ObligationCause::new(self.span,
572                                                      self.fcx.body_id,
573                                                      traits::ItemObligation(def.did)),
574                         &bounds);
575                 } else {
576                     // There are two circumstances in which we ignore
577                     // region obligations.
578                     //
579                     // The first is when we are inside of a closure
580                     // type. This is because in that case the region
581                     // obligations for the parameter types are things
582                     // that the closure body gets to assume and the
583                     // caller must prove at the time of call. In other
584                     // words, if there is a type like `<'a, 'b> | &'a
585                     // &'b int |`, it is well-formed, and caller will
586                     // have to show that `'b : 'a` at the time of
587                     // call.
588                     //
589                     // The second is when we are checking for
590                     // well-formedness outside of a type def'n or fn
591                     // body. This is for a similar reason: in general,
592                     // we only do WF checking for regions in the
593                     // result of expressions and type definitions, so
594                     // to as allow for implicit where clauses.
595                     //
596                     // (I believe we should do the same for traits, but
597                     // that will require an RFC. -nmatsakis)
598                     let bounds = filter_to_trait_obligations(bounds);
599                     self.fcx.add_obligations_for_parameters(
600                         traits::ObligationCause::new(self.span,
601                                                      self.fcx.body_id,
602                                                      traits::ItemObligation(def.did)),
603                         &bounds);
604                 }
605
606                 self.fold_substs(substs);
607             }
608             _ => {
609                 super_fold_ty(self, t);
610             }
611         }
612
613         t // we're not folding to produce a new type, so just return `t` here
614     }
615 }
616
617 ///////////////////////////////////////////////////////////////////////////
618 // ADT
619
620 struct AdtVariant<'tcx> {
621     fields: Vec<AdtField<'tcx>>,
622 }
623
624 struct AdtField<'tcx> {
625     ty: Ty<'tcx>,
626     span: Span,
627 }
628
629 fn struct_variant<'a, 'tcx>(fcx: &FnCtxt<'a, 'tcx>,
630                             struct_def: &ast::StructDef)
631                             -> AdtVariant<'tcx> {
632     let fields =
633         struct_def.fields
634         .iter()
635         .map(|field| {
636             let field_ty = fcx.tcx().node_id_to_type(field.node.id);
637             let field_ty = fcx.instantiate_type_scheme(field.span,
638                                                        &fcx.inh
639                                                            .infcx
640                                                            .parameter_environment
641                                                            .free_substs,
642                                                        &field_ty);
643             AdtField { ty: field_ty, span: field.span }
644         })
645         .collect();
646     AdtVariant { fields: fields }
647 }
648
649 fn enum_variants<'a, 'tcx>(fcx: &FnCtxt<'a, 'tcx>,
650                            enum_def: &ast::EnumDef)
651                            -> Vec<AdtVariant<'tcx>> {
652     enum_def.variants.iter()
653         .map(|variant| {
654             match variant.node.kind {
655                 ast::TupleVariantKind(ref args) if !args.is_empty() => {
656                     let ctor_ty = fcx.tcx().node_id_to_type(variant.node.id);
657
658                     // the regions in the argument types come from the
659                     // enum def'n, and hence will all be early bound
660                     let arg_tys = fcx.tcx().no_late_bound_regions(&ctor_ty.fn_args()).unwrap();
661                     AdtVariant {
662                         fields: args.iter().enumerate().map(|(index, arg)| {
663                             let arg_ty = arg_tys[index];
664                             let arg_ty =
665                                 fcx.instantiate_type_scheme(variant.span,
666                                                             &fcx.inh
667                                                                 .infcx
668                                                                 .parameter_environment
669                                                                 .free_substs,
670                                                             &arg_ty);
671                             AdtField {
672                                 ty: arg_ty,
673                                 span: arg.ty.span
674                             }
675                         }).collect()
676                     }
677                 }
678                 ast::TupleVariantKind(_) => {
679                     AdtVariant {
680                         fields: Vec::new()
681                     }
682                 }
683                 ast::StructVariantKind(ref struct_def) => {
684                     struct_variant(fcx, &**struct_def)
685                 }
686             }
687         })
688         .collect()
689 }
690
691 fn filter_to_trait_obligations<'tcx>(bounds: ty::InstantiatedPredicates<'tcx>)
692                                      -> ty::InstantiatedPredicates<'tcx>
693 {
694     let mut result = ty::InstantiatedPredicates::empty();
695     for (space, _, predicate) in bounds.predicates.iter_enumerated() {
696         match *predicate {
697             ty::Predicate::Trait(..) |
698             ty::Predicate::Projection(..) => {
699                 result.predicates.push(space, predicate.clone())
700             }
701             ty::Predicate::WellFormed(..) |
702             ty::Predicate::ObjectSafe(..) |
703             ty::Predicate::Equate(..) |
704             ty::Predicate::TypeOutlives(..) |
705             ty::Predicate::RegionOutlives(..) => {
706             }
707         }
708     }
709     result
710 }