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