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