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