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::resolve_lifetime as rl;
32 use rustc::mir::mono::Linkage;
33 use rustc::ty::subst::Substs;
34 use rustc::ty::{ToPredicate, ReprOptions};
35 use rustc::ty::{self, AdtKind, ToPolyTraitRef, Ty, TyCtxt};
36 use rustc::ty::query::Providers;
37 use rustc::ty::util::IntTypeExt;
38 use rustc::ty::util::Discr;
39 use rustc::util::captures::Captures;
40 use rustc::util::nodemap::FxHashMap;
41 use rustc_target::spec::abi;
44 use syntax::ast::MetaItemKind;
45 use syntax::attr::{InlineAttr, list_contains_name, mark_used};
46 use syntax::codemap::Spanned;
47 use syntax::symbol::{Symbol, keywords};
48 use syntax::feature_gate;
49 use syntax_pos::{Span, DUMMY_SP};
51 use rustc::hir::{self, map as hir_map, CodegenFnAttrs, CodegenFnAttrFlags, Unsafety};
52 use rustc::hir::GenericParamKind;
53 use rustc::hir::intravisit::{self, Visitor, NestedVisitorMap};
54 use rustc::hir::def::{Def, CtorKind};
55 use rustc::hir::def_id::{DefId, LOCAL_CRATE};
57 ///////////////////////////////////////////////////////////////////////////
60 pub fn collect_item_types<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>) {
61 let mut visitor = CollectItemTypesVisitor { tcx: tcx };
62 tcx.hir.krate().visit_all_item_likes(&mut visitor.as_deep_visitor());
65 pub fn provide(providers: &mut Providers) {
66 *providers = Providers {
70 predicates_defined_on,
71 explicit_predicates_of,
73 type_param_predicates,
85 ///////////////////////////////////////////////////////////////////////////
87 /// Context specific to some particular item. This is what implements
88 /// AstConv. It has information about the predicates that are defined
89 /// on the trait. Unfortunately, this predicate information is
90 /// available in various different forms at various points in the
91 /// process. So we can't just store a pointer to e.g. the AST or the
92 /// parsed ty form, we have to be more flexible. To this end, the
93 /// `ItemCtxt` is parameterized by a `DefId` that it uses to satisfy
94 /// `get_type_parameter_bounds` requests, drawing the information from
95 /// the AST (`hir::Generics`), recursively.
96 pub struct ItemCtxt<'a,'tcx:'a> {
97 tcx: TyCtxt<'a, 'tcx, 'tcx>,
101 ///////////////////////////////////////////////////////////////////////////
103 struct CollectItemTypesVisitor<'a, 'tcx: 'a> {
104 tcx: TyCtxt<'a, 'tcx, 'tcx>
107 impl<'a, 'tcx> Visitor<'tcx> for CollectItemTypesVisitor<'a, 'tcx> {
108 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
109 NestedVisitorMap::OnlyBodies(&self.tcx.hir)
112 fn visit_item(&mut self, item: &'tcx hir::Item) {
113 convert_item(self.tcx, item.id);
114 intravisit::walk_item(self, item);
117 fn visit_generics(&mut self, generics: &'tcx hir::Generics) {
118 for param in &generics.params {
120 hir::GenericParamKind::Lifetime { .. } => {}
121 hir::GenericParamKind::Type { default: Some(_), .. } => {
122 let def_id = self.tcx.hir.local_def_id(param.id);
123 self.tcx.type_of(def_id);
125 hir::GenericParamKind::Type { .. } => {}
128 intravisit::walk_generics(self, generics);
131 fn visit_expr(&mut self, expr: &'tcx hir::Expr) {
132 if let hir::ExprKind::Closure(..) = expr.node {
133 let def_id = self.tcx.hir.local_def_id(expr.id);
134 self.tcx.generics_of(def_id);
135 self.tcx.type_of(def_id);
137 intravisit::walk_expr(self, expr);
140 fn visit_trait_item(&mut self, trait_item: &'tcx hir::TraitItem) {
141 convert_trait_item(self.tcx, trait_item.id);
142 intravisit::walk_trait_item(self, trait_item);
145 fn visit_impl_item(&mut self, impl_item: &'tcx hir::ImplItem) {
146 convert_impl_item(self.tcx, impl_item.id);
147 intravisit::walk_impl_item(self, impl_item);
151 ///////////////////////////////////////////////////////////////////////////
152 // Utility types and common code for the above passes.
154 impl<'a, 'tcx> ItemCtxt<'a, 'tcx> {
155 pub fn new(tcx: TyCtxt<'a, 'tcx, 'tcx>, item_def_id: DefId)
156 -> ItemCtxt<'a,'tcx> {
164 impl<'a,'tcx> ItemCtxt<'a,'tcx> {
165 pub fn to_ty(&self, ast_ty: &hir::Ty) -> Ty<'tcx> {
166 AstConv::ast_ty_to_ty(self, ast_ty)
170 impl<'a, 'tcx> AstConv<'tcx, 'tcx> for ItemCtxt<'a, 'tcx> {
171 fn tcx<'b>(&'b self) -> TyCtxt<'b, 'tcx, 'tcx> { self.tcx }
173 fn get_type_parameter_bounds(&self,
176 -> ty::GenericPredicates<'tcx>
178 self.tcx.at(span).type_param_predicates((self.item_def_id, def_id))
181 fn re_infer(&self, _span: Span, _def: Option<&ty::GenericParamDef>)
182 -> Option<ty::Region<'tcx>> {
186 fn ty_infer(&self, span: Span) -> Ty<'tcx> {
191 "the type placeholder `_` is not allowed within types on item signatures"
192 ).span_label(span, "not allowed in type signatures")
197 fn projected_ty_from_poly_trait_ref(&self,
200 poly_trait_ref: ty::PolyTraitRef<'tcx>)
203 if let Some(trait_ref) = poly_trait_ref.no_late_bound_regions() {
204 self.tcx().mk_projection(item_def_id, trait_ref.substs)
206 // no late-bound regions, we can just ignore the binder
207 span_err!(self.tcx().sess, span, E0212,
208 "cannot extract an associated type from a higher-ranked trait bound \
214 fn normalize_ty(&self, _span: Span, ty: Ty<'tcx>) -> Ty<'tcx> {
215 // types in item signatures are not normalized, to avoid undue
220 fn set_tainted_by_errors(&self) {
221 // no obvious place to track this, just let it go
224 fn record_ty(&self, _hir_id: hir::HirId, _ty: Ty<'tcx>, _span: Span) {
225 // no place to record types from signatures?
229 fn type_param_predicates<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
230 (item_def_id, def_id): (DefId, DefId))
231 -> ty::GenericPredicates<'tcx> {
232 use rustc::hir::map::*;
235 // In the AST, bounds can derive from two places. Either
236 // written inline like `<T:Foo>` or in a where clause like
239 let param_id = tcx.hir.as_local_node_id(def_id).unwrap();
240 let param_owner = tcx.hir.ty_param_owner(param_id);
241 let param_owner_def_id = tcx.hir.local_def_id(param_owner);
242 let generics = tcx.generics_of(param_owner_def_id);
243 let index = generics.param_def_id_to_index[&def_id];
244 let ty = tcx.mk_ty_param(index, tcx.hir.ty_param_name(param_id).as_interned_str());
246 // Don't look for bounds where the type parameter isn't in scope.
247 let parent = if item_def_id == param_owner_def_id {
250 tcx.generics_of(item_def_id).parent
253 let mut result = parent.map_or(ty::GenericPredicates {
257 let icx = ItemCtxt::new(tcx, parent);
258 icx.get_type_parameter_bounds(DUMMY_SP, def_id)
261 let item_node_id = tcx.hir.as_local_node_id(item_def_id).unwrap();
262 let ast_generics = match tcx.hir.get(item_node_id) {
263 NodeTraitItem(item) => &item.generics,
265 NodeImplItem(item) => &item.generics,
269 ItemKind::Fn(.., ref generics, _) |
270 ItemKind::Impl(_, _, _, ref generics, ..) |
271 ItemKind::Ty(_, ref generics) |
272 ItemKind::Existential(ExistTy { ref generics, impl_trait_fn: None, ..}) |
273 ItemKind::Enum(_, ref generics) |
274 ItemKind::Struct(_, ref generics) |
275 ItemKind::Union(_, ref generics) => generics,
276 ItemKind::Trait(_, _, ref generics, ..) => {
277 // Implied `Self: Trait` and supertrait bounds.
278 if param_id == item_node_id {
279 result.predicates.push(
280 ty::TraitRef::identity(tcx, item_def_id).to_predicate()
289 NodeForeignItem(item) => {
291 ForeignItemKind::Fn(_, _, ref generics) => generics,
299 let icx = ItemCtxt::new(tcx, item_def_id);
300 result.predicates.extend(
301 icx.type_parameter_bounds_in_generics(ast_generics, param_id, ty));
305 impl<'a, 'tcx> ItemCtxt<'a, 'tcx> {
306 /// Find bounds from hir::Generics. This requires scanning through the
307 /// AST. We do this to avoid having to convert *all* the bounds, which
308 /// would create artificial cycles. Instead we can only convert the
309 /// bounds for a type parameter `X` if `X::Foo` is used.
310 fn type_parameter_bounds_in_generics(&self,
311 ast_generics: &hir::Generics,
312 param_id: ast::NodeId,
314 -> Vec<ty::Predicate<'tcx>>
317 ast_generics.params.iter()
318 .filter_map(|param| match param.kind {
319 GenericParamKind::Type { .. } if param.id == param_id => Some(¶m.bounds),
322 .flat_map(|bounds| bounds.iter())
323 .flat_map(|b| predicates_from_bound(self, ty, b));
325 let from_where_clauses =
326 ast_generics.where_clause
329 .filter_map(|wp| match *wp {
330 hir::WherePredicate::BoundPredicate(ref bp) => Some(bp),
333 .filter(|bp| is_param(self.tcx, &bp.bounded_ty, param_id))
334 .flat_map(|bp| bp.bounds.iter())
335 .flat_map(|b| predicates_from_bound(self, ty, b));
337 from_ty_params.chain(from_where_clauses).collect()
341 /// Tests whether this is the AST for a reference to the type
342 /// parameter with id `param_id`. We use this so as to avoid running
343 /// `ast_ty_to_ty`, because we want to avoid triggering an all-out
344 /// conversion of the type to avoid inducing unnecessary cycles.
345 fn is_param<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
347 param_id: ast::NodeId)
350 if let hir::TyKind::Path(hir::QPath::Resolved(None, ref path)) = ast_ty.node {
352 Def::SelfTy(Some(def_id), None) |
353 Def::TyParam(def_id) => {
354 def_id == tcx.hir.local_def_id(param_id)
363 fn convert_item<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, item_id: ast::NodeId) {
364 let it = tcx.hir.expect_item(item_id);
365 debug!("convert: item {} with id {}", it.name, it.id);
366 let def_id = tcx.hir.local_def_id(item_id);
368 // These don't define types.
369 hir::ItemKind::ExternCrate(_) |
370 hir::ItemKind::Use(..) |
371 hir::ItemKind::Mod(_) |
372 hir::ItemKind::GlobalAsm(_) => {}
373 hir::ItemKind::ForeignMod(ref foreign_mod) => {
374 for item in &foreign_mod.items {
375 let def_id = tcx.hir.local_def_id(item.id);
376 tcx.generics_of(def_id);
378 tcx.predicates_of(def_id);
379 if let hir::ForeignItemKind::Fn(..) = item.node {
384 hir::ItemKind::Enum(ref enum_definition, _) => {
385 tcx.generics_of(def_id);
387 tcx.predicates_of(def_id);
388 convert_enum_variant_types(tcx, def_id, &enum_definition.variants);
390 hir::ItemKind::Impl(..) => {
391 tcx.generics_of(def_id);
393 tcx.impl_trait_ref(def_id);
394 tcx.predicates_of(def_id);
396 hir::ItemKind::Trait(..) => {
397 tcx.generics_of(def_id);
398 tcx.trait_def(def_id);
399 tcx.at(it.span).super_predicates_of(def_id);
400 tcx.predicates_of(def_id);
402 hir::ItemKind::TraitAlias(..) => {
403 span_err!(tcx.sess, it.span, E0645,
404 "trait aliases are not yet implemented (see issue #41517)");
406 hir::ItemKind::Struct(ref struct_def, _) |
407 hir::ItemKind::Union(ref struct_def, _) => {
408 tcx.generics_of(def_id);
410 tcx.predicates_of(def_id);
412 for f in struct_def.fields() {
413 let def_id = tcx.hir.local_def_id(f.id);
414 tcx.generics_of(def_id);
416 tcx.predicates_of(def_id);
419 if !struct_def.is_struct() {
420 convert_variant_ctor(tcx, struct_def.id());
424 // Desugared from `impl Trait` -> visited by the function's return type
425 hir::ItemKind::Existential(hir::ExistTy { impl_trait_fn: Some(_), .. }) => {}
427 hir::ItemKind::Existential(..) |
428 hir::ItemKind::Ty(..) |
429 hir::ItemKind::Static(..) |
430 hir::ItemKind::Const(..) |
431 hir::ItemKind::Fn(..) => {
432 tcx.generics_of(def_id);
434 tcx.predicates_of(def_id);
435 if let hir::ItemKind::Fn(..) = it.node {
442 fn convert_trait_item<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, trait_item_id: ast::NodeId) {
443 let trait_item = tcx.hir.expect_trait_item(trait_item_id);
444 let def_id = tcx.hir.local_def_id(trait_item.id);
445 tcx.generics_of(def_id);
447 match trait_item.node {
448 hir::TraitItemKind::Const(..) |
449 hir::TraitItemKind::Type(_, Some(_)) |
450 hir::TraitItemKind::Method(..) => {
452 if let hir::TraitItemKind::Method(..) = trait_item.node {
457 hir::TraitItemKind::Type(_, None) => {}
460 tcx.predicates_of(def_id);
463 fn convert_impl_item<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, impl_item_id: ast::NodeId) {
464 let def_id = tcx.hir.local_def_id(impl_item_id);
465 tcx.generics_of(def_id);
467 tcx.predicates_of(def_id);
468 if let hir::ImplItemKind::Method(..) = tcx.hir.expect_impl_item(impl_item_id).node {
473 fn convert_variant_ctor<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
474 ctor_id: ast::NodeId) {
475 let def_id = tcx.hir.local_def_id(ctor_id);
476 tcx.generics_of(def_id);
478 tcx.predicates_of(def_id);
481 fn convert_enum_variant_types<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
483 variants: &[hir::Variant]) {
484 let def = tcx.adt_def(def_id);
485 let repr_type = def.repr.discr_type();
486 let initial = repr_type.initial_discriminant(tcx);
487 let mut prev_discr = None::<Discr<'tcx>>;
489 // fill the discriminant values and field types
490 for variant in variants {
491 let wrapped_discr = prev_discr.map_or(initial, |d| d.wrap_incr(tcx));
492 prev_discr = Some(if let Some(ref e) = variant.node.disr_expr {
493 let expr_did = tcx.hir.local_def_id(e.id);
494 def.eval_explicit_discr(tcx, expr_did)
495 } else if let Some(discr) = repr_type.disr_incr(tcx, prev_discr) {
498 struct_span_err!(tcx.sess, variant.span, E0370,
499 "enum discriminant overflowed")
500 .span_label(variant.span, format!("overflowed on value after {}",
501 prev_discr.unwrap()))
502 .note(&format!("explicitly set `{} = {}` if that is desired outcome",
503 variant.node.name, wrapped_discr))
506 }.unwrap_or(wrapped_discr));
508 for f in variant.node.data.fields() {
509 let def_id = tcx.hir.local_def_id(f.id);
510 tcx.generics_of(def_id);
512 tcx.predicates_of(def_id);
515 // Convert the ctor, if any. This also registers the variant as
517 convert_variant_ctor(tcx, variant.node.data.id());
521 fn convert_struct_variant<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
524 discr: ty::VariantDiscr,
525 def: &hir::VariantData)
527 let mut seen_fields: FxHashMap<ast::Ident, Span> = FxHashMap();
528 let node_id = tcx.hir.as_local_node_id(did).unwrap();
529 let fields = def.fields().iter().map(|f| {
530 let fid = tcx.hir.local_def_id(f.id);
531 let dup_span = seen_fields.get(&f.ident.modern()).cloned();
532 if let Some(prev_span) = dup_span {
533 struct_span_err!(tcx.sess, f.span, E0124,
534 "field `{}` is already declared",
536 .span_label(f.span, "field already declared")
537 .span_label(prev_span, format!("`{}` first declared here", f.ident))
540 seen_fields.insert(f.ident.modern(), f.span);
546 vis: ty::Visibility::from_hir(&f.vis, node_id, tcx)
554 ctor_kind: CtorKind::from_hir(def),
558 fn adt_def<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
560 -> &'tcx ty::AdtDef {
561 use rustc::hir::map::*;
564 let node_id = tcx.hir.as_local_node_id(def_id).unwrap();
565 let item = match tcx.hir.get(node_id) {
566 NodeItem(item) => item,
570 let repr = ReprOptions::new(tcx, def_id);
571 let (kind, variants) = match item.node {
572 ItemKind::Enum(ref def, _) => {
573 let mut distance_from_explicit = 0;
574 (AdtKind::Enum, def.variants.iter().map(|v| {
575 let did = tcx.hir.local_def_id(v.node.data.id());
576 let discr = if let Some(ref e) = v.node.disr_expr {
577 distance_from_explicit = 0;
578 ty::VariantDiscr::Explicit(tcx.hir.local_def_id(e.id))
580 ty::VariantDiscr::Relative(distance_from_explicit)
582 distance_from_explicit += 1;
584 convert_struct_variant(tcx, did, v.node.name, discr, &v.node.data)
587 ItemKind::Struct(ref def, _) => {
588 // Use separate constructor id for unit/tuple structs and reuse did for braced structs.
589 let ctor_id = if !def.is_struct() {
590 Some(tcx.hir.local_def_id(def.id()))
594 (AdtKind::Struct, vec![
595 convert_struct_variant(tcx, ctor_id.unwrap_or(def_id), item.name,
596 ty::VariantDiscr::Relative(0), def)
599 ItemKind::Union(ref def, _) => {
600 (AdtKind::Union, vec![
601 convert_struct_variant(tcx, def_id, item.name,
602 ty::VariantDiscr::Relative(0), def)
607 tcx.alloc_adt_def(def_id, kind, variants, repr)
610 /// Ensures that the super-predicates of the trait with def-id
611 /// trait_def_id are converted and stored. This also ensures that
612 /// the transitive super-predicates are converted;
613 fn super_predicates_of<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
615 -> ty::GenericPredicates<'tcx> {
616 debug!("super_predicates(trait_def_id={:?})", trait_def_id);
617 let trait_node_id = tcx.hir.as_local_node_id(trait_def_id).unwrap();
619 let item = match tcx.hir.get(trait_node_id) {
620 hir_map::NodeItem(item) => item,
621 _ => bug!("trait_node_id {} is not an item", trait_node_id)
624 let (generics, bounds) = match item.node {
625 hir::ItemKind::Trait(.., ref generics, ref supertraits, _) => (generics, supertraits),
626 hir::ItemKind::TraitAlias(ref generics, ref supertraits) => (generics, supertraits),
627 _ => span_bug!(item.span,
628 "super_predicates invoked on non-trait"),
631 let icx = ItemCtxt::new(tcx, trait_def_id);
633 // Convert the bounds that follow the colon, e.g. `Bar+Zed` in `trait Foo : Bar+Zed`.
634 let self_param_ty = tcx.mk_self_type();
635 let superbounds1 = compute_bounds(&icx,
641 let superbounds1 = superbounds1.predicates(tcx, self_param_ty);
643 // Convert any explicit superbounds in the where clause,
644 // e.g. `trait Foo where Self : Bar`:
645 let superbounds2 = icx.type_parameter_bounds_in_generics(generics, item.id, self_param_ty);
647 // Combine the two lists to form the complete set of superbounds:
648 let superbounds: Vec<_> = superbounds1.into_iter().chain(superbounds2).collect();
650 // Now require that immediate supertraits are converted,
651 // which will, in turn, reach indirect supertraits.
652 for bound in superbounds.iter().filter_map(|p| p.to_opt_poly_trait_ref()) {
653 tcx.at(item.span).super_predicates_of(bound.def_id());
656 ty::GenericPredicates {
658 predicates: superbounds
662 fn trait_def<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
664 -> &'tcx ty::TraitDef {
665 let node_id = tcx.hir.as_local_node_id(def_id).unwrap();
666 let item = tcx.hir.expect_item(node_id);
668 let (is_auto, unsafety) = match item.node {
669 hir::ItemKind::Trait(is_auto, unsafety, ..) => (is_auto == hir::IsAuto::Yes, unsafety),
670 hir::ItemKind::TraitAlias(..) => (false, hir::Unsafety::Normal),
671 _ => span_bug!(item.span, "trait_def_of_item invoked on non-trait"),
674 let paren_sugar = tcx.has_attr(def_id, "rustc_paren_sugar");
675 if paren_sugar && !tcx.features().unboxed_closures {
676 let mut err = tcx.sess.struct_span_err(
678 "the `#[rustc_paren_sugar]` attribute is a temporary means of controlling \
679 which traits can use parenthetical notation");
681 "add `#![feature(unboxed_closures)]` to \
682 the crate attributes to use it");
686 let def_path_hash = tcx.def_path_hash(def_id);
687 let def = ty::TraitDef::new(def_id,
692 tcx.alloc_trait_def(def)
695 fn has_late_bound_regions<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
696 node: hir_map::Node<'tcx>)
698 struct LateBoundRegionsDetector<'a, 'tcx: 'a> {
699 tcx: TyCtxt<'a, 'tcx, 'tcx>,
700 outer_index: ty::DebruijnIndex,
701 has_late_bound_regions: Option<Span>,
704 impl<'a, 'tcx> Visitor<'tcx> for LateBoundRegionsDetector<'a, 'tcx> {
705 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
706 NestedVisitorMap::None
709 fn visit_ty(&mut self, ty: &'tcx hir::Ty) {
710 if self.has_late_bound_regions.is_some() { return }
712 hir::TyKind::BareFn(..) => {
713 self.outer_index.shift_in(1);
714 intravisit::walk_ty(self, ty);
715 self.outer_index.shift_out(1);
717 _ => intravisit::walk_ty(self, ty)
721 fn visit_poly_trait_ref(&mut self,
722 tr: &'tcx hir::PolyTraitRef,
723 m: hir::TraitBoundModifier) {
724 if self.has_late_bound_regions.is_some() { return }
725 self.outer_index.shift_in(1);
726 intravisit::walk_poly_trait_ref(self, tr, m);
727 self.outer_index.shift_out(1);
730 fn visit_lifetime(&mut self, lt: &'tcx hir::Lifetime) {
731 if self.has_late_bound_regions.is_some() { return }
733 let hir_id = self.tcx.hir.node_to_hir_id(lt.id);
734 match self.tcx.named_region(hir_id) {
735 Some(rl::Region::Static) | Some(rl::Region::EarlyBound(..)) => {}
736 Some(rl::Region::LateBound(debruijn, _, _)) |
737 Some(rl::Region::LateBoundAnon(debruijn, _))
738 if debruijn < self.outer_index => {}
739 Some(rl::Region::LateBound(..)) |
740 Some(rl::Region::LateBoundAnon(..)) |
741 Some(rl::Region::Free(..)) |
743 self.has_late_bound_regions = Some(lt.span);
749 fn has_late_bound_regions<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
750 generics: &'tcx hir::Generics,
751 decl: &'tcx hir::FnDecl)
753 let mut visitor = LateBoundRegionsDetector {
755 outer_index: ty::INNERMOST,
756 has_late_bound_regions: None,
758 for param in &generics.params {
760 GenericParamKind::Lifetime { .. } => {
761 let hir_id = tcx.hir.node_to_hir_id(param.id);
762 if tcx.is_late_bound(hir_id) {
763 return Some(param.span);
769 visitor.visit_fn_decl(decl);
770 visitor.has_late_bound_regions
774 hir_map::NodeTraitItem(item) => match item.node {
775 hir::TraitItemKind::Method(ref sig, _) =>
776 has_late_bound_regions(tcx, &item.generics, &sig.decl),
779 hir_map::NodeImplItem(item) => match item.node {
780 hir::ImplItemKind::Method(ref sig, _) =>
781 has_late_bound_regions(tcx, &item.generics, &sig.decl),
784 hir_map::NodeForeignItem(item) => match item.node {
785 hir::ForeignItemKind::Fn(ref fn_decl, _, ref generics) =>
786 has_late_bound_regions(tcx, generics, fn_decl),
789 hir_map::NodeItem(item) => match item.node {
790 hir::ItemKind::Fn(ref fn_decl, .., ref generics, _) =>
791 has_late_bound_regions(tcx, generics, fn_decl),
798 fn generics_of<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
800 -> &'tcx ty::Generics {
801 use rustc::hir::map::*;
804 let node_id = tcx.hir.as_local_node_id(def_id).unwrap();
806 let node = tcx.hir.get(node_id);
807 let parent_def_id = match node {
813 let parent_id = tcx.hir.get_parent(node_id);
814 Some(tcx.hir.local_def_id(parent_id))
816 NodeExpr(&hir::Expr { node: hir::ExprKind::Closure(..), .. }) => {
817 Some(tcx.closure_base_def_id(def_id))
821 ItemKind::Existential(hir::ExistTy { impl_trait_fn, .. }) => impl_trait_fn,
828 let mut opt_self = None;
829 let mut allow_defaults = false;
831 let no_generics = hir::Generics::empty();
832 let ast_generics = match node {
833 NodeTraitItem(item) => &item.generics,
835 NodeImplItem(item) => &item.generics,
839 ItemKind::Fn(.., ref generics, _) |
840 ItemKind::Impl(_, _, _, ref generics, ..) => generics,
842 ItemKind::Ty(_, ref generics) |
843 ItemKind::Enum(_, ref generics) |
844 ItemKind::Struct(_, ref generics) |
845 ItemKind::Existential(hir::ExistTy { ref generics, .. }) |
846 ItemKind::Union(_, ref generics) => {
847 allow_defaults = true;
851 ItemKind::Trait(_, _, ref generics, ..) |
852 ItemKind::TraitAlias(ref generics, ..) => {
853 // Add in the self type parameter.
855 // Something of a hack: use the node id for the trait, also as
856 // the node id for the Self type parameter.
857 let param_id = item.id;
859 opt_self = Some(ty::GenericParamDef {
861 name: keywords::SelfType.name().as_interned_str(),
862 def_id: tcx.hir.local_def_id(param_id),
863 pure_wrt_drop: false,
864 kind: ty::GenericParamDefKind::Type {
866 object_lifetime_default: rl::Set1::Empty,
871 allow_defaults = true;
879 NodeForeignItem(item) => {
881 ForeignItemKind::Static(..) => &no_generics,
882 ForeignItemKind::Fn(_, _, ref generics) => generics,
883 ForeignItemKind::Type => &no_generics,
890 let has_self = opt_self.is_some();
891 let mut parent_has_self = false;
892 let mut own_start = has_self as u32;
893 let parent_count = parent_def_id.map_or(0, |def_id| {
894 let generics = tcx.generics_of(def_id);
895 assert_eq!(has_self, false);
896 parent_has_self = generics.has_self;
897 own_start = generics.count() as u32;
898 generics.parent_count + generics.params.len()
901 let mut params: Vec<_> = opt_self.into_iter().collect();
903 let early_lifetimes = early_bound_lifetimes_from_generics(tcx, ast_generics);
904 params.extend(early_lifetimes.enumerate().map(|(i, param)| {
905 ty::GenericParamDef {
906 name: param.name.ident().as_interned_str(),
907 index: own_start + i as u32,
908 def_id: tcx.hir.local_def_id(param.id),
909 pure_wrt_drop: param.pure_wrt_drop,
910 kind: ty::GenericParamDefKind::Lifetime,
914 let hir_id = tcx.hir.node_to_hir_id(node_id);
915 let object_lifetime_defaults = tcx.object_lifetime_defaults(hir_id);
917 // Now create the real type parameters.
918 let type_start = own_start - has_self as u32 + params.len() as u32;
920 params.extend(ast_generics.params.iter().filter_map(|param| match param.kind {
921 GenericParamKind::Type { ref default, synthetic, .. } => {
922 if param.name.ident().name == keywords::SelfType.name() {
923 span_bug!(param.span, "`Self` should not be the name of a regular parameter");
926 if !allow_defaults && default.is_some() {
927 if !tcx.features().default_type_parameter_fallback {
929 lint::builtin::INVALID_TYPE_PARAM_DEFAULT,
932 &format!("defaults for type parameters are only allowed in \
933 `struct`, `enum`, `type`, or `trait` definitions."));
937 let ty_param = ty::GenericParamDef {
938 index: type_start + i as u32,
939 name: param.name.ident().as_interned_str(),
940 def_id: tcx.hir.local_def_id(param.id),
941 pure_wrt_drop: param.pure_wrt_drop,
942 kind: ty::GenericParamDefKind::Type {
943 has_default: default.is_some(),
944 object_lifetime_default:
945 object_lifetime_defaults.as_ref().map_or(rl::Set1::Empty, |o| o[i]),
955 // provide junk type parameter defs - the only place that
956 // cares about anything but the length is instantiation,
957 // and we don't do that for closures.
958 if let NodeExpr(&hir::Expr { node: hir::ExprKind::Closure(.., gen), .. }) = node {
959 let dummy_args = if gen.is_some() {
960 &["<yield_ty>", "<return_ty>", "<witness>"][..]
962 &["<closure_kind>", "<closure_signature>"][..]
966 dummy_args.iter().enumerate().map(|(i, &arg)|
967 ty::GenericParamDef {
968 index: type_start + i as u32,
969 name: Symbol::intern(arg).as_interned_str(),
971 pure_wrt_drop: false,
972 kind: ty::GenericParamDefKind::Type {
974 object_lifetime_default: rl::Set1::Empty,
981 tcx.with_freevars(node_id, |fv| {
982 params.extend(fv.iter().zip((dummy_args.len() as u32)..).map(|(_, i)| {
983 ty::GenericParamDef {
984 index: type_start + i,
985 name: Symbol::intern("<upvar>").as_interned_str(),
987 pure_wrt_drop: false,
988 kind: ty::GenericParamDefKind::Type {
990 object_lifetime_default: rl::Set1::Empty,
998 let param_def_id_to_index = params.iter()
999 .map(|param| (param.def_id, param.index))
1002 tcx.alloc_generics(ty::Generics {
1003 parent: parent_def_id,
1006 param_def_id_to_index,
1007 has_self: has_self || parent_has_self,
1008 has_late_bound_regions: has_late_bound_regions(tcx, node),
1012 fn report_assoc_ty_on_inherent_impl<'a, 'tcx>(
1013 tcx: TyCtxt<'a, 'tcx, 'tcx>,
1016 span_err!(tcx.sess, span, E0202, "associated types are not allowed in inherent impls");
1019 fn type_of<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
1022 use rustc::hir::map::*;
1025 let node_id = tcx.hir.as_local_node_id(def_id).unwrap();
1027 let icx = ItemCtxt::new(tcx, def_id);
1029 match tcx.hir.get(node_id) {
1030 NodeTraitItem(item) => {
1032 TraitItemKind::Method(..) => {
1033 let substs = Substs::identity_for_item(tcx, def_id);
1034 tcx.mk_fn_def(def_id, substs)
1036 TraitItemKind::Const(ref ty, _) |
1037 TraitItemKind::Type(_, Some(ref ty)) => icx.to_ty(ty),
1038 TraitItemKind::Type(_, None) => {
1039 span_bug!(item.span, "associated type missing default");
1044 NodeImplItem(item) => {
1046 ImplItemKind::Method(..) => {
1047 let substs = Substs::identity_for_item(tcx, def_id);
1048 tcx.mk_fn_def(def_id, substs)
1050 ImplItemKind::Const(ref ty, _) => icx.to_ty(ty),
1051 ImplItemKind::Existential(_) => {
1052 if tcx.impl_trait_ref(tcx.hir.get_parent_did(node_id)).is_none() {
1053 report_assoc_ty_on_inherent_impl(tcx, item.span);
1056 find_existential_constraints(tcx, def_id)
1058 ImplItemKind::Type(ref ty) => {
1059 if tcx.impl_trait_ref(tcx.hir.get_parent_did(node_id)).is_none() {
1060 report_assoc_ty_on_inherent_impl(tcx, item.span);
1070 ItemKind::Static(ref t, ..) | ItemKind::Const(ref t, _) |
1071 ItemKind::Ty(ref t, _) | ItemKind::Impl(.., ref t, _) => {
1074 ItemKind::Fn(..) => {
1075 let substs = Substs::identity_for_item(tcx, def_id);
1076 tcx.mk_fn_def(def_id, substs)
1078 ItemKind::Enum(..) |
1079 ItemKind::Struct(..) |
1080 ItemKind::Union(..) => {
1081 let def = tcx.adt_def(def_id);
1082 let substs = Substs::identity_for_item(tcx, def_id);
1083 tcx.mk_adt(def, substs)
1085 ItemKind::Existential(hir::ExistTy { impl_trait_fn: None, .. }) => {
1086 find_existential_constraints(tcx, def_id)
1088 // existential types desugared from impl Trait
1089 ItemKind::Existential(hir::ExistTy { impl_trait_fn: Some(owner), .. }) => {
1090 tcx.typeck_tables_of(owner).concrete_existential_types[&def_id]
1092 ItemKind::Trait(..) | ItemKind::TraitAlias(..) |
1094 ItemKind::ForeignMod(..) |
1095 ItemKind::GlobalAsm(..) |
1096 ItemKind::ExternCrate(..) |
1097 ItemKind::Use(..) => {
1100 "compute_type_of_item: unexpected item type: {:?}",
1106 NodeForeignItem(foreign_item) => {
1107 match foreign_item.node {
1108 ForeignItemKind::Fn(..) => {
1109 let substs = Substs::identity_for_item(tcx, def_id);
1110 tcx.mk_fn_def(def_id, substs)
1112 ForeignItemKind::Static(ref t, _) => icx.to_ty(t),
1113 ForeignItemKind::Type => tcx.mk_foreign(def_id),
1117 NodeStructCtor(&ref def) |
1118 NodeVariant(&Spanned { node: hir::VariantKind { data: ref def, .. }, .. }) => {
1120 VariantData::Unit(..) | VariantData::Struct(..) => {
1121 tcx.type_of(tcx.hir.get_parent_did(node_id))
1123 VariantData::Tuple(..) => {
1124 let substs = Substs::identity_for_item(tcx, def_id);
1125 tcx.mk_fn_def(def_id, substs)
1130 NodeField(field) => icx.to_ty(&field.ty),
1132 NodeExpr(&hir::Expr { node: hir::ExprKind::Closure(.., gen), .. }) => {
1134 let hir_id = tcx.hir.node_to_hir_id(node_id);
1135 return tcx.typeck_tables_of(def_id).node_id_to_type(hir_id);
1138 let substs = ty::ClosureSubsts {
1139 substs: Substs::identity_for_item(tcx, def_id),
1142 tcx.mk_closure(def_id, substs)
1145 NodeAnonConst(_) => match tcx.hir.get(tcx.hir.get_parent_node(node_id)) {
1146 NodeTy(&hir::Ty { node: hir::TyKind::Array(_, ref constant), .. }) |
1147 NodeTy(&hir::Ty { node: hir::TyKind::Typeof(ref constant), .. }) |
1148 NodeExpr(&hir::Expr { node: ExprKind::Repeat(_, ref constant), .. })
1149 if constant.id == node_id => tcx.types.usize,
1151 NodeVariant(&Spanned { node: VariantKind { disr_expr: Some(ref e), .. }, .. })
1152 if e.id == node_id => {
1153 tcx.adt_def(tcx.hir.get_parent_did(node_id))
1154 .repr.discr_type().to_ty(tcx)
1158 bug!("unexpected const parent in type_of_def_id(): {:?}", x);
1162 NodeGenericParam(param) => {
1164 hir::GenericParamKind::Type { default: Some(ref ty), .. } => {
1167 _ => bug!("unexpected non-type NodeGenericParam"),
1172 bug!("unexpected sort of node in type_of_def_id(): {:?}", x);
1177 fn find_existential_constraints<'a, 'tcx>(
1178 tcx: TyCtxt<'a, 'tcx, 'tcx>,
1181 use rustc::hir::map::*;
1184 struct ConstraintLocator<'a, 'tcx: 'a> {
1185 tcx: TyCtxt<'a, 'tcx, 'tcx>,
1187 found: Option<(Span, ty::Ty<'tcx>)>,
1189 impl<'a, 'tcx> ConstraintLocator<'a, 'tcx> {
1190 fn check(&mut self, def_id: DefId) {
1191 trace!("checking {:?}", def_id);
1192 // don't try to check items that cannot possibly constrain the type
1193 if !self.tcx.has_typeck_tables(def_id) {
1194 trace!("no typeck tables for {:?}", def_id);
1199 .typeck_tables_of(def_id)
1200 .concrete_existential_types
1203 if let Some(ty) = ty {
1204 // FIXME(oli-obk): trace the actual span from inference to improve errors
1205 let span = self.tcx.def_span(def_id);
1206 if let Some((prev_span, prev_ty)) = self.found {
1208 // found different concrete types for the existential type
1209 let mut err = self.tcx.sess.struct_span_err(
1211 "defining existential type use differs from previous",
1213 err.span_note(prev_span, "previous use here");
1217 self.found = Some((span, ty));
1222 impl<'a, 'tcx> intravisit::Visitor<'tcx> for ConstraintLocator<'a, 'tcx> {
1223 fn nested_visit_map<'this>(&'this mut self) -> intravisit::NestedVisitorMap<'this, 'tcx> {
1224 intravisit::NestedVisitorMap::All(&self.tcx.hir)
1226 fn visit_item(&mut self, it: &'tcx Item) {
1227 let def_id = self.tcx.hir.local_def_id(it.id);
1228 // the existential type itself or its children are not within its reveal scope
1229 if def_id != self.def_id {
1231 intravisit::walk_item(self, it);
1234 fn visit_impl_item(&mut self, it: &'tcx ImplItem) {
1235 let def_id = self.tcx.hir.local_def_id(it.id);
1236 // the existential type itself or its children are not within its reveal scope
1237 if def_id != self.def_id {
1239 intravisit::walk_impl_item(self, it);
1242 fn visit_trait_item(&mut self, it: &'tcx TraitItem) {
1243 let def_id = self.tcx.hir.local_def_id(it.id);
1245 intravisit::walk_trait_item(self, it);
1248 let mut locator = ConstraintLocator { def_id, tcx, found: None };
1249 let node_id = tcx.hir.as_local_node_id(def_id).unwrap();
1250 let parent = tcx.hir.get_parent(node_id);
1251 trace!("parent_id: {:?}", parent);
1252 if parent == ast::CRATE_NODE_ID {
1253 intravisit::walk_crate(&mut locator, tcx.hir.krate());
1255 trace!("parent: {:?}", tcx.hir.get(parent));
1256 match tcx.hir.get(parent) {
1257 NodeItem(ref it) => intravisit::walk_item(&mut locator, it),
1258 NodeImplItem(ref it) => intravisit::walk_impl_item(&mut locator, it),
1259 NodeTraitItem(ref it) => intravisit::walk_trait_item(&mut locator, it),
1260 other => bug!("{:?} is not a valid parent of an existential type item", other),
1263 match locator.found {
1264 Some((_, ty)) => ty,
1266 let span = tcx.def_span(def_id);
1267 tcx.sess.span_err(span, "could not find defining uses");
1273 fn fn_sig<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
1275 -> ty::PolyFnSig<'tcx> {
1276 use rustc::hir::map::*;
1279 let node_id = tcx.hir.as_local_node_id(def_id).unwrap();
1281 let icx = ItemCtxt::new(tcx, def_id);
1283 match tcx.hir.get(node_id) {
1284 NodeTraitItem(hir::TraitItem { node: TraitItemKind::Method(sig, _), .. }) |
1285 NodeImplItem(hir::ImplItem { node: ImplItemKind::Method(sig, _), .. }) => {
1286 AstConv::ty_of_fn(&icx, sig.header.unsafety, sig.header.abi, &sig.decl)
1289 NodeItem(hir::Item { node: ItemKind::Fn(decl, header, _, _), .. }) => {
1290 AstConv::ty_of_fn(&icx, header.unsafety, header.abi, decl)
1293 NodeForeignItem(&hir::ForeignItem { node: ForeignItemKind::Fn(ref fn_decl, _, _), .. }) => {
1294 let abi = tcx.hir.get_foreign_abi(node_id);
1295 compute_sig_of_foreign_fn_decl(tcx, def_id, fn_decl, abi)
1298 NodeStructCtor(&VariantData::Tuple(ref fields, _)) |
1299 NodeVariant(&Spanned { node: hir::VariantKind {
1300 data: VariantData::Tuple(ref fields, _), ..
1302 let ty = tcx.type_of(tcx.hir.get_parent_did(node_id));
1303 let inputs = fields.iter().map(|f| {
1304 tcx.type_of(tcx.hir.local_def_id(f.id))
1306 ty::Binder::bind(tcx.mk_fn_sig(
1310 hir::Unsafety::Normal,
1315 NodeExpr(&hir::Expr { node: hir::ExprKind::Closure(..), .. }) => {
1316 // Closure signatures are not like other function
1317 // signatures and cannot be accessed through `fn_sig`. For
1318 // example, a closure signature excludes the `self`
1319 // argument. In any case they are embedded within the
1320 // closure type as part of the `ClosureSubsts`.
1323 // the signature of a closure, you should use the
1324 // `closure_sig` method on the `ClosureSubsts`:
1326 // closure_substs.closure_sig(def_id, tcx)
1328 // or, inside of an inference context, you can use
1330 // infcx.closure_sig(def_id, closure_substs)
1331 bug!("to get the signature of a closure, use `closure_sig()` not `fn_sig()`");
1335 bug!("unexpected sort of node in fn_sig(): {:?}", x);
1340 fn impl_trait_ref<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
1342 -> Option<ty::TraitRef<'tcx>> {
1343 let icx = ItemCtxt::new(tcx, def_id);
1345 let node_id = tcx.hir.as_local_node_id(def_id).unwrap();
1346 match tcx.hir.expect_item(node_id).node {
1347 hir::ItemKind::Impl(.., ref opt_trait_ref, _, _) => {
1348 opt_trait_ref.as_ref().map(|ast_trait_ref| {
1349 let selfty = tcx.type_of(def_id);
1350 AstConv::instantiate_mono_trait_ref(&icx, ast_trait_ref, selfty)
1357 fn impl_polarity<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
1359 -> hir::ImplPolarity {
1360 let node_id = tcx.hir.as_local_node_id(def_id).unwrap();
1361 match tcx.hir.expect_item(node_id).node {
1362 hir::ItemKind::Impl(_, polarity, ..) => polarity,
1363 ref item => bug!("impl_polarity: {:?} not an impl", item)
1367 // Is it marked with ?Sized
1368 fn is_unsized<'gcx: 'tcx, 'tcx>(astconv: &dyn AstConv<'gcx, 'tcx>,
1369 ast_bounds: &[hir::GenericBound],
1372 let tcx = astconv.tcx();
1374 // Try to find an unbound in bounds.
1375 let mut unbound = None;
1376 for ab in ast_bounds {
1377 if let &hir::GenericBound::Trait(ref ptr, hir::TraitBoundModifier::Maybe) = ab {
1378 if unbound.is_none() {
1379 unbound = Some(ptr.trait_ref.clone());
1381 span_err!(tcx.sess, span, E0203,
1382 "type parameter has more than one relaxed default \
1383 bound, only one is supported");
1388 let kind_id = tcx.lang_items().require(SizedTraitLangItem);
1391 // FIXME(#8559) currently requires the unbound to be built-in.
1392 if let Ok(kind_id) = kind_id {
1393 if tpb.path.def != Def::Trait(kind_id) {
1394 tcx.sess.span_warn(span,
1395 "default bound relaxed for a type parameter, but \
1396 this does nothing because the given bound is not \
1397 a default. Only `?Sized` is supported");
1401 _ if kind_id.is_ok() => {
1404 // No lang item for Sized, so we can't add it as a bound.
1411 /// Returns the early-bound lifetimes declared in this generics
1412 /// listing. For anything other than fns/methods, this is just all
1413 /// the lifetimes that are declared. For fns or methods, we have to
1414 /// screen out those that do not appear in any where-clauses etc using
1415 /// `resolve_lifetime::early_bound_lifetimes`.
1416 fn early_bound_lifetimes_from_generics<'a, 'tcx>(
1417 tcx: TyCtxt<'a, 'tcx, 'tcx>,
1418 generics: &'a hir::Generics)
1419 -> impl Iterator<Item=&'a hir::GenericParam> + Captures<'tcx>
1421 generics.params.iter().filter(move |param| match param.kind {
1422 GenericParamKind::Lifetime { .. } => {
1423 let hir_id = tcx.hir.node_to_hir_id(param.id);
1424 !tcx.is_late_bound(hir_id)
1430 fn predicates_defined_on<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
1432 -> ty::GenericPredicates<'tcx> {
1433 let explicit = tcx.explicit_predicates_of(def_id);
1434 let predicates = if tcx.sess.features_untracked().infer_outlives_requirements {
1435 [&explicit.predicates[..], &tcx.inferred_outlives_of(def_id)[..]].concat()
1436 } else { explicit.predicates };
1438 ty::GenericPredicates {
1439 parent: explicit.parent,
1440 predicates: predicates,
1444 fn predicates_of<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
1446 -> ty::GenericPredicates<'tcx> {
1447 let ty::GenericPredicates { parent, mut predicates } =
1448 tcx.predicates_defined_on(def_id);
1450 if tcx.is_trait(def_id) {
1451 // For traits, add `Self: Trait` predicate. This is
1452 // not part of the predicates that a user writes, but it
1453 // is something that one must prove in order to invoke a
1454 // method or project an associated type.
1456 // In the chalk setup, this predicate is not part of the
1457 // "predicates" for a trait item. But it is useful in
1458 // rustc because if you directly (e.g.) invoke a trait
1459 // method like `Trait::method(...)`, you must naturally
1460 // prove that the trait applies to the types that were
1461 // used, and adding the predicate into this list ensures
1462 // that this is done.
1463 predicates.push(ty::TraitRef::identity(tcx, def_id).to_predicate());
1466 ty::GenericPredicates { parent, predicates }
1469 fn explicit_predicates_of<'a, 'tcx>(
1470 tcx: TyCtxt<'a, 'tcx, 'tcx>,
1472 ) -> ty::GenericPredicates<'tcx> {
1473 use rustc::hir::map::*;
1476 debug!("explicit_predicates_of(def_id={:?})", def_id);
1478 let node_id = tcx.hir.as_local_node_id(def_id).unwrap();
1479 let node = tcx.hir.get(node_id);
1481 let mut is_trait = None;
1482 let mut is_default_impl_trait = None;
1484 let icx = ItemCtxt::new(tcx, def_id);
1485 let no_generics = hir::Generics::empty();
1487 let mut predicates = vec![];
1489 let ast_generics = match node {
1490 NodeTraitItem(item) => {
1494 NodeImplItem(item) => match item.node {
1495 ImplItemKind::Existential(ref bounds) => {
1496 let substs = Substs::identity_for_item(tcx, def_id);
1497 let anon_ty = tcx.mk_anon(def_id, substs);
1499 // Collect the bounds, i.e. the `A+B+'c` in `impl A+B+'c`.
1500 let bounds = compute_bounds(&icx,
1503 SizedByDefault::Yes,
1504 tcx.def_span(def_id));
1506 predicates.extend(bounds.predicates(tcx, anon_ty));
1509 _ => &item.generics,
1514 ItemKind::Impl(_, _, defaultness, ref generics, ..) => {
1515 if defaultness.is_default() {
1516 is_default_impl_trait = tcx.impl_trait_ref(def_id);
1520 ItemKind::Fn(.., ref generics, _) |
1521 ItemKind::Ty(_, ref generics) |
1522 ItemKind::Enum(_, ref generics) |
1523 ItemKind::Struct(_, ref generics) |
1524 ItemKind::Union(_, ref generics) => generics,
1526 ItemKind::Trait(_, _, ref generics, .., ref items) => {
1527 is_trait = Some((ty::TraitRef::identity(tcx, def_id), items));
1530 ItemKind::Existential(ExistTy { ref bounds, impl_trait_fn, ref generics }) => {
1531 let substs = Substs::identity_for_item(tcx, def_id);
1532 let anon_ty = tcx.mk_anon(def_id, substs);
1534 // Collect the bounds, i.e. the `A+B+'c` in `impl A+B+'c`.
1535 let bounds = compute_bounds(&icx,
1538 SizedByDefault::Yes,
1539 tcx.def_span(def_id));
1541 if impl_trait_fn.is_some() {
1543 return ty::GenericPredicates {
1545 predicates: bounds.predicates(tcx, anon_ty),
1548 // named existential types
1549 predicates.extend(bounds.predicates(tcx, anon_ty));
1558 NodeForeignItem(item) => {
1560 ForeignItemKind::Static(..) => &no_generics,
1561 ForeignItemKind::Fn(_, _, ref generics) => generics,
1562 ForeignItemKind::Type => &no_generics,
1569 let generics = tcx.generics_of(def_id);
1570 let parent_count = generics.parent_count as u32;
1571 let has_own_self = generics.has_self && parent_count == 0;
1573 // Below we'll consider the bounds on the type parameters (including `Self`)
1574 // and the explicit where-clauses, but to get the full set of predicates
1575 // on a trait we need to add in the supertrait bounds and bounds found on
1576 // associated types.
1577 if let Some((_trait_ref, _)) = is_trait {
1578 predicates = tcx.super_predicates_of(def_id).predicates;
1581 // In default impls, we can assume that the self type implements
1582 // the trait. So in:
1584 // default impl Foo for Bar { .. }
1586 // we add a default where clause `Foo: Bar`. We do a similar thing for traits
1587 // (see below). Recall that a default impl is not itself an impl, but rather a
1588 // set of defaults that can be incorporated into another impl.
1589 if let Some(trait_ref) = is_default_impl_trait {
1590 predicates.push(trait_ref.to_poly_trait_ref().to_predicate());
1593 // Collect the region predicates that were declared inline as
1594 // well. In the case of parameters declared on a fn or method, we
1595 // have to be careful to only iterate over early-bound regions.
1596 let mut index = parent_count + has_own_self as u32;
1597 for param in early_bound_lifetimes_from_generics(tcx, ast_generics) {
1598 let region = tcx.mk_region(ty::ReEarlyBound(ty::EarlyBoundRegion {
1599 def_id: tcx.hir.local_def_id(param.id),
1601 name: param.name.ident().as_interned_str(),
1606 GenericParamKind::Lifetime { .. } => {
1607 param.bounds.iter().for_each(|bound| match bound {
1608 hir::GenericBound::Outlives(lt) => {
1609 let bound = AstConv::ast_region_to_region(&icx, <, None);
1610 let outlives = ty::Binder::bind(ty::OutlivesPredicate(region, bound));
1611 predicates.push(outlives.to_predicate());
1620 // Collect the predicates that were written inline by the user on each
1621 // type parameter (e.g., `<T:Foo>`).
1622 for param in &ast_generics.params {
1624 GenericParamKind::Type { .. } => {
1625 let name = param.name.ident().as_interned_str();
1626 let param_ty = ty::ParamTy::new(index, name).to_ty(tcx);
1629 let sized = SizedByDefault::Yes;
1630 let bounds = compute_bounds(&icx, param_ty, ¶m.bounds, sized, param.span);
1631 predicates.extend(bounds.predicates(tcx, param_ty));
1637 // Add in the bounds that appear in the where-clause
1638 let where_clause = &ast_generics.where_clause;
1639 for predicate in &where_clause.predicates {
1641 &hir::WherePredicate::BoundPredicate(ref bound_pred) => {
1642 let ty = icx.to_ty(&bound_pred.bounded_ty);
1644 for bound in bound_pred.bounds.iter() {
1646 &hir::GenericBound::Trait(ref poly_trait_ref, _) => {
1647 let mut projections = Vec::new();
1650 AstConv::instantiate_poly_trait_ref(&icx,
1655 predicates.push(trait_ref.to_predicate());
1656 predicates.extend(projections.iter().map(|p| p.to_predicate()));
1659 &hir::GenericBound::Outlives(ref lifetime) => {
1660 let region = AstConv::ast_region_to_region(&icx,
1663 let pred = ty::Binder::bind(ty::OutlivesPredicate(ty, region));
1664 predicates.push(ty::Predicate::TypeOutlives(pred))
1670 &hir::WherePredicate::RegionPredicate(ref region_pred) => {
1671 let r1 = AstConv::ast_region_to_region(&icx, ®ion_pred.lifetime, None);
1672 for bound in ®ion_pred.bounds {
1673 let r2 = match bound {
1674 hir::GenericBound::Outlives(lt) => {
1675 AstConv::ast_region_to_region(&icx, lt, None)
1679 let pred = ty::Binder::bind(ty::OutlivesPredicate(r1, r2));
1680 predicates.push(ty::Predicate::RegionOutlives(pred))
1684 &hir::WherePredicate::EqPredicate(..) => {
1690 // Add predicates from associated type bounds.
1691 if let Some((self_trait_ref, trait_items)) = is_trait {
1692 predicates.extend(trait_items.iter().flat_map(|trait_item_ref| {
1693 let trait_item = tcx.hir.trait_item(trait_item_ref.id);
1694 let bounds = match trait_item.node {
1695 hir::TraitItemKind::Type(ref bounds, _) => bounds,
1697 return vec![].into_iter();
1701 let assoc_ty = tcx.mk_projection(
1702 tcx.hir.local_def_id(trait_item.id),
1703 self_trait_ref.substs,
1706 let bounds = compute_bounds(&ItemCtxt::new(tcx, def_id),
1709 SizedByDefault::Yes,
1712 bounds.predicates(tcx, assoc_ty).into_iter()
1716 // Subtle: before we store the predicates into the tcx, we
1717 // sort them so that predicates like `T: Foo<Item=U>` come
1718 // before uses of `U`. This avoids false ambiguity errors
1719 // in trait checking. See `setup_constraining_predicates`
1721 if let NodeItem(&Item { node: ItemKind::Impl(..), .. }) = node {
1722 let self_ty = tcx.type_of(def_id);
1723 let trait_ref = tcx.impl_trait_ref(def_id);
1724 ctp::setup_constraining_predicates(tcx,
1727 &mut ctp::parameters_for_impl(self_ty, trait_ref));
1730 ty::GenericPredicates {
1731 parent: generics.parent,
1736 pub enum SizedByDefault { Yes, No, }
1738 /// Translate the AST's notion of ty param bounds (which are an enum consisting of a newtyped Ty or
1739 /// a region) to ty's notion of ty param bounds, which can either be user-defined traits, or the
1740 /// built-in trait (formerly known as kind): Send.
1741 pub fn compute_bounds<'gcx: 'tcx, 'tcx>(astconv: &dyn AstConv<'gcx, 'tcx>,
1743 ast_bounds: &[hir::GenericBound],
1744 sized_by_default: SizedByDefault,
1748 let mut region_bounds = vec![];
1749 let mut trait_bounds = vec![];
1750 for ast_bound in ast_bounds {
1752 hir::GenericBound::Trait(ref b, hir::TraitBoundModifier::None) => trait_bounds.push(b),
1753 hir::GenericBound::Trait(_, hir::TraitBoundModifier::Maybe) => {}
1754 hir::GenericBound::Outlives(ref l) => region_bounds.push(l),
1758 let mut projection_bounds = vec![];
1760 let mut trait_bounds: Vec<_> = trait_bounds.iter().map(|&bound| {
1761 astconv.instantiate_poly_trait_ref(bound, param_ty, &mut projection_bounds)
1764 let region_bounds = region_bounds.into_iter().map(|r| {
1765 astconv.ast_region_to_region(r, None)
1768 trait_bounds.sort_by_key(|t| t.def_id());
1770 let implicitly_sized = if let SizedByDefault::Yes = sized_by_default {
1771 !is_unsized(astconv, ast_bounds, span)
1784 /// Converts a specific GenericBound from the AST into a set of
1785 /// predicates that apply to the self-type. A vector is returned
1786 /// because this can be anywhere from 0 predicates (`T:?Sized` adds no
1787 /// predicates) to 1 (`T:Foo`) to many (`T:Bar<X=i32>` adds `T:Bar`
1788 /// and `<T as Bar>::X == i32`).
1789 fn predicates_from_bound<'tcx>(astconv: &dyn AstConv<'tcx, 'tcx>,
1791 bound: &hir::GenericBound)
1792 -> Vec<ty::Predicate<'tcx>>
1795 hir::GenericBound::Trait(ref tr, hir::TraitBoundModifier::None) => {
1796 let mut projections = Vec::new();
1797 let pred = astconv.instantiate_poly_trait_ref(tr,
1800 projections.into_iter()
1801 .map(|p| p.to_predicate())
1802 .chain(Some(pred.to_predicate()))
1805 hir::GenericBound::Outlives(ref lifetime) => {
1806 let region = astconv.ast_region_to_region(lifetime, None);
1807 let pred = ty::Binder::bind(ty::OutlivesPredicate(param_ty, region));
1808 vec![ty::Predicate::TypeOutlives(pred)]
1810 hir::GenericBound::Trait(_, hir::TraitBoundModifier::Maybe) => vec![],
1814 fn compute_sig_of_foreign_fn_decl<'a, 'tcx>(
1815 tcx: TyCtxt<'a, 'tcx, 'tcx>,
1819 -> ty::PolyFnSig<'tcx>
1821 let fty = AstConv::ty_of_fn(&ItemCtxt::new(tcx, def_id), hir::Unsafety::Unsafe, abi, decl);
1823 // feature gate SIMD types in FFI, since I (huonw) am not sure the
1824 // ABIs are handled at all correctly.
1825 if abi != abi::Abi::RustIntrinsic && abi != abi::Abi::PlatformIntrinsic
1826 && !tcx.features().simd_ffi {
1827 let check = |ast_ty: &hir::Ty, ty: Ty| {
1829 tcx.sess.struct_span_err(ast_ty.span,
1830 &format!("use of SIMD type `{}` in FFI is highly experimental and \
1831 may result in invalid code",
1832 tcx.hir.node_to_pretty_string(ast_ty.id)))
1833 .help("add #![feature(simd_ffi)] to the crate attributes to enable")
1837 for (input, ty) in decl.inputs.iter().zip(*fty.inputs().skip_binder()) {
1840 if let hir::Return(ref ty) = decl.output {
1841 check(&ty, *fty.output().skip_binder())
1848 fn is_foreign_item<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
1851 match tcx.hir.get_if_local(def_id) {
1852 Some(hir_map::NodeForeignItem(..)) => true,
1854 _ => bug!("is_foreign_item applied to non-local def-id {:?}", def_id)
1858 fn from_target_feature(
1861 attr: &ast::Attribute,
1862 whitelist: &FxHashMap<String, Option<String>>,
1863 target_features: &mut Vec<Symbol>,
1865 let list = match attr.meta_item_list() {
1868 let msg = "#[target_feature] attribute must be of the form \
1869 #[target_feature(..)]";
1870 tcx.sess.span_err(attr.span, &msg);
1874 let rust_features = tcx.features();
1876 // Only `enable = ...` is accepted in the meta item list
1877 if !item.check_name("enable") {
1878 let msg = "#[target_feature(..)] only accepts sub-keys of `enable` \
1880 tcx.sess.span_err(item.span, &msg);
1884 // Must be of the form `enable = "..."` ( a string)
1885 let value = match item.value_str() {
1886 Some(value) => value,
1888 let msg = "#[target_feature] attribute must be of the form \
1889 #[target_feature(enable = \"..\")]";
1890 tcx.sess.span_err(item.span, &msg);
1895 // We allow comma separation to enable multiple features
1896 for feature in value.as_str().split(',') {
1898 // Only allow whitelisted features per platform
1899 let feature_gate = match whitelist.get(feature) {
1902 let msg = format!("the feature named `{}` is not valid for \
1903 this target", feature);
1904 let mut err = tcx.sess.struct_span_err(item.span, &msg);
1906 if feature.starts_with("+") {
1907 let valid = whitelist.contains_key(&feature[1..]);
1909 err.help("consider removing the leading `+` in the feature name");
1917 // Only allow features whose feature gates have been enabled
1918 let allowed = match feature_gate.as_ref().map(|s| &**s) {
1919 Some("arm_target_feature") => rust_features.arm_target_feature,
1920 Some("aarch64_target_feature") => rust_features.aarch64_target_feature,
1921 Some("hexagon_target_feature") => rust_features.hexagon_target_feature,
1922 Some("powerpc_target_feature") => rust_features.powerpc_target_feature,
1923 Some("mips_target_feature") => rust_features.mips_target_feature,
1924 Some("avx512_target_feature") => rust_features.avx512_target_feature,
1925 Some("mmx_target_feature") => rust_features.mmx_target_feature,
1926 Some("sse4a_target_feature") => rust_features.sse4a_target_feature,
1927 Some("tbm_target_feature") => rust_features.tbm_target_feature,
1928 Some(name) => bug!("unknown target feature gate {}", name),
1931 if !allowed && id.is_local() {
1932 feature_gate::emit_feature_err(
1933 &tcx.sess.parse_sess,
1934 feature_gate.as_ref().unwrap(),
1936 feature_gate::GateIssue::Language,
1937 &format!("the target feature `{}` is currently unstable",
1942 target_features.push(Symbol::intern(feature));
1947 fn linkage_by_name<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId, name: &str) -> Linkage {
1948 use rustc::mir::mono::Linkage::*;
1950 // Use the names from src/llvm/docs/LangRef.rst here. Most types are only
1951 // applicable to variable declarations and may not really make sense for
1952 // Rust code in the first place but whitelist them anyway and trust that
1953 // the user knows what s/he's doing. Who knows, unanticipated use cases
1954 // may pop up in the future.
1956 // ghost, dllimport, dllexport and linkonce_odr_autohide are not supported
1957 // and don't have to be, LLVM treats them as no-ops.
1959 "appending" => Appending,
1960 "available_externally" => AvailableExternally,
1962 "extern_weak" => ExternalWeak,
1963 "external" => External,
1964 "internal" => Internal,
1965 "linkonce" => LinkOnceAny,
1966 "linkonce_odr" => LinkOnceODR,
1967 "private" => Private,
1969 "weak_odr" => WeakODR,
1971 let span = tcx.hir.span_if_local(def_id);
1972 if let Some(span) = span {
1973 tcx.sess.span_fatal(span, "invalid linkage specified")
1975 tcx.sess.fatal(&format!("invalid linkage specified: {}", name))
1981 fn codegen_fn_attrs<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, id: DefId) -> CodegenFnAttrs {
1982 let attrs = tcx.get_attrs(id);
1984 let mut codegen_fn_attrs = CodegenFnAttrs::new();
1986 let whitelist = tcx.target_features_whitelist(LOCAL_CRATE);
1988 let mut inline_span = None;
1989 for attr in attrs.iter() {
1990 if attr.check_name("cold") {
1991 codegen_fn_attrs.flags |= CodegenFnAttrFlags::COLD;
1992 } else if attr.check_name("allocator") {
1993 codegen_fn_attrs.flags |= CodegenFnAttrFlags::ALLOCATOR;
1994 } else if attr.check_name("unwind") {
1995 codegen_fn_attrs.flags |= CodegenFnAttrFlags::UNWIND;
1996 } else if attr.check_name("rustc_allocator_nounwind") {
1997 codegen_fn_attrs.flags |= CodegenFnAttrFlags::RUSTC_ALLOCATOR_NOUNWIND;
1998 } else if attr.check_name("naked") {
1999 codegen_fn_attrs.flags |= CodegenFnAttrFlags::NAKED;
2000 } else if attr.check_name("no_mangle") {
2001 codegen_fn_attrs.flags |= CodegenFnAttrFlags::NO_MANGLE;
2002 } else if attr.check_name("rustc_std_internal_symbol") {
2003 codegen_fn_attrs.flags |= CodegenFnAttrFlags::RUSTC_STD_INTERNAL_SYMBOL;
2004 } else if attr.check_name("no_debug") {
2005 codegen_fn_attrs.flags |= CodegenFnAttrFlags::NO_DEBUG;
2006 } else if attr.check_name("used") {
2007 codegen_fn_attrs.flags |= CodegenFnAttrFlags::USED;
2008 } else if attr.check_name("thread_local") {
2009 codegen_fn_attrs.flags |= CodegenFnAttrFlags::THREAD_LOCAL;
2010 } else if attr.check_name("inline") {
2011 codegen_fn_attrs.inline = attrs.iter().fold(InlineAttr::None, |ia, attr| {
2012 if attr.path != "inline" {
2015 let meta = match attr.meta() {
2016 Some(meta) => meta.node,
2020 MetaItemKind::Word => {
2024 MetaItemKind::List(ref items) => {
2026 inline_span = Some(attr.span);
2027 if items.len() != 1 {
2028 span_err!(tcx.sess.diagnostic(), attr.span, E0534,
2029 "expected one argument");
2031 } else if list_contains_name(&items[..], "always") {
2033 } else if list_contains_name(&items[..], "never") {
2036 span_err!(tcx.sess.diagnostic(), items[0].span, E0535,
2037 "invalid argument");
2045 } else if attr.check_name("export_name") {
2046 if let Some(s) = attr.value_str() {
2047 if s.as_str().contains("\0") {
2048 // `#[export_name = ...]` will be converted to a null-terminated string,
2049 // so it may not contain any null characters.
2050 struct_span_err!(tcx.sess, attr.span, E0648,
2051 "`export_name` may not contain null characters")
2054 codegen_fn_attrs.export_name = Some(s);
2056 struct_span_err!(tcx.sess, attr.span, E0558,
2057 "`export_name` attribute has invalid format")
2058 .span_label(attr.span, "did you mean #[export_name=\"*\"]?")
2061 } else if attr.check_name("target_feature") {
2062 if tcx.fn_sig(id).unsafety() == Unsafety::Normal {
2063 let msg = "#[target_feature(..)] can only be applied to \
2065 tcx.sess.span_err(attr.span, msg);
2067 from_target_feature(tcx, id, attr, &whitelist, &mut codegen_fn_attrs.target_features);
2068 } else if attr.check_name("linkage") {
2069 if let Some(val) = attr.value_str() {
2070 codegen_fn_attrs.linkage = Some(linkage_by_name(tcx, id, &val.as_str()));
2072 } else if attr.check_name("link_section") {
2073 if let Some(val) = attr.value_str() {
2074 if val.as_str().bytes().any(|b| b == 0) {
2075 let msg = format!("illegal null byte in link_section \
2076 value: `{}`", &val);
2077 tcx.sess.span_err(attr.span, &msg);
2079 codegen_fn_attrs.link_section = Some(val);
2085 // If a function uses #[target_feature] it can't be inlined into general
2086 // purpose functions as they wouldn't have the right target features
2087 // enabled. For that reason we also forbid #[inline(always)] as it can't be
2089 if codegen_fn_attrs.target_features.len() > 0 {
2090 if codegen_fn_attrs.inline == InlineAttr::Always {
2091 if let Some(span) = inline_span {
2092 tcx.sess.span_err(span, "cannot use #[inline(always)] with \
2093 #[target_feature]");