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};
28 use constrained_type_params as ctp;
30 use middle::lang_items::SizedTraitLangItem;
31 use middle::resolve_lifetime as rl;
32 use middle::weak_lang_items;
33 use rustc::mir::mono::Linkage;
34 use rustc::ty::query::Providers;
35 use rustc::ty::subst::Substs;
36 use rustc::ty::util::Discr;
37 use rustc::ty::util::IntTypeExt;
38 use rustc::ty::{self, AdtKind, ToPolyTraitRef, Ty, TyCtxt};
39 use rustc::ty::{ReprOptions, ToPredicate};
40 use rustc::util::captures::Captures;
41 use rustc::util::nodemap::FxHashMap;
42 use rustc_target::spec::abi;
45 use syntax::ast::MetaItemKind;
46 use syntax::attr::{InlineAttr, list_contains_name, mark_used};
47 use syntax::source_map::Spanned;
48 use syntax::feature_gate;
49 use syntax::symbol::{keywords, Symbol};
50 use syntax_pos::{Span, DUMMY_SP};
52 use rustc::hir::def::{CtorKind, Def};
54 use rustc::hir::def_id::{DefId, LOCAL_CRATE};
55 use rustc::hir::intravisit::{self, NestedVisitorMap, Visitor};
56 use rustc::hir::GenericParamKind;
57 use rustc::hir::{self, CodegenFnAttrFlags, CodegenFnAttrs, Unsafety};
61 ///////////////////////////////////////////////////////////////////////////
64 pub fn collect_item_types<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>) {
65 let mut visitor = CollectItemTypesVisitor { tcx: tcx };
68 .visit_all_item_likes(&mut visitor.as_deep_visitor());
71 pub fn provide(providers: &mut Providers) {
72 *providers = Providers {
76 predicates_defined_on,
77 explicit_predicates_of,
79 type_param_predicates,
91 ///////////////////////////////////////////////////////////////////////////
93 /// Context specific to some particular item. This is what implements
94 /// AstConv. It has information about the predicates that are defined
95 /// on the trait. Unfortunately, this predicate information is
96 /// available in various different forms at various points in the
97 /// process. So we can't just store a pointer to e.g. the AST or the
98 /// parsed ty form, we have to be more flexible. To this end, the
99 /// `ItemCtxt` is parameterized by a `DefId` that it uses to satisfy
100 /// `get_type_parameter_bounds` requests, drawing the information from
101 /// the AST (`hir::Generics`), recursively.
102 pub struct ItemCtxt<'a, 'tcx: 'a> {
103 tcx: TyCtxt<'a, 'tcx, 'tcx>,
107 ///////////////////////////////////////////////////////////////////////////
109 struct CollectItemTypesVisitor<'a, 'tcx: 'a> {
110 tcx: TyCtxt<'a, 'tcx, 'tcx>,
113 impl<'a, 'tcx> Visitor<'tcx> for CollectItemTypesVisitor<'a, 'tcx> {
114 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
115 NestedVisitorMap::OnlyBodies(&self.tcx.hir)
118 fn visit_item(&mut self, item: &'tcx hir::Item) {
119 convert_item(self.tcx, item.id);
120 intravisit::walk_item(self, item);
123 fn visit_generics(&mut self, generics: &'tcx hir::Generics) {
124 for param in &generics.params {
126 hir::GenericParamKind::Lifetime { .. } => {}
127 hir::GenericParamKind::Type {
130 let def_id = self.tcx.hir.local_def_id(param.id);
131 self.tcx.type_of(def_id);
133 hir::GenericParamKind::Type { .. } => {}
136 intravisit::walk_generics(self, generics);
139 fn visit_expr(&mut self, expr: &'tcx hir::Expr) {
140 if let hir::ExprKind::Closure(..) = expr.node {
141 let def_id = self.tcx.hir.local_def_id(expr.id);
142 self.tcx.generics_of(def_id);
143 self.tcx.type_of(def_id);
145 intravisit::walk_expr(self, expr);
148 fn visit_trait_item(&mut self, trait_item: &'tcx hir::TraitItem) {
149 convert_trait_item(self.tcx, trait_item.id);
150 intravisit::walk_trait_item(self, trait_item);
153 fn visit_impl_item(&mut self, impl_item: &'tcx hir::ImplItem) {
154 convert_impl_item(self.tcx, impl_item.id);
155 intravisit::walk_impl_item(self, impl_item);
159 ///////////////////////////////////////////////////////////////////////////
160 // Utility types and common code for the above passes.
162 impl<'a, 'tcx> ItemCtxt<'a, 'tcx> {
163 pub fn new(tcx: TyCtxt<'a, 'tcx, 'tcx>, item_def_id: DefId) -> ItemCtxt<'a, 'tcx> {
164 ItemCtxt { tcx, item_def_id }
168 impl<'a, 'tcx> ItemCtxt<'a, 'tcx> {
169 pub fn to_ty(&self, ast_ty: &hir::Ty) -> Ty<'tcx> {
170 AstConv::ast_ty_to_ty(self, ast_ty)
174 impl<'a, 'tcx> AstConv<'tcx, 'tcx> for ItemCtxt<'a, 'tcx> {
175 fn tcx<'b>(&'b self) -> TyCtxt<'b, 'tcx, 'tcx> {
179 fn get_type_parameter_bounds(&self, span: Span, def_id: DefId) -> ty::GenericPredicates<'tcx> {
182 .type_param_predicates((self.item_def_id, def_id))
188 _def: Option<&ty::GenericParamDef>,
189 ) -> Option<ty::Region<'tcx>> {
193 fn ty_infer(&self, span: Span) -> Ty<'tcx> {
198 "the type placeholder `_` is not allowed within types on item signatures"
199 ).span_label(span, "not allowed in type signatures")
205 fn projected_ty_from_poly_trait_ref(
209 poly_trait_ref: ty::PolyTraitRef<'tcx>,
211 if let Some(trait_ref) = poly_trait_ref.no_late_bound_regions() {
212 self.tcx().mk_projection(item_def_id, trait_ref.substs)
214 // no late-bound regions, we can just ignore the binder
219 "cannot extract an associated type from a higher-ranked trait bound \
226 fn normalize_ty(&self, _span: Span, ty: Ty<'tcx>) -> Ty<'tcx> {
227 // types in item signatures are not normalized, to avoid undue
232 fn set_tainted_by_errors(&self) {
233 // no obvious place to track this, just let it go
236 fn record_ty(&self, _hir_id: hir::HirId, _ty: Ty<'tcx>, _span: Span) {
237 // no place to record types from signatures?
241 fn type_param_predicates<'a, 'tcx>(
242 tcx: TyCtxt<'a, 'tcx, 'tcx>,
243 (item_def_id, def_id): (DefId, DefId),
244 ) -> ty::GenericPredicates<'tcx> {
247 // In the AST, bounds can derive from two places. Either
248 // written inline like `<T:Foo>` or in a where clause like
251 let param_id = tcx.hir.as_local_node_id(def_id).unwrap();
252 let param_owner = tcx.hir.ty_param_owner(param_id);
253 let param_owner_def_id = tcx.hir.local_def_id(param_owner);
254 let generics = tcx.generics_of(param_owner_def_id);
255 let index = generics.param_def_id_to_index[&def_id];
256 let ty = tcx.mk_ty_param(index, tcx.hir.ty_param_name(param_id).as_interned_str());
258 // Don't look for bounds where the type parameter isn't in scope.
259 let parent = if item_def_id == param_owner_def_id {
262 tcx.generics_of(item_def_id).parent
265 let mut result = parent.map_or(
266 ty::GenericPredicates {
271 let icx = ItemCtxt::new(tcx, parent);
272 icx.get_type_parameter_bounds(DUMMY_SP, def_id)
276 let item_node_id = tcx.hir.as_local_node_id(item_def_id).unwrap();
277 let ast_generics = match tcx.hir.get(item_node_id) {
278 Node::TraitItem(item) => &item.generics,
280 Node::ImplItem(item) => &item.generics,
282 Node::Item(item) => {
284 ItemKind::Fn(.., ref generics, _)
285 | ItemKind::Impl(_, _, _, ref generics, ..)
286 | ItemKind::Ty(_, ref generics)
287 | ItemKind::Existential(ExistTy {
292 | ItemKind::Enum(_, ref generics)
293 | ItemKind::Struct(_, ref generics)
294 | ItemKind::Union(_, ref generics) => generics,
295 ItemKind::Trait(_, _, ref generics, ..) => {
296 // Implied `Self: Trait` and supertrait bounds.
297 if param_id == item_node_id {
298 let identity_trait_ref = ty::TraitRef::identity(tcx, item_def_id);
301 .push((identity_trait_ref.to_predicate(), item.span));
309 Node::ForeignItem(item) => match item.node {
310 ForeignItemKind::Fn(_, _, ref generics) => generics,
317 let icx = ItemCtxt::new(tcx, item_def_id);
320 .extend(icx.type_parameter_bounds_in_generics(ast_generics, param_id, ty));
324 impl<'a, 'tcx> ItemCtxt<'a, 'tcx> {
325 /// Find bounds from hir::Generics. This requires scanning through the
326 /// AST. We do this to avoid having to convert *all* the bounds, which
327 /// would create artificial cycles. Instead we can only convert the
328 /// bounds for a type parameter `X` if `X::Foo` is used.
329 fn type_parameter_bounds_in_generics(
331 ast_generics: &hir::Generics,
332 param_id: ast::NodeId,
334 ) -> Vec<(ty::Predicate<'tcx>, Span)> {
335 let from_ty_params = ast_generics
338 .filter_map(|param| match param.kind {
339 GenericParamKind::Type { .. } if param.id == param_id => Some(¶m.bounds),
342 .flat_map(|bounds| bounds.iter())
343 .flat_map(|b| predicates_from_bound(self, ty, b));
345 let from_where_clauses = ast_generics
349 .filter_map(|wp| match *wp {
350 hir::WherePredicate::BoundPredicate(ref bp) => Some(bp),
353 .filter(|bp| is_param(self.tcx, &bp.bounded_ty, param_id))
354 .flat_map(|bp| bp.bounds.iter())
355 .flat_map(|b| predicates_from_bound(self, ty, b));
357 from_ty_params.chain(from_where_clauses).collect()
361 /// Tests whether this is the AST for a reference to the type
362 /// parameter with id `param_id`. We use this so as to avoid running
363 /// `ast_ty_to_ty`, because we want to avoid triggering an all-out
364 /// conversion of the type to avoid inducing unnecessary cycles.
365 fn is_param<'a, 'tcx>(
366 tcx: TyCtxt<'a, 'tcx, 'tcx>,
368 param_id: ast::NodeId,
370 if let hir::TyKind::Path(hir::QPath::Resolved(None, ref path)) = ast_ty.node {
372 Def::SelfTy(Some(def_id), None) | Def::TyParam(def_id) => {
373 def_id == tcx.hir.local_def_id(param_id)
382 fn convert_item<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, item_id: ast::NodeId) {
383 let it = tcx.hir.expect_item(item_id);
384 debug!("convert: item {} with id {}", it.name, it.id);
385 let def_id = tcx.hir.local_def_id(item_id);
387 // These don't define types.
388 hir::ItemKind::ExternCrate(_)
389 | hir::ItemKind::Use(..)
390 | hir::ItemKind::Mod(_)
391 | hir::ItemKind::GlobalAsm(_) => {}
392 hir::ItemKind::ForeignMod(ref foreign_mod) => {
393 for item in &foreign_mod.items {
394 let def_id = tcx.hir.local_def_id(item.id);
395 tcx.generics_of(def_id);
397 tcx.predicates_of(def_id);
398 if let hir::ForeignItemKind::Fn(..) = item.node {
403 hir::ItemKind::Enum(ref enum_definition, _) => {
404 tcx.generics_of(def_id);
406 tcx.predicates_of(def_id);
407 convert_enum_variant_types(tcx, def_id, &enum_definition.variants);
409 hir::ItemKind::Impl(..) => {
410 tcx.generics_of(def_id);
412 tcx.impl_trait_ref(def_id);
413 tcx.predicates_of(def_id);
415 hir::ItemKind::Trait(..) => {
416 tcx.generics_of(def_id);
417 tcx.trait_def(def_id);
418 tcx.at(it.span).super_predicates_of(def_id);
419 tcx.predicates_of(def_id);
421 hir::ItemKind::TraitAlias(..) => {
426 "trait aliases are not yet implemented (see issue #41517)"
429 hir::ItemKind::Struct(ref struct_def, _) | hir::ItemKind::Union(ref struct_def, _) => {
430 tcx.generics_of(def_id);
432 tcx.predicates_of(def_id);
434 for f in struct_def.fields() {
435 let def_id = tcx.hir.local_def_id(f.id);
436 tcx.generics_of(def_id);
438 tcx.predicates_of(def_id);
441 if !struct_def.is_struct() {
442 convert_variant_ctor(tcx, struct_def.id());
446 // Desugared from `impl Trait` -> visited by the function's return type
447 hir::ItemKind::Existential(hir::ExistTy {
448 impl_trait_fn: Some(_),
452 hir::ItemKind::Existential(..)
453 | hir::ItemKind::Ty(..)
454 | hir::ItemKind::Static(..)
455 | hir::ItemKind::Const(..)
456 | hir::ItemKind::Fn(..) => {
457 tcx.generics_of(def_id);
459 tcx.predicates_of(def_id);
460 if let hir::ItemKind::Fn(..) = it.node {
467 fn convert_trait_item<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, trait_item_id: ast::NodeId) {
468 let trait_item = tcx.hir.expect_trait_item(trait_item_id);
469 let def_id = tcx.hir.local_def_id(trait_item.id);
470 tcx.generics_of(def_id);
472 match trait_item.node {
473 hir::TraitItemKind::Const(..)
474 | hir::TraitItemKind::Type(_, Some(_))
475 | hir::TraitItemKind::Method(..) => {
477 if let hir::TraitItemKind::Method(..) = trait_item.node {
482 hir::TraitItemKind::Type(_, None) => {}
485 tcx.predicates_of(def_id);
488 fn convert_impl_item<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, impl_item_id: ast::NodeId) {
489 let def_id = tcx.hir.local_def_id(impl_item_id);
490 tcx.generics_of(def_id);
492 tcx.predicates_of(def_id);
493 if let hir::ImplItemKind::Method(..) = tcx.hir.expect_impl_item(impl_item_id).node {
498 fn convert_variant_ctor<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, ctor_id: ast::NodeId) {
499 let def_id = tcx.hir.local_def_id(ctor_id);
500 tcx.generics_of(def_id);
502 tcx.predicates_of(def_id);
505 fn convert_enum_variant_types<'a, 'tcx>(
506 tcx: TyCtxt<'a, 'tcx, 'tcx>,
508 variants: &[hir::Variant],
510 let def = tcx.adt_def(def_id);
511 let repr_type = def.repr.discr_type();
512 let initial = repr_type.initial_discriminant(tcx);
513 let mut prev_discr = None::<Discr<'tcx>>;
515 // fill the discriminant values and field types
516 for variant in variants {
517 let wrapped_discr = prev_discr.map_or(initial, |d| d.wrap_incr(tcx));
519 if let Some(ref e) = variant.node.disr_expr {
520 let expr_did = tcx.hir.local_def_id(e.id);
521 def.eval_explicit_discr(tcx, expr_did)
522 } else if let Some(discr) = repr_type.disr_incr(tcx, prev_discr) {
529 "enum discriminant overflowed"
532 format!("overflowed on value after {}", prev_discr.unwrap()),
534 "explicitly set `{} = {}` if that is desired outcome",
535 variant.node.name, wrapped_discr
539 }.unwrap_or(wrapped_discr),
542 for f in variant.node.data.fields() {
543 let def_id = tcx.hir.local_def_id(f.id);
544 tcx.generics_of(def_id);
546 tcx.predicates_of(def_id);
549 // Convert the ctor, if any. This also registers the variant as
551 convert_variant_ctor(tcx, variant.node.data.id());
555 fn convert_variant<'a, 'tcx>(
556 tcx: TyCtxt<'a, 'tcx, 'tcx>,
559 discr: ty::VariantDiscr,
560 def: &hir::VariantData,
561 adt_kind: ty::AdtKind,
562 attribute_def_id: DefId
563 ) -> ty::VariantDef {
564 let mut seen_fields: FxHashMap<ast::Ident, Span> = Default::default();
565 let node_id = tcx.hir.as_local_node_id(did).unwrap();
570 let fid = tcx.hir.local_def_id(f.id);
571 let dup_span = seen_fields.get(&f.ident.modern()).cloned();
572 if let Some(prev_span) = dup_span {
577 "field `{}` is already declared",
579 ).span_label(f.span, "field already declared")
580 .span_label(prev_span, format!("`{}` first declared here", f.ident))
583 seen_fields.insert(f.ident.modern(), f.span);
589 vis: ty::Visibility::from_hir(&f.vis, node_id, tcx),
593 ty::VariantDef::new(tcx,
599 CtorKind::from_hir(def),
603 fn adt_def<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId) -> &'tcx ty::AdtDef {
606 let node_id = tcx.hir.as_local_node_id(def_id).unwrap();
607 let item = match tcx.hir.get(node_id) {
608 Node::Item(item) => item,
612 let repr = ReprOptions::new(tcx, def_id);
613 let (kind, variants) = match item.node {
614 ItemKind::Enum(ref def, _) => {
615 let mut distance_from_explicit = 0;
621 let did = tcx.hir.local_def_id(v.node.data.id());
622 let discr = if let Some(ref e) = v.node.disr_expr {
623 distance_from_explicit = 0;
624 ty::VariantDiscr::Explicit(tcx.hir.local_def_id(e.id))
626 ty::VariantDiscr::Relative(distance_from_explicit)
628 distance_from_explicit += 1;
630 convert_variant(tcx, did, v.node.name, discr, &v.node.data, AdtKind::Enum,
636 ItemKind::Struct(ref def, _) => {
637 // Use separate constructor id for unit/tuple structs and reuse did for braced structs.
638 let ctor_id = if !def.is_struct() {
639 Some(tcx.hir.local_def_id(def.id()))
645 vec![convert_variant(
647 ctor_id.unwrap_or(def_id),
649 ty::VariantDiscr::Relative(0),
656 ItemKind::Union(ref def, _) => (
658 vec![convert_variant(
662 ty::VariantDiscr::Relative(0),
670 tcx.alloc_adt_def(def_id, kind, variants, repr)
673 /// Ensures that the super-predicates of the trait with def-id
674 /// trait_def_id are converted and stored. This also ensures that
675 /// the transitive super-predicates are converted;
676 fn super_predicates_of<'a, 'tcx>(
677 tcx: TyCtxt<'a, 'tcx, 'tcx>,
679 ) -> ty::GenericPredicates<'tcx> {
680 debug!("super_predicates(trait_def_id={:?})", trait_def_id);
681 let trait_node_id = tcx.hir.as_local_node_id(trait_def_id).unwrap();
683 let item = match tcx.hir.get(trait_node_id) {
684 Node::Item(item) => item,
685 _ => bug!("trait_node_id {} is not an item", trait_node_id),
688 let (generics, bounds) = match item.node {
689 hir::ItemKind::Trait(.., ref generics, ref supertraits, _) => (generics, supertraits),
690 hir::ItemKind::TraitAlias(ref generics, ref supertraits) => (generics, supertraits),
691 _ => span_bug!(item.span, "super_predicates invoked on non-trait"),
694 let icx = ItemCtxt::new(tcx, trait_def_id);
696 // Convert the bounds that follow the colon, e.g. `Bar+Zed` in `trait Foo : Bar+Zed`.
697 let self_param_ty = tcx.mk_self_type();
698 let superbounds1 = compute_bounds(&icx, self_param_ty, bounds, SizedByDefault::No, item.span);
700 let superbounds1 = superbounds1.predicates(tcx, self_param_ty);
702 // Convert any explicit superbounds in the where clause,
703 // e.g. `trait Foo where Self : Bar`:
704 let superbounds2 = icx.type_parameter_bounds_in_generics(generics, item.id, self_param_ty);
706 // Combine the two lists to form the complete set of superbounds:
707 let superbounds: Vec<_> = superbounds1.into_iter().chain(superbounds2).collect();
709 // Now require that immediate supertraits are converted,
710 // which will, in turn, reach indirect supertraits.
711 for &(pred, span) in &superbounds {
712 if let ty::Predicate::Trait(bound) = pred {
713 tcx.at(span).super_predicates_of(bound.def_id());
717 ty::GenericPredicates {
719 predicates: superbounds,
723 fn trait_def<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId) -> &'tcx ty::TraitDef {
724 let node_id = tcx.hir.as_local_node_id(def_id).unwrap();
725 let item = tcx.hir.expect_item(node_id);
727 let (is_auto, unsafety) = match item.node {
728 hir::ItemKind::Trait(is_auto, unsafety, ..) => (is_auto == hir::IsAuto::Yes, unsafety),
729 hir::ItemKind::TraitAlias(..) => (false, hir::Unsafety::Normal),
730 _ => span_bug!(item.span, "trait_def_of_item invoked on non-trait"),
733 let paren_sugar = tcx.has_attr(def_id, "rustc_paren_sugar");
734 if paren_sugar && !tcx.features().unboxed_closures {
735 let mut err = tcx.sess.struct_span_err(
737 "the `#[rustc_paren_sugar]` attribute is a temporary means of controlling \
738 which traits can use parenthetical notation",
742 "add `#![feature(unboxed_closures)]` to \
743 the crate attributes to use it"
748 let is_marker = tcx.has_attr(def_id, "marker");
749 let def_path_hash = tcx.def_path_hash(def_id);
750 let def = ty::TraitDef::new(def_id, unsafety, paren_sugar, is_auto, is_marker, def_path_hash);
751 tcx.alloc_trait_def(def)
754 fn has_late_bound_regions<'a, 'tcx>(
755 tcx: TyCtxt<'a, 'tcx, 'tcx>,
758 struct LateBoundRegionsDetector<'a, 'tcx: 'a> {
759 tcx: TyCtxt<'a, 'tcx, 'tcx>,
760 outer_index: ty::DebruijnIndex,
761 has_late_bound_regions: Option<Span>,
764 impl<'a, 'tcx> Visitor<'tcx> for LateBoundRegionsDetector<'a, 'tcx> {
765 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
766 NestedVisitorMap::None
769 fn visit_ty(&mut self, ty: &'tcx hir::Ty) {
770 if self.has_late_bound_regions.is_some() {
774 hir::TyKind::BareFn(..) => {
775 self.outer_index.shift_in(1);
776 intravisit::walk_ty(self, ty);
777 self.outer_index.shift_out(1);
779 _ => intravisit::walk_ty(self, ty),
783 fn visit_poly_trait_ref(
785 tr: &'tcx hir::PolyTraitRef,
786 m: hir::TraitBoundModifier,
788 if self.has_late_bound_regions.is_some() {
791 self.outer_index.shift_in(1);
792 intravisit::walk_poly_trait_ref(self, tr, m);
793 self.outer_index.shift_out(1);
796 fn visit_lifetime(&mut self, lt: &'tcx hir::Lifetime) {
797 if self.has_late_bound_regions.is_some() {
801 let hir_id = self.tcx.hir.node_to_hir_id(lt.id);
802 match self.tcx.named_region(hir_id) {
803 Some(rl::Region::Static) | Some(rl::Region::EarlyBound(..)) => {}
804 Some(rl::Region::LateBound(debruijn, _, _))
805 | Some(rl::Region::LateBoundAnon(debruijn, _)) if debruijn < self.outer_index => {}
806 Some(rl::Region::LateBound(..))
807 | Some(rl::Region::LateBoundAnon(..))
808 | Some(rl::Region::Free(..))
810 self.has_late_bound_regions = Some(lt.span);
816 fn has_late_bound_regions<'a, 'tcx>(
817 tcx: TyCtxt<'a, 'tcx, 'tcx>,
818 generics: &'tcx hir::Generics,
819 decl: &'tcx hir::FnDecl,
821 let mut visitor = LateBoundRegionsDetector {
823 outer_index: ty::INNERMOST,
824 has_late_bound_regions: None,
826 for param in &generics.params {
827 if let GenericParamKind::Lifetime { .. } = param.kind {
828 let hir_id = tcx.hir.node_to_hir_id(param.id);
829 if tcx.is_late_bound(hir_id) {
830 return Some(param.span);
834 visitor.visit_fn_decl(decl);
835 visitor.has_late_bound_regions
839 Node::TraitItem(item) => match item.node {
840 hir::TraitItemKind::Method(ref sig, _) => {
841 has_late_bound_regions(tcx, &item.generics, &sig.decl)
845 Node::ImplItem(item) => match item.node {
846 hir::ImplItemKind::Method(ref sig, _) => {
847 has_late_bound_regions(tcx, &item.generics, &sig.decl)
851 Node::ForeignItem(item) => match item.node {
852 hir::ForeignItemKind::Fn(ref fn_decl, _, ref generics) => {
853 has_late_bound_regions(tcx, generics, fn_decl)
857 Node::Item(item) => match item.node {
858 hir::ItemKind::Fn(ref fn_decl, .., ref generics, _) => {
859 has_late_bound_regions(tcx, generics, fn_decl)
867 fn generics_of<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId) -> &'tcx ty::Generics {
870 let node_id = tcx.hir.as_local_node_id(def_id).unwrap();
872 let node = tcx.hir.get(node_id);
873 let parent_def_id = match node {
874 Node::ImplItem(_) | Node::TraitItem(_) | Node::Variant(_)
875 | Node::StructCtor(_) | Node::Field(_) => {
876 let parent_id = tcx.hir.get_parent(node_id);
877 Some(tcx.hir.local_def_id(parent_id))
879 Node::Expr(&hir::Expr {
880 node: hir::ExprKind::Closure(..),
882 }) => Some(tcx.closure_base_def_id(def_id)),
883 Node::Item(item) => match item.node {
884 ItemKind::Existential(hir::ExistTy { impl_trait_fn, .. }) => impl_trait_fn,
890 let mut opt_self = None;
891 let mut allow_defaults = false;
893 let no_generics = hir::Generics::empty();
894 let ast_generics = match node {
895 Node::TraitItem(item) => &item.generics,
897 Node::ImplItem(item) => &item.generics,
899 Node::Item(item) => {
901 ItemKind::Fn(.., ref generics, _) | ItemKind::Impl(_, _, _, ref generics, ..) => {
905 ItemKind::Ty(_, ref generics)
906 | ItemKind::Enum(_, ref generics)
907 | ItemKind::Struct(_, ref generics)
908 | ItemKind::Existential(hir::ExistTy { ref generics, .. })
909 | ItemKind::Union(_, ref generics) => {
910 allow_defaults = true;
914 ItemKind::Trait(_, _, ref generics, ..)
915 | ItemKind::TraitAlias(ref generics, ..) => {
916 // Add in the self type parameter.
918 // Something of a hack: use the node id for the trait, also as
919 // the node id for the Self type parameter.
920 let param_id = item.id;
922 opt_self = Some(ty::GenericParamDef {
924 name: keywords::SelfType.name().as_interned_str(),
925 def_id: tcx.hir.local_def_id(param_id),
926 pure_wrt_drop: false,
927 kind: ty::GenericParamDefKind::Type {
929 object_lifetime_default: rl::Set1::Empty,
934 allow_defaults = true;
942 Node::ForeignItem(item) => match item.node {
943 ForeignItemKind::Static(..) => &no_generics,
944 ForeignItemKind::Fn(_, _, ref generics) => generics,
945 ForeignItemKind::Type => &no_generics,
951 let has_self = opt_self.is_some();
952 let mut parent_has_self = false;
953 let mut own_start = has_self as u32;
954 let parent_count = parent_def_id.map_or(0, |def_id| {
955 let generics = tcx.generics_of(def_id);
956 assert_eq!(has_self, false);
957 parent_has_self = generics.has_self;
958 own_start = generics.count() as u32;
959 generics.parent_count + generics.params.len()
962 let mut params: Vec<_> = opt_self.into_iter().collect();
964 let early_lifetimes = early_bound_lifetimes_from_generics(tcx, ast_generics);
968 .map(|(i, param)| ty::GenericParamDef {
969 name: param.name.ident().as_interned_str(),
970 index: own_start + i as u32,
971 def_id: tcx.hir.local_def_id(param.id),
972 pure_wrt_drop: param.pure_wrt_drop,
973 kind: ty::GenericParamDefKind::Lifetime,
977 let hir_id = tcx.hir.node_to_hir_id(node_id);
978 let object_lifetime_defaults = tcx.object_lifetime_defaults(hir_id);
980 // Now create the real type parameters.
981 let type_start = own_start - has_self as u32 + params.len() as u32;
987 .filter_map(|param| match param.kind {
988 GenericParamKind::Type {
993 if param.name.ident().name == keywords::SelfType.name() {
996 "`Self` should not be the name of a regular parameter"
1000 if !allow_defaults && default.is_some() {
1001 if !tcx.features().default_type_parameter_fallback {
1003 lint::builtin::INVALID_TYPE_PARAM_DEFAULT,
1007 "defaults for type parameters are only allowed in \
1008 `struct`, `enum`, `type`, or `trait` definitions."
1014 let ty_param = ty::GenericParamDef {
1015 index: type_start + i as u32,
1016 name: param.name.ident().as_interned_str(),
1017 def_id: tcx.hir.local_def_id(param.id),
1018 pure_wrt_drop: param.pure_wrt_drop,
1019 kind: ty::GenericParamDefKind::Type {
1020 has_default: default.is_some(),
1021 object_lifetime_default: object_lifetime_defaults
1023 .map_or(rl::Set1::Empty, |o| o[i]),
1034 // provide junk type parameter defs - the only place that
1035 // cares about anything but the length is instantiation,
1036 // and we don't do that for closures.
1037 if let Node::Expr(&hir::Expr {
1038 node: hir::ExprKind::Closure(.., gen),
1042 let dummy_args = if gen.is_some() {
1043 &["<yield_ty>", "<return_ty>", "<witness>"][..]
1045 &["<closure_kind>", "<closure_signature>"][..]
1052 .map(|(i, &arg)| ty::GenericParamDef {
1053 index: type_start + i as u32,
1054 name: Symbol::intern(arg).as_interned_str(),
1056 pure_wrt_drop: false,
1057 kind: ty::GenericParamDefKind::Type {
1059 object_lifetime_default: rl::Set1::Empty,
1065 tcx.with_freevars(node_id, |fv| {
1066 params.extend(fv.iter().zip((dummy_args.len() as u32)..).map(|(_, i)| {
1067 ty::GenericParamDef {
1068 index: type_start + i,
1069 name: Symbol::intern("<upvar>").as_interned_str(),
1071 pure_wrt_drop: false,
1072 kind: ty::GenericParamDefKind::Type {
1074 object_lifetime_default: rl::Set1::Empty,
1082 let param_def_id_to_index = params
1084 .map(|param| (param.def_id, param.index))
1087 tcx.alloc_generics(ty::Generics {
1088 parent: parent_def_id,
1091 param_def_id_to_index,
1092 has_self: has_self || parent_has_self,
1093 has_late_bound_regions: has_late_bound_regions(tcx, node),
1097 fn report_assoc_ty_on_inherent_impl<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, span: Span) {
1102 "associated types are not allowed in inherent impls"
1106 fn type_of<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId) -> Ty<'tcx> {
1109 let node_id = tcx.hir.as_local_node_id(def_id).unwrap();
1111 let icx = ItemCtxt::new(tcx, def_id);
1113 match tcx.hir.get(node_id) {
1114 Node::TraitItem(item) => match item.node {
1115 TraitItemKind::Method(..) => {
1116 let substs = Substs::identity_for_item(tcx, def_id);
1117 tcx.mk_fn_def(def_id, substs)
1119 TraitItemKind::Const(ref ty, _) | TraitItemKind::Type(_, Some(ref ty)) => icx.to_ty(ty),
1120 TraitItemKind::Type(_, None) => {
1121 span_bug!(item.span, "associated type missing default");
1125 Node::ImplItem(item) => match item.node {
1126 ImplItemKind::Method(..) => {
1127 let substs = Substs::identity_for_item(tcx, def_id);
1128 tcx.mk_fn_def(def_id, substs)
1130 ImplItemKind::Const(ref ty, _) => icx.to_ty(ty),
1131 ImplItemKind::Existential(_) => {
1133 .impl_trait_ref(tcx.hir.get_parent_did(node_id))
1136 report_assoc_ty_on_inherent_impl(tcx, item.span);
1139 find_existential_constraints(tcx, def_id)
1141 ImplItemKind::Type(ref ty) => {
1143 .impl_trait_ref(tcx.hir.get_parent_did(node_id))
1146 report_assoc_ty_on_inherent_impl(tcx, item.span);
1153 Node::Item(item) => {
1155 ItemKind::Static(ref t, ..)
1156 | ItemKind::Const(ref t, _)
1157 | ItemKind::Ty(ref t, _)
1158 | ItemKind::Impl(.., ref t, _) => icx.to_ty(t),
1159 ItemKind::Fn(..) => {
1160 let substs = Substs::identity_for_item(tcx, def_id);
1161 tcx.mk_fn_def(def_id, substs)
1163 ItemKind::Enum(..) | ItemKind::Struct(..) | ItemKind::Union(..) => {
1164 let def = tcx.adt_def(def_id);
1165 let substs = Substs::identity_for_item(tcx, def_id);
1166 tcx.mk_adt(def, substs)
1168 ItemKind::Existential(hir::ExistTy {
1169 impl_trait_fn: None,
1171 }) => find_existential_constraints(tcx, def_id),
1172 // existential types desugared from impl Trait
1173 ItemKind::Existential(hir::ExistTy {
1174 impl_trait_fn: Some(owner),
1177 tcx.typeck_tables_of(owner)
1178 .concrete_existential_types
1181 .unwrap_or_else(|| {
1182 // This can occur if some error in the
1183 // owner fn prevented us from populating
1184 // the `concrete_existential_types` table.
1185 tcx.sess.delay_span_bug(
1188 "owner {:?} has no existential type for {:?} in its tables",
1196 | ItemKind::TraitAlias(..)
1198 | ItemKind::ForeignMod(..)
1199 | ItemKind::GlobalAsm(..)
1200 | ItemKind::ExternCrate(..)
1201 | ItemKind::Use(..) => {
1204 "compute_type_of_item: unexpected item type: {:?}",
1211 Node::ForeignItem(foreign_item) => match foreign_item.node {
1212 ForeignItemKind::Fn(..) => {
1213 let substs = Substs::identity_for_item(tcx, def_id);
1214 tcx.mk_fn_def(def_id, substs)
1216 ForeignItemKind::Static(ref t, _) => icx.to_ty(t),
1217 ForeignItemKind::Type => tcx.mk_foreign(def_id),
1220 Node::StructCtor(&ref def)
1221 | Node::Variant(&Spanned {
1222 node: hir::VariantKind { data: ref def, .. },
1225 VariantData::Unit(..) | VariantData::Struct(..) => {
1226 tcx.type_of(tcx.hir.get_parent_did(node_id))
1228 VariantData::Tuple(..) => {
1229 let substs = Substs::identity_for_item(tcx, def_id);
1230 tcx.mk_fn_def(def_id, substs)
1234 Node::Field(field) => icx.to_ty(&field.ty),
1236 Node::Expr(&hir::Expr {
1237 node: hir::ExprKind::Closure(.., gen),
1241 let hir_id = tcx.hir.node_to_hir_id(node_id);
1242 return tcx.typeck_tables_of(def_id).node_id_to_type(hir_id);
1245 let substs = ty::ClosureSubsts {
1246 substs: Substs::identity_for_item(tcx, def_id),
1249 tcx.mk_closure(def_id, substs)
1252 Node::AnonConst(_) => match tcx.hir.get(tcx.hir.get_parent_node(node_id)) {
1254 node: hir::TyKind::Array(_, ref constant),
1257 | Node::Ty(&hir::Ty {
1258 node: hir::TyKind::Typeof(ref constant),
1261 | Node::Expr(&hir::Expr {
1262 node: ExprKind::Repeat(_, ref constant),
1264 }) if constant.id == node_id =>
1269 Node::Variant(&Spanned {
1272 disr_expr: Some(ref e),
1276 }) if e.id == node_id =>
1278 tcx.adt_def(tcx.hir.get_parent_did(node_id))
1285 bug!("unexpected const parent in type_of_def_id(): {:?}", x);
1289 Node::GenericParam(param) => match param.kind {
1290 hir::GenericParamKind::Type {
1291 default: Some(ref ty),
1294 _ => bug!("unexpected non-type NodeGenericParam"),
1298 bug!("unexpected sort of node in type_of_def_id(): {:?}", x);
1303 fn find_existential_constraints<'a, 'tcx>(
1304 tcx: TyCtxt<'a, 'tcx, 'tcx>,
1309 struct ConstraintLocator<'a, 'tcx: 'a> {
1310 tcx: TyCtxt<'a, 'tcx, 'tcx>,
1312 found: Option<(Span, ty::Ty<'tcx>)>,
1315 impl<'a, 'tcx> ConstraintLocator<'a, 'tcx> {
1316 fn check(&mut self, def_id: DefId) {
1317 trace!("checking {:?}", def_id);
1318 // don't try to check items that cannot possibly constrain the type
1319 if !self.tcx.has_typeck_tables(def_id) {
1320 trace!("no typeck tables for {:?}", def_id);
1325 .typeck_tables_of(def_id)
1326 .concrete_existential_types
1329 if let Some(ty) = ty {
1330 // FIXME(oli-obk): trace the actual span from inference to improve errors
1331 let span = self.tcx.def_span(def_id);
1332 if let Some((prev_span, prev_ty)) = self.found {
1334 // found different concrete types for the existential type
1335 let mut err = self.tcx.sess.struct_span_err(
1337 "defining existential type use differs from previous",
1339 err.span_note(prev_span, "previous use here");
1343 self.found = Some((span, ty));
1349 impl<'a, 'tcx> intravisit::Visitor<'tcx> for ConstraintLocator<'a, 'tcx> {
1350 fn nested_visit_map<'this>(&'this mut self) -> intravisit::NestedVisitorMap<'this, 'tcx> {
1351 intravisit::NestedVisitorMap::All(&self.tcx.hir)
1353 fn visit_item(&mut self, it: &'tcx Item) {
1354 let def_id = self.tcx.hir.local_def_id(it.id);
1355 // the existential type itself or its children are not within its reveal scope
1356 if def_id != self.def_id {
1358 intravisit::walk_item(self, it);
1361 fn visit_impl_item(&mut self, it: &'tcx ImplItem) {
1362 let def_id = self.tcx.hir.local_def_id(it.id);
1363 // the existential type itself or its children are not within its reveal scope
1364 if def_id != self.def_id {
1366 intravisit::walk_impl_item(self, it);
1369 fn visit_trait_item(&mut self, it: &'tcx TraitItem) {
1370 let def_id = self.tcx.hir.local_def_id(it.id);
1372 intravisit::walk_trait_item(self, it);
1376 let mut locator = ConstraintLocator {
1381 let node_id = tcx.hir.as_local_node_id(def_id).unwrap();
1382 let parent = tcx.hir.get_parent(node_id);
1384 trace!("parent_id: {:?}", parent);
1386 if parent == ast::CRATE_NODE_ID {
1387 intravisit::walk_crate(&mut locator, tcx.hir.krate());
1389 trace!("parent: {:?}", tcx.hir.get(parent));
1390 match tcx.hir.get(parent) {
1391 Node::Item(ref it) => intravisit::walk_item(&mut locator, it),
1392 Node::ImplItem(ref it) => intravisit::walk_impl_item(&mut locator, it),
1393 Node::TraitItem(ref it) => intravisit::walk_trait_item(&mut locator, it),
1395 "{:?} is not a valid parent of an existential type item",
1401 match locator.found {
1402 Some((_, ty)) => ty,
1404 let span = tcx.def_span(def_id);
1405 tcx.sess.span_err(span, "could not find defining uses");
1411 fn fn_sig<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId) -> ty::PolyFnSig<'tcx> {
1413 use rustc::hir::Node::*;
1415 let node_id = tcx.hir.as_local_node_id(def_id).unwrap();
1417 let icx = ItemCtxt::new(tcx, def_id);
1419 match tcx.hir.get(node_id) {
1420 TraitItem(hir::TraitItem {
1421 node: TraitItemKind::Method(sig, _),
1424 | ImplItem(hir::ImplItem {
1425 node: ImplItemKind::Method(sig, _),
1427 }) => AstConv::ty_of_fn(&icx, sig.header.unsafety, sig.header.abi, &sig.decl),
1430 node: ItemKind::Fn(decl, header, _, _),
1432 }) => AstConv::ty_of_fn(&icx, header.unsafety, header.abi, decl),
1434 ForeignItem(&hir::ForeignItem {
1435 node: ForeignItemKind::Fn(ref fn_decl, _, _),
1438 let abi = tcx.hir.get_foreign_abi(node_id);
1439 compute_sig_of_foreign_fn_decl(tcx, def_id, fn_decl, abi)
1442 StructCtor(&VariantData::Tuple(ref fields, _))
1443 | Variant(&Spanned {
1446 data: VariantData::Tuple(ref fields, _),
1451 let ty = tcx.type_of(tcx.hir.get_parent_did(node_id));
1454 .map(|f| tcx.type_of(tcx.hir.local_def_id(f.id)));
1455 ty::Binder::bind(tcx.mk_fn_sig(
1459 hir::Unsafety::Normal,
1465 node: hir::ExprKind::Closure(..),
1468 // Closure signatures are not like other function
1469 // signatures and cannot be accessed through `fn_sig`. For
1470 // example, a closure signature excludes the `self`
1471 // argument. In any case they are embedded within the
1472 // closure type as part of the `ClosureSubsts`.
1475 // the signature of a closure, you should use the
1476 // `closure_sig` method on the `ClosureSubsts`:
1478 // closure_substs.closure_sig(def_id, tcx)
1480 // or, inside of an inference context, you can use
1482 // infcx.closure_sig(def_id, closure_substs)
1483 bug!("to get the signature of a closure, use `closure_sig()` not `fn_sig()`");
1487 bug!("unexpected sort of node in fn_sig(): {:?}", x);
1492 fn impl_trait_ref<'a, 'tcx>(
1493 tcx: TyCtxt<'a, 'tcx, 'tcx>,
1495 ) -> Option<ty::TraitRef<'tcx>> {
1496 let icx = ItemCtxt::new(tcx, def_id);
1498 let node_id = tcx.hir.as_local_node_id(def_id).unwrap();
1499 match tcx.hir.expect_item(node_id).node {
1500 hir::ItemKind::Impl(.., ref opt_trait_ref, _, _) => {
1501 opt_trait_ref.as_ref().map(|ast_trait_ref| {
1502 let selfty = tcx.type_of(def_id);
1503 AstConv::instantiate_mono_trait_ref(&icx, ast_trait_ref, selfty)
1510 fn impl_polarity<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId) -> hir::ImplPolarity {
1511 let node_id = tcx.hir.as_local_node_id(def_id).unwrap();
1512 match tcx.hir.expect_item(node_id).node {
1513 hir::ItemKind::Impl(_, polarity, ..) => polarity,
1514 ref item => bug!("impl_polarity: {:?} not an impl", item),
1518 // Is it marked with ?Sized
1519 fn is_unsized<'gcx: 'tcx, 'tcx>(
1520 astconv: &dyn AstConv<'gcx, 'tcx>,
1521 ast_bounds: &[hir::GenericBound],
1524 let tcx = astconv.tcx();
1526 // Try to find an unbound in bounds.
1527 let mut unbound = None;
1528 for ab in ast_bounds {
1529 if let &hir::GenericBound::Trait(ref ptr, hir::TraitBoundModifier::Maybe) = ab {
1530 if unbound.is_none() {
1531 unbound = Some(ptr.trait_ref.clone());
1537 "type parameter has more than one relaxed default \
1538 bound, only one is supported"
1544 let kind_id = tcx.lang_items().require(SizedTraitLangItem);
1547 // FIXME(#8559) currently requires the unbound to be built-in.
1548 if let Ok(kind_id) = kind_id {
1549 if tpb.path.def != Def::Trait(kind_id) {
1552 "default bound relaxed for a type parameter, but \
1553 this does nothing because the given bound is not \
1554 a default. Only `?Sized` is supported",
1559 _ if kind_id.is_ok() => {
1562 // No lang item for Sized, so we can't add it as a bound.
1569 /// Returns the early-bound lifetimes declared in this generics
1570 /// listing. For anything other than fns/methods, this is just all
1571 /// the lifetimes that are declared. For fns or methods, we have to
1572 /// screen out those that do not appear in any where-clauses etc using
1573 /// `resolve_lifetime::early_bound_lifetimes`.
1574 fn early_bound_lifetimes_from_generics<'a, 'tcx>(
1575 tcx: TyCtxt<'a, 'tcx, 'tcx>,
1576 generics: &'a hir::Generics,
1577 ) -> impl Iterator<Item = &'a hir::GenericParam> + Captures<'tcx> {
1581 .filter(move |param| match param.kind {
1582 GenericParamKind::Lifetime { .. } => {
1583 let hir_id = tcx.hir.node_to_hir_id(param.id);
1584 !tcx.is_late_bound(hir_id)
1590 fn predicates_defined_on<'a, 'tcx>(
1591 tcx: TyCtxt<'a, 'tcx, 'tcx>,
1593 ) -> ty::GenericPredicates<'tcx> {
1594 let explicit = tcx.explicit_predicates_of(def_id);
1595 let span = tcx.def_span(def_id);
1596 let predicates = explicit.predicates.into_iter().chain(
1597 tcx.inferred_outlives_of(def_id).iter().map(|&p| (p, span))
1600 ty::GenericPredicates {
1601 parent: explicit.parent,
1602 predicates: predicates,
1606 fn predicates_of<'a, 'tcx>(
1607 tcx: TyCtxt<'a, 'tcx, 'tcx>,
1609 ) -> ty::GenericPredicates<'tcx> {
1610 let ty::GenericPredicates {
1613 } = tcx.predicates_defined_on(def_id);
1615 if tcx.is_trait(def_id) {
1616 // For traits, add `Self: Trait` predicate. This is
1617 // not part of the predicates that a user writes, but it
1618 // is something that one must prove in order to invoke a
1619 // method or project an associated type.
1621 // In the chalk setup, this predicate is not part of the
1622 // "predicates" for a trait item. But it is useful in
1623 // rustc because if you directly (e.g.) invoke a trait
1624 // method like `Trait::method(...)`, you must naturally
1625 // prove that the trait applies to the types that were
1626 // used, and adding the predicate into this list ensures
1627 // that this is done.
1628 let span = tcx.def_span(def_id);
1629 predicates.push((ty::TraitRef::identity(tcx, def_id).to_predicate(), span));
1632 ty::GenericPredicates { parent, predicates }
1635 fn explicit_predicates_of<'a, 'tcx>(
1636 tcx: TyCtxt<'a, 'tcx, 'tcx>,
1638 ) -> ty::GenericPredicates<'tcx> {
1640 use rustc_data_structures::fx::FxHashSet;
1642 debug!("explicit_predicates_of(def_id={:?})", def_id);
1644 /// A data structure with unique elements, which preserves order of insertion.
1645 /// Preserving the order of insertion is important here so as not to break
1646 /// compile-fail UI tests.
1647 struct UniquePredicates<'tcx> {
1648 predicates: Vec<(ty::Predicate<'tcx>, Span)>,
1649 uniques: FxHashSet<(ty::Predicate<'tcx>, Span)>,
1652 impl<'tcx> UniquePredicates<'tcx> {
1656 uniques: FxHashSet::default(),
1660 fn push(&mut self, value: (ty::Predicate<'tcx>, Span)) {
1661 if self.uniques.insert(value) {
1662 self.predicates.push(value);
1666 fn extend<I: IntoIterator<Item = (ty::Predicate<'tcx>, Span)>>(&mut self, iter: I) {
1673 let node_id = tcx.hir.as_local_node_id(def_id).unwrap();
1674 let node = tcx.hir.get(node_id);
1676 let mut is_trait = None;
1677 let mut is_default_impl_trait = None;
1679 let icx = ItemCtxt::new(tcx, def_id);
1680 let no_generics = hir::Generics::empty();
1682 let mut predicates = UniquePredicates::new();
1684 let ast_generics = match node {
1685 Node::TraitItem(item) => &item.generics,
1687 Node::ImplItem(item) => match item.node {
1688 ImplItemKind::Existential(ref bounds) => {
1689 let substs = Substs::identity_for_item(tcx, def_id);
1690 let opaque_ty = tcx.mk_opaque(def_id, substs);
1692 // Collect the bounds, i.e. the `A+B+'c` in `impl A+B+'c`.
1693 let bounds = compute_bounds(
1697 SizedByDefault::Yes,
1698 tcx.def_span(def_id),
1701 predicates.extend(bounds.predicates(tcx, opaque_ty));
1704 _ => &item.generics,
1707 Node::Item(item) => {
1709 ItemKind::Impl(_, _, defaultness, ref generics, ..) => {
1710 if defaultness.is_default() {
1711 is_default_impl_trait = tcx.impl_trait_ref(def_id);
1715 ItemKind::Fn(.., ref generics, _)
1716 | ItemKind::Ty(_, ref generics)
1717 | ItemKind::Enum(_, ref generics)
1718 | ItemKind::Struct(_, ref generics)
1719 | ItemKind::Union(_, ref generics) => generics,
1721 ItemKind::Trait(_, _, ref generics, .., ref items) => {
1722 is_trait = Some((ty::TraitRef::identity(tcx, def_id), items));
1725 ItemKind::Existential(ExistTy {
1730 let substs = Substs::identity_for_item(tcx, def_id);
1731 let opaque_ty = tcx.mk_opaque(def_id, substs);
1733 // Collect the bounds, i.e. the `A+B+'c` in `impl A+B+'c`.
1734 let bounds = compute_bounds(
1738 SizedByDefault::Yes,
1739 tcx.def_span(def_id),
1742 if impl_trait_fn.is_some() {
1744 return ty::GenericPredicates {
1746 predicates: bounds.predicates(tcx, opaque_ty),
1749 // named existential types
1750 predicates.extend(bounds.predicates(tcx, opaque_ty));
1759 Node::ForeignItem(item) => match item.node {
1760 ForeignItemKind::Static(..) => &no_generics,
1761 ForeignItemKind::Fn(_, _, ref generics) => generics,
1762 ForeignItemKind::Type => &no_generics,
1768 let generics = tcx.generics_of(def_id);
1769 let parent_count = generics.parent_count as u32;
1770 let has_own_self = generics.has_self && parent_count == 0;
1772 // Below we'll consider the bounds on the type parameters (including `Self`)
1773 // and the explicit where-clauses, but to get the full set of predicates
1774 // on a trait we need to add in the supertrait bounds and bounds found on
1775 // associated types.
1776 if let Some((_trait_ref, _)) = is_trait {
1777 predicates.extend(tcx.super_predicates_of(def_id).predicates);
1780 // In default impls, we can assume that the self type implements
1781 // the trait. So in:
1783 // default impl Foo for Bar { .. }
1785 // we add a default where clause `Foo: Bar`. We do a similar thing for traits
1786 // (see below). Recall that a default impl is not itself an impl, but rather a
1787 // set of defaults that can be incorporated into another impl.
1788 if let Some(trait_ref) = is_default_impl_trait {
1789 predicates.push((trait_ref.to_poly_trait_ref().to_predicate(), tcx.def_span(def_id)));
1792 // Collect the region predicates that were declared inline as
1793 // well. In the case of parameters declared on a fn or method, we
1794 // have to be careful to only iterate over early-bound regions.
1795 let mut index = parent_count + has_own_self as u32;
1796 for param in early_bound_lifetimes_from_generics(tcx, ast_generics) {
1797 let region = tcx.mk_region(ty::ReEarlyBound(ty::EarlyBoundRegion {
1798 def_id: tcx.hir.local_def_id(param.id),
1800 name: param.name.ident().as_interned_str(),
1805 GenericParamKind::Lifetime { .. } => {
1806 param.bounds.iter().for_each(|bound| match bound {
1807 hir::GenericBound::Outlives(lt) => {
1808 let bound = AstConv::ast_region_to_region(&icx, <, None);
1809 let outlives = ty::Binder::bind(ty::OutlivesPredicate(region, bound));
1810 predicates.push((outlives.to_predicate(), lt.span));
1819 // Collect the predicates that were written inline by the user on each
1820 // type parameter (e.g., `<T:Foo>`).
1821 for param in &ast_generics.params {
1822 if let GenericParamKind::Type { .. } = param.kind {
1823 let name = param.name.ident().as_interned_str();
1824 let param_ty = ty::ParamTy::new(index, name).to_ty(tcx);
1827 let sized = SizedByDefault::Yes;
1828 let bounds = compute_bounds(&icx, param_ty, ¶m.bounds, sized, param.span);
1829 predicates.extend(bounds.predicates(tcx, param_ty));
1833 // Add in the bounds that appear in the where-clause
1834 let where_clause = &ast_generics.where_clause;
1835 for predicate in &where_clause.predicates {
1837 &hir::WherePredicate::BoundPredicate(ref bound_pred) => {
1838 let ty = icx.to_ty(&bound_pred.bounded_ty);
1840 // Keep the type around in a WF predicate, in case of no bounds.
1841 // That way, `where Ty:` is not a complete noop (see #53696).
1842 if bound_pred.bounds.is_empty() {
1843 if let ty::Param(_) = ty.sty {
1844 // This is a `where T:`, which can be in the HIR from the
1845 // transformation that moves `?Sized` to `T`'s declaration.
1846 // We can skip the predicate because type parameters are
1847 // trivially WF, but also we *should*, to avoid exposing
1848 // users who never wrote `where Type:,` themselves, to
1849 // compiler/tooling bugs from not handling WF predicates.
1851 let span = bound_pred.bounded_ty.span;
1852 predicates.push((ty::Predicate::WellFormed(ty), span));
1856 for bound in bound_pred.bounds.iter() {
1858 &hir::GenericBound::Trait(ref poly_trait_ref, _) => {
1859 let mut projections = Vec::new();
1861 let trait_ref = AstConv::instantiate_poly_trait_ref(
1869 iter::once((trait_ref.to_predicate(), poly_trait_ref.span)).chain(
1870 projections.iter().map(|&(p, span)| (p.to_predicate(), span)
1874 &hir::GenericBound::Outlives(ref lifetime) => {
1875 let region = AstConv::ast_region_to_region(&icx, lifetime, None);
1876 let pred = ty::Binder::bind(ty::OutlivesPredicate(ty, region));
1877 predicates.push((ty::Predicate::TypeOutlives(pred), lifetime.span))
1883 &hir::WherePredicate::RegionPredicate(ref region_pred) => {
1884 let r1 = AstConv::ast_region_to_region(&icx, ®ion_pred.lifetime, None);
1885 predicates.extend(region_pred.bounds.iter().map(|bound| {
1886 let (r2, span) = match bound {
1887 hir::GenericBound::Outlives(lt) => {
1888 (AstConv::ast_region_to_region(&icx, lt, None), lt.span)
1892 let pred = ty::Binder::bind(ty::OutlivesPredicate(r1, r2));
1894 (ty::Predicate::RegionOutlives(pred), span)
1898 &hir::WherePredicate::EqPredicate(..) => {
1904 // Add predicates from associated type bounds.
1905 if let Some((self_trait_ref, trait_items)) = is_trait {
1906 predicates.extend(trait_items.iter().flat_map(|trait_item_ref| {
1907 let trait_item = tcx.hir.trait_item(trait_item_ref.id);
1908 let bounds = match trait_item.node {
1909 hir::TraitItemKind::Type(ref bounds, _) => bounds,
1910 _ => return vec![].into_iter()
1914 tcx.mk_projection(tcx.hir.local_def_id(trait_item.id), self_trait_ref.substs);
1916 let bounds = compute_bounds(
1917 &ItemCtxt::new(tcx, def_id),
1920 SizedByDefault::Yes,
1924 bounds.predicates(tcx, assoc_ty).into_iter()
1928 let mut predicates = predicates.predicates;
1930 // Subtle: before we store the predicates into the tcx, we
1931 // sort them so that predicates like `T: Foo<Item=U>` come
1932 // before uses of `U`. This avoids false ambiguity errors
1933 // in trait checking. See `setup_constraining_predicates`
1935 if let Node::Item(&Item {
1936 node: ItemKind::Impl(..),
1940 let self_ty = tcx.type_of(def_id);
1941 let trait_ref = tcx.impl_trait_ref(def_id);
1942 ctp::setup_constraining_predicates(
1946 &mut ctp::parameters_for_impl(self_ty, trait_ref),
1950 ty::GenericPredicates {
1951 parent: generics.parent,
1956 pub enum SizedByDefault {
1961 /// Translate the AST's notion of ty param bounds (which are an enum consisting of a newtyped Ty or
1962 /// a region) to ty's notion of ty param bounds, which can either be user-defined traits, or the
1963 /// built-in trait (formerly known as kind): Send.
1964 pub fn compute_bounds<'gcx: 'tcx, 'tcx>(
1965 astconv: &dyn AstConv<'gcx, 'tcx>,
1967 ast_bounds: &[hir::GenericBound],
1968 sized_by_default: SizedByDefault,
1971 let mut region_bounds = vec![];
1972 let mut trait_bounds = vec![];
1974 for ast_bound in ast_bounds {
1976 hir::GenericBound::Trait(ref b, hir::TraitBoundModifier::None) => trait_bounds.push(b),
1977 hir::GenericBound::Trait(_, hir::TraitBoundModifier::Maybe) => {}
1978 hir::GenericBound::Outlives(ref l) => region_bounds.push(l),
1982 let mut projection_bounds = vec![];
1984 let mut trait_bounds: Vec<_> = trait_bounds.iter().map(|&bound| {
1985 (astconv.instantiate_poly_trait_ref(bound, param_ty, &mut projection_bounds), bound.span)
1988 let region_bounds = region_bounds
1990 .map(|r| (astconv.ast_region_to_region(r, None), r.span))
1993 trait_bounds.sort_by_key(|(t, _)| t.def_id());
1995 let implicitly_sized = if let SizedByDefault::Yes = sized_by_default {
1996 if !is_unsized(astconv, ast_bounds, span) {
2013 /// Converts a specific GenericBound from the AST into a set of
2014 /// predicates that apply to the self-type. A vector is returned
2015 /// because this can be anywhere from 0 predicates (`T:?Sized` adds no
2016 /// predicates) to 1 (`T:Foo`) to many (`T:Bar<X=i32>` adds `T:Bar`
2017 /// and `<T as Bar>::X == i32`).
2018 fn predicates_from_bound<'tcx>(
2019 astconv: &dyn AstConv<'tcx, 'tcx>,
2021 bound: &hir::GenericBound,
2022 ) -> Vec<(ty::Predicate<'tcx>, Span)> {
2024 hir::GenericBound::Trait(ref tr, hir::TraitBoundModifier::None) => {
2025 let mut projections = Vec::new();
2026 let pred = astconv.instantiate_poly_trait_ref(tr, param_ty, &mut projections);
2027 iter::once((pred.to_predicate(), tr.span)).chain(
2030 .map(|(p, span)| (p.to_predicate(), span))
2033 hir::GenericBound::Outlives(ref lifetime) => {
2034 let region = astconv.ast_region_to_region(lifetime, None);
2035 let pred = ty::Binder::bind(ty::OutlivesPredicate(param_ty, region));
2036 vec![(ty::Predicate::TypeOutlives(pred), lifetime.span)]
2038 hir::GenericBound::Trait(_, hir::TraitBoundModifier::Maybe) => vec![],
2042 fn compute_sig_of_foreign_fn_decl<'a, 'tcx>(
2043 tcx: TyCtxt<'a, 'tcx, 'tcx>,
2047 ) -> ty::PolyFnSig<'tcx> {
2048 let unsafety = if abi == abi::Abi::RustIntrinsic {
2049 match &*tcx.item_name(def_id).as_str() {
2050 "size_of" | "min_align_of" | "needs_drop" => hir::Unsafety::Normal,
2051 _ => hir::Unsafety::Unsafe,
2054 hir::Unsafety::Unsafe
2056 let fty = AstConv::ty_of_fn(&ItemCtxt::new(tcx, def_id), unsafety, abi, decl);
2058 // feature gate SIMD types in FFI, since I (huonw) am not sure the
2059 // ABIs are handled at all correctly.
2060 if abi != abi::Abi::RustIntrinsic
2061 && abi != abi::Abi::PlatformIntrinsic
2062 && !tcx.features().simd_ffi
2064 let check = |ast_ty: &hir::Ty, ty: Ty| {
2070 "use of SIMD type `{}` in FFI is highly experimental and \
2071 may result in invalid code",
2072 tcx.hir.node_to_pretty_string(ast_ty.id)
2075 .help("add #![feature(simd_ffi)] to the crate attributes to enable")
2079 for (input, ty) in decl.inputs.iter().zip(*fty.inputs().skip_binder()) {
2082 if let hir::Return(ref ty) = decl.output {
2083 check(&ty, *fty.output().skip_binder())
2090 fn is_foreign_item<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId) -> bool {
2091 match tcx.hir.get_if_local(def_id) {
2092 Some(Node::ForeignItem(..)) => true,
2094 _ => bug!("is_foreign_item applied to non-local def-id {:?}", def_id),
2098 fn from_target_feature(
2101 attr: &ast::Attribute,
2102 whitelist: &FxHashMap<String, Option<String>>,
2103 target_features: &mut Vec<Symbol>,
2105 let list = match attr.meta_item_list() {
2108 let msg = "#[target_feature] attribute must be of the form \
2109 #[target_feature(..)]";
2110 tcx.sess.span_err(attr.span, &msg);
2114 let rust_features = tcx.features();
2116 // Only `enable = ...` is accepted in the meta item list
2117 if !item.check_name("enable") {
2118 let msg = "#[target_feature(..)] only accepts sub-keys of `enable` \
2120 tcx.sess.span_err(item.span, &msg);
2124 // Must be of the form `enable = "..."` ( a string)
2125 let value = match item.value_str() {
2126 Some(value) => value,
2128 let msg = "#[target_feature] attribute must be of the form \
2129 #[target_feature(enable = \"..\")]";
2130 tcx.sess.span_err(item.span, &msg);
2135 // We allow comma separation to enable multiple features
2136 target_features.extend(value.as_str().split(',').filter_map(|feature| {
2137 // Only allow whitelisted features per platform
2138 let feature_gate = match whitelist.get(feature) {
2142 "the feature named `{}` is not valid for \
2146 let mut err = tcx.sess.struct_span_err(item.span, &msg);
2148 if feature.starts_with("+") {
2149 let valid = whitelist.contains_key(&feature[1..]);
2151 err.help("consider removing the leading `+` in the feature name");
2159 // Only allow features whose feature gates have been enabled
2160 let allowed = match feature_gate.as_ref().map(|s| &**s) {
2161 Some("arm_target_feature") => rust_features.arm_target_feature,
2162 Some("aarch64_target_feature") => rust_features.aarch64_target_feature,
2163 Some("hexagon_target_feature") => rust_features.hexagon_target_feature,
2164 Some("powerpc_target_feature") => rust_features.powerpc_target_feature,
2165 Some("mips_target_feature") => rust_features.mips_target_feature,
2166 Some("avx512_target_feature") => rust_features.avx512_target_feature,
2167 Some("mmx_target_feature") => rust_features.mmx_target_feature,
2168 Some("sse4a_target_feature") => rust_features.sse4a_target_feature,
2169 Some("tbm_target_feature") => rust_features.tbm_target_feature,
2170 Some("wasm_target_feature") => rust_features.wasm_target_feature,
2171 Some(name) => bug!("unknown target feature gate {}", name),
2174 if !allowed && id.is_local() {
2175 feature_gate::emit_feature_err(
2176 &tcx.sess.parse_sess,
2177 feature_gate.as_ref().unwrap(),
2179 feature_gate::GateIssue::Language,
2180 &format!("the target feature `{}` is currently unstable", feature),
2184 Some(Symbol::intern(feature))
2189 fn linkage_by_name<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId, name: &str) -> Linkage {
2190 use rustc::mir::mono::Linkage::*;
2192 // Use the names from src/llvm/docs/LangRef.rst here. Most types are only
2193 // applicable to variable declarations and may not really make sense for
2194 // Rust code in the first place but whitelist them anyway and trust that
2195 // the user knows what s/he's doing. Who knows, unanticipated use cases
2196 // may pop up in the future.
2198 // ghost, dllimport, dllexport and linkonce_odr_autohide are not supported
2199 // and don't have to be, LLVM treats them as no-ops.
2201 "appending" => Appending,
2202 "available_externally" => AvailableExternally,
2204 "extern_weak" => ExternalWeak,
2205 "external" => External,
2206 "internal" => Internal,
2207 "linkonce" => LinkOnceAny,
2208 "linkonce_odr" => LinkOnceODR,
2209 "private" => Private,
2211 "weak_odr" => WeakODR,
2213 let span = tcx.hir.span_if_local(def_id);
2214 if let Some(span) = span {
2215 tcx.sess.span_fatal(span, "invalid linkage specified")
2218 .fatal(&format!("invalid linkage specified: {}", name))
2224 fn codegen_fn_attrs<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, id: DefId) -> CodegenFnAttrs {
2225 let attrs = tcx.get_attrs(id);
2227 let mut codegen_fn_attrs = CodegenFnAttrs::new();
2229 let whitelist = tcx.target_features_whitelist(LOCAL_CRATE);
2231 let mut inline_span = None;
2232 for attr in attrs.iter() {
2233 if attr.check_name("cold") {
2234 codegen_fn_attrs.flags |= CodegenFnAttrFlags::COLD;
2235 } else if attr.check_name("allocator") {
2236 codegen_fn_attrs.flags |= CodegenFnAttrFlags::ALLOCATOR;
2237 } else if attr.check_name("unwind") {
2238 codegen_fn_attrs.flags |= CodegenFnAttrFlags::UNWIND;
2239 } else if attr.check_name("rustc_allocator_nounwind") {
2240 codegen_fn_attrs.flags |= CodegenFnAttrFlags::RUSTC_ALLOCATOR_NOUNWIND;
2241 } else if attr.check_name("naked") {
2242 codegen_fn_attrs.flags |= CodegenFnAttrFlags::NAKED;
2243 } else if attr.check_name("no_mangle") {
2244 codegen_fn_attrs.flags |= CodegenFnAttrFlags::NO_MANGLE;
2245 } else if attr.check_name("rustc_std_internal_symbol") {
2246 codegen_fn_attrs.flags |= CodegenFnAttrFlags::RUSTC_STD_INTERNAL_SYMBOL;
2247 } else if attr.check_name("no_debug") {
2248 codegen_fn_attrs.flags |= CodegenFnAttrFlags::NO_DEBUG;
2249 } else if attr.check_name("used") {
2250 codegen_fn_attrs.flags |= CodegenFnAttrFlags::USED;
2251 } else if attr.check_name("thread_local") {
2252 codegen_fn_attrs.flags |= CodegenFnAttrFlags::THREAD_LOCAL;
2253 } else if attr.check_name("inline") {
2254 codegen_fn_attrs.inline = attrs.iter().fold(InlineAttr::None, |ia, attr| {
2255 if attr.path != "inline" {
2258 let meta = match attr.meta() {
2259 Some(meta) => meta.node,
2263 MetaItemKind::Word => {
2267 MetaItemKind::List(ref items) => {
2269 inline_span = Some(attr.span);
2270 if items.len() != 1 {
2272 tcx.sess.diagnostic(),
2275 "expected one argument"
2278 } else if list_contains_name(&items[..], "always") {
2280 } else if list_contains_name(&items[..], "never") {
2284 tcx.sess.diagnostic(),
2296 } else if attr.check_name("export_name") {
2297 if let Some(s) = attr.value_str() {
2298 if s.as_str().contains("\0") {
2299 // `#[export_name = ...]` will be converted to a null-terminated string,
2300 // so it may not contain any null characters.
2305 "`export_name` may not contain null characters"
2308 codegen_fn_attrs.export_name = Some(s);
2314 "`export_name` attribute has invalid format"
2315 ).span_label(attr.span, "did you mean #[export_name=\"*\"]?")
2318 } else if attr.check_name("target_feature") {
2319 if tcx.fn_sig(id).unsafety() == Unsafety::Normal {
2320 let msg = "#[target_feature(..)] can only be applied to \
2322 tcx.sess.span_err(attr.span, msg);
2324 from_target_feature(
2329 &mut codegen_fn_attrs.target_features,
2331 } else if attr.check_name("linkage") {
2332 if let Some(val) = attr.value_str() {
2333 codegen_fn_attrs.linkage = Some(linkage_by_name(tcx, id, &val.as_str()));
2335 } else if attr.check_name("link_section") {
2336 if let Some(val) = attr.value_str() {
2337 if val.as_str().bytes().any(|b| b == 0) {
2339 "illegal null byte in link_section \
2343 tcx.sess.span_err(attr.span, &msg);
2345 codegen_fn_attrs.link_section = Some(val);
2348 } else if attr.check_name("link_name") {
2349 codegen_fn_attrs.link_name = attr.value_str();
2353 // If a function uses #[target_feature] it can't be inlined into general
2354 // purpose functions as they wouldn't have the right target features
2355 // enabled. For that reason we also forbid #[inline(always)] as it can't be
2357 if codegen_fn_attrs.target_features.len() > 0 {
2358 if codegen_fn_attrs.inline == InlineAttr::Always {
2359 if let Some(span) = inline_span {
2362 "cannot use #[inline(always)] with \
2369 // Weak lang items have the same semantics as "std internal" symbols in the
2370 // sense that they're preserved through all our LTO passes and only
2371 // strippable by the linker.
2373 // Additionally weak lang items have predetermined symbol names.
2374 if tcx.is_weak_lang_item(id) {
2375 codegen_fn_attrs.flags |= CodegenFnAttrFlags::RUSTC_STD_INTERNAL_SYMBOL;
2377 if let Some(name) = weak_lang_items::link_name(&attrs) {
2378 codegen_fn_attrs.export_name = Some(name);
2379 codegen_fn_attrs.link_name = Some(name);
2382 // Internal symbols to the standard library all have no_mangle semantics in
2383 // that they have defined symbol names present in the function name. This
2384 // also applies to weak symbols where they all have known symbol names.
2385 if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::RUSTC_STD_INTERNAL_SYMBOL) {
2386 codegen_fn_attrs.flags |= CodegenFnAttrFlags::NO_MANGLE;