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