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