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