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