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