]> git.lizzy.rs Git - rust.git/blob - src/librustc_typeck/collect.rs
run EndRegion when unwinding otherwise-empty scopes
[rust.git] / src / librustc_typeck / collect.rs
1 // Copyright 2012-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 //! "Collection" is the process of determining the type and other external
12 //! details of each item in Rust. Collection is specifically concerned
13 //! with *interprocedural* things -- for example, for a function
14 //! definition, collection will figure out the type and signature of the
15 //! function, but it will not visit the *body* of the function in any way,
16 //! nor examine type annotations on local variables (that's the job of
17 //! type *checking*).
18 //!
19 //! Collecting is ultimately defined by a bundle of queries that
20 //! inquire after various facts about the items in the crate (e.g.,
21 //! `type_of`, `generics_of`, `predicates_of`, etc). See the `provide` function
22 //! for the full set.
23 //!
24 //! At present, however, we do run collection across all items in the
25 //! crate as a kind of pass. This should eventually be factored away.
26
27 use astconv::{AstConv, Bounds};
28 use lint;
29 use constrained_type_params as ctp;
30 use middle::lang_items::SizedTraitLangItem;
31 use middle::const_val::ConstVal;
32 use middle::resolve_lifetime as rl;
33 use rustc::traits::Reveal;
34 use rustc::ty::subst::Substs;
35 use rustc::ty::{ToPredicate, ReprOptions};
36 use rustc::ty::{self, AdtKind, ToPolyTraitRef, Ty, TyCtxt};
37 use rustc::ty::maps::Providers;
38 use rustc::ty::util::IntTypeExt;
39 use util::nodemap::FxHashMap;
40
41 use rustc_const_math::ConstInt;
42
43 use std::collections::BTreeMap;
44
45 use syntax::{abi, ast};
46 use syntax::codemap::Spanned;
47 use syntax::symbol::{Symbol, keywords};
48 use syntax_pos::{Span, DUMMY_SP};
49
50 use rustc::hir::{self, map as hir_map};
51 use rustc::hir::intravisit::{self, Visitor, NestedVisitorMap};
52 use rustc::hir::def::{Def, CtorKind};
53 use rustc::hir::def_id::DefId;
54
55 ///////////////////////////////////////////////////////////////////////////
56 // Main entry point
57
58 pub fn collect_item_types<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>) {
59     let mut visitor = CollectItemTypesVisitor { tcx: tcx };
60     tcx.hir.krate().visit_all_item_likes(&mut visitor.as_deep_visitor());
61 }
62
63 pub fn provide(providers: &mut Providers) {
64     *providers = Providers {
65         type_of,
66         generics_of,
67         predicates_of,
68         super_predicates_of,
69         type_param_predicates,
70         trait_def,
71         adt_def,
72         fn_sig,
73         impl_trait_ref,
74         impl_polarity,
75         is_foreign_item,
76         is_default_impl,
77         ..*providers
78     };
79 }
80
81 ///////////////////////////////////////////////////////////////////////////
82
83 /// Context specific to some particular item. This is what implements
84 /// AstConv. It has information about the predicates that are defined
85 /// on the trait. Unfortunately, this predicate information is
86 /// available in various different forms at various points in the
87 /// process. So we can't just store a pointer to e.g. the AST or the
88 /// parsed ty form, we have to be more flexible. To this end, the
89 /// `ItemCtxt` is parameterized by a `DefId` that it uses to satisfy
90 /// `get_type_parameter_bounds` requests, drawing the information from
91 /// the AST (`hir::Generics`), recursively.
92 pub struct ItemCtxt<'a,'tcx:'a> {
93     tcx: TyCtxt<'a, 'tcx, 'tcx>,
94     item_def_id: DefId,
95 }
96
97 ///////////////////////////////////////////////////////////////////////////
98
99 struct CollectItemTypesVisitor<'a, 'tcx: 'a> {
100     tcx: TyCtxt<'a, 'tcx, 'tcx>
101 }
102
103 impl<'a, 'tcx> Visitor<'tcx> for CollectItemTypesVisitor<'a, 'tcx> {
104     fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
105         NestedVisitorMap::OnlyBodies(&self.tcx.hir)
106     }
107
108     fn visit_item(&mut self, item: &'tcx hir::Item) {
109         convert_item(self.tcx, item.id);
110         intravisit::walk_item(self, item);
111     }
112
113     fn visit_generics(&mut self, generics: &'tcx hir::Generics) {
114         for param in &generics.ty_params {
115             if param.default.is_some() {
116                 let def_id = self.tcx.hir.local_def_id(param.id);
117                 self.tcx.type_of(def_id);
118             }
119         }
120         intravisit::walk_generics(self, generics);
121     }
122
123     fn visit_expr(&mut self, expr: &'tcx hir::Expr) {
124         if let hir::ExprClosure(..) = expr.node {
125             let def_id = self.tcx.hir.local_def_id(expr.id);
126             self.tcx.generics_of(def_id);
127             self.tcx.type_of(def_id);
128         }
129         intravisit::walk_expr(self, expr);
130     }
131
132     fn visit_ty(&mut self, ty: &'tcx hir::Ty) {
133         if let hir::TyImplTrait(..) = ty.node {
134             let def_id = self.tcx.hir.local_def_id(ty.id);
135             self.tcx.generics_of(def_id);
136             self.tcx.predicates_of(def_id);
137         }
138         intravisit::walk_ty(self, ty);
139     }
140
141     fn visit_trait_item(&mut self, trait_item: &'tcx hir::TraitItem) {
142         convert_trait_item(self.tcx, trait_item.id);
143         intravisit::walk_trait_item(self, trait_item);
144     }
145
146     fn visit_impl_item(&mut self, impl_item: &'tcx hir::ImplItem) {
147         convert_impl_item(self.tcx, impl_item.id);
148         intravisit::walk_impl_item(self, impl_item);
149     }
150 }
151
152 ///////////////////////////////////////////////////////////////////////////
153 // Utility types and common code for the above passes.
154
155 impl<'a, 'tcx> ItemCtxt<'a, 'tcx> {
156     pub fn new(tcx: TyCtxt<'a, 'tcx, 'tcx>, item_def_id: DefId)
157            -> ItemCtxt<'a,'tcx> {
158         ItemCtxt {
159             tcx,
160             item_def_id,
161         }
162     }
163 }
164
165 impl<'a,'tcx> ItemCtxt<'a,'tcx> {
166     pub fn to_ty(&self, ast_ty: &hir::Ty) -> Ty<'tcx> {
167         AstConv::ast_ty_to_ty(self, ast_ty)
168     }
169 }
170
171 impl<'a, 'tcx> AstConv<'tcx, 'tcx> for ItemCtxt<'a, 'tcx> {
172     fn tcx<'b>(&'b self) -> TyCtxt<'b, 'tcx, 'tcx> { self.tcx }
173
174     fn get_type_parameter_bounds(&self,
175                                  span: Span,
176                                  def_id: DefId)
177                                  -> ty::GenericPredicates<'tcx>
178     {
179         self.tcx.at(span).type_param_predicates((self.item_def_id, def_id))
180     }
181
182     fn re_infer(&self, _span: Span, _def: Option<&ty::RegionParameterDef>)
183                 -> Option<ty::Region<'tcx>> {
184         None
185     }
186
187     fn ty_infer(&self, span: Span) -> Ty<'tcx> {
188         struct_span_err!(
189             self.tcx().sess,
190             span,
191             E0121,
192             "the type placeholder `_` is not allowed within types on item signatures"
193         ).span_label(span, "not allowed in type signatures")
194         .emit();
195         self.tcx().types.err
196     }
197
198     fn projected_ty_from_poly_trait_ref(&self,
199                                         span: Span,
200                                         item_def_id: DefId,
201                                         poly_trait_ref: ty::PolyTraitRef<'tcx>)
202                                         -> Ty<'tcx>
203     {
204         if let Some(trait_ref) = self.tcx().no_late_bound_regions(&poly_trait_ref) {
205             self.tcx().mk_projection(item_def_id, trait_ref.substs)
206         } else {
207             // no late-bound regions, we can just ignore the binder
208             span_err!(self.tcx().sess, span, E0212,
209                 "cannot extract an associated type from a higher-ranked trait bound \
210                  in this context");
211             self.tcx().types.err
212         }
213     }
214
215     fn normalize_ty(&self, _span: Span, ty: Ty<'tcx>) -> Ty<'tcx> {
216         // types in item signatures are not normalized, to avoid undue
217         // dependencies.
218         ty
219     }
220
221     fn set_tainted_by_errors(&self) {
222         // no obvious place to track this, just let it go
223     }
224
225     fn record_ty(&self, _hir_id: hir::HirId, _ty: Ty<'tcx>, _span: Span) {
226         // no place to record types from signatures?
227     }
228 }
229
230 fn type_param_predicates<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
231                                    (item_def_id, def_id): (DefId, DefId))
232                                    -> ty::GenericPredicates<'tcx> {
233     use rustc::hir::map::*;
234     use rustc::hir::*;
235
236     // In the AST, bounds can derive from two places. Either
237     // written inline like `<T:Foo>` or in a where clause like
238     // `where T:Foo`.
239
240     let param_id = tcx.hir.as_local_node_id(def_id).unwrap();
241     let param_owner = tcx.hir.ty_param_owner(param_id);
242     let param_owner_def_id = tcx.hir.local_def_id(param_owner);
243     let generics = tcx.generics_of(param_owner_def_id);
244     let index = generics.type_param_to_index[&def_id.index];
245     let ty = tcx.mk_param(index, tcx.hir.ty_param_name(param_id));
246
247     // Don't look for bounds where the type parameter isn't in scope.
248     let parent = if item_def_id == param_owner_def_id {
249         None
250     } else {
251         tcx.generics_of(item_def_id).parent
252     };
253
254     let mut result = parent.map_or(ty::GenericPredicates {
255         parent: None,
256         predicates: vec![]
257     }, |parent| {
258         let icx = ItemCtxt::new(tcx, parent);
259         icx.get_type_parameter_bounds(DUMMY_SP, def_id)
260     });
261
262     let item_node_id = tcx.hir.as_local_node_id(item_def_id).unwrap();
263     let ast_generics = match tcx.hir.get(item_node_id) {
264         NodeTraitItem(item) => {
265             match item.node {
266                 TraitItemKind::Method(ref sig, _) => &sig.generics,
267                 _ => return result
268             }
269         }
270
271         NodeImplItem(item) => {
272             match item.node {
273                 ImplItemKind::Method(ref sig, _) => &sig.generics,
274                 _ => return result
275             }
276         }
277
278         NodeItem(item) => {
279             match item.node {
280                 ItemFn(.., ref generics, _) |
281                 ItemImpl(_, _, _, ref generics, ..) |
282                 ItemTy(_, ref generics) |
283                 ItemEnum(_, ref generics) |
284                 ItemStruct(_, ref generics) |
285                 ItemUnion(_, ref generics) => generics,
286                 ItemTrait(_, ref generics, ..) => {
287                     // Implied `Self: Trait` and supertrait bounds.
288                     if param_id == item_node_id {
289                         result.predicates.push(ty::TraitRef {
290                             def_id: item_def_id,
291                             substs: Substs::identity_for_item(tcx, item_def_id)
292                         }.to_predicate());
293                     }
294                     generics
295                 }
296                 _ => return result
297             }
298         }
299
300         NodeForeignItem(item) => {
301             match item.node {
302                 ForeignItemFn(_, _, ref generics) => generics,
303                 _ => return result
304             }
305         }
306
307         _ => return result
308     };
309
310     let icx = ItemCtxt::new(tcx, item_def_id);
311     result.predicates.extend(
312         icx.type_parameter_bounds_in_generics(ast_generics, param_id, ty));
313     result
314 }
315
316 impl<'a, 'tcx> ItemCtxt<'a, 'tcx> {
317     /// Find bounds from hir::Generics. This requires scanning through the
318     /// AST. We do this to avoid having to convert *all* the bounds, which
319     /// would create artificial cycles. Instead we can only convert the
320     /// bounds for a type parameter `X` if `X::Foo` is used.
321     fn type_parameter_bounds_in_generics(&self,
322                                          ast_generics: &hir::Generics,
323                                          param_id: ast::NodeId,
324                                          ty: Ty<'tcx>)
325                                          -> Vec<ty::Predicate<'tcx>>
326     {
327         let from_ty_params =
328             ast_generics.ty_params
329                 .iter()
330                 .filter(|p| p.id == param_id)
331                 .flat_map(|p| p.bounds.iter())
332                 .flat_map(|b| predicates_from_bound(self, ty, b));
333
334         let from_where_clauses =
335             ast_generics.where_clause
336                 .predicates
337                 .iter()
338                 .filter_map(|wp| match *wp {
339                     hir::WherePredicate::BoundPredicate(ref bp) => Some(bp),
340                     _ => None
341                 })
342                 .filter(|bp| is_param(self.tcx, &bp.bounded_ty, param_id))
343                 .flat_map(|bp| bp.bounds.iter())
344                 .flat_map(|b| predicates_from_bound(self, ty, b));
345
346         from_ty_params.chain(from_where_clauses).collect()
347     }
348 }
349
350 /// Tests whether this is the AST for a reference to the type
351 /// parameter with id `param_id`. We use this so as to avoid running
352 /// `ast_ty_to_ty`, because we want to avoid triggering an all-out
353 /// conversion of the type to avoid inducing unnecessary cycles.
354 fn is_param<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
355                       ast_ty: &hir::Ty,
356                       param_id: ast::NodeId)
357                       -> bool
358 {
359     if let hir::TyPath(hir::QPath::Resolved(None, ref path)) = ast_ty.node {
360         match path.def {
361             Def::SelfTy(Some(def_id), None) |
362             Def::TyParam(def_id) => {
363                 def_id == tcx.hir.local_def_id(param_id)
364             }
365             _ => false
366         }
367     } else {
368         false
369     }
370 }
371
372 fn ensure_no_ty_param_bounds(tcx: TyCtxt,
373                              span: Span,
374                              generics: &hir::Generics,
375                              thing: &'static str) {
376     let mut warn = false;
377
378     for ty_param in generics.ty_params.iter() {
379         for bound in ty_param.bounds.iter() {
380             match *bound {
381                 hir::TraitTyParamBound(..) => {
382                     warn = true;
383                 }
384                 hir::RegionTyParamBound(..) => { }
385             }
386         }
387     }
388
389     for predicate in generics.where_clause.predicates.iter() {
390         match *predicate {
391             hir::WherePredicate::BoundPredicate(..) => {
392                 warn = true;
393             }
394             hir::WherePredicate::RegionPredicate(..) => { }
395             hir::WherePredicate::EqPredicate(..) => { }
396         }
397     }
398
399     if warn {
400         // According to accepted RFC #XXX, we should
401         // eventually accept these, but it will not be
402         // part of this PR. Still, convert to warning to
403         // make bootstrapping easier.
404         span_warn!(tcx.sess, span, E0122,
405                    "trait bounds are not (yet) enforced \
406                    in {} definitions",
407                    thing);
408     }
409 }
410
411 fn convert_item<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, item_id: ast::NodeId) {
412     let it = tcx.hir.expect_item(item_id);
413     debug!("convert: item {} with id {}", it.name, it.id);
414     let def_id = tcx.hir.local_def_id(item_id);
415     match it.node {
416         // These don't define types.
417         hir::ItemExternCrate(_) |
418         hir::ItemUse(..) |
419         hir::ItemMod(_) |
420         hir::ItemGlobalAsm(_) => {}
421         hir::ItemForeignMod(ref foreign_mod) => {
422             for item in &foreign_mod.items {
423                 let def_id = tcx.hir.local_def_id(item.id);
424                 tcx.generics_of(def_id);
425                 tcx.type_of(def_id);
426                 tcx.predicates_of(def_id);
427                 if let hir::ForeignItemFn(..) = item.node {
428                     tcx.fn_sig(def_id);
429                 }
430             }
431         }
432         hir::ItemEnum(ref enum_definition, _) => {
433             tcx.generics_of(def_id);
434             tcx.type_of(def_id);
435             tcx.predicates_of(def_id);
436             convert_enum_variant_types(tcx, def_id, &enum_definition.variants);
437         },
438         hir::ItemDefaultImpl(..) => {
439             tcx.impl_trait_ref(def_id);
440         }
441         hir::ItemImpl(..) => {
442             tcx.generics_of(def_id);
443             tcx.type_of(def_id);
444             tcx.impl_trait_ref(def_id);
445             tcx.predicates_of(def_id);
446         },
447         hir::ItemTrait(..) => {
448             tcx.generics_of(def_id);
449             tcx.trait_def(def_id);
450             tcx.at(it.span).super_predicates_of(def_id);
451             tcx.predicates_of(def_id);
452         },
453         hir::ItemStruct(ref struct_def, _) |
454         hir::ItemUnion(ref struct_def, _) => {
455             tcx.generics_of(def_id);
456             tcx.type_of(def_id);
457             tcx.predicates_of(def_id);
458
459             for f in struct_def.fields() {
460                 let def_id = tcx.hir.local_def_id(f.id);
461                 tcx.generics_of(def_id);
462                 tcx.type_of(def_id);
463                 tcx.predicates_of(def_id);
464             }
465
466             if !struct_def.is_struct() {
467                 convert_variant_ctor(tcx, struct_def.id());
468             }
469         },
470         hir::ItemTy(_, ref generics) => {
471             ensure_no_ty_param_bounds(tcx, it.span, generics, "type");
472             tcx.generics_of(def_id);
473             tcx.type_of(def_id);
474             tcx.predicates_of(def_id);
475         }
476         hir::ItemStatic(..) | hir::ItemConst(..) | hir::ItemFn(..) => {
477             tcx.generics_of(def_id);
478             tcx.type_of(def_id);
479             tcx.predicates_of(def_id);
480             if let hir::ItemFn(..) = it.node {
481                 tcx.fn_sig(def_id);
482             }
483         }
484     }
485 }
486
487 fn convert_trait_item<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, trait_item_id: ast::NodeId) {
488     let trait_item = tcx.hir.expect_trait_item(trait_item_id);
489     let def_id = tcx.hir.local_def_id(trait_item.id);
490     tcx.generics_of(def_id);
491
492     match trait_item.node {
493         hir::TraitItemKind::Const(..) |
494         hir::TraitItemKind::Type(_, Some(_)) |
495         hir::TraitItemKind::Method(..) => {
496             tcx.type_of(def_id);
497             if let hir::TraitItemKind::Method(..) = trait_item.node {
498                 tcx.fn_sig(def_id);
499             }
500         }
501
502         hir::TraitItemKind::Type(_, None) => {}
503     };
504
505     tcx.predicates_of(def_id);
506 }
507
508 fn convert_impl_item<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, impl_item_id: ast::NodeId) {
509     let def_id = tcx.hir.local_def_id(impl_item_id);
510     tcx.generics_of(def_id);
511     tcx.type_of(def_id);
512     tcx.predicates_of(def_id);
513     if let hir::ImplItemKind::Method(..) = tcx.hir.expect_impl_item(impl_item_id).node {
514         tcx.fn_sig(def_id);
515     }
516 }
517
518 fn convert_variant_ctor<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
519                                   ctor_id: ast::NodeId) {
520     let def_id = tcx.hir.local_def_id(ctor_id);
521     tcx.generics_of(def_id);
522     tcx.type_of(def_id);
523     tcx.predicates_of(def_id);
524 }
525
526 fn convert_enum_variant_types<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
527                                         def_id: DefId,
528                                         variants: &[hir::Variant]) {
529     let param_env = ty::ParamEnv::empty(Reveal::UserFacing);
530     let def = tcx.adt_def(def_id);
531     let repr_type = def.repr.discr_type();
532     let initial = repr_type.initial_discriminant(tcx);
533     let mut prev_discr = None::<ConstInt>;
534
535     // fill the discriminant values and field types
536     for variant in variants {
537         let wrapped_discr = prev_discr.map_or(initial, |d| d.wrap_incr());
538         prev_discr = Some(if let Some(e) = variant.node.disr_expr {
539             let expr_did = tcx.hir.local_def_id(e.node_id);
540             let substs = Substs::identity_for_item(tcx, expr_did);
541             let result = tcx.at(variant.span).const_eval(param_env.and((expr_did, substs)));
542
543             // enum variant evaluation happens before the global constant check
544             // so we need to report the real error
545             if let Err(ref err) = result {
546                 err.report(tcx, variant.span, "enum discriminant");
547             }
548
549             match result {
550                 Ok(&ty::Const { val: ConstVal::Integral(x), .. }) => Some(x),
551                 _ => None
552             }
553         } else if let Some(discr) = repr_type.disr_incr(tcx, prev_discr) {
554             Some(discr)
555         } else {
556             struct_span_err!(tcx.sess, variant.span, E0370,
557                              "enum discriminant overflowed")
558                 .span_label(variant.span, format!("overflowed on value after {}",
559                                                    prev_discr.unwrap()))
560                 .note(&format!("explicitly set `{} = {}` if that is desired outcome",
561                                variant.node.name, wrapped_discr))
562                 .emit();
563             None
564         }.unwrap_or(wrapped_discr));
565
566         for f in variant.node.data.fields() {
567             let def_id = tcx.hir.local_def_id(f.id);
568             tcx.generics_of(def_id);
569             tcx.type_of(def_id);
570             tcx.predicates_of(def_id);
571         }
572
573         // Convert the ctor, if any. This also registers the variant as
574         // an item.
575         convert_variant_ctor(tcx, variant.node.data.id());
576     }
577 }
578
579 fn convert_struct_variant<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
580                                     did: DefId,
581                                     name: ast::Name,
582                                     discr: ty::VariantDiscr,
583                                     def: &hir::VariantData)
584                                     -> ty::VariantDef {
585     let mut seen_fields: FxHashMap<ast::Name, Span> = FxHashMap();
586     let node_id = tcx.hir.as_local_node_id(did).unwrap();
587     let fields = def.fields().iter().map(|f| {
588         let fid = tcx.hir.local_def_id(f.id);
589         let dup_span = seen_fields.get(&f.name).cloned();
590         if let Some(prev_span) = dup_span {
591             struct_span_err!(tcx.sess, f.span, E0124,
592                              "field `{}` is already declared",
593                              f.name)
594                 .span_label(f.span, "field already declared")
595                 .span_label(prev_span, format!("`{}` first declared here", f.name))
596                 .emit();
597         } else {
598             seen_fields.insert(f.name, f.span);
599         }
600
601         ty::FieldDef {
602             did: fid,
603             name: f.name,
604             vis: ty::Visibility::from_hir(&f.vis, node_id, tcx)
605         }
606     }).collect();
607     ty::VariantDef {
608         did,
609         name,
610         discr,
611         fields,
612         ctor_kind: CtorKind::from_hir(def),
613     }
614 }
615
616 fn adt_def<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
617                      def_id: DefId)
618                      -> &'tcx ty::AdtDef {
619     use rustc::hir::map::*;
620     use rustc::hir::*;
621
622     let node_id = tcx.hir.as_local_node_id(def_id).unwrap();
623     let item = match tcx.hir.get(node_id) {
624         NodeItem(item) => item,
625         _ => bug!()
626     };
627
628     let repr = ReprOptions::new(tcx, def_id);
629     let (kind, variants) = match item.node {
630         ItemEnum(ref def, _) => {
631             let mut distance_from_explicit = 0;
632             (AdtKind::Enum, def.variants.iter().map(|v| {
633                 let did = tcx.hir.local_def_id(v.node.data.id());
634                 let discr = if let Some(e) = v.node.disr_expr {
635                     distance_from_explicit = 0;
636                     ty::VariantDiscr::Explicit(tcx.hir.local_def_id(e.node_id))
637                 } else {
638                     ty::VariantDiscr::Relative(distance_from_explicit)
639                 };
640                 distance_from_explicit += 1;
641
642                 convert_struct_variant(tcx, did, v.node.name, discr, &v.node.data)
643             }).collect())
644         }
645         ItemStruct(ref def, _) => {
646             // Use separate constructor id for unit/tuple structs and reuse did for braced structs.
647             let ctor_id = if !def.is_struct() {
648                 Some(tcx.hir.local_def_id(def.id()))
649             } else {
650                 None
651             };
652             (AdtKind::Struct, vec![
653                 convert_struct_variant(tcx, ctor_id.unwrap_or(def_id), item.name,
654                                        ty::VariantDiscr::Relative(0), def)
655             ])
656         }
657         ItemUnion(ref def, _) => {
658             (AdtKind::Union, vec![
659                 convert_struct_variant(tcx, def_id, item.name,
660                                        ty::VariantDiscr::Relative(0), def)
661             ])
662         }
663         _ => bug!()
664     };
665     tcx.alloc_adt_def(def_id, kind, variants, repr)
666 }
667
668 /// Ensures that the super-predicates of the trait with def-id
669 /// trait_def_id are converted and stored. This also ensures that
670 /// the transitive super-predicates are converted;
671 fn super_predicates_of<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
672                                  trait_def_id: DefId)
673                                  -> ty::GenericPredicates<'tcx> {
674     debug!("super_predicates(trait_def_id={:?})", trait_def_id);
675     let trait_node_id = tcx.hir.as_local_node_id(trait_def_id).unwrap();
676
677     let item = match tcx.hir.get(trait_node_id) {
678         hir_map::NodeItem(item) => item,
679         _ => bug!("trait_node_id {} is not an item", trait_node_id)
680     };
681
682     let (generics, bounds) = match item.node {
683         hir::ItemTrait(_, ref generics, ref supertraits, _) => (generics, supertraits),
684         _ => span_bug!(item.span,
685                        "super_predicates invoked on non-trait"),
686     };
687
688     let icx = ItemCtxt::new(tcx, trait_def_id);
689
690     // Convert the bounds that follow the colon, e.g. `Bar+Zed` in `trait Foo : Bar+Zed`.
691     let self_param_ty = tcx.mk_self_type();
692     let superbounds1 = compute_bounds(&icx,
693                                       self_param_ty,
694                                       bounds,
695                                       SizedByDefault::No,
696                                       item.span);
697
698     let superbounds1 = superbounds1.predicates(tcx, self_param_ty);
699
700     // Convert any explicit superbounds in the where clause,
701     // e.g. `trait Foo where Self : Bar`:
702     let superbounds2 = icx.type_parameter_bounds_in_generics(generics, item.id, self_param_ty);
703
704     // Combine the two lists to form the complete set of superbounds:
705     let superbounds: Vec<_> = superbounds1.into_iter().chain(superbounds2).collect();
706
707     // Now require that immediate supertraits are converted,
708     // which will, in turn, reach indirect supertraits.
709     for bound in superbounds.iter().filter_map(|p| p.to_opt_poly_trait_ref()) {
710         tcx.at(item.span).super_predicates_of(bound.def_id());
711     }
712
713     ty::GenericPredicates {
714         parent: None,
715         predicates: superbounds
716     }
717 }
718
719 fn trait_def<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
720                        def_id: DefId)
721                        -> &'tcx ty::TraitDef {
722     let node_id = tcx.hir.as_local_node_id(def_id).unwrap();
723     let item = tcx.hir.expect_item(node_id);
724
725     let unsafety = match item.node {
726         hir::ItemTrait(unsafety, ..) => unsafety,
727         _ => span_bug!(item.span, "trait_def_of_item invoked on non-trait"),
728     };
729
730     let paren_sugar = tcx.has_attr(def_id, "rustc_paren_sugar");
731     if paren_sugar && !tcx.sess.features.borrow().unboxed_closures {
732         let mut err = tcx.sess.struct_span_err(
733             item.span,
734             "the `#[rustc_paren_sugar]` attribute is a temporary means of controlling \
735              which traits can use parenthetical notation");
736         help!(&mut err,
737             "add `#![feature(unboxed_closures)]` to \
738              the crate attributes to use it");
739         err.emit();
740     }
741
742     let def_path_hash = tcx.def_path_hash(def_id);
743     let has_default_impl = tcx.hir.trait_is_auto(def_id);
744     let def = ty::TraitDef::new(def_id,
745                                 unsafety,
746                                 paren_sugar,
747                                 has_default_impl,
748                                 def_path_hash);
749     tcx.alloc_trait_def(def)
750 }
751
752 fn has_late_bound_regions<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
753                                     node: hir_map::Node<'tcx>)
754                                     -> Option<Span> {
755     struct LateBoundRegionsDetector<'a, 'tcx: 'a> {
756         tcx: TyCtxt<'a, 'tcx, 'tcx>,
757         binder_depth: u32,
758         has_late_bound_regions: Option<Span>,
759     }
760
761     impl<'a, 'tcx> Visitor<'tcx> for LateBoundRegionsDetector<'a, 'tcx> {
762         fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
763             NestedVisitorMap::None
764         }
765
766         fn visit_ty(&mut self, ty: &'tcx hir::Ty) {
767             if self.has_late_bound_regions.is_some() { return }
768             match ty.node {
769                 hir::TyBareFn(..) => {
770                     self.binder_depth += 1;
771                     intravisit::walk_ty(self, ty);
772                     self.binder_depth -= 1;
773                 }
774                 _ => intravisit::walk_ty(self, ty)
775             }
776         }
777
778         fn visit_poly_trait_ref(&mut self,
779                                 tr: &'tcx hir::PolyTraitRef,
780                                 m: hir::TraitBoundModifier) {
781             if self.has_late_bound_regions.is_some() { return }
782             self.binder_depth += 1;
783             intravisit::walk_poly_trait_ref(self, tr, m);
784             self.binder_depth -= 1;
785         }
786
787         fn visit_lifetime(&mut self, lt: &'tcx hir::Lifetime) {
788             if self.has_late_bound_regions.is_some() { return }
789
790             let hir_id = self.tcx.hir.node_to_hir_id(lt.id);
791             match self.tcx.named_region(hir_id) {
792                 Some(rl::Region::Static) | Some(rl::Region::EarlyBound(..)) => {}
793                 Some(rl::Region::LateBound(debruijn, _)) |
794                 Some(rl::Region::LateBoundAnon(debruijn, _))
795                     if debruijn.depth < self.binder_depth => {}
796                 _ => self.has_late_bound_regions = Some(lt.span),
797             }
798         }
799     }
800
801     fn has_late_bound_regions<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
802                                         generics: &'tcx hir::Generics,
803                                         decl: &'tcx hir::FnDecl)
804                                         -> Option<Span> {
805         let mut visitor = LateBoundRegionsDetector {
806             tcx, binder_depth: 1, has_late_bound_regions: None
807         };
808         for lifetime in &generics.lifetimes {
809             let hir_id = tcx.hir.node_to_hir_id(lifetime.lifetime.id);
810             if tcx.is_late_bound(hir_id) {
811                 return Some(lifetime.lifetime.span);
812             }
813         }
814         visitor.visit_fn_decl(decl);
815         visitor.has_late_bound_regions
816     }
817
818     match node {
819         hir_map::NodeTraitItem(item) => match item.node {
820             hir::TraitItemKind::Method(ref sig, _) =>
821                 has_late_bound_regions(tcx, &sig.generics, &sig.decl),
822             _ => None,
823         },
824         hir_map::NodeImplItem(item) => match item.node {
825             hir::ImplItemKind::Method(ref sig, _) =>
826                 has_late_bound_regions(tcx, &sig.generics, &sig.decl),
827             _ => None,
828         },
829         hir_map::NodeForeignItem(item) => match item.node {
830             hir::ForeignItemFn(ref fn_decl, _, ref generics) =>
831                 has_late_bound_regions(tcx, generics, fn_decl),
832             _ => None,
833         },
834         hir_map::NodeItem(item) => match item.node {
835             hir::ItemFn(ref fn_decl, .., ref generics, _) =>
836                 has_late_bound_regions(tcx, generics, fn_decl),
837             _ => None,
838         },
839         _ => None
840     }
841 }
842
843 fn generics_of<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
844                          def_id: DefId)
845                          -> &'tcx ty::Generics {
846     use rustc::hir::map::*;
847     use rustc::hir::*;
848
849     let node_id = tcx.hir.as_local_node_id(def_id).unwrap();
850
851     let node = tcx.hir.get(node_id);
852     let parent_def_id = match node {
853         NodeImplItem(_) |
854         NodeTraitItem(_) |
855         NodeVariant(_) |
856         NodeStructCtor(_) |
857         NodeField(_) => {
858             let parent_id = tcx.hir.get_parent(node_id);
859             Some(tcx.hir.local_def_id(parent_id))
860         }
861         NodeExpr(&hir::Expr { node: hir::ExprClosure(..), .. }) => {
862             Some(tcx.closure_base_def_id(def_id))
863         }
864         NodeTy(&hir::Ty { node: hir::TyImplTrait(..), .. }) => {
865             let mut parent_id = node_id;
866             loop {
867                 match tcx.hir.get(parent_id) {
868                     NodeItem(_) | NodeImplItem(_) | NodeTraitItem(_) => break,
869                     _ => {
870                         parent_id = tcx.hir.get_parent_node(parent_id);
871                     }
872                 }
873             }
874             Some(tcx.hir.local_def_id(parent_id))
875         }
876         _ => None
877     };
878
879     let mut opt_self = None;
880     let mut allow_defaults = false;
881
882     let no_generics = hir::Generics::empty();
883     let ast_generics = match node {
884         NodeTraitItem(item) => {
885             match item.node {
886                 TraitItemKind::Method(ref sig, _) => &sig.generics,
887                 _ => &no_generics
888             }
889         }
890
891         NodeImplItem(item) => {
892             match item.node {
893                 ImplItemKind::Method(ref sig, _) => &sig.generics,
894                 _ => &no_generics
895             }
896         }
897
898         NodeItem(item) => {
899             match item.node {
900                 ItemFn(.., ref generics, _) |
901                 ItemImpl(_, _, _, ref generics, ..) => generics,
902
903                 ItemTy(_, ref generics) |
904                 ItemEnum(_, ref generics) |
905                 ItemStruct(_, ref generics) |
906                 ItemUnion(_, ref generics) => {
907                     allow_defaults = true;
908                     generics
909                 }
910
911                 ItemTrait(_, ref generics, ..) => {
912                     // Add in the self type parameter.
913                     //
914                     // Something of a hack: use the node id for the trait, also as
915                     // the node id for the Self type parameter.
916                     let param_id = item.id;
917
918                     opt_self = Some(ty::TypeParameterDef {
919                         index: 0,
920                         name: keywords::SelfType.name(),
921                         def_id: tcx.hir.local_def_id(param_id),
922                         has_default: false,
923                         object_lifetime_default: rl::Set1::Empty,
924                         pure_wrt_drop: false,
925                         synthetic: None,
926                     });
927
928                     allow_defaults = true;
929                     generics
930                 }
931
932                 _ => &no_generics
933             }
934         }
935
936         NodeForeignItem(item) => {
937             match item.node {
938                 ForeignItemStatic(..) => &no_generics,
939                 ForeignItemFn(_, _, ref generics) => generics
940             }
941         }
942
943         _ => &no_generics
944     };
945
946     let has_self = opt_self.is_some();
947     let mut parent_has_self = false;
948     let mut own_start = has_self as u32;
949     let (parent_regions, parent_types) = parent_def_id.map_or((0, 0), |def_id| {
950         let generics = tcx.generics_of(def_id);
951         assert_eq!(has_self, false);
952         parent_has_self = generics.has_self;
953         own_start = generics.count() as u32;
954         (generics.parent_regions + generics.regions.len() as u32,
955             generics.parent_types + generics.types.len() as u32)
956     });
957
958     let early_lifetimes = early_bound_lifetimes_from_generics(tcx, ast_generics);
959     let regions = early_lifetimes.enumerate().map(|(i, l)| {
960         ty::RegionParameterDef {
961             name: l.lifetime.name.name(),
962             index: own_start + i as u32,
963             def_id: tcx.hir.local_def_id(l.lifetime.id),
964             pure_wrt_drop: l.pure_wrt_drop,
965         }
966     }).collect::<Vec<_>>();
967
968     let hir_id = tcx.hir.node_to_hir_id(node_id);
969     let object_lifetime_defaults = tcx.object_lifetime_defaults(hir_id);
970
971     // Now create the real type parameters.
972     let type_start = own_start + regions.len() as u32;
973     let types = ast_generics.ty_params.iter().enumerate().map(|(i, p)| {
974         if p.name == keywords::SelfType.name() {
975             span_bug!(p.span, "`Self` should not be the name of a regular parameter");
976         }
977
978         if !allow_defaults && p.default.is_some() {
979             if !tcx.sess.features.borrow().default_type_parameter_fallback {
980                 tcx.lint_node(
981                     lint::builtin::INVALID_TYPE_PARAM_DEFAULT,
982                     p.id,
983                     p.span,
984                     &format!("defaults for type parameters are only allowed in `struct`, \
985                               `enum`, `type`, or `trait` definitions."));
986             }
987         }
988
989         ty::TypeParameterDef {
990             index: type_start + i as u32,
991             name: p.name,
992             def_id: tcx.hir.local_def_id(p.id),
993             has_default: p.default.is_some(),
994             object_lifetime_default:
995                 object_lifetime_defaults.as_ref().map_or(rl::Set1::Empty, |o| o[i]),
996             pure_wrt_drop: p.pure_wrt_drop,
997             synthetic: p.synthetic,
998         }
999     });
1000     let mut types: Vec<_> = opt_self.into_iter().chain(types).collect();
1001
1002     // provide junk type parameter defs - the only place that
1003     // cares about anything but the length is instantiation,
1004     // and we don't do that for closures.
1005     if let NodeExpr(&hir::Expr { node: hir::ExprClosure(..), .. }) = node {
1006         tcx.with_freevars(node_id, |fv| {
1007             types.extend(fv.iter().enumerate().map(|(i, _)| ty::TypeParameterDef {
1008                 index: type_start + i as u32,
1009                 name: Symbol::intern("<upvar>"),
1010                 def_id,
1011                 has_default: false,
1012                 object_lifetime_default: rl::Set1::Empty,
1013                 pure_wrt_drop: false,
1014                 synthetic: None,
1015             }));
1016         });
1017     }
1018
1019     let mut type_param_to_index = BTreeMap::new();
1020     for param in &types {
1021         type_param_to_index.insert(param.def_id.index, param.index);
1022     }
1023
1024     tcx.alloc_generics(ty::Generics {
1025         parent: parent_def_id,
1026         parent_regions,
1027         parent_types,
1028         regions,
1029         types,
1030         type_param_to_index,
1031         has_self: has_self || parent_has_self,
1032         has_late_bound_regions: has_late_bound_regions(tcx, node),
1033     })
1034 }
1035
1036 fn type_of<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
1037                      def_id: DefId)
1038                      -> Ty<'tcx> {
1039     use rustc::hir::map::*;
1040     use rustc::hir::*;
1041
1042     let node_id = tcx.hir.as_local_node_id(def_id).unwrap();
1043
1044     let icx = ItemCtxt::new(tcx, def_id);
1045
1046     match tcx.hir.get(node_id) {
1047         NodeTraitItem(item) => {
1048             match item.node {
1049                 TraitItemKind::Method(..) => {
1050                     let substs = Substs::identity_for_item(tcx, def_id);
1051                     tcx.mk_fn_def(def_id, substs)
1052                 }
1053                 TraitItemKind::Const(ref ty, _) |
1054                 TraitItemKind::Type(_, Some(ref ty)) => icx.to_ty(ty),
1055                 TraitItemKind::Type(_, None) => {
1056                     span_bug!(item.span, "associated type missing default");
1057                 }
1058             }
1059         }
1060
1061         NodeImplItem(item) => {
1062             match item.node {
1063                 ImplItemKind::Method(..) => {
1064                     let substs = Substs::identity_for_item(tcx, def_id);
1065                     tcx.mk_fn_def(def_id, substs)
1066                 }
1067                 ImplItemKind::Const(ref ty, _) => icx.to_ty(ty),
1068                 ImplItemKind::Type(ref ty) => {
1069                     if tcx.impl_trait_ref(tcx.hir.get_parent_did(node_id)).is_none() {
1070                         span_err!(tcx.sess, item.span, E0202,
1071                                   "associated types are not allowed in inherent impls");
1072                     }
1073
1074                     icx.to_ty(ty)
1075                 }
1076             }
1077         }
1078
1079         NodeItem(item) => {
1080             match item.node {
1081                 ItemStatic(ref t, ..) | ItemConst(ref t, _) |
1082                 ItemTy(ref t, _) | ItemImpl(.., ref t, _) => {
1083                     icx.to_ty(t)
1084                 }
1085                 ItemFn(..) => {
1086                     let substs = Substs::identity_for_item(tcx, def_id);
1087                     tcx.mk_fn_def(def_id, substs)
1088                 }
1089                 ItemEnum(..) |
1090                 ItemStruct(..) |
1091                 ItemUnion(..) => {
1092                     let def = tcx.adt_def(def_id);
1093                     let substs = Substs::identity_for_item(tcx, def_id);
1094                     tcx.mk_adt(def, substs)
1095                 }
1096                 ItemDefaultImpl(..) |
1097                 ItemTrait(..) |
1098                 ItemMod(..) |
1099                 ItemForeignMod(..) |
1100                 ItemGlobalAsm(..) |
1101                 ItemExternCrate(..) |
1102                 ItemUse(..) => {
1103                     span_bug!(
1104                         item.span,
1105                         "compute_type_of_item: unexpected item type: {:?}",
1106                         item.node);
1107                 }
1108             }
1109         }
1110
1111         NodeForeignItem(foreign_item) => {
1112             match foreign_item.node {
1113                 ForeignItemFn(..) => {
1114                     let substs = Substs::identity_for_item(tcx, def_id);
1115                     tcx.mk_fn_def(def_id, substs)
1116                 }
1117                 ForeignItemStatic(ref t, _) => icx.to_ty(t)
1118             }
1119         }
1120
1121         NodeStructCtor(&ref def) |
1122         NodeVariant(&Spanned { node: hir::Variant_ { data: ref def, .. }, .. }) => {
1123             match *def {
1124                 VariantData::Unit(..) | VariantData::Struct(..) => {
1125                     tcx.type_of(tcx.hir.get_parent_did(node_id))
1126                 }
1127                 VariantData::Tuple(..) => {
1128                     let substs = Substs::identity_for_item(tcx, def_id);
1129                     tcx.mk_fn_def(def_id, substs)
1130                 }
1131             }
1132         }
1133
1134         NodeField(field) => icx.to_ty(&field.ty),
1135
1136         NodeExpr(&hir::Expr { node: hir::ExprClosure(.., is_generator), .. }) => {
1137             if is_generator {
1138                 let hir_id = tcx.hir.node_to_hir_id(node_id);
1139                 return tcx.typeck_tables_of(def_id).node_id_to_type(hir_id);
1140             }
1141
1142             tcx.mk_closure(def_id, Substs::for_item(
1143                 tcx, def_id,
1144                 |def, _| {
1145                     let region = def.to_early_bound_region_data();
1146                     tcx.mk_region(ty::ReEarlyBound(region))
1147                 },
1148                 |def, _| tcx.mk_param_from_def(def)
1149             ))
1150         }
1151
1152         NodeExpr(_) => match tcx.hir.get(tcx.hir.get_parent_node(node_id)) {
1153             NodeTy(&hir::Ty { node: TyArray(_, body), .. }) |
1154             NodeTy(&hir::Ty { node: TyTypeof(body), .. }) |
1155             NodeExpr(&hir::Expr { node: ExprRepeat(_, body), .. })
1156                 if body.node_id == node_id => tcx.types.usize,
1157
1158             NodeVariant(&Spanned { node: Variant_ { disr_expr: Some(e), .. }, .. })
1159                 if e.node_id == node_id => {
1160                     tcx.adt_def(tcx.hir.get_parent_did(node_id))
1161                         .repr.discr_type().to_ty(tcx)
1162                 }
1163
1164             x => {
1165                 bug!("unexpected expr parent in type_of_def_id(): {:?}", x);
1166             }
1167         },
1168
1169         NodeTyParam(&hir::TyParam { default: Some(ref ty), .. }) => {
1170             icx.to_ty(ty)
1171         }
1172
1173         NodeTy(&hir::Ty { node: TyImplTrait(..), .. }) => {
1174             let owner = tcx.hir.get_parent_did(node_id);
1175             let hir_id = tcx.hir.node_to_hir_id(node_id);
1176             tcx.typeck_tables_of(owner).node_id_to_type(hir_id)
1177         }
1178
1179         x => {
1180             bug!("unexpected sort of node in type_of_def_id(): {:?}", x);
1181         }
1182     }
1183 }
1184
1185 fn fn_sig<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
1186                     def_id: DefId)
1187                     -> ty::PolyFnSig<'tcx> {
1188     use rustc::hir::map::*;
1189     use rustc::hir::*;
1190
1191     let node_id = tcx.hir.as_local_node_id(def_id).unwrap();
1192
1193     let icx = ItemCtxt::new(tcx, def_id);
1194
1195     match tcx.hir.get(node_id) {
1196         NodeTraitItem(&hir::TraitItem { node: TraitItemKind::Method(ref sig, _), .. }) |
1197         NodeImplItem(&hir::ImplItem { node: ImplItemKind::Method(ref sig, _), .. }) => {
1198             AstConv::ty_of_fn(&icx, sig.unsafety, sig.abi, &sig.decl)
1199         }
1200
1201         NodeItem(&hir::Item { node: ItemFn(ref decl, unsafety, _, abi, _, _), .. }) => {
1202             AstConv::ty_of_fn(&icx, unsafety, abi, decl)
1203         }
1204
1205         NodeForeignItem(&hir::ForeignItem { node: ForeignItemFn(ref fn_decl, _, _), .. }) => {
1206             let abi = tcx.hir.get_foreign_abi(node_id);
1207             compute_sig_of_foreign_fn_decl(tcx, def_id, fn_decl, abi)
1208         }
1209
1210         NodeStructCtor(&VariantData::Tuple(ref fields, _)) |
1211         NodeVariant(&Spanned { node: hir::Variant_ {
1212             data: VariantData::Tuple(ref fields, _), ..
1213         }, .. }) => {
1214             let ty = tcx.type_of(tcx.hir.get_parent_did(node_id));
1215             let inputs = fields.iter().map(|f| {
1216                 tcx.type_of(tcx.hir.local_def_id(f.id))
1217             });
1218             ty::Binder(tcx.mk_fn_sig(
1219                 inputs,
1220                 ty,
1221                 false,
1222                 hir::Unsafety::Normal,
1223                 abi::Abi::Rust
1224             ))
1225         }
1226
1227         NodeExpr(&hir::Expr { node: hir::ExprClosure(..), hir_id, .. }) => {
1228             tcx.typeck_tables_of(def_id).closure_tys()[hir_id]
1229         }
1230
1231         x => {
1232             bug!("unexpected sort of node in fn_sig(): {:?}", x);
1233         }
1234     }
1235 }
1236
1237 fn impl_trait_ref<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
1238                             def_id: DefId)
1239                             -> Option<ty::TraitRef<'tcx>> {
1240     let icx = ItemCtxt::new(tcx, def_id);
1241
1242     let node_id = tcx.hir.as_local_node_id(def_id).unwrap();
1243     match tcx.hir.expect_item(node_id).node {
1244         hir::ItemDefaultImpl(_, ref ast_trait_ref) => {
1245             Some(AstConv::instantiate_mono_trait_ref(&icx,
1246                                                      ast_trait_ref,
1247                                                      tcx.mk_self_type()))
1248         }
1249         hir::ItemImpl(.., ref opt_trait_ref, _, _) => {
1250             opt_trait_ref.as_ref().map(|ast_trait_ref| {
1251                 let selfty = tcx.type_of(def_id);
1252                 AstConv::instantiate_mono_trait_ref(&icx, ast_trait_ref, selfty)
1253             })
1254         }
1255         _ => bug!()
1256     }
1257 }
1258
1259 fn impl_polarity<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
1260                            def_id: DefId)
1261                            -> hir::ImplPolarity {
1262     let node_id = tcx.hir.as_local_node_id(def_id).unwrap();
1263     match tcx.hir.expect_item(node_id).node {
1264         hir::ItemImpl(_, polarity, ..) => polarity,
1265         ref item => bug!("impl_polarity: {:?} not an impl", item)
1266     }
1267 }
1268
1269 // Is it marked with ?Sized
1270 fn is_unsized<'gcx: 'tcx, 'tcx>(astconv: &AstConv<'gcx, 'tcx>,
1271                                 ast_bounds: &[hir::TyParamBound],
1272                                 span: Span) -> bool
1273 {
1274     let tcx = astconv.tcx();
1275
1276     // Try to find an unbound in bounds.
1277     let mut unbound = None;
1278     for ab in ast_bounds {
1279         if let &hir::TraitTyParamBound(ref ptr, hir::TraitBoundModifier::Maybe) = ab  {
1280             if unbound.is_none() {
1281                 unbound = Some(ptr.trait_ref.clone());
1282             } else {
1283                 span_err!(tcx.sess, span, E0203,
1284                           "type parameter has more than one relaxed default \
1285                                                 bound, only one is supported");
1286             }
1287         }
1288     }
1289
1290     let kind_id = tcx.lang_items().require(SizedTraitLangItem);
1291     match unbound {
1292         Some(ref tpb) => {
1293             // FIXME(#8559) currently requires the unbound to be built-in.
1294             if let Ok(kind_id) = kind_id {
1295                 if tpb.path.def != Def::Trait(kind_id) {
1296                     tcx.sess.span_warn(span,
1297                                        "default bound relaxed for a type parameter, but \
1298                                        this does nothing because the given bound is not \
1299                                        a default. Only `?Sized` is supported");
1300                 }
1301             }
1302         }
1303         _ if kind_id.is_ok() => {
1304             return false;
1305         }
1306         // No lang item for Sized, so we can't add it as a bound.
1307         None => {}
1308     }
1309
1310     true
1311 }
1312
1313 /// Returns the early-bound lifetimes declared in this generics
1314 /// listing.  For anything other than fns/methods, this is just all
1315 /// the lifetimes that are declared. For fns or methods, we have to
1316 /// screen out those that do not appear in any where-clauses etc using
1317 /// `resolve_lifetime::early_bound_lifetimes`.
1318 fn early_bound_lifetimes_from_generics<'a, 'tcx>(
1319     tcx: TyCtxt<'a, 'tcx, 'tcx>,
1320     ast_generics: &'a hir::Generics)
1321     -> impl Iterator<Item=&'a hir::LifetimeDef>
1322 {
1323     ast_generics
1324         .lifetimes
1325         .iter()
1326         .filter(move |l| {
1327             let hir_id = tcx.hir.node_to_hir_id(l.lifetime.id);
1328             !tcx.is_late_bound(hir_id)
1329         })
1330 }
1331
1332 fn predicates_of<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
1333                            def_id: DefId)
1334                            -> ty::GenericPredicates<'tcx> {
1335     explicit_predicates_of(tcx, def_id)
1336 }
1337
1338 fn explicit_predicates_of<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
1339                            def_id: DefId)
1340                            -> ty::GenericPredicates<'tcx> {
1341     use rustc::hir::map::*;
1342     use rustc::hir::*;
1343
1344     let node_id = tcx.hir.as_local_node_id(def_id).unwrap();
1345     let node = tcx.hir.get(node_id);
1346
1347     let mut is_trait = None;
1348
1349     let icx = ItemCtxt::new(tcx, def_id);
1350     let no_generics = hir::Generics::empty();
1351     let ast_generics = match node {
1352         NodeTraitItem(item) => {
1353             match item.node {
1354                 TraitItemKind::Method(ref sig, _) => &sig.generics,
1355                 _ => &no_generics
1356             }
1357         }
1358
1359         NodeImplItem(item) => {
1360             match item.node {
1361                 ImplItemKind::Method(ref sig, _) => &sig.generics,
1362                 _ => &no_generics
1363             }
1364         }
1365
1366         NodeItem(item) => {
1367             match item.node {
1368                 ItemFn(.., ref generics, _) |
1369                 ItemImpl(_, _, _, ref generics, ..) |
1370                 ItemTy(_, ref generics) |
1371                 ItemEnum(_, ref generics) |
1372                 ItemStruct(_, ref generics) |
1373                 ItemUnion(_, ref generics) => {
1374                     generics
1375                 }
1376
1377                 ItemTrait(_, ref generics, .., ref items) => {
1378                     is_trait = Some((ty::TraitRef {
1379                         def_id,
1380                         substs: Substs::identity_for_item(tcx, def_id)
1381                     }, items));
1382                     generics
1383                 }
1384
1385                 _ => &no_generics
1386             }
1387         }
1388
1389         NodeForeignItem(item) => {
1390             match item.node {
1391                 ForeignItemStatic(..) => &no_generics,
1392                 ForeignItemFn(_, _, ref generics) => generics
1393             }
1394         }
1395
1396         NodeTy(&Ty { node: TyImplTrait(ref bounds), span, .. }) => {
1397             let substs = Substs::identity_for_item(tcx, def_id);
1398             let anon_ty = tcx.mk_anon(def_id, substs);
1399
1400             // Collect the bounds, i.e. the `A+B+'c` in `impl A+B+'c`.
1401             let bounds = compute_bounds(&icx, anon_ty, bounds,
1402                                         SizedByDefault::Yes,
1403                                         span);
1404             return ty::GenericPredicates {
1405                 parent: None,
1406                 predicates: bounds.predicates(tcx, anon_ty)
1407             };
1408         }
1409
1410         _ => &no_generics
1411     };
1412
1413     let generics = tcx.generics_of(def_id);
1414     let parent_count = generics.parent_count() as u32;
1415     let has_own_self = generics.has_self && parent_count == 0;
1416
1417     let mut predicates = vec![];
1418
1419     // Below we'll consider the bounds on the type parameters (including `Self`)
1420     // and the explicit where-clauses, but to get the full set of predicates
1421     // on a trait we need to add in the supertrait bounds and bounds found on
1422     // associated types.
1423     if let Some((trait_ref, _)) = is_trait {
1424         predicates = tcx.super_predicates_of(def_id).predicates;
1425
1426         // Add in a predicate that `Self:Trait` (where `Trait` is the
1427         // current trait).  This is needed for builtin bounds.
1428         predicates.push(trait_ref.to_poly_trait_ref().to_predicate());
1429     }
1430
1431     // Collect the region predicates that were declared inline as
1432     // well. In the case of parameters declared on a fn or method, we
1433     // have to be careful to only iterate over early-bound regions.
1434     let mut index = parent_count + has_own_self as u32;
1435     for param in early_bound_lifetimes_from_generics(tcx, ast_generics) {
1436         let region = tcx.mk_region(ty::ReEarlyBound(ty::EarlyBoundRegion {
1437             def_id: tcx.hir.local_def_id(param.lifetime.id),
1438             index,
1439             name: param.lifetime.name.name(),
1440         }));
1441         index += 1;
1442
1443         for bound in &param.bounds {
1444             let bound_region = AstConv::ast_region_to_region(&icx, bound, None);
1445             let outlives = ty::Binder(ty::OutlivesPredicate(region, bound_region));
1446             predicates.push(outlives.to_predicate());
1447         }
1448     }
1449
1450     // Collect the predicates that were written inline by the user on each
1451     // type parameter (e.g., `<T:Foo>`).
1452     for param in &ast_generics.ty_params {
1453         let param_ty = ty::ParamTy::new(index, param.name).to_ty(tcx);
1454         index += 1;
1455
1456         let bounds = compute_bounds(&icx,
1457                                     param_ty,
1458                                     &param.bounds,
1459                                     SizedByDefault::Yes,
1460                                     param.span);
1461         predicates.extend(bounds.predicates(tcx, param_ty));
1462     }
1463
1464     // Add in the bounds that appear in the where-clause
1465     let where_clause = &ast_generics.where_clause;
1466     for predicate in &where_clause.predicates {
1467         match predicate {
1468             &hir::WherePredicate::BoundPredicate(ref bound_pred) => {
1469                 let ty = icx.to_ty(&bound_pred.bounded_ty);
1470
1471                 for bound in bound_pred.bounds.iter() {
1472                     match bound {
1473                         &hir::TyParamBound::TraitTyParamBound(ref poly_trait_ref, _) => {
1474                             let mut projections = Vec::new();
1475
1476                             let trait_ref =
1477                                 AstConv::instantiate_poly_trait_ref(&icx,
1478                                                                     poly_trait_ref,
1479                                                                     ty,
1480                                                                     &mut projections);
1481
1482                             predicates.push(trait_ref.to_predicate());
1483
1484                             for projection in &projections {
1485                                 predicates.push(projection.to_predicate());
1486                             }
1487                         }
1488
1489                         &hir::TyParamBound::RegionTyParamBound(ref lifetime) => {
1490                             let region = AstConv::ast_region_to_region(&icx,
1491                                                                        lifetime,
1492                                                                        None);
1493                             let pred = ty::Binder(ty::OutlivesPredicate(ty, region));
1494                             predicates.push(ty::Predicate::TypeOutlives(pred))
1495                         }
1496                     }
1497                 }
1498             }
1499
1500             &hir::WherePredicate::RegionPredicate(ref region_pred) => {
1501                 let r1 = AstConv::ast_region_to_region(&icx, &region_pred.lifetime, None);
1502                 for bound in &region_pred.bounds {
1503                     let r2 = AstConv::ast_region_to_region(&icx, bound, None);
1504                     let pred = ty::Binder(ty::OutlivesPredicate(r1, r2));
1505                     predicates.push(ty::Predicate::RegionOutlives(pred))
1506                 }
1507             }
1508
1509             &hir::WherePredicate::EqPredicate(..) => {
1510                 // FIXME(#20041)
1511             }
1512         }
1513     }
1514
1515     // Add predicates from associated type bounds.
1516     if let Some((self_trait_ref, trait_items)) = is_trait {
1517         predicates.extend(trait_items.iter().flat_map(|trait_item_ref| {
1518             let trait_item = tcx.hir.trait_item(trait_item_ref.id);
1519             let bounds = match trait_item.node {
1520                 hir::TraitItemKind::Type(ref bounds, _) => bounds,
1521                 _ => {
1522                     return vec![].into_iter();
1523                 }
1524             };
1525
1526             let assoc_ty = tcx.mk_projection(
1527                 tcx.hir.local_def_id(trait_item.id),
1528                 self_trait_ref.substs,
1529             );
1530
1531             let bounds = compute_bounds(&ItemCtxt::new(tcx, def_id),
1532                                         assoc_ty,
1533                                         bounds,
1534                                         SizedByDefault::Yes,
1535                                         trait_item.span);
1536
1537             bounds.predicates(tcx, assoc_ty).into_iter()
1538         }))
1539     }
1540
1541     // Subtle: before we store the predicates into the tcx, we
1542     // sort them so that predicates like `T: Foo<Item=U>` come
1543     // before uses of `U`.  This avoids false ambiguity errors
1544     // in trait checking. See `setup_constraining_predicates`
1545     // for details.
1546     if let NodeItem(&Item { node: ItemImpl(..), .. }) = node {
1547         let self_ty = tcx.type_of(def_id);
1548         let trait_ref = tcx.impl_trait_ref(def_id);
1549         ctp::setup_constraining_predicates(tcx,
1550                                            &mut predicates,
1551                                            trait_ref,
1552                                            &mut ctp::parameters_for_impl(self_ty, trait_ref));
1553     }
1554
1555     ty::GenericPredicates {
1556         parent: generics.parent,
1557         predicates,
1558     }
1559 }
1560
1561 pub enum SizedByDefault { Yes, No, }
1562
1563 /// Translate the AST's notion of ty param bounds (which are an enum consisting of a newtyped Ty or
1564 /// a region) to ty's notion of ty param bounds, which can either be user-defined traits, or the
1565 /// built-in trait (formerly known as kind): Send.
1566 pub fn compute_bounds<'gcx: 'tcx, 'tcx>(astconv: &AstConv<'gcx, 'tcx>,
1567                                         param_ty: Ty<'tcx>,
1568                                         ast_bounds: &[hir::TyParamBound],
1569                                         sized_by_default: SizedByDefault,
1570                                         span: Span)
1571                                         -> Bounds<'tcx>
1572 {
1573     let mut region_bounds = vec![];
1574     let mut trait_bounds = vec![];
1575     for ast_bound in ast_bounds {
1576         match *ast_bound {
1577             hir::TraitTyParamBound(ref b, hir::TraitBoundModifier::None) => {
1578                 trait_bounds.push(b);
1579             }
1580             hir::TraitTyParamBound(_, hir::TraitBoundModifier::Maybe) => {}
1581             hir::RegionTyParamBound(ref l) => {
1582                 region_bounds.push(l);
1583             }
1584         }
1585     }
1586
1587     let mut projection_bounds = vec![];
1588
1589     let mut trait_bounds: Vec<_> = trait_bounds.iter().map(|&bound| {
1590         astconv.instantiate_poly_trait_ref(bound,
1591                                            param_ty,
1592                                            &mut projection_bounds)
1593     }).collect();
1594
1595     let region_bounds = region_bounds.into_iter().map(|r| {
1596         astconv.ast_region_to_region(r, None)
1597     }).collect();
1598
1599     trait_bounds.sort_by(|a,b| a.def_id().cmp(&b.def_id()));
1600
1601     let implicitly_sized = if let SizedByDefault::Yes = sized_by_default {
1602         !is_unsized(astconv, ast_bounds, span)
1603     } else {
1604         false
1605     };
1606
1607     Bounds {
1608         region_bounds,
1609         implicitly_sized,
1610         trait_bounds,
1611         projection_bounds,
1612     }
1613 }
1614
1615 /// Converts a specific TyParamBound from the AST into a set of
1616 /// predicates that apply to the self-type. A vector is returned
1617 /// because this can be anywhere from 0 predicates (`T:?Sized` adds no
1618 /// predicates) to 1 (`T:Foo`) to many (`T:Bar<X=i32>` adds `T:Bar`
1619 /// and `<T as Bar>::X == i32`).
1620 fn predicates_from_bound<'tcx>(astconv: &AstConv<'tcx, 'tcx>,
1621                                param_ty: Ty<'tcx>,
1622                                bound: &hir::TyParamBound)
1623                                -> Vec<ty::Predicate<'tcx>>
1624 {
1625     match *bound {
1626         hir::TraitTyParamBound(ref tr, hir::TraitBoundModifier::None) => {
1627             let mut projections = Vec::new();
1628             let pred = astconv.instantiate_poly_trait_ref(tr,
1629                                                           param_ty,
1630                                                           &mut projections);
1631             projections.into_iter()
1632                        .map(|p| p.to_predicate())
1633                        .chain(Some(pred.to_predicate()))
1634                        .collect()
1635         }
1636         hir::RegionTyParamBound(ref lifetime) => {
1637             let region = astconv.ast_region_to_region(lifetime, None);
1638             let pred = ty::Binder(ty::OutlivesPredicate(param_ty, region));
1639             vec![ty::Predicate::TypeOutlives(pred)]
1640         }
1641         hir::TraitTyParamBound(_, hir::TraitBoundModifier::Maybe) => {
1642             Vec::new()
1643         }
1644     }
1645 }
1646
1647 fn compute_sig_of_foreign_fn_decl<'a, 'tcx>(
1648     tcx: TyCtxt<'a, 'tcx, 'tcx>,
1649     def_id: DefId,
1650     decl: &hir::FnDecl,
1651     abi: abi::Abi)
1652     -> ty::PolyFnSig<'tcx>
1653 {
1654     let fty = AstConv::ty_of_fn(&ItemCtxt::new(tcx, def_id), hir::Unsafety::Unsafe, abi, decl);
1655
1656     // feature gate SIMD types in FFI, since I (huonw) am not sure the
1657     // ABIs are handled at all correctly.
1658     if abi != abi::Abi::RustIntrinsic && abi != abi::Abi::PlatformIntrinsic
1659             && !tcx.sess.features.borrow().simd_ffi {
1660         let check = |ast_ty: &hir::Ty, ty: Ty| {
1661             if ty.is_simd() {
1662                 tcx.sess.struct_span_err(ast_ty.span,
1663                               &format!("use of SIMD type `{}` in FFI is highly experimental and \
1664                                         may result in invalid code",
1665                                        tcx.hir.node_to_pretty_string(ast_ty.id)))
1666                     .help("add #![feature(simd_ffi)] to the crate attributes to enable")
1667                     .emit();
1668             }
1669         };
1670         for (input, ty) in decl.inputs.iter().zip(*fty.inputs().skip_binder()) {
1671             check(&input, ty)
1672         }
1673         if let hir::Return(ref ty) = decl.output {
1674             check(&ty, *fty.output().skip_binder())
1675         }
1676     }
1677
1678     fty
1679 }
1680
1681 fn is_foreign_item<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
1682                              def_id: DefId)
1683                              -> bool {
1684     match tcx.hir.get_if_local(def_id) {
1685         Some(hir_map::NodeForeignItem(..)) => true,
1686         Some(_) => false,
1687         _ => bug!("is_foreign_item applied to non-local def-id {:?}", def_id)
1688     }
1689 }
1690
1691 fn is_default_impl<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
1692                              def_id: DefId)
1693                              -> bool {
1694     match tcx.hir.get_if_local(def_id) {
1695         Some(hir_map::NodeItem(&hir::Item { node: hir::ItemDefaultImpl(..), .. }))
1696              => true,
1697         Some(_) => false,
1698         _ => bug!("is_default_impl applied to non-local def-id {:?}", def_id)
1699     }
1700 }