]> git.lizzy.rs Git - rust.git/blob - src/librustc_typeck/collect.rs
Rollup merge of #61056 - euclio:custom-discriminant-error, r=estebank
[rust.git] / src / librustc_typeck / collect.rs
1 //! "Collection" is the process of determining the type and other external
2 //! details of each item in Rust. Collection is specifically concerned
3 //! with *interprocedural* things -- for example, for a function
4 //! definition, collection will figure out the type and signature of the
5 //! function, but it will not visit the *body* of the function in any way,
6 //! nor examine type annotations on local variables (that's the job of
7 //! type *checking*).
8 //!
9 //! Collecting is ultimately defined by a bundle of queries that
10 //! inquire after various facts about the items in the crate (e.g.,
11 //! `type_of`, `generics_of`, `predicates_of`, etc). See the `provide` function
12 //! for the full set.
13 //!
14 //! At present, however, we do run collection across all items in the
15 //! crate as a kind of pass. This should eventually be factored away.
16
17 use crate::astconv::{AstConv, Bounds};
18 use crate::constrained_generic_params as cgp;
19 use crate::check::intrinsic::intrisic_operation_unsafety;
20 use crate::lint;
21 use crate::middle::lang_items::SizedTraitLangItem;
22 use crate::middle::resolve_lifetime as rl;
23 use crate::middle::weak_lang_items;
24 use rustc::mir::mono::Linkage;
25 use rustc::ty::query::Providers;
26 use rustc::ty::subst::{Subst, InternalSubsts};
27 use rustc::ty::util::Discr;
28 use rustc::ty::util::IntTypeExt;
29 use rustc::ty::subst::UnpackedKind;
30 use rustc::ty::{self, AdtKind, ToPolyTraitRef, Ty, TyCtxt};
31 use rustc::ty::{ReprOptions, ToPredicate};
32 use rustc::util::captures::Captures;
33 use rustc::util::nodemap::FxHashMap;
34 use rustc_target::spec::abi;
35
36 use syntax::ast;
37 use syntax::ast::{Ident, MetaItemKind};
38 use syntax::attr::{InlineAttr, OptimizeAttr, list_contains_name, mark_used};
39 use syntax::source_map::Spanned;
40 use syntax::feature_gate;
41 use syntax::symbol::{InternedString, kw, Symbol, sym};
42 use syntax_pos::{Span, DUMMY_SP};
43
44 use rustc::hir::def::{CtorKind, Res, DefKind};
45 use rustc::hir::Node;
46 use rustc::hir::def_id::{DefId, LOCAL_CRATE};
47 use rustc::hir::intravisit::{self, NestedVisitorMap, Visitor};
48 use rustc::hir::GenericParamKind;
49 use rustc::hir::{self, CodegenFnAttrFlags, CodegenFnAttrs, Unsafety};
50
51 use std::iter;
52
53 struct OnlySelfBounds(bool);
54
55 ///////////////////////////////////////////////////////////////////////////
56 // Main entry point
57
58 fn collect_mod_item_types<'tcx>(tcx: TyCtxt<'_, 'tcx, 'tcx>, module_def_id: DefId) {
59     tcx.hir().visit_item_likes_in_module(
60         module_def_id,
61         &mut CollectItemTypesVisitor { tcx }.as_deep_visitor()
62     );
63 }
64
65 pub fn provide(providers: &mut Providers<'_>) {
66     *providers = Providers {
67         type_of,
68         generics_of,
69         predicates_of,
70         predicates_defined_on,
71         explicit_predicates_of,
72         super_predicates_of,
73         type_param_predicates,
74         trait_def,
75         adt_def,
76         fn_sig,
77         impl_trait_ref,
78         impl_polarity,
79         is_foreign_item,
80         static_mutability,
81         codegen_fn_attrs,
82         collect_mod_item_types,
83         ..*providers
84     };
85 }
86
87 ///////////////////////////////////////////////////////////////////////////
88
89 /// Context specific to some particular item. This is what implements
90 /// `AstConv`. It has information about the predicates that are defined
91 /// on the trait. Unfortunately, this predicate information is
92 /// available in various different forms at various points in the
93 /// process. So we can't just store a pointer to e.g., the AST or the
94 /// parsed ty form, we have to be more flexible. To this end, the
95 /// `ItemCtxt` is parameterized by a `DefId` that it uses to satisfy
96 /// `get_type_parameter_bounds` requests, drawing the information from
97 /// the AST (`hir::Generics`), recursively.
98 pub struct ItemCtxt<'a, 'tcx: 'a> {
99     tcx: TyCtxt<'a, 'tcx, 'tcx>,
100     item_def_id: DefId,
101 }
102
103 ///////////////////////////////////////////////////////////////////////////
104
105 struct CollectItemTypesVisitor<'a, 'tcx: 'a> {
106     tcx: TyCtxt<'a, 'tcx, 'tcx>,
107 }
108
109 impl<'a, 'tcx> Visitor<'tcx> for CollectItemTypesVisitor<'a, 'tcx> {
110     fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
111         NestedVisitorMap::OnlyBodies(&self.tcx.hir())
112     }
113
114     fn visit_item(&mut self, item: &'tcx hir::Item) {
115         convert_item(self.tcx, item.hir_id);
116         intravisit::walk_item(self, item);
117     }
118
119     fn visit_generics(&mut self, generics: &'tcx hir::Generics) {
120         for param in &generics.params {
121             match param.kind {
122                 hir::GenericParamKind::Lifetime { .. } => {}
123                 hir::GenericParamKind::Type {
124                     default: Some(_), ..
125                 } => {
126                     let def_id = self.tcx.hir().local_def_id_from_hir_id(param.hir_id);
127                     self.tcx.type_of(def_id);
128                 }
129                 hir::GenericParamKind::Type { .. } => {}
130                 hir::GenericParamKind::Const { .. } => {
131                     let def_id = self.tcx.hir().local_def_id_from_hir_id(param.hir_id);
132                     self.tcx.type_of(def_id);
133                 }
134             }
135         }
136         intravisit::walk_generics(self, generics);
137     }
138
139     fn visit_expr(&mut self, expr: &'tcx hir::Expr) {
140         if let hir::ExprKind::Closure(..) = expr.node {
141             let def_id = self.tcx.hir().local_def_id_from_hir_id(expr.hir_id);
142             self.tcx.generics_of(def_id);
143             self.tcx.type_of(def_id);
144         }
145         intravisit::walk_expr(self, expr);
146     }
147
148     fn visit_trait_item(&mut self, trait_item: &'tcx hir::TraitItem) {
149         convert_trait_item(self.tcx, trait_item.hir_id);
150         intravisit::walk_trait_item(self, trait_item);
151     }
152
153     fn visit_impl_item(&mut self, impl_item: &'tcx hir::ImplItem) {
154         convert_impl_item(self.tcx, impl_item.hir_id);
155         intravisit::walk_impl_item(self, impl_item);
156     }
157 }
158
159 ///////////////////////////////////////////////////////////////////////////
160 // Utility types and common code for the above passes.
161
162 impl<'a, 'tcx> ItemCtxt<'a, 'tcx> {
163     pub fn new(tcx: TyCtxt<'a, 'tcx, 'tcx>, item_def_id: DefId) -> ItemCtxt<'a, 'tcx> {
164         ItemCtxt { tcx, item_def_id }
165     }
166 }
167
168 impl<'a, 'tcx> ItemCtxt<'a, 'tcx> {
169     pub fn to_ty(&self, ast_ty: &hir::Ty) -> Ty<'tcx> {
170         AstConv::ast_ty_to_ty(self, ast_ty)
171     }
172 }
173
174 impl<'a, 'tcx> AstConv<'tcx, 'tcx> for ItemCtxt<'a, 'tcx> {
175     fn tcx<'b>(&'b self) -> TyCtxt<'b, 'tcx, 'tcx> {
176         self.tcx
177     }
178
179     fn get_type_parameter_bounds(&self, span: Span, def_id: DefId)
180                                  -> &'tcx ty::GenericPredicates<'tcx> {
181         self.tcx
182             .at(span)
183             .type_param_predicates((self.item_def_id, def_id))
184     }
185
186     fn re_infer(
187         &self,
188         _span: Span,
189         _def: Option<&ty::GenericParamDef>,
190     ) -> Option<ty::Region<'tcx>> {
191         None
192     }
193
194     fn ty_infer(&self, span: Span) -> Ty<'tcx> {
195         struct_span_err!(
196             self.tcx().sess,
197             span,
198             E0121,
199             "the type placeholder `_` is not allowed within types on item signatures"
200         ).span_label(span, "not allowed in type signatures")
201          .emit();
202
203         self.tcx().types.err
204     }
205
206     fn projected_ty_from_poly_trait_ref(
207         &self,
208         span: Span,
209         item_def_id: DefId,
210         poly_trait_ref: ty::PolyTraitRef<'tcx>,
211     ) -> Ty<'tcx> {
212         if let Some(trait_ref) = poly_trait_ref.no_bound_vars() {
213             self.tcx().mk_projection(item_def_id, trait_ref.substs)
214         } else {
215             // no late-bound regions, we can just ignore the binder
216             span_err!(
217                 self.tcx().sess,
218                 span,
219                 E0212,
220                 "cannot extract an associated type from a higher-ranked trait bound \
221                  in this context"
222             );
223             self.tcx().types.err
224         }
225     }
226
227     fn normalize_ty(&self, _span: Span, ty: Ty<'tcx>) -> Ty<'tcx> {
228         // types in item signatures are not normalized, to avoid undue
229         // dependencies.
230         ty
231     }
232
233     fn set_tainted_by_errors(&self) {
234         // no obvious place to track this, just let it go
235     }
236
237     fn record_ty(&self, _hir_id: hir::HirId, _ty: Ty<'tcx>, _span: Span) {
238         // no place to record types from signatures?
239     }
240 }
241
242 fn type_param_predicates<'a, 'tcx>(
243     tcx: TyCtxt<'a, 'tcx, 'tcx>,
244     (item_def_id, def_id): (DefId, DefId),
245 ) -> &'tcx ty::GenericPredicates<'tcx> {
246     use rustc::hir::*;
247
248     // In the AST, bounds can derive from two places. Either
249     // written inline like `<T : Foo>` or in a where clause like
250     // `where T : Foo`.
251
252     let param_id = tcx.hir().as_local_hir_id(def_id).unwrap();
253     let param_owner = tcx.hir().ty_param_owner(param_id);
254     let param_owner_def_id = tcx.hir().local_def_id_from_hir_id(param_owner);
255     let generics = tcx.generics_of(param_owner_def_id);
256     let index = generics.param_def_id_to_index[&def_id];
257     let ty = tcx.mk_ty_param(index, tcx.hir().ty_param_name(param_id).as_interned_str());
258
259     // Don't look for bounds where the type parameter isn't in scope.
260     let parent = if item_def_id == param_owner_def_id {
261         None
262     } else {
263         tcx.generics_of(item_def_id).parent
264     };
265
266     let result = parent.map_or(&tcx.common.empty_predicates, |parent| {
267         let icx = ItemCtxt::new(tcx, parent);
268         icx.get_type_parameter_bounds(DUMMY_SP, def_id)
269     });
270     let mut extend = None;
271
272     let item_hir_id = tcx.hir().as_local_hir_id(item_def_id).unwrap();
273     let ast_generics = match tcx.hir().get_by_hir_id(item_hir_id) {
274         Node::TraitItem(item) => &item.generics,
275
276         Node::ImplItem(item) => &item.generics,
277
278         Node::Item(item) => {
279             match item.node {
280                 ItemKind::Fn(.., ref generics, _)
281                 | ItemKind::Impl(_, _, _, ref generics, ..)
282                 | ItemKind::Ty(_, ref generics)
283                 | ItemKind::Existential(ExistTy {
284                     ref generics,
285                     impl_trait_fn: None,
286                     ..
287                 })
288                 | ItemKind::Enum(_, ref generics)
289                 | ItemKind::Struct(_, ref generics)
290                 | ItemKind::Union(_, ref generics) => generics,
291                 ItemKind::Trait(_, _, ref generics, ..) => {
292                     // Implied `Self: Trait` and supertrait bounds.
293                     if param_id == item_hir_id {
294                         let identity_trait_ref = ty::TraitRef::identity(tcx, item_def_id);
295                         extend = Some((identity_trait_ref.to_predicate(), item.span));
296                     }
297                     generics
298                 }
299                 _ => return result,
300             }
301         }
302
303         Node::ForeignItem(item) => match item.node {
304             ForeignItemKind::Fn(_, _, ref generics) => generics,
305             _ => return result,
306         },
307
308         _ => return result,
309     };
310
311     let icx = ItemCtxt::new(tcx, item_def_id);
312     let mut result = (*result).clone();
313     result.predicates.extend(extend.into_iter());
314     result.predicates
315           .extend(icx.type_parameter_bounds_in_generics(ast_generics, param_id, ty,
316                   OnlySelfBounds(true)));
317     tcx.arena.alloc(result)
318 }
319
320 impl<'a, 'tcx> ItemCtxt<'a, 'tcx> {
321     /// Finds bounds from `hir::Generics`. This requires scanning through the
322     /// AST. We do this to avoid having to convert *all* the bounds, which
323     /// would create artificial cycles. Instead we can only convert the
324     /// bounds for a type parameter `X` if `X::Foo` is used.
325     fn type_parameter_bounds_in_generics(
326         &self,
327         ast_generics: &hir::Generics,
328         param_id: hir::HirId,
329         ty: Ty<'tcx>,
330         only_self_bounds: OnlySelfBounds,
331     ) -> Vec<(ty::Predicate<'tcx>, Span)> {
332         let from_ty_params = ast_generics
333             .params
334             .iter()
335             .filter_map(|param| match param.kind {
336                 GenericParamKind::Type { .. } if param.hir_id == param_id => Some(&param.bounds),
337                 _ => None,
338             })
339             .flat_map(|bounds| bounds.iter())
340             .flat_map(|b| predicates_from_bound(self, ty, b));
341
342         let from_where_clauses = ast_generics
343             .where_clause
344             .predicates
345             .iter()
346             .filter_map(|wp| match *wp {
347                 hir::WherePredicate::BoundPredicate(ref bp) => Some(bp),
348                 _ => None,
349             })
350             .flat_map(|bp| {
351                 let bt = if is_param(self.tcx, &bp.bounded_ty, param_id) {
352                     Some(ty)
353                 } else if !only_self_bounds.0 {
354                     Some(self.to_ty(&bp.bounded_ty))
355                 } else {
356                     None
357                 };
358                 bp.bounds.iter().filter_map(move |b| bt.map(|bt| (bt, b)))
359             })
360             .flat_map(|(bt, b)| predicates_from_bound(self, bt, b));
361
362         from_ty_params.chain(from_where_clauses).collect()
363     }
364 }
365
366 /// Tests whether this is the AST for a reference to the type
367 /// parameter with ID `param_id`. We use this so as to avoid running
368 /// `ast_ty_to_ty`, because we want to avoid triggering an all-out
369 /// conversion of the type to avoid inducing unnecessary cycles.
370 fn is_param<'a, 'tcx>(
371     tcx: TyCtxt<'a, 'tcx, 'tcx>,
372     ast_ty: &hir::Ty,
373     param_id: hir::HirId,
374 ) -> bool {
375     if let hir::TyKind::Path(hir::QPath::Resolved(None, ref path)) = ast_ty.node {
376         match path.res {
377             Res::SelfTy(Some(def_id), None) | Res::Def(DefKind::TyParam, def_id) => {
378                 def_id == tcx.hir().local_def_id_from_hir_id(param_id)
379             }
380             _ => false,
381         }
382     } else {
383         false
384     }
385 }
386
387 fn convert_item<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, item_id: hir::HirId) {
388     let it = tcx.hir().expect_item_by_hir_id(item_id);
389     debug!("convert: item {} with id {}", it.ident, it.hir_id);
390     let def_id = tcx.hir().local_def_id_from_hir_id(item_id);
391     match it.node {
392         // These don't define types.
393         hir::ItemKind::ExternCrate(_)
394         | hir::ItemKind::Use(..)
395         | hir::ItemKind::Mod(_)
396         | hir::ItemKind::GlobalAsm(_) => {}
397         hir::ItemKind::ForeignMod(ref foreign_mod) => {
398             for item in &foreign_mod.items {
399                 let def_id = tcx.hir().local_def_id_from_hir_id(item.hir_id);
400                 tcx.generics_of(def_id);
401                 tcx.type_of(def_id);
402                 tcx.predicates_of(def_id);
403                 if let hir::ForeignItemKind::Fn(..) = item.node {
404                     tcx.fn_sig(def_id);
405                 }
406             }
407         }
408         hir::ItemKind::Enum(ref enum_definition, _) => {
409             tcx.generics_of(def_id);
410             tcx.type_of(def_id);
411             tcx.predicates_of(def_id);
412             convert_enum_variant_types(tcx, def_id, &enum_definition.variants);
413         }
414         hir::ItemKind::Impl(..) => {
415             tcx.generics_of(def_id);
416             tcx.type_of(def_id);
417             tcx.impl_trait_ref(def_id);
418             tcx.predicates_of(def_id);
419         }
420         hir::ItemKind::Trait(..) => {
421             tcx.generics_of(def_id);
422             tcx.trait_def(def_id);
423             tcx.at(it.span).super_predicates_of(def_id);
424             tcx.predicates_of(def_id);
425         }
426         hir::ItemKind::TraitAlias(..) => {
427             tcx.generics_of(def_id);
428             tcx.at(it.span).super_predicates_of(def_id);
429             tcx.predicates_of(def_id);
430         }
431         hir::ItemKind::Struct(ref struct_def, _) | hir::ItemKind::Union(ref struct_def, _) => {
432             tcx.generics_of(def_id);
433             tcx.type_of(def_id);
434             tcx.predicates_of(def_id);
435
436             for f in struct_def.fields() {
437                 let def_id = tcx.hir().local_def_id_from_hir_id(f.hir_id);
438                 tcx.generics_of(def_id);
439                 tcx.type_of(def_id);
440                 tcx.predicates_of(def_id);
441             }
442
443             if let Some(ctor_hir_id) = struct_def.ctor_hir_id() {
444                 convert_variant_ctor(tcx, ctor_hir_id);
445             }
446         }
447
448         // Desugared from `impl Trait` -> visited by the function's return type
449         hir::ItemKind::Existential(hir::ExistTy {
450             impl_trait_fn: Some(_),
451             ..
452         }) => {}
453
454         hir::ItemKind::Existential(..)
455         | hir::ItemKind::Ty(..)
456         | hir::ItemKind::Static(..)
457         | hir::ItemKind::Const(..)
458         | hir::ItemKind::Fn(..) => {
459             tcx.generics_of(def_id);
460             tcx.type_of(def_id);
461             tcx.predicates_of(def_id);
462             if let hir::ItemKind::Fn(..) = it.node {
463                 tcx.fn_sig(def_id);
464             }
465         }
466     }
467 }
468
469 fn convert_trait_item<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, trait_item_id: hir::HirId) {
470     let trait_item = tcx.hir().expect_trait_item(trait_item_id);
471     let def_id = tcx.hir().local_def_id_from_hir_id(trait_item.hir_id);
472     tcx.generics_of(def_id);
473
474     match trait_item.node {
475         hir::TraitItemKind::Const(..)
476         | hir::TraitItemKind::Type(_, Some(_))
477         | hir::TraitItemKind::Method(..) => {
478             tcx.type_of(def_id);
479             if let hir::TraitItemKind::Method(..) = trait_item.node {
480                 tcx.fn_sig(def_id);
481             }
482         }
483
484         hir::TraitItemKind::Type(_, None) => {}
485     };
486
487     tcx.predicates_of(def_id);
488 }
489
490 fn convert_impl_item<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, impl_item_id: hir::HirId) {
491     let def_id = tcx.hir().local_def_id_from_hir_id(impl_item_id);
492     tcx.generics_of(def_id);
493     tcx.type_of(def_id);
494     tcx.predicates_of(def_id);
495     if let hir::ImplItemKind::Method(..) = tcx.hir().expect_impl_item(impl_item_id).node {
496         tcx.fn_sig(def_id);
497     }
498 }
499
500 fn convert_variant_ctor<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, ctor_id: hir::HirId) {
501     let def_id = tcx.hir().local_def_id_from_hir_id(ctor_id);
502     tcx.generics_of(def_id);
503     tcx.type_of(def_id);
504     tcx.predicates_of(def_id);
505 }
506
507 fn convert_enum_variant_types<'a, 'tcx>(
508     tcx: TyCtxt<'a, 'tcx, 'tcx>,
509     def_id: DefId,
510     variants: &[hir::Variant],
511 ) {
512     let def = tcx.adt_def(def_id);
513     let repr_type = def.repr.discr_type();
514     let initial = repr_type.initial_discriminant(tcx);
515     let mut prev_discr = None::<Discr<'tcx>>;
516
517     // fill the discriminant values and field types
518     for variant in variants {
519         let wrapped_discr = prev_discr.map_or(initial, |d| d.wrap_incr(tcx));
520         prev_discr = Some(
521             if let Some(ref e) = variant.node.disr_expr {
522                 let expr_did = tcx.hir().local_def_id_from_hir_id(e.hir_id);
523                 def.eval_explicit_discr(tcx, expr_did)
524             } else if let Some(discr) = repr_type.disr_incr(tcx, prev_discr) {
525                 Some(discr)
526             } else {
527                 struct_span_err!(
528                     tcx.sess,
529                     variant.span,
530                     E0370,
531                     "enum discriminant overflowed"
532                 ).span_label(
533                     variant.span,
534                     format!("overflowed on value after {}", prev_discr.unwrap()),
535                 ).note(&format!(
536                     "explicitly set `{} = {}` if that is desired outcome",
537                     variant.node.ident, wrapped_discr
538                 ))
539                 .emit();
540                 None
541             }.unwrap_or(wrapped_discr),
542         );
543
544         for f in variant.node.data.fields() {
545             let def_id = tcx.hir().local_def_id_from_hir_id(f.hir_id);
546             tcx.generics_of(def_id);
547             tcx.type_of(def_id);
548             tcx.predicates_of(def_id);
549         }
550
551         // Convert the ctor, if any. This also registers the variant as
552         // an item.
553         if let Some(ctor_hir_id) = variant.node.data.ctor_hir_id() {
554             convert_variant_ctor(tcx, ctor_hir_id);
555         }
556     }
557 }
558
559 fn convert_variant<'a, 'tcx>(
560     tcx: TyCtxt<'a, 'tcx, 'tcx>,
561     variant_did: Option<DefId>,
562     ctor_did: Option<DefId>,
563     ident: Ident,
564     discr: ty::VariantDiscr,
565     def: &hir::VariantData,
566     adt_kind: ty::AdtKind,
567     parent_did: DefId
568 ) -> ty::VariantDef {
569     let mut seen_fields: FxHashMap<ast::Ident, Span> = Default::default();
570     let hir_id = tcx.hir().as_local_hir_id(variant_did.unwrap_or(parent_did)).unwrap();
571     let fields = def
572         .fields()
573         .iter()
574         .map(|f| {
575             let fid = tcx.hir().local_def_id_from_hir_id(f.hir_id);
576             let dup_span = seen_fields.get(&f.ident.modern()).cloned();
577             if let Some(prev_span) = dup_span {
578                 struct_span_err!(
579                     tcx.sess,
580                     f.span,
581                     E0124,
582                     "field `{}` is already declared",
583                     f.ident
584                 ).span_label(f.span, "field already declared")
585                  .span_label(prev_span, format!("`{}` first declared here", f.ident))
586                  .emit();
587             } else {
588                 seen_fields.insert(f.ident.modern(), f.span);
589             }
590
591             ty::FieldDef {
592                 did: fid,
593                 ident: f.ident,
594                 vis: ty::Visibility::from_hir(&f.vis, hir_id, tcx),
595             }
596         })
597         .collect();
598     let recovered = match def {
599         hir::VariantData::Struct(_, r) => *r,
600         _ => false,
601     };
602     ty::VariantDef::new(
603         tcx,
604         ident,
605         variant_did,
606         ctor_did,
607         discr,
608         fields,
609         CtorKind::from_hir(def),
610         adt_kind,
611         parent_did,
612         recovered,
613     )
614 }
615
616 fn adt_def<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId) -> &'tcx ty::AdtDef {
617     use rustc::hir::*;
618
619     let hir_id = tcx.hir().as_local_hir_id(def_id).unwrap();
620     let item = match tcx.hir().get_by_hir_id(hir_id) {
621         Node::Item(item) => item,
622         _ => bug!(),
623     };
624
625     let repr = ReprOptions::new(tcx, def_id);
626     let (kind, variants) = match item.node {
627         ItemKind::Enum(ref def, _) => {
628             let mut distance_from_explicit = 0;
629             let variants = def.variants
630                 .iter()
631                 .map(|v| {
632                     let variant_did = Some(tcx.hir().local_def_id_from_hir_id(v.node.id));
633                     let ctor_did = v.node.data.ctor_hir_id()
634                         .map(|hir_id| tcx.hir().local_def_id_from_hir_id(hir_id));
635
636                     let discr = if let Some(ref e) = v.node.disr_expr {
637                         distance_from_explicit = 0;
638                         ty::VariantDiscr::Explicit(tcx.hir().local_def_id_from_hir_id(e.hir_id))
639                     } else {
640                         ty::VariantDiscr::Relative(distance_from_explicit)
641                     };
642                     distance_from_explicit += 1;
643
644                     convert_variant(tcx, variant_did, ctor_did, v.node.ident, discr,
645                                     &v.node.data, AdtKind::Enum, def_id)
646                 })
647                 .collect();
648
649             (AdtKind::Enum, variants)
650         }
651         ItemKind::Struct(ref def, _) => {
652             let variant_did = None;
653             let ctor_did = def.ctor_hir_id()
654                 .map(|hir_id| tcx.hir().local_def_id_from_hir_id(hir_id));
655
656             let variants = std::iter::once(convert_variant(
657                 tcx, variant_did, ctor_did, item.ident, ty::VariantDiscr::Relative(0), def,
658                 AdtKind::Struct, def_id,
659             )).collect();
660
661             (AdtKind::Struct, variants)
662         }
663         ItemKind::Union(ref def, _) => {
664             let variant_did = None;
665             let ctor_did = def.ctor_hir_id()
666                 .map(|hir_id| tcx.hir().local_def_id_from_hir_id(hir_id));
667
668             let variants = std::iter::once(convert_variant(
669                 tcx, variant_did, ctor_did, item.ident, ty::VariantDiscr::Relative(0), def,
670                 AdtKind::Union, def_id,
671             )).collect();
672
673             (AdtKind::Union, variants)
674         },
675         _ => bug!(),
676     };
677     tcx.alloc_adt_def(def_id, kind, variants, repr)
678 }
679
680 /// Ensures that the super-predicates of the trait with a `DefId`
681 /// of `trait_def_id` are converted and stored. This also ensures that
682 /// the transitive super-predicates are converted.
683 fn super_predicates_of<'a, 'tcx>(
684     tcx: TyCtxt<'a, 'tcx, 'tcx>,
685     trait_def_id: DefId,
686 ) -> &'tcx ty::GenericPredicates<'tcx> {
687     debug!("super_predicates(trait_def_id={:?})", trait_def_id);
688     let trait_hir_id = tcx.hir().as_local_hir_id(trait_def_id).unwrap();
689
690     let item = match tcx.hir().get_by_hir_id(trait_hir_id) {
691         Node::Item(item) => item,
692         _ => bug!("trait_node_id {} is not an item", trait_hir_id),
693     };
694
695     let (generics, bounds) = match item.node {
696         hir::ItemKind::Trait(.., ref generics, ref supertraits, _) => (generics, supertraits),
697         hir::ItemKind::TraitAlias(ref generics, ref supertraits) => (generics, supertraits),
698         _ => span_bug!(item.span, "super_predicates invoked on non-trait"),
699     };
700
701     let icx = ItemCtxt::new(tcx, trait_def_id);
702
703     // Convert the bounds that follow the colon, e.g., `Bar + Zed` in `trait Foo: Bar + Zed`.
704     let self_param_ty = tcx.mk_self_type();
705     let superbounds1 = compute_bounds(&icx, self_param_ty, bounds, SizedByDefault::No, item.span);
706
707     let superbounds1 = superbounds1.predicates(tcx, self_param_ty);
708
709     // Convert any explicit superbounds in the where-clause,
710     // e.g., `trait Foo where Self: Bar`.
711     // In the case of trait aliases, however, we include all bounds in the where-clause,
712     // so e.g., `trait Foo = where u32: PartialEq<Self>` would include `u32: PartialEq<Self>`
713     // as one of its "superpredicates".
714     let is_trait_alias = tcx.is_trait_alias(trait_def_id);
715     let superbounds2 = icx.type_parameter_bounds_in_generics(
716         generics, item.hir_id, self_param_ty, OnlySelfBounds(!is_trait_alias));
717
718     // Combine the two lists to form the complete set of superbounds:
719     let superbounds: Vec<_> = superbounds1.into_iter().chain(superbounds2).collect();
720
721     // Now require that immediate supertraits are converted,
722     // which will, in turn, reach indirect supertraits.
723     for &(pred, span) in &superbounds {
724         debug!("superbound: {:?}", pred);
725         if let ty::Predicate::Trait(bound) = pred {
726             tcx.at(span).super_predicates_of(bound.def_id());
727         }
728     }
729
730     tcx.arena.alloc(ty::GenericPredicates {
731         parent: None,
732         predicates: superbounds,
733     })
734 }
735
736 fn trait_def<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId) -> &'tcx ty::TraitDef {
737     let hir_id = tcx.hir().as_local_hir_id(def_id).unwrap();
738     let item = tcx.hir().expect_item_by_hir_id(hir_id);
739
740     let (is_auto, unsafety) = match item.node {
741         hir::ItemKind::Trait(is_auto, unsafety, ..) => (is_auto == hir::IsAuto::Yes, unsafety),
742         hir::ItemKind::TraitAlias(..) => (false, hir::Unsafety::Normal),
743         _ => span_bug!(item.span, "trait_def_of_item invoked on non-trait"),
744     };
745
746     let paren_sugar = tcx.has_attr(def_id, sym::rustc_paren_sugar);
747     if paren_sugar && !tcx.features().unboxed_closures {
748         let mut err = tcx.sess.struct_span_err(
749             item.span,
750             "the `#[rustc_paren_sugar]` attribute is a temporary means of controlling \
751              which traits can use parenthetical notation",
752         );
753         help!(
754             &mut err,
755             "add `#![feature(unboxed_closures)]` to \
756              the crate attributes to use it"
757         );
758         err.emit();
759     }
760
761     let is_marker = tcx.has_attr(def_id, sym::marker);
762     let def_path_hash = tcx.def_path_hash(def_id);
763     let def = ty::TraitDef::new(def_id, unsafety, paren_sugar, is_auto, is_marker, def_path_hash);
764     tcx.alloc_trait_def(def)
765 }
766
767 fn has_late_bound_regions<'a, 'tcx>(
768     tcx: TyCtxt<'a, 'tcx, 'tcx>,
769     node: Node<'tcx>,
770 ) -> Option<Span> {
771     struct LateBoundRegionsDetector<'a, 'tcx: 'a> {
772         tcx: TyCtxt<'a, 'tcx, 'tcx>,
773         outer_index: ty::DebruijnIndex,
774         has_late_bound_regions: Option<Span>,
775     }
776
777     impl<'a, 'tcx> Visitor<'tcx> for LateBoundRegionsDetector<'a, 'tcx> {
778         fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
779             NestedVisitorMap::None
780         }
781
782         fn visit_ty(&mut self, ty: &'tcx hir::Ty) {
783             if self.has_late_bound_regions.is_some() {
784                 return;
785             }
786             match ty.node {
787                 hir::TyKind::BareFn(..) => {
788                     self.outer_index.shift_in(1);
789                     intravisit::walk_ty(self, ty);
790                     self.outer_index.shift_out(1);
791                 }
792                 _ => intravisit::walk_ty(self, ty),
793             }
794         }
795
796         fn visit_poly_trait_ref(
797             &mut self,
798             tr: &'tcx hir::PolyTraitRef,
799             m: hir::TraitBoundModifier,
800         ) {
801             if self.has_late_bound_regions.is_some() {
802                 return;
803             }
804             self.outer_index.shift_in(1);
805             intravisit::walk_poly_trait_ref(self, tr, m);
806             self.outer_index.shift_out(1);
807         }
808
809         fn visit_lifetime(&mut self, lt: &'tcx hir::Lifetime) {
810             if self.has_late_bound_regions.is_some() {
811                 return;
812             }
813
814             match self.tcx.named_region(lt.hir_id) {
815                 Some(rl::Region::Static) | Some(rl::Region::EarlyBound(..)) => {}
816                 Some(rl::Region::LateBound(debruijn, _, _))
817                 | Some(rl::Region::LateBoundAnon(debruijn, _)) if debruijn < self.outer_index => {}
818                 Some(rl::Region::LateBound(..))
819                 | Some(rl::Region::LateBoundAnon(..))
820                 | Some(rl::Region::Free(..))
821                 | None => {
822                     self.has_late_bound_regions = Some(lt.span);
823                 }
824             }
825         }
826     }
827
828     fn has_late_bound_regions<'a, 'tcx>(
829         tcx: TyCtxt<'a, 'tcx, 'tcx>,
830         generics: &'tcx hir::Generics,
831         decl: &'tcx hir::FnDecl,
832     ) -> Option<Span> {
833         let mut visitor = LateBoundRegionsDetector {
834             tcx,
835             outer_index: ty::INNERMOST,
836             has_late_bound_regions: None,
837         };
838         for param in &generics.params {
839             if let GenericParamKind::Lifetime { .. } = param.kind {
840                 if tcx.is_late_bound(param.hir_id) {
841                     return Some(param.span);
842                 }
843             }
844         }
845         visitor.visit_fn_decl(decl);
846         visitor.has_late_bound_regions
847     }
848
849     match node {
850         Node::TraitItem(item) => match item.node {
851             hir::TraitItemKind::Method(ref sig, _) => {
852                 has_late_bound_regions(tcx, &item.generics, &sig.decl)
853             }
854             _ => None,
855         },
856         Node::ImplItem(item) => match item.node {
857             hir::ImplItemKind::Method(ref sig, _) => {
858                 has_late_bound_regions(tcx, &item.generics, &sig.decl)
859             }
860             _ => None,
861         },
862         Node::ForeignItem(item) => match item.node {
863             hir::ForeignItemKind::Fn(ref fn_decl, _, ref generics) => {
864                 has_late_bound_regions(tcx, generics, fn_decl)
865             }
866             _ => None,
867         },
868         Node::Item(item) => match item.node {
869             hir::ItemKind::Fn(ref fn_decl, .., ref generics, _) => {
870                 has_late_bound_regions(tcx, generics, fn_decl)
871             }
872             _ => None,
873         },
874         _ => None,
875     }
876 }
877
878 fn generics_of<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId) -> &'tcx ty::Generics {
879     use rustc::hir::*;
880
881     let hir_id = tcx.hir().as_local_hir_id(def_id).unwrap();
882
883     let node = tcx.hir().get_by_hir_id(hir_id);
884     let parent_def_id = match node {
885         Node::ImplItem(_) | Node::TraitItem(_) | Node::Variant(_) |
886         Node::Ctor(..) | Node::Field(_) => {
887             let parent_id = tcx.hir().get_parent_item(hir_id);
888             Some(tcx.hir().local_def_id_from_hir_id(parent_id))
889         }
890         Node::Expr(&hir::Expr {
891             node: hir::ExprKind::Closure(..),
892             ..
893         }) => Some(tcx.closure_base_def_id(def_id)),
894         Node::Item(item) => match item.node {
895             ItemKind::Existential(hir::ExistTy { impl_trait_fn, .. }) => impl_trait_fn,
896             _ => None,
897         },
898         _ => None,
899     };
900
901     let mut opt_self = None;
902     let mut allow_defaults = false;
903
904     let no_generics = hir::Generics::empty();
905     let ast_generics = match node {
906         Node::TraitItem(item) => &item.generics,
907
908         Node::ImplItem(item) => &item.generics,
909
910         Node::Item(item) => {
911             match item.node {
912                 ItemKind::Fn(.., ref generics, _) | ItemKind::Impl(_, _, _, ref generics, ..) => {
913                     generics
914                 }
915
916                 ItemKind::Ty(_, ref generics)
917                 | ItemKind::Enum(_, ref generics)
918                 | ItemKind::Struct(_, ref generics)
919                 | ItemKind::Existential(hir::ExistTy { ref generics, .. })
920                 | ItemKind::Union(_, ref generics) => {
921                     allow_defaults = true;
922                     generics
923                 }
924
925                 ItemKind::Trait(_, _, ref generics, ..)
926                 | ItemKind::TraitAlias(ref generics, ..) => {
927                     // Add in the self type parameter.
928                     //
929                     // Something of a hack: use the node id for the trait, also as
930                     // the node id for the Self type parameter.
931                     let param_id = item.hir_id;
932
933                     opt_self = Some(ty::GenericParamDef {
934                         index: 0,
935                         name: kw::SelfUpper.as_interned_str(),
936                         def_id: tcx.hir().local_def_id_from_hir_id(param_id),
937                         pure_wrt_drop: false,
938                         kind: ty::GenericParamDefKind::Type {
939                             has_default: false,
940                             object_lifetime_default: rl::Set1::Empty,
941                             synthetic: None,
942                         },
943                     });
944
945                     allow_defaults = true;
946                     generics
947                 }
948
949                 _ => &no_generics,
950             }
951         }
952
953         Node::ForeignItem(item) => match item.node {
954             ForeignItemKind::Static(..) => &no_generics,
955             ForeignItemKind::Fn(_, _, ref generics) => generics,
956             ForeignItemKind::Type => &no_generics,
957         },
958
959         _ => &no_generics,
960     };
961
962     let has_self = opt_self.is_some();
963     let mut parent_has_self = false;
964     let mut own_start = has_self as u32;
965     let parent_count = parent_def_id.map_or(0, |def_id| {
966         let generics = tcx.generics_of(def_id);
967         assert_eq!(has_self, false);
968         parent_has_self = generics.has_self;
969         own_start = generics.count() as u32;
970         generics.parent_count + generics.params.len()
971     });
972
973     let mut params: Vec<_> = opt_self.into_iter().collect();
974
975     let early_lifetimes = early_bound_lifetimes_from_generics(tcx, ast_generics);
976     params.extend(
977         early_lifetimes
978             .enumerate()
979             .map(|(i, param)| ty::GenericParamDef {
980                 name: param.name.ident().as_interned_str(),
981                 index: own_start + i as u32,
982                 def_id: tcx.hir().local_def_id_from_hir_id(param.hir_id),
983                 pure_wrt_drop: param.pure_wrt_drop,
984                 kind: ty::GenericParamDefKind::Lifetime,
985             }),
986     );
987
988     let object_lifetime_defaults = tcx.object_lifetime_defaults(hir_id);
989
990     // Now create the real type parameters.
991     let type_start = own_start - has_self as u32 + params.len() as u32;
992     let mut i = 0;
993     params.extend(
994         ast_generics
995             .params
996             .iter()
997             .filter_map(|param| {
998                 let kind = match param.kind {
999                     GenericParamKind::Type {
1000                         ref default,
1001                         synthetic,
1002                         ..
1003                     } => {
1004                         if param.name.ident().name == kw::SelfUpper {
1005                             span_bug!(
1006                                 param.span,
1007                                 "`Self` should not be the name of a regular parameter"
1008                             );
1009                         }
1010
1011                         if !allow_defaults && default.is_some() {
1012                             if !tcx.features().default_type_parameter_fallback {
1013                                 tcx.lint_hir(
1014                                     lint::builtin::INVALID_TYPE_PARAM_DEFAULT,
1015                                     param.hir_id,
1016                                     param.span,
1017                                     &format!(
1018                                         "defaults for type parameters are only allowed in \
1019                                         `struct`, `enum`, `type`, or `trait` definitions."
1020                                     ),
1021                                 );
1022                             }
1023                         }
1024
1025                         ty::GenericParamDefKind::Type {
1026                             has_default: default.is_some(),
1027                             object_lifetime_default: object_lifetime_defaults
1028                                 .as_ref()
1029                                 .map_or(rl::Set1::Empty, |o| o[i]),
1030                             synthetic,
1031                         }
1032                     }
1033                     GenericParamKind::Const { .. } => {
1034                         if param.name.ident().name == kw::SelfUpper {
1035                             span_bug!(
1036                                 param.span,
1037                                 "`Self` should not be the name of a regular parameter",
1038                             );
1039                         }
1040
1041                         ty::GenericParamDefKind::Const
1042                     }
1043                     _ => return None,
1044                 };
1045
1046                 let param_def = ty::GenericParamDef {
1047                     index: type_start + i as u32,
1048                     name: param.name.ident().as_interned_str(),
1049                     def_id: tcx.hir().local_def_id_from_hir_id(param.hir_id),
1050                     pure_wrt_drop: param.pure_wrt_drop,
1051                     kind,
1052                 };
1053                 i += 1;
1054                 Some(param_def)
1055             })
1056     );
1057
1058     // provide junk type parameter defs - the only place that
1059     // cares about anything but the length is instantiation,
1060     // and we don't do that for closures.
1061     if let Node::Expr(&hir::Expr {
1062         node: hir::ExprKind::Closure(.., gen),
1063         ..
1064     }) = node
1065     {
1066         let dummy_args = if gen.is_some() {
1067             &["<yield_ty>", "<return_ty>", "<witness>"][..]
1068         } else {
1069             &["<closure_kind>", "<closure_signature>"][..]
1070         };
1071
1072         params.extend(
1073             dummy_args
1074                 .iter()
1075                 .enumerate()
1076                 .map(|(i, &arg)| ty::GenericParamDef {
1077                     index: type_start + i as u32,
1078                     name: InternedString::intern(arg),
1079                     def_id,
1080                     pure_wrt_drop: false,
1081                     kind: ty::GenericParamDefKind::Type {
1082                         has_default: false,
1083                         object_lifetime_default: rl::Set1::Empty,
1084                         synthetic: None,
1085                     },
1086                 }),
1087         );
1088
1089         if let Some(upvars) = tcx.upvars(def_id) {
1090             params.extend(upvars.iter().zip((dummy_args.len() as u32)..).map(|(_, i)| {
1091                 ty::GenericParamDef {
1092                     index: type_start + i,
1093                     name: InternedString::intern("<upvar>"),
1094                     def_id,
1095                     pure_wrt_drop: false,
1096                     kind: ty::GenericParamDefKind::Type {
1097                         has_default: false,
1098                         object_lifetime_default: rl::Set1::Empty,
1099                         synthetic: None,
1100                     },
1101                 }
1102             }));
1103         }
1104     }
1105
1106     let param_def_id_to_index = params
1107         .iter()
1108         .map(|param| (param.def_id, param.index))
1109         .collect();
1110
1111     tcx.alloc_generics(ty::Generics {
1112         parent: parent_def_id,
1113         parent_count,
1114         params,
1115         param_def_id_to_index,
1116         has_self: has_self || parent_has_self,
1117         has_late_bound_regions: has_late_bound_regions(tcx, node),
1118     })
1119 }
1120
1121 fn report_assoc_ty_on_inherent_impl<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, span: Span) {
1122     span_err!(
1123         tcx.sess,
1124         span,
1125         E0202,
1126         "associated types are not yet supported in inherent impls (see #8995)"
1127     );
1128 }
1129
1130 fn type_of<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId) -> Ty<'tcx> {
1131     checked_type_of(tcx, def_id, true).unwrap()
1132 }
1133
1134 /// Same as [`type_of`] but returns [`Option`] instead of failing.
1135 ///
1136 /// If you want to fail anyway, you can set the `fail` parameter to true, but in this case,
1137 /// you'd better just call [`type_of`] directly.
1138 pub fn checked_type_of<'a, 'tcx>(
1139     tcx: TyCtxt<'a, 'tcx, 'tcx>,
1140     def_id: DefId,
1141     fail: bool,
1142 ) -> Option<Ty<'tcx>> {
1143     use rustc::hir::*;
1144
1145     let hir_id = match tcx.hir().as_local_hir_id(def_id) {
1146         Some(hir_id) => hir_id,
1147         None => {
1148             if !fail {
1149                 return None;
1150             }
1151             bug!("invalid node");
1152         }
1153     };
1154
1155     let icx = ItemCtxt::new(tcx, def_id);
1156
1157     Some(match tcx.hir().get_by_hir_id(hir_id) {
1158         Node::TraitItem(item) => match item.node {
1159             TraitItemKind::Method(..) => {
1160                 let substs = InternalSubsts::identity_for_item(tcx, def_id);
1161                 tcx.mk_fn_def(def_id, substs)
1162             }
1163             TraitItemKind::Const(ref ty, _) | TraitItemKind::Type(_, Some(ref ty)) => icx.to_ty(ty),
1164             TraitItemKind::Type(_, None) => {
1165                 if !fail {
1166                     return None;
1167                 }
1168                 span_bug!(item.span, "associated type missing default");
1169             }
1170         },
1171
1172         Node::ImplItem(item) => match item.node {
1173             ImplItemKind::Method(..) => {
1174                 let substs = InternalSubsts::identity_for_item(tcx, def_id);
1175                 tcx.mk_fn_def(def_id, substs)
1176             }
1177             ImplItemKind::Const(ref ty, _) => icx.to_ty(ty),
1178             ImplItemKind::Existential(_) => {
1179                 if tcx
1180                     .impl_trait_ref(tcx.hir().get_parent_did_by_hir_id(hir_id))
1181                     .is_none()
1182                 {
1183                     report_assoc_ty_on_inherent_impl(tcx, item.span);
1184                 }
1185
1186                 find_existential_constraints(tcx, def_id)
1187             }
1188             ImplItemKind::Type(ref ty) => {
1189                 if tcx
1190                     .impl_trait_ref(tcx.hir().get_parent_did_by_hir_id(hir_id))
1191                     .is_none()
1192                 {
1193                     report_assoc_ty_on_inherent_impl(tcx, item.span);
1194                 }
1195
1196                 icx.to_ty(ty)
1197             }
1198         },
1199
1200         Node::Item(item) => {
1201             match item.node {
1202                 ItemKind::Static(ref t, ..)
1203                 | ItemKind::Const(ref t, _)
1204                 | ItemKind::Ty(ref t, _)
1205                 | ItemKind::Impl(.., ref t, _) => icx.to_ty(t),
1206                 ItemKind::Fn(..) => {
1207                     let substs = InternalSubsts::identity_for_item(tcx, def_id);
1208                     tcx.mk_fn_def(def_id, substs)
1209                 }
1210                 ItemKind::Enum(..) | ItemKind::Struct(..) | ItemKind::Union(..) => {
1211                     let def = tcx.adt_def(def_id);
1212                     let substs = InternalSubsts::identity_for_item(tcx, def_id);
1213                     tcx.mk_adt(def, substs)
1214                 }
1215                 ItemKind::Existential(hir::ExistTy {
1216                     impl_trait_fn: None,
1217                     ..
1218                 }) => find_existential_constraints(tcx, def_id),
1219                 // existential types desugared from impl Trait
1220                 ItemKind::Existential(hir::ExistTy {
1221                     impl_trait_fn: Some(owner),
1222                     ..
1223                 }) => {
1224                     tcx.typeck_tables_of(owner)
1225                         .concrete_existential_types
1226                         .get(&def_id)
1227                         .map(|opaque| opaque.concrete_type)
1228                         .unwrap_or_else(|| {
1229                             // This can occur if some error in the
1230                             // owner fn prevented us from populating
1231                             // the `concrete_existential_types` table.
1232                             tcx.sess.delay_span_bug(
1233                                 DUMMY_SP,
1234                                 &format!(
1235                                     "owner {:?} has no existential type for {:?} in its tables",
1236                                     owner, def_id,
1237                                 ),
1238                             );
1239                             tcx.types.err
1240                         })
1241                 }
1242                 ItemKind::Trait(..)
1243                 | ItemKind::TraitAlias(..)
1244                 | ItemKind::Mod(..)
1245                 | ItemKind::ForeignMod(..)
1246                 | ItemKind::GlobalAsm(..)
1247                 | ItemKind::ExternCrate(..)
1248                 | ItemKind::Use(..) => {
1249                     if !fail {
1250                         return None;
1251                     }
1252                     span_bug!(
1253                         item.span,
1254                         "compute_type_of_item: unexpected item type: {:?}",
1255                         item.node
1256                     );
1257                 }
1258             }
1259         }
1260
1261         Node::ForeignItem(foreign_item) => match foreign_item.node {
1262             ForeignItemKind::Fn(..) => {
1263                 let substs = InternalSubsts::identity_for_item(tcx, def_id);
1264                 tcx.mk_fn_def(def_id, substs)
1265             }
1266             ForeignItemKind::Static(ref t, _) => icx.to_ty(t),
1267             ForeignItemKind::Type => tcx.mk_foreign(def_id),
1268         },
1269
1270         Node::Ctor(&ref def) | Node::Variant(&Spanned {
1271             node: hir::VariantKind { data: ref def, .. },
1272             ..
1273         }) => match *def {
1274             VariantData::Unit(..) | VariantData::Struct(..) => {
1275                 tcx.type_of(tcx.hir().get_parent_did_by_hir_id(hir_id))
1276             }
1277             VariantData::Tuple(..) => {
1278                 let substs = InternalSubsts::identity_for_item(tcx, def_id);
1279                 tcx.mk_fn_def(def_id, substs)
1280             }
1281         },
1282
1283         Node::Field(field) => icx.to_ty(&field.ty),
1284
1285         Node::Expr(&hir::Expr {
1286             node: hir::ExprKind::Closure(.., gen),
1287             ..
1288         }) => {
1289             if gen.is_some() {
1290                 return Some(tcx.typeck_tables_of(def_id).node_type(hir_id));
1291             }
1292
1293             let substs = ty::ClosureSubsts {
1294                 substs: InternalSubsts::identity_for_item(tcx, def_id),
1295             };
1296
1297             tcx.mk_closure(def_id, substs)
1298         }
1299
1300         Node::AnonConst(_) => {
1301             let parent_node = tcx.hir().get_by_hir_id(tcx.hir().get_parent_node_by_hir_id(hir_id));
1302             match parent_node {
1303                 Node::Ty(&hir::Ty {
1304                     node: hir::TyKind::Array(_, ref constant),
1305                     ..
1306                 })
1307                 | Node::Ty(&hir::Ty {
1308                     node: hir::TyKind::Typeof(ref constant),
1309                     ..
1310                 })
1311                 | Node::Expr(&hir::Expr {
1312                     node: ExprKind::Repeat(_, ref constant),
1313                     ..
1314                 }) if constant.hir_id == hir_id =>
1315                 {
1316                     tcx.types.usize
1317                 }
1318
1319                 Node::Variant(&Spanned {
1320                     node:
1321                         VariantKind {
1322                             disr_expr: Some(ref e),
1323                             ..
1324                         },
1325                     ..
1326                 }) if e.hir_id == hir_id =>
1327                 {
1328                     tcx.adt_def(tcx.hir().get_parent_did_by_hir_id(hir_id))
1329                         .repr
1330                         .discr_type()
1331                         .to_ty(tcx)
1332                 }
1333
1334                 Node::Ty(&hir::Ty { node: hir::TyKind::Path(_), .. }) |
1335                 Node::Expr(&hir::Expr { node: ExprKind::Struct(..), .. }) |
1336                 Node::Expr(&hir::Expr { node: ExprKind::Path(_), .. }) => {
1337                     let path = match parent_node {
1338                         Node::Ty(&hir::Ty { node: hir::TyKind::Path(ref path), .. }) |
1339                         Node::Expr(&hir::Expr { node: ExprKind::Path(ref path), .. }) => {
1340                             path
1341                         }
1342                         Node::Expr(&hir::Expr { node: ExprKind::Struct(ref path, ..), .. }) => {
1343                             &*path
1344                         }
1345                         _ => unreachable!(),
1346                     };
1347
1348                     match path {
1349                         QPath::Resolved(_, ref path) => {
1350                             let mut arg_index = 0;
1351                             let mut found_const = false;
1352                             for seg in &path.segments {
1353                                 if let Some(generic_args) = &seg.args {
1354                                     let args = &generic_args.args;
1355                                     for arg in args {
1356                                         if let GenericArg::Const(ct) = arg {
1357                                             if ct.value.hir_id == hir_id {
1358                                                 found_const = true;
1359                                                 break;
1360                                             }
1361                                             arg_index += 1;
1362                                         }
1363                                     }
1364                                 }
1365                             }
1366                             // Sanity check to make sure everything is as expected.
1367                             if !found_const {
1368                                 if !fail {
1369                                     return None;
1370                                 }
1371                                 bug!("no arg matching AnonConst in path")
1372                             }
1373                             match path.res {
1374                                 // We've encountered an `AnonConst` in some path, so we need to
1375                                 // figure out which generic parameter it corresponds to and return
1376                                 // the relevant type.
1377                                 Res::Def(DefKind::Struct, def_id)
1378                                 | Res::Def(DefKind::Union, def_id)
1379                                 | Res::Def(DefKind::Enum, def_id)
1380                                 | Res::Def(DefKind::Fn, def_id) => {
1381                                     let generics = tcx.generics_of(def_id);
1382                                     let mut param_index = 0;
1383                                     for param in &generics.params {
1384                                         if let ty::GenericParamDefKind::Const = param.kind {
1385                                             if param_index == arg_index {
1386                                                 return Some(tcx.type_of(param.def_id));
1387                                             }
1388                                             param_index += 1;
1389                                         }
1390                                     }
1391                                     // This is no generic parameter associated with the arg. This is
1392                                     // probably from an extra arg where one is not needed.
1393                                     return Some(tcx.types.err);
1394                                 }
1395                                 Res::Err => tcx.types.err,
1396                                 x => {
1397                                     if !fail {
1398                                         return None;
1399                                     }
1400                                     tcx.sess.delay_span_bug(
1401                                         DUMMY_SP,
1402                                         &format!(
1403                                             "unexpected const parent path def {:?}", x
1404                                         ),
1405                                     );
1406                                     tcx.types.err
1407                                 }
1408                             }
1409                         }
1410                         x => {
1411                             if !fail {
1412                                 return None;
1413                             }
1414                             tcx.sess.delay_span_bug(
1415                                 DUMMY_SP,
1416                                 &format!(
1417                                     "unexpected const parent path {:?}", x
1418                                 ),
1419                             );
1420                             tcx.types.err
1421                         }
1422                     }
1423                 }
1424
1425                 x => {
1426                     if !fail {
1427                         return None;
1428                     }
1429                     tcx.sess.delay_span_bug(
1430                         DUMMY_SP,
1431                         &format!(
1432                             "unexpected const parent in type_of_def_id(): {:?}", x
1433                         ),
1434                     );
1435                     tcx.types.err
1436                 }
1437             }
1438         }
1439
1440         Node::GenericParam(param) => match &param.kind {
1441             hir::GenericParamKind::Type { default: Some(ref ty), .. } |
1442             hir::GenericParamKind::Const { ref ty, .. } => {
1443                 icx.to_ty(ty)
1444             }
1445             x => {
1446                 if !fail {
1447                     return None;
1448                 }
1449                 bug!("unexpected non-type Node::GenericParam: {:?}", x)
1450             },
1451         },
1452
1453         x => {
1454             if !fail {
1455                 return None;
1456             }
1457             bug!("unexpected sort of node in type_of_def_id(): {:?}", x);
1458         }
1459     })
1460 }
1461
1462 fn find_existential_constraints<'a, 'tcx>(
1463     tcx: TyCtxt<'a, 'tcx, 'tcx>,
1464     def_id: DefId,
1465 ) -> Ty<'tcx> {
1466     use rustc::hir::{ImplItem, Item, TraitItem};
1467
1468     struct ConstraintLocator<'a, 'tcx: 'a> {
1469         tcx: TyCtxt<'a, 'tcx, 'tcx>,
1470         def_id: DefId,
1471         // First found type span, actual type, mapping from the existential type's generic
1472         // parameters to the concrete type's generic parameters
1473         //
1474         // The mapping is an index for each use site of a generic parameter in the concrete type
1475         //
1476         // The indices index into the generic parameters on the existential type.
1477         found: Option<(Span, Ty<'tcx>, Vec<usize>)>,
1478     }
1479
1480     impl<'a, 'tcx> ConstraintLocator<'a, 'tcx> {
1481         fn check(&mut self, def_id: DefId) {
1482             trace!("checking {:?}", def_id);
1483             // don't try to check items that cannot possibly constrain the type
1484             if !self.tcx.has_typeck_tables(def_id) {
1485                 trace!("no typeck tables for {:?}", def_id);
1486                 return;
1487             }
1488             let ty = self
1489                 .tcx
1490                 .typeck_tables_of(def_id)
1491                 .concrete_existential_types
1492                 .get(&self.def_id);
1493             if let Some(ty::ResolvedOpaqueTy { concrete_type, substs }) = ty {
1494                 // FIXME(oli-obk): trace the actual span from inference to improve errors
1495                 let span = self.tcx.def_span(def_id);
1496                 // used to quickly look up the position of a generic parameter
1497                 let mut index_map: FxHashMap<ty::ParamTy, usize> = FxHashMap::default();
1498                 // skip binder is ok, since we only use this to find generic parameters and their
1499                 // positions.
1500                 for (idx, subst) in substs.iter().enumerate() {
1501                     if let UnpackedKind::Type(ty) = subst.unpack() {
1502                         if let ty::Param(p) = ty.sty {
1503                             if index_map.insert(p, idx).is_some() {
1504                                 // there was already an entry for `p`, meaning a generic parameter
1505                                 // was used twice
1506                                 self.tcx.sess.span_err(
1507                                     span,
1508                                     &format!("defining existential type use restricts existential \
1509                                     type by using the generic parameter `{}` twice", p.name),
1510                                 );
1511                                 return;
1512                             }
1513                         } else {
1514                             self.tcx.sess.delay_span_bug(
1515                                 span,
1516                                 &format!(
1517                                     "non-defining exist ty use in defining scope: {:?}, {:?}",
1518                                     concrete_type, substs,
1519                                 ),
1520                             );
1521                         }
1522                     }
1523                 }
1524                 // compute the index within the existential type for each generic parameter used in
1525                 // the concrete type
1526                 let indices = concrete_type
1527                     .subst(self.tcx, substs)
1528                     .walk()
1529                     .filter_map(|t| match &t.sty {
1530                         ty::Param(p) => Some(*index_map.get(p).unwrap()),
1531                         _ => None,
1532                     }).collect();
1533                 let is_param = |ty: Ty<'_>| match ty.sty {
1534                     ty::Param(_) => true,
1535                     _ => false,
1536                 };
1537                 if !substs.types().all(is_param) {
1538                     self.tcx.sess.span_err(
1539                         span,
1540                         "defining existential type use does not fully define existential type",
1541                     );
1542                 } else if let Some((prev_span, prev_ty, ref prev_indices)) = self.found {
1543                     let mut ty = concrete_type.walk().fuse();
1544                     let mut p_ty = prev_ty.walk().fuse();
1545                     let iter_eq = (&mut ty).zip(&mut p_ty).all(|(t, p)| match (&t.sty, &p.sty) {
1546                         // type parameters are equal to any other type parameter for the purpose of
1547                         // concrete type equality, as it is possible to obtain the same type just
1548                         // by passing matching parameters to a function.
1549                         (ty::Param(_), ty::Param(_)) => true,
1550                         _ => t == p,
1551                     });
1552                     if !iter_eq || ty.next().is_some() || p_ty.next().is_some() {
1553                         // found different concrete types for the existential type
1554                         let mut err = self.tcx.sess.struct_span_err(
1555                             span,
1556                             "concrete type differs from previous defining existential type use",
1557                         );
1558                         err.span_label(
1559                             span,
1560                             format!("expected `{}`, got `{}`", prev_ty, concrete_type),
1561                         );
1562                         err.span_note(prev_span, "previous use here");
1563                         err.emit();
1564                     } else if indices != *prev_indices {
1565                         // found "same" concrete types, but the generic parameter order differs
1566                         let mut err = self.tcx.sess.struct_span_err(
1567                             span,
1568                             "concrete type's generic parameters differ from previous defining use",
1569                         );
1570                         use std::fmt::Write;
1571                         let mut s = String::new();
1572                         write!(s, "expected [").unwrap();
1573                         let list = |s: &mut String, indices: &Vec<usize>| {
1574                             let mut indices = indices.iter().cloned();
1575                             if let Some(first) = indices.next() {
1576                                 write!(s, "`{}`", substs[first]).unwrap();
1577                                 for i in indices {
1578                                     write!(s, ", `{}`", substs[i]).unwrap();
1579                                 }
1580                             }
1581                         };
1582                         list(&mut s, prev_indices);
1583                         write!(s, "], got [").unwrap();
1584                         list(&mut s, &indices);
1585                         write!(s, "]").unwrap();
1586                         err.span_label(span, s);
1587                         err.span_note(prev_span, "previous use here");
1588                         err.emit();
1589                     }
1590                 } else {
1591                     self.found = Some((span, concrete_type, indices));
1592                 }
1593             }
1594         }
1595     }
1596
1597     impl<'a, 'tcx> intravisit::Visitor<'tcx> for ConstraintLocator<'a, 'tcx> {
1598         fn nested_visit_map<'this>(&'this mut self) -> intravisit::NestedVisitorMap<'this, 'tcx> {
1599             intravisit::NestedVisitorMap::All(&self.tcx.hir())
1600         }
1601         fn visit_item(&mut self, it: &'tcx Item) {
1602             let def_id = self.tcx.hir().local_def_id_from_hir_id(it.hir_id);
1603             // the existential type itself or its children are not within its reveal scope
1604             if def_id != self.def_id {
1605                 self.check(def_id);
1606                 intravisit::walk_item(self, it);
1607             }
1608         }
1609         fn visit_impl_item(&mut self, it: &'tcx ImplItem) {
1610             let def_id = self.tcx.hir().local_def_id_from_hir_id(it.hir_id);
1611             // the existential type itself or its children are not within its reveal scope
1612             if def_id != self.def_id {
1613                 self.check(def_id);
1614                 intravisit::walk_impl_item(self, it);
1615             }
1616         }
1617         fn visit_trait_item(&mut self, it: &'tcx TraitItem) {
1618             let def_id = self.tcx.hir().local_def_id_from_hir_id(it.hir_id);
1619             self.check(def_id);
1620             intravisit::walk_trait_item(self, it);
1621         }
1622     }
1623
1624     let mut locator = ConstraintLocator {
1625         def_id,
1626         tcx,
1627         found: None,
1628     };
1629     let hir_id = tcx.hir().as_local_hir_id(def_id).unwrap();
1630     let parent = tcx.hir().get_parent_item(hir_id);
1631
1632     trace!("parent_id: {:?}", parent);
1633
1634     if parent == hir::CRATE_HIR_ID {
1635         intravisit::walk_crate(&mut locator, tcx.hir().krate());
1636     } else {
1637         trace!("parent: {:?}", tcx.hir().get_by_hir_id(parent));
1638         match tcx.hir().get_by_hir_id(parent) {
1639             Node::Item(ref it) => intravisit::walk_item(&mut locator, it),
1640             Node::ImplItem(ref it) => intravisit::walk_impl_item(&mut locator, it),
1641             Node::TraitItem(ref it) => intravisit::walk_trait_item(&mut locator, it),
1642             other => bug!(
1643                 "{:?} is not a valid parent of an existential type item",
1644                 other
1645             ),
1646         }
1647     }
1648
1649     match locator.found {
1650         Some((_, ty, _)) => ty,
1651         None => {
1652             let span = tcx.def_span(def_id);
1653             tcx.sess.span_err(span, "could not find defining uses");
1654             tcx.types.err
1655         }
1656     }
1657 }
1658
1659 fn fn_sig<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId) -> ty::PolyFnSig<'tcx> {
1660     use rustc::hir::*;
1661     use rustc::hir::Node::*;
1662
1663     let hir_id = tcx.hir().as_local_hir_id(def_id).unwrap();
1664
1665     let icx = ItemCtxt::new(tcx, def_id);
1666
1667     match tcx.hir().get_by_hir_id(hir_id) {
1668         TraitItem(hir::TraitItem {
1669             node: TraitItemKind::Method(sig, _),
1670             ..
1671         })
1672         | ImplItem(hir::ImplItem {
1673             node: ImplItemKind::Method(sig, _),
1674             ..
1675         }) => AstConv::ty_of_fn(&icx, sig.header.unsafety, sig.header.abi, &sig.decl),
1676
1677         Item(hir::Item {
1678             node: ItemKind::Fn(decl, header, _, _),
1679             ..
1680         }) => AstConv::ty_of_fn(&icx, header.unsafety, header.abi, decl),
1681
1682         ForeignItem(&hir::ForeignItem {
1683             node: ForeignItemKind::Fn(ref fn_decl, _, _),
1684             ..
1685         }) => {
1686             let abi = tcx.hir().get_foreign_abi_by_hir_id(hir_id);
1687             compute_sig_of_foreign_fn_decl(tcx, def_id, fn_decl, abi)
1688         }
1689
1690         Ctor(data) | Variant(Spanned {
1691             node: hir::VariantKind { data, ..  },
1692             ..
1693         }) if data.ctor_hir_id().is_some() => {
1694             let ty = tcx.type_of(tcx.hir().get_parent_did_by_hir_id(hir_id));
1695             let inputs = data.fields()
1696                 .iter()
1697                 .map(|f| tcx.type_of(tcx.hir().local_def_id_from_hir_id(f.hir_id)));
1698             ty::Binder::bind(tcx.mk_fn_sig(
1699                 inputs,
1700                 ty,
1701                 false,
1702                 hir::Unsafety::Normal,
1703                 abi::Abi::Rust,
1704             ))
1705         }
1706
1707         Expr(&hir::Expr {
1708             node: hir::ExprKind::Closure(..),
1709             ..
1710         }) => {
1711             // Closure signatures are not like other function
1712             // signatures and cannot be accessed through `fn_sig`. For
1713             // example, a closure signature excludes the `self`
1714             // argument. In any case they are embedded within the
1715             // closure type as part of the `ClosureSubsts`.
1716             //
1717             // To get
1718             // the signature of a closure, you should use the
1719             // `closure_sig` method on the `ClosureSubsts`:
1720             //
1721             //    closure_substs.closure_sig(def_id, tcx)
1722             //
1723             // or, inside of an inference context, you can use
1724             //
1725             //    infcx.closure_sig(def_id, closure_substs)
1726             bug!("to get the signature of a closure, use `closure_sig()` not `fn_sig()`");
1727         }
1728
1729         x => {
1730             bug!("unexpected sort of node in fn_sig(): {:?}", x);
1731         }
1732     }
1733 }
1734
1735 fn impl_trait_ref<'a, 'tcx>(
1736     tcx: TyCtxt<'a, 'tcx, 'tcx>,
1737     def_id: DefId,
1738 ) -> Option<ty::TraitRef<'tcx>> {
1739     let icx = ItemCtxt::new(tcx, def_id);
1740
1741     let hir_id = tcx.hir().as_local_hir_id(def_id).unwrap();
1742     match tcx.hir().expect_item_by_hir_id(hir_id).node {
1743         hir::ItemKind::Impl(.., ref opt_trait_ref, _, _) => {
1744             opt_trait_ref.as_ref().map(|ast_trait_ref| {
1745                 let selfty = tcx.type_of(def_id);
1746                 AstConv::instantiate_mono_trait_ref(&icx, ast_trait_ref, selfty)
1747             })
1748         }
1749         _ => bug!(),
1750     }
1751 }
1752
1753 fn impl_polarity<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId) -> hir::ImplPolarity {
1754     let hir_id = tcx.hir().as_local_hir_id(def_id).unwrap();
1755     match tcx.hir().expect_item_by_hir_id(hir_id).node {
1756         hir::ItemKind::Impl(_, polarity, ..) => polarity,
1757         ref item => bug!("impl_polarity: {:?} not an impl", item),
1758     }
1759 }
1760
1761 // Is it marked with ?Sized
1762 fn is_unsized<'gcx: 'tcx, 'tcx>(
1763     astconv: &dyn AstConv<'gcx, 'tcx>,
1764     ast_bounds: &[hir::GenericBound],
1765     span: Span,
1766 ) -> bool {
1767     let tcx = astconv.tcx();
1768
1769     // Try to find an unbound in bounds.
1770     let mut unbound = None;
1771     for ab in ast_bounds {
1772         if let &hir::GenericBound::Trait(ref ptr, hir::TraitBoundModifier::Maybe) = ab {
1773             if unbound.is_none() {
1774                 unbound = Some(ptr.trait_ref.clone());
1775             } else {
1776                 span_err!(
1777                     tcx.sess,
1778                     span,
1779                     E0203,
1780                     "type parameter has more than one relaxed default \
1781                      bound, only one is supported"
1782                 );
1783             }
1784         }
1785     }
1786
1787     let kind_id = tcx.lang_items().require(SizedTraitLangItem);
1788     match unbound {
1789         Some(ref tpb) => {
1790             // FIXME(#8559) currently requires the unbound to be built-in.
1791             if let Ok(kind_id) = kind_id {
1792                 if tpb.path.res != Res::Def(DefKind::Trait, kind_id) {
1793                     tcx.sess.span_warn(
1794                         span,
1795                         "default bound relaxed for a type parameter, but \
1796                          this does nothing because the given bound is not \
1797                          a default. Only `?Sized` is supported",
1798                     );
1799                 }
1800             }
1801         }
1802         _ if kind_id.is_ok() => {
1803             return false;
1804         }
1805         // No lang item for Sized, so we can't add it as a bound.
1806         None => {}
1807     }
1808
1809     true
1810 }
1811
1812 /// Returns the early-bound lifetimes declared in this generics
1813 /// listing. For anything other than fns/methods, this is just all
1814 /// the lifetimes that are declared. For fns or methods, we have to
1815 /// screen out those that do not appear in any where-clauses etc using
1816 /// `resolve_lifetime::early_bound_lifetimes`.
1817 fn early_bound_lifetimes_from_generics<'a, 'tcx>(
1818     tcx: TyCtxt<'a, 'tcx, 'tcx>,
1819     generics: &'a hir::Generics,
1820 ) -> impl Iterator<Item = &'a hir::GenericParam> + Captures<'tcx> {
1821     generics
1822         .params
1823         .iter()
1824         .filter(move |param| match param.kind {
1825             GenericParamKind::Lifetime { .. } => {
1826                 !tcx.is_late_bound(param.hir_id)
1827             }
1828             _ => false,
1829         })
1830 }
1831
1832 /// Returns a list of type predicates for the definition with ID `def_id`, including inferred
1833 /// lifetime constraints. This includes all predicates returned by `explicit_predicates_of`, plus
1834 /// inferred constraints concerning which regions outlive other regions.
1835 fn predicates_defined_on<'a, 'tcx>(
1836     tcx: TyCtxt<'a, 'tcx, 'tcx>,
1837     def_id: DefId,
1838 ) -> &'tcx ty::GenericPredicates<'tcx> {
1839     debug!("predicates_defined_on({:?})", def_id);
1840     let mut result = tcx.explicit_predicates_of(def_id);
1841     debug!(
1842         "predicates_defined_on: explicit_predicates_of({:?}) = {:?}",
1843         def_id,
1844         result,
1845     );
1846     let inferred_outlives = tcx.inferred_outlives_of(def_id);
1847     if !inferred_outlives.is_empty() {
1848         let span = tcx.def_span(def_id);
1849         debug!(
1850             "predicates_defined_on: inferred_outlives_of({:?}) = {:?}",
1851             def_id,
1852             inferred_outlives,
1853         );
1854         let mut predicates = (*result).clone();
1855         predicates.predicates.extend(inferred_outlives.iter().map(|&p| (p, span)));
1856         result = tcx.arena.alloc(predicates);
1857     }
1858     debug!("predicates_defined_on({:?}) = {:?}", def_id, result);
1859     result
1860 }
1861
1862 /// Returns a list of all type predicates (explicit and implicit) for the definition with
1863 /// ID `def_id`. This includes all predicates returned by `predicates_defined_on`, plus
1864 /// `Self: Trait` predicates for traits.
1865 fn predicates_of<'a, 'tcx>(
1866     tcx: TyCtxt<'a, 'tcx, 'tcx>,
1867     def_id: DefId,
1868 ) -> &'tcx ty::GenericPredicates<'tcx> {
1869     let mut result = tcx.predicates_defined_on(def_id);
1870
1871     if tcx.is_trait(def_id) {
1872         // For traits, add `Self: Trait` predicate. This is
1873         // not part of the predicates that a user writes, but it
1874         // is something that one must prove in order to invoke a
1875         // method or project an associated type.
1876         //
1877         // In the chalk setup, this predicate is not part of the
1878         // "predicates" for a trait item. But it is useful in
1879         // rustc because if you directly (e.g.) invoke a trait
1880         // method like `Trait::method(...)`, you must naturally
1881         // prove that the trait applies to the types that were
1882         // used, and adding the predicate into this list ensures
1883         // that this is done.
1884         let span = tcx.def_span(def_id);
1885         let mut predicates = (*result).clone();
1886         predicates.predicates.push((ty::TraitRef::identity(tcx, def_id).to_predicate(), span));
1887         result = tcx.arena.alloc(predicates);
1888     }
1889     debug!("predicates_of(def_id={:?}) = {:?}", def_id, result);
1890     result
1891 }
1892
1893 /// Returns a list of user-specified type predicates for the definition with ID `def_id`.
1894 /// N.B., this does not include any implied/inferred constraints.
1895 fn explicit_predicates_of<'a, 'tcx>(
1896     tcx: TyCtxt<'a, 'tcx, 'tcx>,
1897     def_id: DefId,
1898 ) -> &'tcx ty::GenericPredicates<'tcx> {
1899     use rustc::hir::*;
1900     use rustc_data_structures::fx::FxHashSet;
1901
1902     debug!("explicit_predicates_of(def_id={:?})", def_id);
1903
1904     /// A data structure with unique elements, which preserves order of insertion.
1905     /// Preserving the order of insertion is important here so as not to break
1906     /// compile-fail UI tests.
1907     struct UniquePredicates<'tcx> {
1908         predicates: Vec<(ty::Predicate<'tcx>, Span)>,
1909         uniques: FxHashSet<(ty::Predicate<'tcx>, Span)>,
1910     }
1911
1912     impl<'tcx> UniquePredicates<'tcx> {
1913         fn new() -> Self {
1914             UniquePredicates {
1915                 predicates: vec![],
1916                 uniques: FxHashSet::default(),
1917             }
1918         }
1919
1920         fn push(&mut self, value: (ty::Predicate<'tcx>, Span)) {
1921             if self.uniques.insert(value) {
1922                 self.predicates.push(value);
1923             }
1924         }
1925
1926         fn extend<I: IntoIterator<Item = (ty::Predicate<'tcx>, Span)>>(&mut self, iter: I) {
1927             for value in iter {
1928                 self.push(value);
1929             }
1930         }
1931     }
1932
1933     let hir_id = match tcx.hir().as_local_hir_id(def_id) {
1934         Some(hir_id) => hir_id,
1935         None => return tcx.predicates_of(def_id),
1936     };
1937     let node = tcx.hir().get_by_hir_id(hir_id);
1938
1939     let mut is_trait = None;
1940     let mut is_default_impl_trait = None;
1941
1942     let icx = ItemCtxt::new(tcx, def_id);
1943     let no_generics = hir::Generics::empty();
1944     let empty_trait_items = HirVec::new();
1945
1946     let mut predicates = UniquePredicates::new();
1947
1948     let ast_generics = match node {
1949         Node::TraitItem(item) => &item.generics,
1950
1951         Node::ImplItem(item) => match item.node {
1952             ImplItemKind::Existential(ref bounds) => {
1953                 let substs = InternalSubsts::identity_for_item(tcx, def_id);
1954                 let opaque_ty = tcx.mk_opaque(def_id, substs);
1955
1956                 // Collect the bounds, i.e., the `A+B+'c` in `impl A+B+'c`.
1957                 let bounds = compute_bounds(
1958                     &icx,
1959                     opaque_ty,
1960                     bounds,
1961                     SizedByDefault::Yes,
1962                     tcx.def_span(def_id),
1963                 );
1964
1965                 predicates.extend(bounds.predicates(tcx, opaque_ty));
1966                 &item.generics
1967             }
1968             _ => &item.generics,
1969         },
1970
1971         Node::Item(item) => {
1972             match item.node {
1973                 ItemKind::Impl(_, _, defaultness, ref generics, ..) => {
1974                     if defaultness.is_default() {
1975                         is_default_impl_trait = tcx.impl_trait_ref(def_id);
1976                     }
1977                     generics
1978                 }
1979                 ItemKind::Fn(.., ref generics, _)
1980                 | ItemKind::Ty(_, ref generics)
1981                 | ItemKind::Enum(_, ref generics)
1982                 | ItemKind::Struct(_, ref generics)
1983                 | ItemKind::Union(_, ref generics) => generics,
1984
1985                 ItemKind::Trait(_, _, ref generics, .., ref items) => {
1986                     is_trait = Some((ty::TraitRef::identity(tcx, def_id), items));
1987                     generics
1988                 }
1989                 ItemKind::TraitAlias(ref generics, _) => {
1990                     is_trait = Some((ty::TraitRef::identity(tcx, def_id), &empty_trait_items));
1991                     generics
1992                 }
1993                 ItemKind::Existential(ExistTy {
1994                     ref bounds,
1995                     impl_trait_fn,
1996                     ref generics,
1997                     origin: _,
1998                 }) => {
1999                     let substs = InternalSubsts::identity_for_item(tcx, def_id);
2000                     let opaque_ty = tcx.mk_opaque(def_id, substs);
2001
2002                     // Collect the bounds, i.e., the `A+B+'c` in `impl A+B+'c`.
2003                     let bounds = compute_bounds(
2004                         &icx,
2005                         opaque_ty,
2006                         bounds,
2007                         SizedByDefault::Yes,
2008                         tcx.def_span(def_id),
2009                     );
2010
2011                     if impl_trait_fn.is_some() {
2012                         // impl Trait
2013                         return tcx.arena.alloc(ty::GenericPredicates {
2014                             parent: None,
2015                             predicates: bounds.predicates(tcx, opaque_ty),
2016                         });
2017                     } else {
2018                         // named existential types
2019                         predicates.extend(bounds.predicates(tcx, opaque_ty));
2020                         generics
2021                     }
2022                 }
2023
2024                 _ => &no_generics,
2025             }
2026         }
2027
2028         Node::ForeignItem(item) => match item.node {
2029             ForeignItemKind::Static(..) => &no_generics,
2030             ForeignItemKind::Fn(_, _, ref generics) => generics,
2031             ForeignItemKind::Type => &no_generics,
2032         },
2033
2034         _ => &no_generics,
2035     };
2036
2037     let generics = tcx.generics_of(def_id);
2038     let parent_count = generics.parent_count as u32;
2039     let has_own_self = generics.has_self && parent_count == 0;
2040
2041     // Below we'll consider the bounds on the type parameters (including `Self`)
2042     // and the explicit where-clauses, but to get the full set of predicates
2043     // on a trait we need to add in the supertrait bounds and bounds found on
2044     // associated types.
2045     if let Some((_trait_ref, _)) = is_trait {
2046         predicates.extend(tcx.super_predicates_of(def_id).predicates.iter().cloned());
2047     }
2048
2049     // In default impls, we can assume that the self type implements
2050     // the trait. So in:
2051     //
2052     //     default impl Foo for Bar { .. }
2053     //
2054     // we add a default where clause `Foo: Bar`. We do a similar thing for traits
2055     // (see below). Recall that a default impl is not itself an impl, but rather a
2056     // set of defaults that can be incorporated into another impl.
2057     if let Some(trait_ref) = is_default_impl_trait {
2058         predicates.push((trait_ref.to_poly_trait_ref().to_predicate(), tcx.def_span(def_id)));
2059     }
2060
2061     // Collect the region predicates that were declared inline as
2062     // well. In the case of parameters declared on a fn or method, we
2063     // have to be careful to only iterate over early-bound regions.
2064     let mut index = parent_count + has_own_self as u32;
2065     for param in early_bound_lifetimes_from_generics(tcx, ast_generics) {
2066         let region = tcx.mk_region(ty::ReEarlyBound(ty::EarlyBoundRegion {
2067             def_id: tcx.hir().local_def_id_from_hir_id(param.hir_id),
2068             index,
2069             name: param.name.ident().as_interned_str(),
2070         }));
2071         index += 1;
2072
2073         match param.kind {
2074             GenericParamKind::Lifetime { .. } => {
2075                 param.bounds.iter().for_each(|bound| match bound {
2076                     hir::GenericBound::Outlives(lt) => {
2077                         let bound = AstConv::ast_region_to_region(&icx, &lt, None);
2078                         let outlives = ty::Binder::bind(ty::OutlivesPredicate(region, bound));
2079                         predicates.push((outlives.to_predicate(), lt.span));
2080                     }
2081                     _ => bug!(),
2082                 });
2083             }
2084             _ => bug!(),
2085         }
2086     }
2087
2088     // Collect the predicates that were written inline by the user on each
2089     // type parameter (e.g., `<T:Foo>`).
2090     for param in &ast_generics.params {
2091         if let GenericParamKind::Type { .. } = param.kind {
2092             let name = param.name.ident().as_interned_str();
2093             let param_ty = ty::ParamTy::new(index, name).to_ty(tcx);
2094             index += 1;
2095
2096             let sized = SizedByDefault::Yes;
2097             let bounds = compute_bounds(&icx, param_ty, &param.bounds, sized, param.span);
2098             predicates.extend(bounds.predicates(tcx, param_ty));
2099         }
2100     }
2101
2102     // Add in the bounds that appear in the where-clause
2103     let where_clause = &ast_generics.where_clause;
2104     for predicate in &where_clause.predicates {
2105         match predicate {
2106             &hir::WherePredicate::BoundPredicate(ref bound_pred) => {
2107                 let ty = icx.to_ty(&bound_pred.bounded_ty);
2108
2109                 // Keep the type around in a dummy predicate, in case of no bounds.
2110                 // That way, `where Ty:` is not a complete noop (see #53696) and `Ty`
2111                 // is still checked for WF.
2112                 if bound_pred.bounds.is_empty() {
2113                     if let ty::Param(_) = ty.sty {
2114                         // This is a `where T:`, which can be in the HIR from the
2115                         // transformation that moves `?Sized` to `T`'s declaration.
2116                         // We can skip the predicate because type parameters are
2117                         // trivially WF, but also we *should*, to avoid exposing
2118                         // users who never wrote `where Type:,` themselves, to
2119                         // compiler/tooling bugs from not handling WF predicates.
2120                     } else {
2121                         let span = bound_pred.bounded_ty.span;
2122                         let predicate = ty::OutlivesPredicate(ty, tcx.mk_region(ty::ReEmpty));
2123                         predicates.push(
2124                             (ty::Predicate::TypeOutlives(ty::Binder::dummy(predicate)), span)
2125                         );
2126                     }
2127                 }
2128
2129                 for bound in bound_pred.bounds.iter() {
2130                     match bound {
2131                         &hir::GenericBound::Trait(ref poly_trait_ref, _) => {
2132                             let mut projections = Vec::new();
2133
2134                             let (trait_ref, _) = AstConv::instantiate_poly_trait_ref(
2135                                 &icx,
2136                                 poly_trait_ref,
2137                                 ty,
2138                                 &mut projections,
2139                             );
2140
2141                             predicates.extend(
2142                                 iter::once((trait_ref.to_predicate(), poly_trait_ref.span)).chain(
2143                                     projections.iter().map(|&(p, span)| (p.to_predicate(), span)
2144                             )));
2145                         }
2146
2147                         &hir::GenericBound::Outlives(ref lifetime) => {
2148                             let region = AstConv::ast_region_to_region(&icx, lifetime, None);
2149                             let pred = ty::Binder::bind(ty::OutlivesPredicate(ty, region));
2150                             predicates.push((ty::Predicate::TypeOutlives(pred), lifetime.span))
2151                         }
2152                     }
2153                 }
2154             }
2155
2156             &hir::WherePredicate::RegionPredicate(ref region_pred) => {
2157                 let r1 = AstConv::ast_region_to_region(&icx, &region_pred.lifetime, None);
2158                 predicates.extend(region_pred.bounds.iter().map(|bound| {
2159                     let (r2, span) = match bound {
2160                         hir::GenericBound::Outlives(lt) => {
2161                             (AstConv::ast_region_to_region(&icx, lt, None), lt.span)
2162                         }
2163                         _ => bug!(),
2164                     };
2165                     let pred = ty::Binder::bind(ty::OutlivesPredicate(r1, r2));
2166
2167                     (ty::Predicate::RegionOutlives(pred), span)
2168                 }))
2169             }
2170
2171             &hir::WherePredicate::EqPredicate(..) => {
2172                 // FIXME(#20041)
2173             }
2174         }
2175     }
2176
2177     // Add predicates from associated type bounds.
2178     if let Some((self_trait_ref, trait_items)) = is_trait {
2179         predicates.extend(trait_items.iter().flat_map(|trait_item_ref| {
2180             let trait_item = tcx.hir().trait_item(trait_item_ref.id);
2181             let bounds = match trait_item.node {
2182                 hir::TraitItemKind::Type(ref bounds, _) => bounds,
2183                 _ => return vec![].into_iter()
2184             };
2185
2186             let assoc_ty =
2187                 tcx.mk_projection(tcx.hir().local_def_id_from_hir_id(trait_item.hir_id),
2188                     self_trait_ref.substs);
2189
2190             let bounds = compute_bounds(
2191                 &ItemCtxt::new(tcx, def_id),
2192                 assoc_ty,
2193                 bounds,
2194                 SizedByDefault::Yes,
2195                 trait_item.span,
2196             );
2197
2198             bounds.predicates(tcx, assoc_ty).into_iter()
2199         }))
2200     }
2201
2202     let mut predicates = predicates.predicates;
2203
2204     // Subtle: before we store the predicates into the tcx, we
2205     // sort them so that predicates like `T: Foo<Item=U>` come
2206     // before uses of `U`.  This avoids false ambiguity errors
2207     // in trait checking. See `setup_constraining_predicates`
2208     // for details.
2209     if let Node::Item(&Item {
2210         node: ItemKind::Impl(..),
2211         ..
2212     }) = node
2213     {
2214         let self_ty = tcx.type_of(def_id);
2215         let trait_ref = tcx.impl_trait_ref(def_id);
2216         cgp::setup_constraining_predicates(
2217             tcx,
2218             &mut predicates,
2219             trait_ref,
2220             &mut cgp::parameters_for_impl(self_ty, trait_ref),
2221         );
2222     }
2223
2224     let result = tcx.arena.alloc(ty::GenericPredicates {
2225         parent: generics.parent,
2226         predicates,
2227     });
2228     debug!("explicit_predicates_of(def_id={:?}) = {:?}", def_id, result);
2229     result
2230 }
2231
2232 pub enum SizedByDefault {
2233     Yes,
2234     No,
2235 }
2236
2237 /// Translate the AST's notion of ty param bounds (which are an enum consisting of a newtyped `Ty`
2238 /// or a region) to ty's notion of ty param bounds, which can either be user-defined traits, or the
2239 /// built-in trait `Send`.
2240 pub fn compute_bounds<'gcx: 'tcx, 'tcx>(
2241     astconv: &dyn AstConv<'gcx, 'tcx>,
2242     param_ty: Ty<'tcx>,
2243     ast_bounds: &[hir::GenericBound],
2244     sized_by_default: SizedByDefault,
2245     span: Span,
2246 ) -> Bounds<'tcx> {
2247     let mut region_bounds = Vec::new();
2248     let mut trait_bounds = Vec::new();
2249
2250     for ast_bound in ast_bounds {
2251         match *ast_bound {
2252             hir::GenericBound::Trait(ref b, hir::TraitBoundModifier::None) => trait_bounds.push(b),
2253             hir::GenericBound::Trait(_, hir::TraitBoundModifier::Maybe) => {}
2254             hir::GenericBound::Outlives(ref l) => region_bounds.push(l),
2255         }
2256     }
2257
2258     let mut projection_bounds = Vec::new();
2259
2260     let mut trait_bounds: Vec<_> = trait_bounds.iter().map(|&bound| {
2261         let (poly_trait_ref, _) = astconv.instantiate_poly_trait_ref(
2262             bound,
2263             param_ty,
2264             &mut projection_bounds,
2265         );
2266         (poly_trait_ref, bound.span)
2267     }).collect();
2268
2269     let region_bounds = region_bounds
2270         .into_iter()
2271         .map(|r| (astconv.ast_region_to_region(r, None), r.span))
2272         .collect();
2273
2274     trait_bounds.sort_by_key(|(t, _)| t.def_id());
2275
2276     let implicitly_sized = if let SizedByDefault::Yes = sized_by_default {
2277         if !is_unsized(astconv, ast_bounds, span) {
2278             Some(span)
2279         } else {
2280             None
2281         }
2282     } else {
2283         None
2284     };
2285
2286     Bounds {
2287         region_bounds,
2288         implicitly_sized,
2289         trait_bounds,
2290         projection_bounds,
2291     }
2292 }
2293
2294 /// Converts a specific `GenericBound` from the AST into a set of
2295 /// predicates that apply to the self type. A vector is returned
2296 /// because this can be anywhere from zero predicates (`T: ?Sized` adds no
2297 /// predicates) to one (`T: Foo`) to many (`T: Bar<X=i32>` adds `T: Bar`
2298 /// and `<T as Bar>::X == i32`).
2299 fn predicates_from_bound<'tcx>(
2300     astconv: &dyn AstConv<'tcx, 'tcx>,
2301     param_ty: Ty<'tcx>,
2302     bound: &hir::GenericBound,
2303 ) -> Vec<(ty::Predicate<'tcx>, Span)> {
2304     match *bound {
2305         hir::GenericBound::Trait(ref tr, hir::TraitBoundModifier::None) => {
2306             let mut projections = Vec::new();
2307             let (pred, _) = astconv.instantiate_poly_trait_ref(tr, param_ty, &mut projections);
2308             iter::once((pred.to_predicate(), tr.span)).chain(
2309                 projections
2310                     .into_iter()
2311                     .map(|(p, span)| (p.to_predicate(), span))
2312             ).collect()
2313         }
2314         hir::GenericBound::Outlives(ref lifetime) => {
2315             let region = astconv.ast_region_to_region(lifetime, None);
2316             let pred = ty::Binder::bind(ty::OutlivesPredicate(param_ty, region));
2317             vec![(ty::Predicate::TypeOutlives(pred), lifetime.span)]
2318         }
2319         hir::GenericBound::Trait(_, hir::TraitBoundModifier::Maybe) => vec![],
2320     }
2321 }
2322
2323 fn compute_sig_of_foreign_fn_decl<'a, 'tcx>(
2324     tcx: TyCtxt<'a, 'tcx, 'tcx>,
2325     def_id: DefId,
2326     decl: &hir::FnDecl,
2327     abi: abi::Abi,
2328 ) -> ty::PolyFnSig<'tcx> {
2329     let unsafety = if abi == abi::Abi::RustIntrinsic {
2330         intrisic_operation_unsafety(&*tcx.item_name(def_id).as_str())
2331     } else {
2332         hir::Unsafety::Unsafe
2333     };
2334     let fty = AstConv::ty_of_fn(&ItemCtxt::new(tcx, def_id), unsafety, abi, decl);
2335
2336     // feature gate SIMD types in FFI, since I (huonw) am not sure the
2337     // ABIs are handled at all correctly.
2338     if abi != abi::Abi::RustIntrinsic
2339         && abi != abi::Abi::PlatformIntrinsic
2340         && !tcx.features().simd_ffi
2341     {
2342         let check = |ast_ty: &hir::Ty, ty: Ty<'_>| {
2343             if ty.is_simd() {
2344                 tcx.sess
2345                    .struct_span_err(
2346                        ast_ty.span,
2347                        &format!(
2348                            "use of SIMD type `{}` in FFI is highly experimental and \
2349                             may result in invalid code",
2350                            tcx.hir().hir_to_pretty_string(ast_ty.hir_id)
2351                        ),
2352                    )
2353                    .help("add #![feature(simd_ffi)] to the crate attributes to enable")
2354                    .emit();
2355             }
2356         };
2357         for (input, ty) in decl.inputs.iter().zip(*fty.inputs().skip_binder()) {
2358             check(&input, ty)
2359         }
2360         if let hir::Return(ref ty) = decl.output {
2361             check(&ty, *fty.output().skip_binder())
2362         }
2363     }
2364
2365     fty
2366 }
2367
2368 fn is_foreign_item<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId) -> bool {
2369     match tcx.hir().get_if_local(def_id) {
2370         Some(Node::ForeignItem(..)) => true,
2371         Some(_) => false,
2372         _ => bug!("is_foreign_item applied to non-local def-id {:?}", def_id),
2373     }
2374 }
2375
2376 fn static_mutability<'a, 'tcx>(
2377     tcx: TyCtxt<'a, 'tcx, 'tcx>,
2378     def_id: DefId,
2379 ) -> Option<hir::Mutability> {
2380     match tcx.hir().get_if_local(def_id) {
2381         Some(Node::Item(&hir::Item {
2382             node: hir::ItemKind::Static(_, mutbl, _), ..
2383         })) |
2384         Some(Node::ForeignItem( &hir::ForeignItem {
2385             node: hir::ForeignItemKind::Static(_, mutbl), ..
2386         })) => Some(mutbl),
2387         Some(_) => None,
2388         _ => bug!("static_mutability applied to non-local def-id {:?}", def_id),
2389     }
2390 }
2391
2392 fn from_target_feature(
2393     tcx: TyCtxt<'_, '_, '_>,
2394     id: DefId,
2395     attr: &ast::Attribute,
2396     whitelist: &FxHashMap<String, Option<Symbol>>,
2397     target_features: &mut Vec<Symbol>,
2398 ) {
2399     let list = match attr.meta_item_list() {
2400         Some(list) => list,
2401         None => return,
2402     };
2403     let rust_features = tcx.features();
2404     for item in list {
2405         // Only `enable = ...` is accepted in the meta item list
2406         if !item.check_name(sym::enable) {
2407             let msg = "#[target_feature(..)] only accepts sub-keys of `enable` \
2408                        currently";
2409             tcx.sess.span_err(item.span(), &msg);
2410             continue;
2411         }
2412
2413         // Must be of the form `enable = "..."` ( a string)
2414         let value = match item.value_str() {
2415             Some(value) => value,
2416             None => {
2417                 let msg = "#[target_feature] attribute must be of the form \
2418                            #[target_feature(enable = \"..\")]";
2419                 tcx.sess.span_err(item.span(), &msg);
2420                 continue;
2421             }
2422         };
2423
2424         // We allow comma separation to enable multiple features
2425         target_features.extend(value.as_str().split(',').filter_map(|feature| {
2426             // Only allow whitelisted features per platform
2427             let feature_gate = match whitelist.get(feature) {
2428                 Some(g) => g,
2429                 None => {
2430                     let msg = format!(
2431                         "the feature named `{}` is not valid for \
2432                          this target",
2433                         feature
2434                     );
2435                     let mut err = tcx.sess.struct_span_err(item.span(), &msg);
2436
2437                     if feature.starts_with("+") {
2438                         let valid = whitelist.contains_key(&feature[1..]);
2439                         if valid {
2440                             err.help("consider removing the leading `+` in the feature name");
2441                         }
2442                     }
2443                     err.emit();
2444                     return None;
2445                 }
2446             };
2447
2448             // Only allow features whose feature gates have been enabled
2449             let allowed = match feature_gate.as_ref().map(|s| *s) {
2450                 Some(sym::arm_target_feature) => rust_features.arm_target_feature,
2451                 Some(sym::aarch64_target_feature) => rust_features.aarch64_target_feature,
2452                 Some(sym::hexagon_target_feature) => rust_features.hexagon_target_feature,
2453                 Some(sym::powerpc_target_feature) => rust_features.powerpc_target_feature,
2454                 Some(sym::mips_target_feature) => rust_features.mips_target_feature,
2455                 Some(sym::avx512_target_feature) => rust_features.avx512_target_feature,
2456                 Some(sym::mmx_target_feature) => rust_features.mmx_target_feature,
2457                 Some(sym::sse4a_target_feature) => rust_features.sse4a_target_feature,
2458                 Some(sym::tbm_target_feature) => rust_features.tbm_target_feature,
2459                 Some(sym::wasm_target_feature) => rust_features.wasm_target_feature,
2460                 Some(sym::cmpxchg16b_target_feature) => rust_features.cmpxchg16b_target_feature,
2461                 Some(sym::adx_target_feature) => rust_features.adx_target_feature,
2462                 Some(sym::movbe_target_feature) => rust_features.movbe_target_feature,
2463                 Some(sym::rtm_target_feature) => rust_features.rtm_target_feature,
2464                 Some(sym::f16c_target_feature) => rust_features.f16c_target_feature,
2465                 Some(name) => bug!("unknown target feature gate {}", name),
2466                 None => true,
2467             };
2468             if !allowed && id.is_local() {
2469                 feature_gate::emit_feature_err(
2470                     &tcx.sess.parse_sess,
2471                     feature_gate.unwrap(),
2472                     item.span(),
2473                     feature_gate::GateIssue::Language,
2474                     &format!("the target feature `{}` is currently unstable", feature),
2475                 );
2476             }
2477             Some(Symbol::intern(feature))
2478         }));
2479     }
2480 }
2481
2482 fn linkage_by_name<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId, name: &str) -> Linkage {
2483     use rustc::mir::mono::Linkage::*;
2484
2485     // Use the names from src/llvm/docs/LangRef.rst here. Most types are only
2486     // applicable to variable declarations and may not really make sense for
2487     // Rust code in the first place but whitelist them anyway and trust that
2488     // the user knows what s/he's doing. Who knows, unanticipated use cases
2489     // may pop up in the future.
2490     //
2491     // ghost, dllimport, dllexport and linkonce_odr_autohide are not supported
2492     // and don't have to be, LLVM treats them as no-ops.
2493     match name {
2494         "appending" => Appending,
2495         "available_externally" => AvailableExternally,
2496         "common" => Common,
2497         "extern_weak" => ExternalWeak,
2498         "external" => External,
2499         "internal" => Internal,
2500         "linkonce" => LinkOnceAny,
2501         "linkonce_odr" => LinkOnceODR,
2502         "private" => Private,
2503         "weak" => WeakAny,
2504         "weak_odr" => WeakODR,
2505         _ => {
2506             let span = tcx.hir().span_if_local(def_id);
2507             if let Some(span) = span {
2508                 tcx.sess.span_fatal(span, "invalid linkage specified")
2509             } else {
2510                 tcx.sess
2511                    .fatal(&format!("invalid linkage specified: {}", name))
2512             }
2513         }
2514     }
2515 }
2516
2517 fn codegen_fn_attrs<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, id: DefId) -> CodegenFnAttrs {
2518     let attrs = tcx.get_attrs(id);
2519
2520     let mut codegen_fn_attrs = CodegenFnAttrs::new();
2521
2522     let whitelist = tcx.target_features_whitelist(LOCAL_CRATE);
2523
2524     let mut inline_span = None;
2525     for attr in attrs.iter() {
2526         if attr.check_name(sym::cold) {
2527             codegen_fn_attrs.flags |= CodegenFnAttrFlags::COLD;
2528         } else if attr.check_name(sym::allocator) {
2529             codegen_fn_attrs.flags |= CodegenFnAttrFlags::ALLOCATOR;
2530         } else if attr.check_name(sym::unwind) {
2531             codegen_fn_attrs.flags |= CodegenFnAttrFlags::UNWIND;
2532         } else if attr.check_name(sym::ffi_returns_twice) {
2533             if tcx.is_foreign_item(id) {
2534                 codegen_fn_attrs.flags |= CodegenFnAttrFlags::FFI_RETURNS_TWICE;
2535             } else {
2536                 // `#[ffi_returns_twice]` is only allowed `extern fn`s
2537                 struct_span_err!(
2538                     tcx.sess,
2539                     attr.span,
2540                     E0724,
2541                     "`#[ffi_returns_twice]` may only be used on foreign functions"
2542                 ).emit();
2543             }
2544         } else if attr.check_name(sym::rustc_allocator_nounwind) {
2545             codegen_fn_attrs.flags |= CodegenFnAttrFlags::RUSTC_ALLOCATOR_NOUNWIND;
2546         } else if attr.check_name(sym::naked) {
2547             codegen_fn_attrs.flags |= CodegenFnAttrFlags::NAKED;
2548         } else if attr.check_name(sym::no_mangle) {
2549             codegen_fn_attrs.flags |= CodegenFnAttrFlags::NO_MANGLE;
2550         } else if attr.check_name(sym::rustc_std_internal_symbol) {
2551             codegen_fn_attrs.flags |= CodegenFnAttrFlags::RUSTC_STD_INTERNAL_SYMBOL;
2552         } else if attr.check_name(sym::no_debug) {
2553             codegen_fn_attrs.flags |= CodegenFnAttrFlags::NO_DEBUG;
2554         } else if attr.check_name(sym::used) {
2555             codegen_fn_attrs.flags |= CodegenFnAttrFlags::USED;
2556         } else if attr.check_name(sym::thread_local) {
2557             codegen_fn_attrs.flags |= CodegenFnAttrFlags::THREAD_LOCAL;
2558         } else if attr.check_name(sym::export_name) {
2559             if let Some(s) = attr.value_str() {
2560                 if s.as_str().contains("\0") {
2561                     // `#[export_name = ...]` will be converted to a null-terminated string,
2562                     // so it may not contain any null characters.
2563                     struct_span_err!(
2564                         tcx.sess,
2565                         attr.span,
2566                         E0648,
2567                         "`export_name` may not contain null characters"
2568                     ).emit();
2569                 }
2570                 codegen_fn_attrs.export_name = Some(s);
2571             }
2572         } else if attr.check_name(sym::target_feature) {
2573             if tcx.fn_sig(id).unsafety() == Unsafety::Normal {
2574                 let msg = "#[target_feature(..)] can only be applied to \
2575                            `unsafe` function";
2576                 tcx.sess.span_err(attr.span, msg);
2577             }
2578             from_target_feature(
2579                 tcx,
2580                 id,
2581                 attr,
2582                 &whitelist,
2583                 &mut codegen_fn_attrs.target_features,
2584             );
2585         } else if attr.check_name(sym::linkage) {
2586             if let Some(val) = attr.value_str() {
2587                 codegen_fn_attrs.linkage = Some(linkage_by_name(tcx, id, &val.as_str()));
2588             }
2589         } else if attr.check_name(sym::link_section) {
2590             if let Some(val) = attr.value_str() {
2591                 if val.as_str().bytes().any(|b| b == 0) {
2592                     let msg = format!(
2593                         "illegal null byte in link_section \
2594                          value: `{}`",
2595                         &val
2596                     );
2597                     tcx.sess.span_err(attr.span, &msg);
2598                 } else {
2599                     codegen_fn_attrs.link_section = Some(val);
2600                 }
2601             }
2602         } else if attr.check_name(sym::link_name) {
2603             codegen_fn_attrs.link_name = attr.value_str();
2604         }
2605     }
2606
2607     codegen_fn_attrs.inline = attrs.iter().fold(InlineAttr::None, |ia, attr| {
2608         if attr.path != sym::inline {
2609             return ia;
2610         }
2611         match attr.meta().map(|i| i.node) {
2612             Some(MetaItemKind::Word) => {
2613                 mark_used(attr);
2614                 InlineAttr::Hint
2615             }
2616             Some(MetaItemKind::List(ref items)) => {
2617                 mark_used(attr);
2618                 inline_span = Some(attr.span);
2619                 if items.len() != 1 {
2620                     span_err!(
2621                         tcx.sess.diagnostic(),
2622                         attr.span,
2623                         E0534,
2624                         "expected one argument"
2625                     );
2626                     InlineAttr::None
2627                 } else if list_contains_name(&items[..], sym::always) {
2628                     InlineAttr::Always
2629                 } else if list_contains_name(&items[..], sym::never) {
2630                     InlineAttr::Never
2631                 } else {
2632                     span_err!(
2633                         tcx.sess.diagnostic(),
2634                         items[0].span(),
2635                         E0535,
2636                         "invalid argument"
2637                     );
2638
2639                     InlineAttr::None
2640                 }
2641             }
2642             Some(MetaItemKind::NameValue(_)) => ia,
2643             None => ia,
2644         }
2645     });
2646
2647     codegen_fn_attrs.optimize = attrs.iter().fold(OptimizeAttr::None, |ia, attr| {
2648         if attr.path != sym::optimize {
2649             return ia;
2650         }
2651         let err = |sp, s| span_err!(tcx.sess.diagnostic(), sp, E0722, "{}", s);
2652         match attr.meta().map(|i| i.node) {
2653             Some(MetaItemKind::Word) => {
2654                 err(attr.span, "expected one argument");
2655                 ia
2656             }
2657             Some(MetaItemKind::List(ref items)) => {
2658                 mark_used(attr);
2659                 inline_span = Some(attr.span);
2660                 if items.len() != 1 {
2661                     err(attr.span, "expected one argument");
2662                     OptimizeAttr::None
2663                 } else if list_contains_name(&items[..], sym::size) {
2664                     OptimizeAttr::Size
2665                 } else if list_contains_name(&items[..], sym::speed) {
2666                     OptimizeAttr::Speed
2667                 } else {
2668                     err(items[0].span(), "invalid argument");
2669                     OptimizeAttr::None
2670                 }
2671             }
2672             Some(MetaItemKind::NameValue(_)) => ia,
2673             None => ia,
2674         }
2675     });
2676
2677     // If a function uses #[target_feature] it can't be inlined into general
2678     // purpose functions as they wouldn't have the right target features
2679     // enabled. For that reason we also forbid #[inline(always)] as it can't be
2680     // respected.
2681     if codegen_fn_attrs.target_features.len() > 0 {
2682         if codegen_fn_attrs.inline == InlineAttr::Always {
2683             if let Some(span) = inline_span {
2684                 tcx.sess.span_err(
2685                     span,
2686                     "cannot use #[inline(always)] with \
2687                      #[target_feature]",
2688                 );
2689             }
2690         }
2691     }
2692
2693     // Weak lang items have the same semantics as "std internal" symbols in the
2694     // sense that they're preserved through all our LTO passes and only
2695     // strippable by the linker.
2696     //
2697     // Additionally weak lang items have predetermined symbol names.
2698     if tcx.is_weak_lang_item(id) {
2699         codegen_fn_attrs.flags |= CodegenFnAttrFlags::RUSTC_STD_INTERNAL_SYMBOL;
2700     }
2701     if let Some(name) = weak_lang_items::link_name(&attrs) {
2702         codegen_fn_attrs.export_name = Some(name);
2703         codegen_fn_attrs.link_name = Some(name);
2704     }
2705
2706     // Internal symbols to the standard library all have no_mangle semantics in
2707     // that they have defined symbol names present in the function name. This
2708     // also applies to weak symbols where they all have known symbol names.
2709     if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::RUSTC_STD_INTERNAL_SYMBOL) {
2710         codegen_fn_attrs.flags |= CodegenFnAttrFlags::NO_MANGLE;
2711     }
2712
2713     codegen_fn_attrs
2714 }