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