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