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.
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.
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
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
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.
27 use astconv::{AstConv, Bounds};
29 use constrained_type_params as ctp;
30 use middle::lang_items::SizedTraitLangItem;
31 use middle::const_val::ConstVal;
32 use middle::resolve_lifetime as rl;
33 use rustc::traits::Reveal;
34 use rustc::ty::subst::Substs;
35 use rustc::ty::{ToPredicate, ReprOptions};
36 use rustc::ty::{self, AdtKind, ToPolyTraitRef, Ty, TyCtxt};
37 use rustc::ty::maps::Providers;
38 use rustc::ty::util::IntTypeExt;
39 use util::nodemap::FxHashMap;
41 use rustc_const_math::ConstInt;
43 use syntax::{abi, ast};
44 use syntax::codemap::Spanned;
45 use syntax::symbol::{Symbol, keywords};
46 use syntax_pos::{Span, DUMMY_SP};
48 use rustc::hir::{self, map as hir_map};
49 use rustc::hir::intravisit::{self, Visitor, NestedVisitorMap};
50 use rustc::hir::def::{Def, CtorKind};
51 use rustc::hir::def_id::DefId;
53 ///////////////////////////////////////////////////////////////////////////
56 pub fn collect_item_types<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>) {
57 let mut visitor = CollectItemTypesVisitor { tcx: tcx };
58 tcx.hir.krate().visit_all_item_likes(&mut visitor.as_deep_visitor());
61 pub fn provide(providers: &mut Providers) {
62 *providers = Providers {
67 type_param_predicates,
78 ///////////////////////////////////////////////////////////////////////////
80 /// Context specific to some particular item. This is what implements
81 /// AstConv. It has information about the predicates that are defined
82 /// on the trait. Unfortunately, this predicate information is
83 /// available in various different forms at various points in the
84 /// process. So we can't just store a pointer to e.g. the AST or the
85 /// parsed ty form, we have to be more flexible. To this end, the
86 /// `ItemCtxt` is parameterized by a `DefId` that it uses to satisfy
87 /// `get_type_parameter_bounds` requests, drawing the information from
88 /// the AST (`hir::Generics`), recursively.
89 pub struct ItemCtxt<'a,'tcx:'a> {
90 tcx: TyCtxt<'a, 'tcx, 'tcx>,
94 ///////////////////////////////////////////////////////////////////////////
96 struct CollectItemTypesVisitor<'a, 'tcx: 'a> {
97 tcx: TyCtxt<'a, 'tcx, 'tcx>
100 impl<'a, 'tcx> Visitor<'tcx> for CollectItemTypesVisitor<'a, 'tcx> {
101 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
102 NestedVisitorMap::OnlyBodies(&self.tcx.hir)
105 fn visit_item(&mut self, item: &'tcx hir::Item) {
106 convert_item(self.tcx, item.id);
107 intravisit::walk_item(self, item);
110 fn visit_generics(&mut self, generics: &'tcx hir::Generics) {
111 for param in generics.ty_params() {
112 if param.default.is_some() {
113 let def_id = self.tcx.hir.local_def_id(param.id);
114 self.tcx.type_of(def_id);
117 intravisit::walk_generics(self, generics);
120 fn visit_expr(&mut self, expr: &'tcx hir::Expr) {
121 if let hir::ExprClosure(..) = expr.node {
122 let def_id = self.tcx.hir.local_def_id(expr.id);
123 self.tcx.generics_of(def_id);
124 self.tcx.type_of(def_id);
126 intravisit::walk_expr(self, expr);
129 fn visit_ty(&mut self, ty: &'tcx hir::Ty) {
130 if let hir::TyImplTraitExistential(..) = ty.node {
131 let def_id = self.tcx.hir.local_def_id(ty.id);
132 self.tcx.generics_of(def_id);
133 self.tcx.predicates_of(def_id);
135 intravisit::walk_ty(self, ty);
138 fn visit_trait_item(&mut self, trait_item: &'tcx hir::TraitItem) {
139 convert_trait_item(self.tcx, trait_item.id);
140 intravisit::walk_trait_item(self, trait_item);
143 fn visit_impl_item(&mut self, impl_item: &'tcx hir::ImplItem) {
144 convert_impl_item(self.tcx, impl_item.id);
145 intravisit::walk_impl_item(self, impl_item);
149 ///////////////////////////////////////////////////////////////////////////
150 // Utility types and common code for the above passes.
152 impl<'a, 'tcx> ItemCtxt<'a, 'tcx> {
153 pub fn new(tcx: TyCtxt<'a, 'tcx, 'tcx>, item_def_id: DefId)
154 -> ItemCtxt<'a,'tcx> {
162 impl<'a,'tcx> ItemCtxt<'a,'tcx> {
163 pub fn to_ty(&self, ast_ty: &hir::Ty) -> Ty<'tcx> {
164 AstConv::ast_ty_to_ty(self, ast_ty)
168 impl<'a, 'tcx> AstConv<'tcx, 'tcx> for ItemCtxt<'a, 'tcx> {
169 fn tcx<'b>(&'b self) -> TyCtxt<'b, 'tcx, 'tcx> { self.tcx }
171 fn get_type_parameter_bounds(&self,
174 -> ty::GenericPredicates<'tcx>
176 self.tcx.at(span).type_param_predicates((self.item_def_id, def_id))
179 fn re_infer(&self, _span: Span, _def: Option<&ty::RegionParameterDef>)
180 -> Option<ty::Region<'tcx>> {
184 fn ty_infer(&self, span: Span) -> Ty<'tcx> {
189 "the type placeholder `_` is not allowed within types on item signatures"
190 ).span_label(span, "not allowed in type signatures")
195 fn projected_ty_from_poly_trait_ref(&self,
198 poly_trait_ref: ty::PolyTraitRef<'tcx>)
201 if let Some(trait_ref) = poly_trait_ref.no_late_bound_regions() {
202 self.tcx().mk_projection(item_def_id, trait_ref.substs)
204 // no late-bound regions, we can just ignore the binder
205 span_err!(self.tcx().sess, span, E0212,
206 "cannot extract an associated type from a higher-ranked trait bound \
212 fn normalize_ty(&self, _span: Span, ty: Ty<'tcx>) -> Ty<'tcx> {
213 // types in item signatures are not normalized, to avoid undue
218 fn set_tainted_by_errors(&self) {
219 // no obvious place to track this, just let it go
222 fn record_ty(&self, _hir_id: hir::HirId, _ty: Ty<'tcx>, _span: Span) {
223 // no place to record types from signatures?
227 fn type_param_predicates<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
228 (item_def_id, def_id): (DefId, DefId))
229 -> ty::GenericPredicates<'tcx> {
230 use rustc::hir::map::*;
233 // In the AST, bounds can derive from two places. Either
234 // written inline like `<T:Foo>` or in a where clause like
237 let param_id = tcx.hir.as_local_node_id(def_id).unwrap();
238 let param_owner = tcx.hir.ty_param_owner(param_id);
239 let param_owner_def_id = tcx.hir.local_def_id(param_owner);
240 let generics = tcx.generics_of(param_owner_def_id);
241 let index = generics.type_param_to_index[&def_id];
242 let ty = tcx.mk_param(index, tcx.hir.ty_param_name(param_id));
244 // Don't look for bounds where the type parameter isn't in scope.
245 let parent = if item_def_id == param_owner_def_id {
248 tcx.generics_of(item_def_id).parent
251 let mut result = parent.map_or(ty::GenericPredicates {
255 let icx = ItemCtxt::new(tcx, parent);
256 icx.get_type_parameter_bounds(DUMMY_SP, def_id)
259 let item_node_id = tcx.hir.as_local_node_id(item_def_id).unwrap();
260 let ast_generics = match tcx.hir.get(item_node_id) {
261 NodeTraitItem(item) => &item.generics,
263 NodeImplItem(item) => &item.generics,
267 ItemFn(.., ref generics, _) |
268 ItemImpl(_, _, _, ref generics, ..) |
269 ItemTy(_, ref generics) |
270 ItemEnum(_, ref generics) |
271 ItemStruct(_, ref generics) |
272 ItemUnion(_, ref generics) => generics,
273 ItemTrait(_, _, ref generics, ..) => {
274 // Implied `Self: Trait` and supertrait bounds.
275 if param_id == item_node_id {
276 result.predicates.push(ty::TraitRef {
278 substs: Substs::identity_for_item(tcx, item_def_id)
287 NodeForeignItem(item) => {
289 ForeignItemFn(_, _, ref generics) => generics,
297 let icx = ItemCtxt::new(tcx, item_def_id);
298 result.predicates.extend(
299 icx.type_parameter_bounds_in_generics(ast_generics, param_id, ty));
303 impl<'a, 'tcx> ItemCtxt<'a, 'tcx> {
304 /// Find bounds from hir::Generics. This requires scanning through the
305 /// AST. We do this to avoid having to convert *all* the bounds, which
306 /// would create artificial cycles. Instead we can only convert the
307 /// bounds for a type parameter `X` if `X::Foo` is used.
308 fn type_parameter_bounds_in_generics(&self,
309 ast_generics: &hir::Generics,
310 param_id: ast::NodeId,
312 -> Vec<ty::Predicate<'tcx>>
315 ast_generics.ty_params()
316 .filter(|p| p.id == param_id)
317 .flat_map(|p| p.bounds.iter())
318 .flat_map(|b| predicates_from_bound(self, ty, b));
320 let from_where_clauses =
321 ast_generics.where_clause
324 .filter_map(|wp| match *wp {
325 hir::WherePredicate::BoundPredicate(ref bp) => Some(bp),
328 .filter(|bp| is_param(self.tcx, &bp.bounded_ty, param_id))
329 .flat_map(|bp| bp.bounds.iter())
330 .flat_map(|b| predicates_from_bound(self, ty, b));
332 from_ty_params.chain(from_where_clauses).collect()
336 /// Tests whether this is the AST for a reference to the type
337 /// parameter with id `param_id`. We use this so as to avoid running
338 /// `ast_ty_to_ty`, because we want to avoid triggering an all-out
339 /// conversion of the type to avoid inducing unnecessary cycles.
340 fn is_param<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
342 param_id: ast::NodeId)
345 if let hir::TyPath(hir::QPath::Resolved(None, ref path)) = ast_ty.node {
347 Def::SelfTy(Some(def_id), None) |
348 Def::TyParam(def_id) => {
349 def_id == tcx.hir.local_def_id(param_id)
358 fn ensure_no_param_bounds(tcx: TyCtxt,
360 generics: &hir::Generics,
361 thing: &'static str) {
362 let mut warn = false;
364 for ty_param in generics.ty_params() {
365 if !ty_param.bounds.is_empty() {
370 for lft_param in generics.lifetimes() {
371 if !lft_param.bounds.is_empty() {
376 if !generics.where_clause.predicates.is_empty() {
381 // According to accepted RFC #XXX, we should
382 // eventually accept these, but it will not be
383 // part of this PR. Still, convert to warning to
384 // make bootstrapping easier.
385 span_warn!(tcx.sess, span, E0122,
386 "generic bounds are ignored in {}",
391 fn convert_item<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, item_id: ast::NodeId) {
392 let it = tcx.hir.expect_item(item_id);
393 debug!("convert: item {} with id {}", it.name, it.id);
394 let def_id = tcx.hir.local_def_id(item_id);
396 // These don't define types.
397 hir::ItemExternCrate(_) |
400 hir::ItemGlobalAsm(_) => {}
401 hir::ItemForeignMod(ref foreign_mod) => {
402 for item in &foreign_mod.items {
403 let def_id = tcx.hir.local_def_id(item.id);
404 tcx.generics_of(def_id);
406 tcx.predicates_of(def_id);
407 if let hir::ForeignItemFn(..) = item.node {
412 hir::ItemEnum(ref enum_definition, _) => {
413 tcx.generics_of(def_id);
415 tcx.predicates_of(def_id);
416 convert_enum_variant_types(tcx, def_id, &enum_definition.variants);
418 hir::ItemImpl(..) => {
419 tcx.generics_of(def_id);
421 tcx.impl_trait_ref(def_id);
422 tcx.predicates_of(def_id);
424 hir::ItemTrait(..) => {
425 tcx.generics_of(def_id);
426 tcx.trait_def(def_id);
427 tcx.at(it.span).super_predicates_of(def_id);
428 tcx.predicates_of(def_id);
430 hir::ItemTraitAlias(..) => {
431 span_err!(tcx.sess, it.span, E0645,
432 "trait aliases are not yet implemented (see issue #41517)");
434 hir::ItemStruct(ref struct_def, _) |
435 hir::ItemUnion(ref struct_def, _) => {
436 tcx.generics_of(def_id);
438 tcx.predicates_of(def_id);
440 for f in struct_def.fields() {
441 let def_id = tcx.hir.local_def_id(f.id);
442 tcx.generics_of(def_id);
444 tcx.predicates_of(def_id);
447 if !struct_def.is_struct() {
448 convert_variant_ctor(tcx, struct_def.id());
451 hir::ItemTy(_, ref generics) => {
452 ensure_no_param_bounds(tcx, it.span, generics, "type aliases");
453 tcx.generics_of(def_id);
455 tcx.predicates_of(def_id);
457 hir::ItemStatic(..) | hir::ItemConst(..) | hir::ItemFn(..) => {
458 tcx.generics_of(def_id);
460 tcx.predicates_of(def_id);
461 if let hir::ItemFn(..) = it.node {
468 fn convert_trait_item<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, trait_item_id: ast::NodeId) {
469 let trait_item = tcx.hir.expect_trait_item(trait_item_id);
470 let def_id = tcx.hir.local_def_id(trait_item.id);
471 tcx.generics_of(def_id);
473 match trait_item.node {
474 hir::TraitItemKind::Const(..) |
475 hir::TraitItemKind::Type(_, Some(_)) |
476 hir::TraitItemKind::Method(..) => {
478 if let hir::TraitItemKind::Method(..) = trait_item.node {
483 hir::TraitItemKind::Type(_, None) => {}
486 tcx.predicates_of(def_id);
489 fn convert_impl_item<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, impl_item_id: ast::NodeId) {
490 let def_id = tcx.hir.local_def_id(impl_item_id);
491 tcx.generics_of(def_id);
493 tcx.predicates_of(def_id);
494 if let hir::ImplItemKind::Method(..) = tcx.hir.expect_impl_item(impl_item_id).node {
499 fn convert_variant_ctor<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
500 ctor_id: ast::NodeId) {
501 let def_id = tcx.hir.local_def_id(ctor_id);
502 tcx.generics_of(def_id);
504 tcx.predicates_of(def_id);
507 fn convert_enum_variant_types<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
509 variants: &[hir::Variant]) {
510 let param_env = ty::ParamEnv::empty(Reveal::UserFacing);
511 let def = tcx.adt_def(def_id);
512 let repr_type = def.repr.discr_type();
513 let initial = repr_type.initial_discriminant(tcx);
514 let mut prev_discr = None::<ConstInt>;
516 // fill the discriminant values and field types
517 for variant in variants {
518 let wrapped_discr = prev_discr.map_or(initial, |d| d.wrap_incr());
519 prev_discr = Some(if let Some(e) = variant.node.disr_expr {
520 let expr_did = tcx.hir.local_def_id(e.node_id);
521 let substs = Substs::identity_for_item(tcx, expr_did);
522 let result = tcx.at(variant.span).const_eval(param_env.and((expr_did, substs)));
524 // enum variant evaluation happens before the global constant check
525 // so we need to report the real error
526 if let Err(ref err) = result {
527 err.report(tcx, variant.span, "enum discriminant");
531 Ok(&ty::Const { val: ConstVal::Integral(x), .. }) => Some(x),
534 } else if let Some(discr) = repr_type.disr_incr(tcx, prev_discr) {
537 struct_span_err!(tcx.sess, variant.span, E0370,
538 "enum discriminant overflowed")
539 .span_label(variant.span, format!("overflowed on value after {}",
540 prev_discr.unwrap()))
541 .note(&format!("explicitly set `{} = {}` if that is desired outcome",
542 variant.node.name, wrapped_discr))
545 }.unwrap_or(wrapped_discr));
547 for f in variant.node.data.fields() {
548 let def_id = tcx.hir.local_def_id(f.id);
549 tcx.generics_of(def_id);
551 tcx.predicates_of(def_id);
554 // Convert the ctor, if any. This also registers the variant as
556 convert_variant_ctor(tcx, variant.node.data.id());
560 fn convert_struct_variant<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
563 discr: ty::VariantDiscr,
564 def: &hir::VariantData)
566 let mut seen_fields: FxHashMap<ast::Name, Span> = FxHashMap();
567 let node_id = tcx.hir.as_local_node_id(did).unwrap();
568 let fields = def.fields().iter().map(|f| {
569 let fid = tcx.hir.local_def_id(f.id);
570 let dup_span = seen_fields.get(&f.name).cloned();
571 if let Some(prev_span) = dup_span {
572 struct_span_err!(tcx.sess, f.span, E0124,
573 "field `{}` is already declared",
575 .span_label(f.span, "field already declared")
576 .span_label(prev_span, format!("`{}` first declared here", f.name))
579 seen_fields.insert(f.name, f.span);
585 vis: ty::Visibility::from_hir(&f.vis, node_id, tcx)
593 ctor_kind: CtorKind::from_hir(def),
597 fn adt_def<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
599 -> &'tcx ty::AdtDef {
600 use rustc::hir::map::*;
603 let node_id = tcx.hir.as_local_node_id(def_id).unwrap();
604 let item = match tcx.hir.get(node_id) {
605 NodeItem(item) => item,
609 let repr = ReprOptions::new(tcx, def_id);
610 let (kind, variants) = match item.node {
611 ItemEnum(ref def, _) => {
612 let mut distance_from_explicit = 0;
613 (AdtKind::Enum, def.variants.iter().map(|v| {
614 let did = tcx.hir.local_def_id(v.node.data.id());
615 let discr = if let Some(e) = v.node.disr_expr {
616 distance_from_explicit = 0;
617 ty::VariantDiscr::Explicit(tcx.hir.local_def_id(e.node_id))
619 ty::VariantDiscr::Relative(distance_from_explicit)
621 distance_from_explicit += 1;
623 convert_struct_variant(tcx, did, v.node.name, discr, &v.node.data)
626 ItemStruct(ref def, _) => {
627 // Use separate constructor id for unit/tuple structs and reuse did for braced structs.
628 let ctor_id = if !def.is_struct() {
629 Some(tcx.hir.local_def_id(def.id()))
633 (AdtKind::Struct, vec![
634 convert_struct_variant(tcx, ctor_id.unwrap_or(def_id), item.name,
635 ty::VariantDiscr::Relative(0), def)
638 ItemUnion(ref def, _) => {
639 (AdtKind::Union, vec![
640 convert_struct_variant(tcx, def_id, item.name,
641 ty::VariantDiscr::Relative(0), def)
646 tcx.alloc_adt_def(def_id, kind, variants, repr)
649 /// Ensures that the super-predicates of the trait with def-id
650 /// trait_def_id are converted and stored. This also ensures that
651 /// the transitive super-predicates are converted;
652 fn super_predicates_of<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
654 -> ty::GenericPredicates<'tcx> {
655 debug!("super_predicates(trait_def_id={:?})", trait_def_id);
656 let trait_node_id = tcx.hir.as_local_node_id(trait_def_id).unwrap();
658 let item = match tcx.hir.get(trait_node_id) {
659 hir_map::NodeItem(item) => item,
660 _ => bug!("trait_node_id {} is not an item", trait_node_id)
663 let (generics, bounds) = match item.node {
664 hir::ItemTrait(.., ref generics, ref supertraits, _) => (generics, supertraits),
665 hir::ItemTraitAlias(ref generics, ref supertraits) => (generics, supertraits),
666 _ => span_bug!(item.span,
667 "super_predicates invoked on non-trait"),
670 let icx = ItemCtxt::new(tcx, trait_def_id);
672 // Convert the bounds that follow the colon, e.g. `Bar+Zed` in `trait Foo : Bar+Zed`.
673 let self_param_ty = tcx.mk_self_type();
674 let superbounds1 = compute_bounds(&icx,
680 let superbounds1 = superbounds1.predicates(tcx, self_param_ty);
682 // Convert any explicit superbounds in the where clause,
683 // e.g. `trait Foo where Self : Bar`:
684 let superbounds2 = icx.type_parameter_bounds_in_generics(generics, item.id, self_param_ty);
686 // Combine the two lists to form the complete set of superbounds:
687 let superbounds: Vec<_> = superbounds1.into_iter().chain(superbounds2).collect();
689 // Now require that immediate supertraits are converted,
690 // which will, in turn, reach indirect supertraits.
691 for bound in superbounds.iter().filter_map(|p| p.to_opt_poly_trait_ref()) {
692 tcx.at(item.span).super_predicates_of(bound.def_id());
695 ty::GenericPredicates {
697 predicates: superbounds
701 fn trait_def<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
703 -> &'tcx ty::TraitDef {
704 let node_id = tcx.hir.as_local_node_id(def_id).unwrap();
705 let item = tcx.hir.expect_item(node_id);
707 let (is_auto, unsafety) = match item.node {
708 hir::ItemTrait(is_auto, unsafety, ..) => (is_auto == hir::IsAuto::Yes, unsafety),
709 hir::ItemTraitAlias(..) => (false, hir::Unsafety::Normal),
710 _ => span_bug!(item.span, "trait_def_of_item invoked on non-trait"),
713 let paren_sugar = tcx.has_attr(def_id, "rustc_paren_sugar");
714 if paren_sugar && !tcx.features().unboxed_closures {
715 let mut err = tcx.sess.struct_span_err(
717 "the `#[rustc_paren_sugar]` attribute is a temporary means of controlling \
718 which traits can use parenthetical notation");
720 "add `#![feature(unboxed_closures)]` to \
721 the crate attributes to use it");
725 let def_path_hash = tcx.def_path_hash(def_id);
726 let def = ty::TraitDef::new(def_id,
731 tcx.alloc_trait_def(def)
734 fn has_late_bound_regions<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
735 node: hir_map::Node<'tcx>)
737 struct LateBoundRegionsDetector<'a, 'tcx: 'a> {
738 tcx: TyCtxt<'a, 'tcx, 'tcx>,
740 has_late_bound_regions: Option<Span>,
743 impl<'a, 'tcx> Visitor<'tcx> for LateBoundRegionsDetector<'a, 'tcx> {
744 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
745 NestedVisitorMap::None
748 fn visit_ty(&mut self, ty: &'tcx hir::Ty) {
749 if self.has_late_bound_regions.is_some() { return }
751 hir::TyBareFn(..) => {
752 self.binder_depth += 1;
753 intravisit::walk_ty(self, ty);
754 self.binder_depth -= 1;
756 _ => intravisit::walk_ty(self, ty)
760 fn visit_poly_trait_ref(&mut self,
761 tr: &'tcx hir::PolyTraitRef,
762 m: hir::TraitBoundModifier) {
763 if self.has_late_bound_regions.is_some() { return }
764 self.binder_depth += 1;
765 intravisit::walk_poly_trait_ref(self, tr, m);
766 self.binder_depth -= 1;
769 fn visit_lifetime(&mut self, lt: &'tcx hir::Lifetime) {
770 if self.has_late_bound_regions.is_some() { return }
772 let hir_id = self.tcx.hir.node_to_hir_id(lt.id);
773 match self.tcx.named_region(hir_id) {
774 Some(rl::Region::Static) | Some(rl::Region::EarlyBound(..)) => {}
775 Some(rl::Region::LateBound(debruijn, _, _)) |
776 Some(rl::Region::LateBoundAnon(debruijn, _))
777 if debruijn.depth < self.binder_depth => {}
778 _ => self.has_late_bound_regions = Some(lt.span),
783 fn has_late_bound_regions<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
784 generics: &'tcx hir::Generics,
785 decl: &'tcx hir::FnDecl)
787 let mut visitor = LateBoundRegionsDetector {
788 tcx, binder_depth: 1, has_late_bound_regions: None
790 for lifetime in generics.lifetimes() {
791 let hir_id = tcx.hir.node_to_hir_id(lifetime.lifetime.id);
792 if tcx.is_late_bound(hir_id) {
793 return Some(lifetime.lifetime.span);
796 visitor.visit_fn_decl(decl);
797 visitor.has_late_bound_regions
801 hir_map::NodeTraitItem(item) => match item.node {
802 hir::TraitItemKind::Method(ref sig, _) =>
803 has_late_bound_regions(tcx, &item.generics, &sig.decl),
806 hir_map::NodeImplItem(item) => match item.node {
807 hir::ImplItemKind::Method(ref sig, _) =>
808 has_late_bound_regions(tcx, &item.generics, &sig.decl),
811 hir_map::NodeForeignItem(item) => match item.node {
812 hir::ForeignItemFn(ref fn_decl, _, ref generics) =>
813 has_late_bound_regions(tcx, generics, fn_decl),
816 hir_map::NodeItem(item) => match item.node {
817 hir::ItemFn(ref fn_decl, .., ref generics, _) =>
818 has_late_bound_regions(tcx, generics, fn_decl),
825 fn generics_of<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
827 -> &'tcx ty::Generics {
828 use rustc::hir::map::*;
831 let node_id = tcx.hir.as_local_node_id(def_id).unwrap();
833 let node = tcx.hir.get(node_id);
834 let parent_def_id = match node {
840 let parent_id = tcx.hir.get_parent(node_id);
841 Some(tcx.hir.local_def_id(parent_id))
843 NodeExpr(&hir::Expr { node: hir::ExprClosure(..), .. }) => {
844 Some(tcx.closure_base_def_id(def_id))
846 NodeTy(&hir::Ty { node: hir::TyImplTraitExistential(..), .. }) => {
847 let mut parent_id = node_id;
849 match tcx.hir.get(parent_id) {
850 NodeItem(_) | NodeImplItem(_) | NodeTraitItem(_) => break,
852 parent_id = tcx.hir.get_parent_node(parent_id);
856 Some(tcx.hir.local_def_id(parent_id))
861 let mut opt_self = None;
862 let mut allow_defaults = false;
864 let no_generics = hir::Generics::empty();
865 let ast_generics = match node {
866 NodeTraitItem(item) => &item.generics,
868 NodeImplItem(item) => &item.generics,
872 ItemFn(.., ref generics, _) |
873 ItemImpl(_, _, _, ref generics, ..) => generics,
875 ItemTy(_, ref generics) |
876 ItemEnum(_, ref generics) |
877 ItemStruct(_, ref generics) |
878 ItemUnion(_, ref generics) => {
879 allow_defaults = true;
883 ItemTrait(_, _, ref generics, ..) | ItemTraitAlias(ref generics, ..) => {
884 // Add in the self type parameter.
886 // Something of a hack: use the node id for the trait, also as
887 // the node id for the Self type parameter.
888 let param_id = item.id;
890 opt_self = Some(ty::TypeParameterDef {
892 name: keywords::SelfType.name(),
893 def_id: tcx.hir.local_def_id(param_id),
895 object_lifetime_default: rl::Set1::Empty,
896 pure_wrt_drop: false,
900 allow_defaults = true;
908 NodeForeignItem(item) => {
910 ForeignItemStatic(..) => &no_generics,
911 ForeignItemFn(_, _, ref generics) => generics,
912 ForeignItemType => &no_generics,
916 NodeTy(&hir::Ty { node: hir::TyImplTraitExistential(ref exist_ty, _), .. }) => {
923 let has_self = opt_self.is_some();
924 let mut parent_has_self = false;
925 let mut own_start = has_self as u32;
926 let (parent_regions, parent_types) = parent_def_id.map_or((0, 0), |def_id| {
927 let generics = tcx.generics_of(def_id);
928 assert_eq!(has_self, false);
929 parent_has_self = generics.has_self;
930 own_start = generics.count() as u32;
931 (generics.parent_regions + generics.regions.len() as u32,
932 generics.parent_types + generics.types.len() as u32)
935 let early_lifetimes = early_bound_lifetimes_from_generics(tcx, ast_generics);
936 let regions = early_lifetimes.enumerate().map(|(i, l)| {
937 ty::RegionParameterDef {
938 name: l.lifetime.name.name(),
939 index: own_start + i as u32,
940 def_id: tcx.hir.local_def_id(l.lifetime.id),
941 pure_wrt_drop: l.pure_wrt_drop,
943 }).collect::<Vec<_>>();
945 let hir_id = tcx.hir.node_to_hir_id(node_id);
946 let object_lifetime_defaults = tcx.object_lifetime_defaults(hir_id);
948 // Now create the real type parameters.
949 let type_start = own_start + regions.len() as u32;
950 let types = ast_generics.ty_params().enumerate().map(|(i, p)| {
951 if p.name == keywords::SelfType.name() {
952 span_bug!(p.span, "`Self` should not be the name of a regular parameter");
955 if !allow_defaults && p.default.is_some() {
956 if !tcx.features().default_type_parameter_fallback {
958 lint::builtin::INVALID_TYPE_PARAM_DEFAULT,
961 &format!("defaults for type parameters are only allowed in `struct`, \
962 `enum`, `type`, or `trait` definitions."));
966 ty::TypeParameterDef {
967 index: type_start + i as u32,
969 def_id: tcx.hir.local_def_id(p.id),
970 has_default: p.default.is_some(),
971 object_lifetime_default:
972 object_lifetime_defaults.as_ref().map_or(rl::Set1::Empty, |o| o[i]),
973 pure_wrt_drop: p.pure_wrt_drop,
974 synthetic: p.synthetic,
978 let mut types: Vec<_> = opt_self.into_iter().chain(types).collect();
980 // provide junk type parameter defs - the only place that
981 // cares about anything but the length is instantiation,
982 // and we don't do that for closures.
983 if let NodeExpr(&hir::Expr { node: hir::ExprClosure(..), .. }) = node {
984 // add a dummy parameter for the closure kind
985 types.push(ty::TypeParameterDef {
987 name: Symbol::intern("<closure_kind>"),
990 object_lifetime_default: rl::Set1::Empty,
991 pure_wrt_drop: false,
995 // add a dummy parameter for the closure signature
996 types.push(ty::TypeParameterDef {
997 index: type_start + 1,
998 name: Symbol::intern("<closure_signature>"),
1001 object_lifetime_default: rl::Set1::Empty,
1002 pure_wrt_drop: false,
1006 tcx.with_freevars(node_id, |fv| {
1007 types.extend(fv.iter().zip(2..).map(|(_, i)| ty::TypeParameterDef {
1008 index: type_start + i,
1009 name: Symbol::intern("<upvar>"),
1012 object_lifetime_default: rl::Set1::Empty,
1013 pure_wrt_drop: false,
1019 let type_param_to_index = types.iter()
1020 .map(|param| (param.def_id, param.index))
1023 tcx.alloc_generics(ty::Generics {
1024 parent: parent_def_id,
1029 type_param_to_index,
1030 has_self: has_self || parent_has_self,
1031 has_late_bound_regions: has_late_bound_regions(tcx, node),
1035 fn type_of<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
1038 use rustc::hir::map::*;
1041 let node_id = tcx.hir.as_local_node_id(def_id).unwrap();
1043 let icx = ItemCtxt::new(tcx, def_id);
1045 match tcx.hir.get(node_id) {
1046 NodeTraitItem(item) => {
1048 TraitItemKind::Method(..) => {
1049 let substs = Substs::identity_for_item(tcx, def_id);
1050 tcx.mk_fn_def(def_id, substs)
1052 TraitItemKind::Const(ref ty, _) |
1053 TraitItemKind::Type(_, Some(ref ty)) => icx.to_ty(ty),
1054 TraitItemKind::Type(_, None) => {
1055 span_bug!(item.span, "associated type missing default");
1060 NodeImplItem(item) => {
1062 ImplItemKind::Method(..) => {
1063 let substs = Substs::identity_for_item(tcx, def_id);
1064 tcx.mk_fn_def(def_id, substs)
1066 ImplItemKind::Const(ref ty, _) => icx.to_ty(ty),
1067 ImplItemKind::Type(ref ty) => {
1068 if tcx.impl_trait_ref(tcx.hir.get_parent_did(node_id)).is_none() {
1069 span_err!(tcx.sess, item.span, E0202,
1070 "associated types are not allowed in inherent impls");
1080 ItemStatic(ref t, ..) | ItemConst(ref t, _) |
1081 ItemTy(ref t, _) | ItemImpl(.., ref t, _) => {
1085 let substs = Substs::identity_for_item(tcx, def_id);
1086 tcx.mk_fn_def(def_id, substs)
1091 let def = tcx.adt_def(def_id);
1092 let substs = Substs::identity_for_item(tcx, def_id);
1093 tcx.mk_adt(def, substs)
1095 ItemTrait(..) | ItemTraitAlias(..) |
1097 ItemForeignMod(..) |
1099 ItemExternCrate(..) |
1103 "compute_type_of_item: unexpected item type: {:?}",
1109 NodeForeignItem(foreign_item) => {
1110 match foreign_item.node {
1111 ForeignItemFn(..) => {
1112 let substs = Substs::identity_for_item(tcx, def_id);
1113 tcx.mk_fn_def(def_id, substs)
1115 ForeignItemStatic(ref t, _) => icx.to_ty(t),
1116 ForeignItemType => tcx.mk_foreign(def_id),
1120 NodeStructCtor(&ref def) |
1121 NodeVariant(&Spanned { node: hir::Variant_ { data: ref def, .. }, .. }) => {
1123 VariantData::Unit(..) | VariantData::Struct(..) => {
1124 tcx.type_of(tcx.hir.get_parent_did(node_id))
1126 VariantData::Tuple(..) => {
1127 let substs = Substs::identity_for_item(tcx, def_id);
1128 tcx.mk_fn_def(def_id, substs)
1133 NodeField(field) => icx.to_ty(&field.ty),
1135 NodeExpr(&hir::Expr { node: hir::ExprClosure(.., gen), .. }) => {
1137 let hir_id = tcx.hir.node_to_hir_id(node_id);
1138 return tcx.typeck_tables_of(def_id).node_id_to_type(hir_id);
1141 let substs = ty::ClosureSubsts {
1142 substs: Substs::for_item(
1146 let region = def.to_early_bound_region_data();
1147 tcx.mk_region(ty::ReEarlyBound(region))
1149 |def, _| tcx.mk_param_from_def(def)
1153 tcx.mk_closure(def_id, substs)
1156 NodeExpr(_) => match tcx.hir.get(tcx.hir.get_parent_node(node_id)) {
1157 NodeTy(&hir::Ty { node: TyArray(_, body), .. }) |
1158 NodeTy(&hir::Ty { node: TyTypeof(body), .. }) |
1159 NodeExpr(&hir::Expr { node: ExprRepeat(_, body), .. })
1160 if body.node_id == node_id => tcx.types.usize,
1162 NodeVariant(&Spanned { node: Variant_ { disr_expr: Some(e), .. }, .. })
1163 if e.node_id == node_id => {
1164 tcx.adt_def(tcx.hir.get_parent_did(node_id))
1165 .repr.discr_type().to_ty(tcx)
1169 bug!("unexpected expr parent in type_of_def_id(): {:?}", x);
1173 NodeTyParam(&hir::TyParam { default: Some(ref ty), .. }) => {
1177 NodeTy(&hir::Ty { node: TyImplTraitExistential(..), .. }) => {
1178 let owner = tcx.hir.get_parent_did(node_id);
1179 let hir_id = tcx.hir.node_to_hir_id(node_id);
1180 tcx.typeck_tables_of(owner).node_id_to_type(hir_id)
1184 bug!("unexpected sort of node in type_of_def_id(): {:?}", x);
1189 fn fn_sig<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
1191 -> ty::PolyFnSig<'tcx> {
1192 use rustc::hir::map::*;
1195 let node_id = tcx.hir.as_local_node_id(def_id).unwrap();
1197 let icx = ItemCtxt::new(tcx, def_id);
1199 match tcx.hir.get(node_id) {
1200 NodeTraitItem(&hir::TraitItem { node: TraitItemKind::Method(ref sig, _), .. }) |
1201 NodeImplItem(&hir::ImplItem { node: ImplItemKind::Method(ref sig, _), .. }) => {
1202 AstConv::ty_of_fn(&icx, sig.unsafety, sig.abi, &sig.decl)
1205 NodeItem(&hir::Item { node: ItemFn(ref decl, unsafety, _, abi, _, _), .. }) => {
1206 AstConv::ty_of_fn(&icx, unsafety, abi, decl)
1209 NodeForeignItem(&hir::ForeignItem { node: ForeignItemFn(ref fn_decl, _, _), .. }) => {
1210 let abi = tcx.hir.get_foreign_abi(node_id);
1211 compute_sig_of_foreign_fn_decl(tcx, def_id, fn_decl, abi)
1214 NodeStructCtor(&VariantData::Tuple(ref fields, _)) |
1215 NodeVariant(&Spanned { node: hir::Variant_ {
1216 data: VariantData::Tuple(ref fields, _), ..
1218 let ty = tcx.type_of(tcx.hir.get_parent_did(node_id));
1219 let inputs = fields.iter().map(|f| {
1220 tcx.type_of(tcx.hir.local_def_id(f.id))
1222 ty::Binder(tcx.mk_fn_sig(
1226 hir::Unsafety::Normal,
1231 NodeExpr(&hir::Expr { node: hir::ExprClosure(..), .. }) => {
1232 // Closure signatures are not like other function
1233 // signatures and cannot be accessed through `fn_sig`. For
1234 // example, a closure signature excludes the `self`
1235 // argument. In any case they are embedded within the
1236 // closure type as part of the `ClosureSubsts`.
1239 // the signature of a closure, you should use the
1240 // `closure_sig` method on the `ClosureSubsts`:
1242 // closure_substs.closure_sig(def_id, tcx)
1244 // or, inside of an inference context, you can use
1246 // infcx.closure_sig(def_id, closure_substs)
1247 bug!("to get the signature of a closure, use `closure_sig()` not `fn_sig()`");
1251 bug!("unexpected sort of node in fn_sig(): {:?}", x);
1256 fn impl_trait_ref<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
1258 -> Option<ty::TraitRef<'tcx>> {
1259 let icx = ItemCtxt::new(tcx, def_id);
1261 let node_id = tcx.hir.as_local_node_id(def_id).unwrap();
1262 match tcx.hir.expect_item(node_id).node {
1263 hir::ItemImpl(.., ref opt_trait_ref, _, _) => {
1264 opt_trait_ref.as_ref().map(|ast_trait_ref| {
1265 let selfty = tcx.type_of(def_id);
1266 AstConv::instantiate_mono_trait_ref(&icx, ast_trait_ref, selfty)
1273 fn impl_polarity<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
1275 -> hir::ImplPolarity {
1276 let node_id = tcx.hir.as_local_node_id(def_id).unwrap();
1277 match tcx.hir.expect_item(node_id).node {
1278 hir::ItemImpl(_, polarity, ..) => polarity,
1279 ref item => bug!("impl_polarity: {:?} not an impl", item)
1283 // Is it marked with ?Sized
1284 fn is_unsized<'gcx: 'tcx, 'tcx>(astconv: &AstConv<'gcx, 'tcx>,
1285 ast_bounds: &[hir::TyParamBound],
1288 let tcx = astconv.tcx();
1290 // Try to find an unbound in bounds.
1291 let mut unbound = None;
1292 for ab in ast_bounds {
1293 if let &hir::TraitTyParamBound(ref ptr, hir::TraitBoundModifier::Maybe) = ab {
1294 if unbound.is_none() {
1295 unbound = Some(ptr.trait_ref.clone());
1297 span_err!(tcx.sess, span, E0203,
1298 "type parameter has more than one relaxed default \
1299 bound, only one is supported");
1304 let kind_id = tcx.lang_items().require(SizedTraitLangItem);
1307 // FIXME(#8559) currently requires the unbound to be built-in.
1308 if let Ok(kind_id) = kind_id {
1309 if tpb.path.def != Def::Trait(kind_id) {
1310 tcx.sess.span_warn(span,
1311 "default bound relaxed for a type parameter, but \
1312 this does nothing because the given bound is not \
1313 a default. Only `?Sized` is supported");
1317 _ if kind_id.is_ok() => {
1320 // No lang item for Sized, so we can't add it as a bound.
1327 /// Returns the early-bound lifetimes declared in this generics
1328 /// listing. For anything other than fns/methods, this is just all
1329 /// the lifetimes that are declared. For fns or methods, we have to
1330 /// screen out those that do not appear in any where-clauses etc using
1331 /// `resolve_lifetime::early_bound_lifetimes`.
1332 fn early_bound_lifetimes_from_generics<'a, 'tcx>(
1333 tcx: TyCtxt<'a, 'tcx, 'tcx>,
1334 ast_generics: &'a hir::Generics)
1335 -> impl Iterator<Item=&'a hir::LifetimeDef>
1340 let hir_id = tcx.hir.node_to_hir_id(l.lifetime.id);
1341 !tcx.is_late_bound(hir_id)
1345 fn predicates_of<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
1347 -> ty::GenericPredicates<'tcx> {
1348 let explicit = explicit_predicates_of(tcx, def_id);
1349 ty::GenericPredicates {
1350 parent: explicit.parent,
1351 predicates: [&explicit.predicates[..], &tcx.inferred_outlives_of(def_id)[..]].concat()
1355 fn explicit_predicates_of<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
1357 -> ty::GenericPredicates<'tcx> {
1358 use rustc::hir::map::*;
1361 debug!("explicit_predicates_of(def_id={:?})", def_id);
1363 let node_id = tcx.hir.as_local_node_id(def_id).unwrap();
1364 let node = tcx.hir.get(node_id);
1366 let mut is_trait = None;
1367 let mut is_default_impl_trait = None;
1369 let icx = ItemCtxt::new(tcx, def_id);
1370 let no_generics = hir::Generics::empty();
1371 let ast_generics = match node {
1372 NodeTraitItem(item) => &item.generics,
1373 NodeImplItem(item) => &item.generics,
1377 ItemImpl(_, _, defaultness, ref generics, ..) => {
1378 if defaultness.is_default() {
1379 is_default_impl_trait = tcx.impl_trait_ref(def_id);
1383 ItemFn(.., ref generics, _) |
1384 ItemTy(_, ref generics) |
1385 ItemEnum(_, ref generics) |
1386 ItemStruct(_, ref generics) |
1387 ItemUnion(_, ref generics) => generics,
1389 ItemTrait(_, _, ref generics, .., ref items) => {
1390 is_trait = Some((ty::TraitRef {
1392 substs: Substs::identity_for_item(tcx, def_id)
1401 NodeForeignItem(item) => {
1403 ForeignItemStatic(..) => &no_generics,
1404 ForeignItemFn(_, _, ref generics) => generics,
1405 ForeignItemType => &no_generics,
1409 NodeTy(&Ty { node: TyImplTraitExistential(ref exist_ty, _), span, .. }) => {
1410 let substs = Substs::identity_for_item(tcx, def_id);
1411 let anon_ty = tcx.mk_anon(def_id, substs);
1413 debug!("explicit_predicates_of: anon_ty={:?}", anon_ty);
1415 // Collect the bounds, i.e. the `A+B+'c` in `impl A+B+'c`.
1416 let bounds = compute_bounds(&icx,
1419 SizedByDefault::Yes,
1422 debug!("explicit_predicates_of: bounds={:?}", bounds);
1424 let predicates = bounds.predicates(tcx, anon_ty);
1426 debug!("explicit_predicates_of: predicates={:?}", predicates);
1428 return ty::GenericPredicates {
1430 predicates: predicates
1437 let generics = tcx.generics_of(def_id);
1438 let parent_count = generics.parent_count() as u32;
1439 let has_own_self = generics.has_self && parent_count == 0;
1441 let mut predicates = vec![];
1443 // Below we'll consider the bounds on the type parameters (including `Self`)
1444 // and the explicit where-clauses, but to get the full set of predicates
1445 // on a trait we need to add in the supertrait bounds and bounds found on
1446 // associated types.
1447 if let Some((trait_ref, _)) = is_trait {
1448 predicates = tcx.super_predicates_of(def_id).predicates;
1450 // Add in a predicate that `Self:Trait` (where `Trait` is the
1451 // current trait). This is needed for builtin bounds.
1452 predicates.push(trait_ref.to_poly_trait_ref().to_predicate());
1455 // In default impls, we can assume that the self type implements
1456 // the trait. So in:
1458 // default impl Foo for Bar { .. }
1460 // we add a default where clause `Foo: Bar`. We do a similar thing for traits
1461 // (see below). Recall that a default impl is not itself an impl, but rather a
1462 // set of defaults that can be incorporated into another impl.
1463 if let Some(trait_ref) = is_default_impl_trait {
1464 predicates.push(trait_ref.to_poly_trait_ref().to_predicate());
1467 // Collect the region predicates that were declared inline as
1468 // well. In the case of parameters declared on a fn or method, we
1469 // have to be careful to only iterate over early-bound regions.
1470 let mut index = parent_count + has_own_self as u32;
1471 for param in early_bound_lifetimes_from_generics(tcx, ast_generics) {
1472 let region = tcx.mk_region(ty::ReEarlyBound(ty::EarlyBoundRegion {
1473 def_id: tcx.hir.local_def_id(param.lifetime.id),
1475 name: param.lifetime.name.name(),
1479 for bound in ¶m.bounds {
1480 let bound_region = AstConv::ast_region_to_region(&icx, bound, None);
1481 let outlives = ty::Binder(ty::OutlivesPredicate(region, bound_region));
1482 predicates.push(outlives.to_predicate());
1486 // Collect the predicates that were written inline by the user on each
1487 // type parameter (e.g., `<T:Foo>`).
1488 for param in ast_generics.ty_params() {
1489 let param_ty = ty::ParamTy::new(index, param.name).to_ty(tcx);
1492 let bounds = compute_bounds(&icx,
1495 SizedByDefault::Yes,
1497 predicates.extend(bounds.predicates(tcx, param_ty));
1500 // Add in the bounds that appear in the where-clause
1501 let where_clause = &ast_generics.where_clause;
1502 for predicate in &where_clause.predicates {
1504 &hir::WherePredicate::BoundPredicate(ref bound_pred) => {
1505 let ty = icx.to_ty(&bound_pred.bounded_ty);
1507 for bound in bound_pred.bounds.iter() {
1509 &hir::TyParamBound::TraitTyParamBound(ref poly_trait_ref, _) => {
1510 let mut projections = Vec::new();
1513 AstConv::instantiate_poly_trait_ref(&icx,
1518 predicates.push(trait_ref.to_predicate());
1520 for projection in &projections {
1521 predicates.push(projection.to_predicate());
1525 &hir::TyParamBound::RegionTyParamBound(ref lifetime) => {
1526 let region = AstConv::ast_region_to_region(&icx,
1529 let pred = ty::Binder(ty::OutlivesPredicate(ty, region));
1530 predicates.push(ty::Predicate::TypeOutlives(pred))
1536 &hir::WherePredicate::RegionPredicate(ref region_pred) => {
1537 let r1 = AstConv::ast_region_to_region(&icx, ®ion_pred.lifetime, None);
1538 for bound in ®ion_pred.bounds {
1539 let r2 = AstConv::ast_region_to_region(&icx, bound, None);
1540 let pred = ty::Binder(ty::OutlivesPredicate(r1, r2));
1541 predicates.push(ty::Predicate::RegionOutlives(pred))
1545 &hir::WherePredicate::EqPredicate(..) => {
1551 // Add predicates from associated type bounds.
1552 if let Some((self_trait_ref, trait_items)) = is_trait {
1553 predicates.extend(trait_items.iter().flat_map(|trait_item_ref| {
1554 let trait_item = tcx.hir.trait_item(trait_item_ref.id);
1555 let bounds = match trait_item.node {
1556 hir::TraitItemKind::Type(ref bounds, _) => bounds,
1558 return vec![].into_iter();
1562 let assoc_ty = tcx.mk_projection(
1563 tcx.hir.local_def_id(trait_item.id),
1564 self_trait_ref.substs,
1567 let bounds = compute_bounds(&ItemCtxt::new(tcx, def_id),
1570 SizedByDefault::Yes,
1573 bounds.predicates(tcx, assoc_ty).into_iter()
1577 // Subtle: before we store the predicates into the tcx, we
1578 // sort them so that predicates like `T: Foo<Item=U>` come
1579 // before uses of `U`. This avoids false ambiguity errors
1580 // in trait checking. See `setup_constraining_predicates`
1582 if let NodeItem(&Item { node: ItemImpl(..), .. }) = node {
1583 let self_ty = tcx.type_of(def_id);
1584 let trait_ref = tcx.impl_trait_ref(def_id);
1585 ctp::setup_constraining_predicates(tcx,
1588 &mut ctp::parameters_for_impl(self_ty, trait_ref));
1591 ty::GenericPredicates {
1592 parent: generics.parent,
1597 pub enum SizedByDefault { Yes, No, }
1599 /// Translate the AST's notion of ty param bounds (which are an enum consisting of a newtyped Ty or
1600 /// a region) to ty's notion of ty param bounds, which can either be user-defined traits, or the
1601 /// built-in trait (formerly known as kind): Send.
1602 pub fn compute_bounds<'gcx: 'tcx, 'tcx>(astconv: &AstConv<'gcx, 'tcx>,
1604 ast_bounds: &[hir::TyParamBound],
1605 sized_by_default: SizedByDefault,
1609 let mut region_bounds = vec![];
1610 let mut trait_bounds = vec![];
1611 for ast_bound in ast_bounds {
1613 hir::TraitTyParamBound(ref b, hir::TraitBoundModifier::None) => {
1614 trait_bounds.push(b);
1616 hir::TraitTyParamBound(_, hir::TraitBoundModifier::Maybe) => {}
1617 hir::RegionTyParamBound(ref l) => {
1618 region_bounds.push(l);
1623 let mut projection_bounds = vec![];
1625 let mut trait_bounds: Vec<_> = trait_bounds.iter().map(|&bound| {
1626 astconv.instantiate_poly_trait_ref(bound,
1628 &mut projection_bounds)
1631 let region_bounds = region_bounds.into_iter().map(|r| {
1632 astconv.ast_region_to_region(r, None)
1635 trait_bounds.sort_by(|a,b| a.def_id().cmp(&b.def_id()));
1637 let implicitly_sized = if let SizedByDefault::Yes = sized_by_default {
1638 !is_unsized(astconv, ast_bounds, span)
1651 /// Converts a specific TyParamBound from the AST into a set of
1652 /// predicates that apply to the self-type. A vector is returned
1653 /// because this can be anywhere from 0 predicates (`T:?Sized` adds no
1654 /// predicates) to 1 (`T:Foo`) to many (`T:Bar<X=i32>` adds `T:Bar`
1655 /// and `<T as Bar>::X == i32`).
1656 fn predicates_from_bound<'tcx>(astconv: &AstConv<'tcx, 'tcx>,
1658 bound: &hir::TyParamBound)
1659 -> Vec<ty::Predicate<'tcx>>
1662 hir::TraitTyParamBound(ref tr, hir::TraitBoundModifier::None) => {
1663 let mut projections = Vec::new();
1664 let pred = astconv.instantiate_poly_trait_ref(tr,
1667 projections.into_iter()
1668 .map(|p| p.to_predicate())
1669 .chain(Some(pred.to_predicate()))
1672 hir::RegionTyParamBound(ref lifetime) => {
1673 let region = astconv.ast_region_to_region(lifetime, None);
1674 let pred = ty::Binder(ty::OutlivesPredicate(param_ty, region));
1675 vec![ty::Predicate::TypeOutlives(pred)]
1677 hir::TraitTyParamBound(_, hir::TraitBoundModifier::Maybe) => {
1683 fn compute_sig_of_foreign_fn_decl<'a, 'tcx>(
1684 tcx: TyCtxt<'a, 'tcx, 'tcx>,
1688 -> ty::PolyFnSig<'tcx>
1690 let fty = AstConv::ty_of_fn(&ItemCtxt::new(tcx, def_id), hir::Unsafety::Unsafe, abi, decl);
1692 // feature gate SIMD types in FFI, since I (huonw) am not sure the
1693 // ABIs are handled at all correctly.
1694 if abi != abi::Abi::RustIntrinsic && abi != abi::Abi::PlatformIntrinsic
1695 && !tcx.features().simd_ffi {
1696 let check = |ast_ty: &hir::Ty, ty: Ty| {
1698 tcx.sess.struct_span_err(ast_ty.span,
1699 &format!("use of SIMD type `{}` in FFI is highly experimental and \
1700 may result in invalid code",
1701 tcx.hir.node_to_pretty_string(ast_ty.id)))
1702 .help("add #![feature(simd_ffi)] to the crate attributes to enable")
1706 for (input, ty) in decl.inputs.iter().zip(*fty.inputs().skip_binder()) {
1709 if let hir::Return(ref ty) = decl.output {
1710 check(&ty, *fty.output().skip_binder())
1717 fn is_foreign_item<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
1720 match tcx.hir.get_if_local(def_id) {
1721 Some(hir_map::NodeForeignItem(..)) => true,
1723 _ => bug!("is_foreign_item applied to non-local def-id {:?}", def_id)