1 //! "Collection" is the process of determining the type and other external
2 //! details of each item in Rust. Collection is specifically concerned
3 //! with *interprocedural* things -- for example, for a function
4 //! definition, collection will figure out the type and signature of the
5 //! function, but it will not visit the *body* of the function in any way,
6 //! nor examine type annotations on local variables (that's the job of
9 //! Collecting is ultimately defined by a bundle of queries that
10 //! inquire after various facts about the items in the crate (e.g.,
11 //! `type_of`, `generics_of`, `predicates_of`, etc). See the `provide` function
14 //! At present, however, we do run collection across all items in the
15 //! crate as a kind of pass. This should eventually be factored away.
17 use crate::astconv::{AstConv, Bounds};
18 use crate::constrained_type_params as ctp;
19 use crate::check::intrinsic::intrisic_operation_unsafety;
21 use crate::middle::lang_items::SizedTraitLangItem;
22 use crate::middle::resolve_lifetime as rl;
23 use crate::middle::weak_lang_items;
24 use rustc::mir::mono::Linkage;
25 use rustc::ty::query::Providers;
26 use rustc::ty::subst::{Subst, InternalSubsts};
27 use rustc::ty::util::Discr;
28 use rustc::ty::util::IntTypeExt;
29 use rustc::ty::subst::UnpackedKind;
30 use rustc::ty::{self, AdtKind, ToPolyTraitRef, Ty, TyCtxt};
31 use rustc::ty::{ReprOptions, ToPredicate};
32 use rustc::util::captures::Captures;
33 use rustc::util::nodemap::FxHashMap;
34 use rustc_data_structures::sync::Lrc;
35 use rustc_target::spec::abi;
38 use syntax::ast::{Ident, MetaItemKind};
39 use syntax::attr::{InlineAttr, OptimizeAttr, list_contains_name, mark_used};
40 use syntax::source_map::Spanned;
41 use syntax::feature_gate;
42 use syntax::symbol::{keywords, Symbol};
43 use syntax_pos::{Span, DUMMY_SP};
45 use rustc::hir::def::{CtorKind, Def};
47 use rustc::hir::def_id::{DefId, LOCAL_CRATE};
48 use rustc::hir::intravisit::{self, NestedVisitorMap, Visitor};
49 use rustc::hir::GenericParamKind;
50 use rustc::hir::{self, CodegenFnAttrFlags, CodegenFnAttrs, Unsafety};
54 struct OnlySelfBounds(bool);
56 ///////////////////////////////////////////////////////////////////////////
59 fn collect_mod_item_types<'tcx>(tcx: TyCtxt<'_, 'tcx, 'tcx>, module_def_id: DefId) {
60 tcx.hir().visit_item_likes_in_module(
62 &mut CollectItemTypesVisitor { tcx }.as_deep_visitor()
66 pub fn provide(providers: &mut Providers<'_>) {
67 *providers = Providers {
71 predicates_defined_on,
72 explicit_predicates_of,
74 type_param_predicates,
82 collect_mod_item_types,
87 ///////////////////////////////////////////////////////////////////////////
89 /// Context specific to some particular item. This is what implements
90 /// `AstConv`. It has information about the predicates that are defined
91 /// on the trait. Unfortunately, this predicate information is
92 /// available in various different forms at various points in the
93 /// process. So we can't just store a pointer to e.g., the AST or the
94 /// parsed ty form, we have to be more flexible. To this end, the
95 /// `ItemCtxt` is parameterized by a `DefId` that it uses to satisfy
96 /// `get_type_parameter_bounds` requests, drawing the information from
97 /// the AST (`hir::Generics`), recursively.
98 pub struct ItemCtxt<'a, 'tcx: 'a> {
99 tcx: TyCtxt<'a, 'tcx, 'tcx>,
103 ///////////////////////////////////////////////////////////////////////////
105 struct CollectItemTypesVisitor<'a, 'tcx: 'a> {
106 tcx: TyCtxt<'a, 'tcx, 'tcx>,
109 impl<'a, 'tcx> Visitor<'tcx> for CollectItemTypesVisitor<'a, 'tcx> {
110 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
111 NestedVisitorMap::OnlyBodies(&self.tcx.hir())
114 fn visit_item(&mut self, item: &'tcx hir::Item) {
115 convert_item(self.tcx, item.hir_id);
116 intravisit::walk_item(self, item);
119 fn visit_generics(&mut self, generics: &'tcx hir::Generics) {
120 for param in &generics.params {
122 hir::GenericParamKind::Lifetime { .. } => {}
123 hir::GenericParamKind::Type {
126 let def_id = self.tcx.hir().local_def_id_from_hir_id(param.hir_id);
127 self.tcx.type_of(def_id);
129 hir::GenericParamKind::Type { .. } => {}
130 hir::GenericParamKind::Const { .. } => {
131 let def_id = self.tcx.hir().local_def_id_from_hir_id(param.hir_id);
132 self.tcx.type_of(def_id);
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_from_hir_id(expr.hir_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.hir_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.hir_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)
180 -> Lrc<ty::GenericPredicates<'tcx>> {
183 .type_param_predicates((self.item_def_id, def_id))
189 _def: Option<&ty::GenericParamDef>,
190 ) -> Option<ty::Region<'tcx>> {
194 fn ty_infer(&self, span: Span) -> Ty<'tcx> {
199 "the type placeholder `_` is not allowed within types on item signatures"
200 ).span_label(span, "not allowed in type signatures")
206 fn projected_ty_from_poly_trait_ref(
210 poly_trait_ref: ty::PolyTraitRef<'tcx>,
212 if let Some(trait_ref) = poly_trait_ref.no_bound_vars() {
213 self.tcx().mk_projection(item_def_id, trait_ref.substs)
215 // no late-bound regions, we can just ignore the binder
220 "cannot extract an associated type from a higher-ranked trait bound \
227 fn normalize_ty(&self, _span: Span, ty: Ty<'tcx>) -> Ty<'tcx> {
228 // types in item signatures are not normalized, to avoid undue
233 fn set_tainted_by_errors(&self) {
234 // no obvious place to track this, just let it go
237 fn record_ty(&self, _hir_id: hir::HirId, _ty: Ty<'tcx>, _span: Span) {
238 // no place to record types from signatures?
242 fn type_param_predicates<'a, 'tcx>(
243 tcx: TyCtxt<'a, 'tcx, 'tcx>,
244 (item_def_id, def_id): (DefId, DefId),
245 ) -> Lrc<ty::GenericPredicates<'tcx>> {
248 // In the AST, bounds can derive from two places. Either
249 // written inline like `<T : Foo>` or in a where clause like
252 let param_id = tcx.hir().as_local_hir_id(def_id).unwrap();
253 let param_owner = tcx.hir().ty_param_owner(param_id);
254 let param_owner_def_id = tcx.hir().local_def_id_from_hir_id(param_owner);
255 let generics = tcx.generics_of(param_owner_def_id);
256 let index = generics.param_def_id_to_index[&def_id];
257 let ty = tcx.mk_ty_param(index, tcx.hir().ty_param_name(param_id).as_interned_str());
259 // Don't look for bounds where the type parameter isn't in scope.
260 let parent = if item_def_id == param_owner_def_id {
263 tcx.generics_of(item_def_id).parent
266 let mut result = parent.map_or_else(
267 || Lrc::new(ty::GenericPredicates {
272 let icx = ItemCtxt::new(tcx, parent);
273 icx.get_type_parameter_bounds(DUMMY_SP, def_id)
277 let item_hir_id = tcx.hir().as_local_hir_id(item_def_id).unwrap();
278 let ast_generics = match tcx.hir().get_by_hir_id(item_hir_id) {
279 Node::TraitItem(item) => &item.generics,
281 Node::ImplItem(item) => &item.generics,
283 Node::Item(item) => {
285 ItemKind::Fn(.., ref generics, _)
286 | ItemKind::Impl(_, _, _, ref generics, ..)
287 | ItemKind::Ty(_, ref generics)
288 | ItemKind::Existential(ExistTy {
293 | ItemKind::Enum(_, ref generics)
294 | ItemKind::Struct(_, ref generics)
295 | ItemKind::Union(_, ref generics) => generics,
296 ItemKind::Trait(_, _, ref generics, ..) => {
297 // Implied `Self: Trait` and supertrait bounds.
298 if param_id == item_hir_id {
299 let identity_trait_ref = ty::TraitRef::identity(tcx, item_def_id);
300 Lrc::make_mut(&mut result)
302 .push((identity_trait_ref.to_predicate(), item.span));
310 Node::ForeignItem(item) => match item.node {
311 ForeignItemKind::Fn(_, _, ref generics) => generics,
318 let icx = ItemCtxt::new(tcx, item_def_id);
319 Lrc::make_mut(&mut result)
321 .extend(icx.type_parameter_bounds_in_generics(ast_generics, param_id, ty,
322 OnlySelfBounds(true)));
326 impl<'a, 'tcx> ItemCtxt<'a, 'tcx> {
327 /// Finds bounds from `hir::Generics`. This requires scanning through the
328 /// AST. We do this to avoid having to convert *all* the bounds, which
329 /// would create artificial cycles. Instead we can only convert the
330 /// bounds for a type parameter `X` if `X::Foo` is used.
331 fn type_parameter_bounds_in_generics(
333 ast_generics: &hir::Generics,
334 param_id: hir::HirId,
336 only_self_bounds: OnlySelfBounds,
337 ) -> Vec<(ty::Predicate<'tcx>, Span)> {
338 let from_ty_params = ast_generics
341 .filter_map(|param| match param.kind {
342 GenericParamKind::Type { .. } if param.hir_id == param_id => Some(¶m.bounds),
345 .flat_map(|bounds| bounds.iter())
346 .flat_map(|b| predicates_from_bound(self, ty, b));
348 let from_where_clauses = ast_generics
352 .filter_map(|wp| match *wp {
353 hir::WherePredicate::BoundPredicate(ref bp) => Some(bp),
357 let bt = if is_param(self.tcx, &bp.bounded_ty, param_id) {
359 } else if !only_self_bounds.0 {
360 Some(self.to_ty(&bp.bounded_ty))
364 bp.bounds.iter().filter_map(move |b| bt.map(|bt| (bt, b)))
366 .flat_map(|(bt, b)| predicates_from_bound(self, bt, b));
368 from_ty_params.chain(from_where_clauses).collect()
372 /// Tests whether this is the AST for a reference to the type
373 /// parameter with ID `param_id`. We use this so as to avoid running
374 /// `ast_ty_to_ty`, because we want to avoid triggering an all-out
375 /// conversion of the type to avoid inducing unnecessary cycles.
376 fn is_param<'a, 'tcx>(
377 tcx: TyCtxt<'a, 'tcx, 'tcx>,
379 param_id: hir::HirId,
381 if let hir::TyKind::Path(hir::QPath::Resolved(None, ref path)) = ast_ty.node {
383 Def::SelfTy(Some(def_id), None) | Def::TyParam(def_id) => {
384 def_id == tcx.hir().local_def_id_from_hir_id(param_id)
393 fn convert_item<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, item_id: hir::HirId) {
394 let it = tcx.hir().expect_item_by_hir_id(item_id);
395 debug!("convert: item {} with id {}", it.ident, it.hir_id);
396 let def_id = tcx.hir().local_def_id_from_hir_id(item_id);
398 // These don't define types.
399 hir::ItemKind::ExternCrate(_)
400 | hir::ItemKind::Use(..)
401 | hir::ItemKind::Mod(_)
402 | hir::ItemKind::GlobalAsm(_) => {}
403 hir::ItemKind::ForeignMod(ref foreign_mod) => {
404 for item in &foreign_mod.items {
405 let def_id = tcx.hir().local_def_id_from_hir_id(item.hir_id);
406 tcx.generics_of(def_id);
408 tcx.predicates_of(def_id);
409 if let hir::ForeignItemKind::Fn(..) = item.node {
414 hir::ItemKind::Enum(ref enum_definition, _) => {
415 tcx.generics_of(def_id);
417 tcx.predicates_of(def_id);
418 convert_enum_variant_types(tcx, def_id, &enum_definition.variants);
420 hir::ItemKind::Impl(..) => {
421 tcx.generics_of(def_id);
423 tcx.impl_trait_ref(def_id);
424 tcx.predicates_of(def_id);
426 hir::ItemKind::Trait(..) => {
427 tcx.generics_of(def_id);
428 tcx.trait_def(def_id);
429 tcx.at(it.span).super_predicates_of(def_id);
430 tcx.predicates_of(def_id);
432 hir::ItemKind::TraitAlias(..) => {
433 tcx.generics_of(def_id);
434 tcx.at(it.span).super_predicates_of(def_id);
435 tcx.predicates_of(def_id);
437 hir::ItemKind::Struct(ref struct_def, _) | hir::ItemKind::Union(ref struct_def, _) => {
438 tcx.generics_of(def_id);
440 tcx.predicates_of(def_id);
442 for f in struct_def.fields() {
443 let def_id = tcx.hir().local_def_id_from_hir_id(f.hir_id);
444 tcx.generics_of(def_id);
446 tcx.predicates_of(def_id);
449 if let Some(ctor_hir_id) = struct_def.ctor_hir_id() {
450 convert_variant_ctor(tcx, ctor_hir_id);
454 // Desugared from `impl Trait` -> visited by the function's return type
455 hir::ItemKind::Existential(hir::ExistTy {
456 impl_trait_fn: Some(_),
460 hir::ItemKind::Existential(..)
461 | hir::ItemKind::Ty(..)
462 | hir::ItemKind::Static(..)
463 | hir::ItemKind::Const(..)
464 | hir::ItemKind::Fn(..) => {
465 tcx.generics_of(def_id);
467 tcx.predicates_of(def_id);
468 if let hir::ItemKind::Fn(..) = it.node {
475 fn convert_trait_item<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, trait_item_id: hir::HirId) {
476 let trait_item = tcx.hir().expect_trait_item(trait_item_id);
477 let def_id = tcx.hir().local_def_id_from_hir_id(trait_item.hir_id);
478 tcx.generics_of(def_id);
480 match trait_item.node {
481 hir::TraitItemKind::Const(..)
482 | hir::TraitItemKind::Type(_, Some(_))
483 | hir::TraitItemKind::Method(..) => {
485 if let hir::TraitItemKind::Method(..) = trait_item.node {
490 hir::TraitItemKind::Type(_, None) => {}
493 tcx.predicates_of(def_id);
496 fn convert_impl_item<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, impl_item_id: hir::HirId) {
497 let def_id = tcx.hir().local_def_id_from_hir_id(impl_item_id);
498 tcx.generics_of(def_id);
500 tcx.predicates_of(def_id);
501 if let hir::ImplItemKind::Method(..) = tcx.hir().expect_impl_item(impl_item_id).node {
506 fn convert_variant_ctor<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, ctor_id: hir::HirId) {
507 let def_id = tcx.hir().local_def_id_from_hir_id(ctor_id);
508 tcx.generics_of(def_id);
510 tcx.predicates_of(def_id);
513 fn convert_enum_variant_types<'a, 'tcx>(
514 tcx: TyCtxt<'a, 'tcx, 'tcx>,
516 variants: &[hir::Variant],
518 let def = tcx.adt_def(def_id);
519 let repr_type = def.repr.discr_type();
520 let initial = repr_type.initial_discriminant(tcx);
521 let mut prev_discr = None::<Discr<'tcx>>;
523 // fill the discriminant values and field types
524 for variant in variants {
525 let wrapped_discr = prev_discr.map_or(initial, |d| d.wrap_incr(tcx));
527 if let Some(ref e) = variant.node.disr_expr {
528 let expr_did = tcx.hir().local_def_id_from_hir_id(e.hir_id);
529 def.eval_explicit_discr(tcx, expr_did)
530 } else if let Some(discr) = repr_type.disr_incr(tcx, prev_discr) {
537 "enum discriminant overflowed"
540 format!("overflowed on value after {}", prev_discr.unwrap()),
542 "explicitly set `{} = {}` if that is desired outcome",
543 variant.node.ident, wrapped_discr
547 }.unwrap_or(wrapped_discr),
550 for f in variant.node.data.fields() {
551 let def_id = tcx.hir().local_def_id_from_hir_id(f.hir_id);
552 tcx.generics_of(def_id);
554 tcx.predicates_of(def_id);
557 // Convert the ctor, if any. This also registers the variant as
559 if let Some(ctor_hir_id) = variant.node.data.ctor_hir_id() {
560 convert_variant_ctor(tcx, ctor_hir_id);
565 fn convert_variant<'a, 'tcx>(
566 tcx: TyCtxt<'a, 'tcx, 'tcx>,
567 variant_did: Option<DefId>,
568 ctor_did: Option<DefId>,
570 discr: ty::VariantDiscr,
571 def: &hir::VariantData,
572 adt_kind: ty::AdtKind,
574 ) -> ty::VariantDef {
575 let mut seen_fields: FxHashMap<ast::Ident, Span> = Default::default();
576 let hir_id = tcx.hir().as_local_hir_id(variant_did.unwrap_or(parent_did)).unwrap();
581 let fid = tcx.hir().local_def_id_from_hir_id(f.hir_id);
582 let dup_span = seen_fields.get(&f.ident.modern()).cloned();
583 if let Some(prev_span) = dup_span {
588 "field `{}` is already declared",
590 ).span_label(f.span, "field already declared")
591 .span_label(prev_span, format!("`{}` first declared here", f.ident))
594 seen_fields.insert(f.ident.modern(), f.span);
600 vis: ty::Visibility::from_hir(&f.vis, hir_id, tcx),
604 let recovered = match def {
605 hir::VariantData::Struct(_, r) => *r,
615 CtorKind::from_hir(def),
622 fn adt_def<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId) -> &'tcx ty::AdtDef {
625 let hir_id = tcx.hir().as_local_hir_id(def_id).unwrap();
626 let item = match tcx.hir().get_by_hir_id(hir_id) {
627 Node::Item(item) => item,
631 let repr = ReprOptions::new(tcx, def_id);
632 let (kind, variants) = match item.node {
633 ItemKind::Enum(ref def, _) => {
634 let mut distance_from_explicit = 0;
635 let variants = def.variants
638 let variant_did = Some(tcx.hir().local_def_id_from_hir_id(v.node.id));
639 let ctor_did = v.node.data.ctor_hir_id()
640 .map(|hir_id| tcx.hir().local_def_id_from_hir_id(hir_id));
642 let discr = if let Some(ref e) = v.node.disr_expr {
643 distance_from_explicit = 0;
644 ty::VariantDiscr::Explicit(tcx.hir().local_def_id_from_hir_id(e.hir_id))
646 ty::VariantDiscr::Relative(distance_from_explicit)
648 distance_from_explicit += 1;
650 convert_variant(tcx, variant_did, ctor_did, v.node.ident, discr,
651 &v.node.data, AdtKind::Enum, def_id)
655 (AdtKind::Enum, variants)
657 ItemKind::Struct(ref def, _) => {
658 let variant_did = None;
659 let ctor_did = def.ctor_hir_id()
660 .map(|hir_id| tcx.hir().local_def_id_from_hir_id(hir_id));
662 let variants = std::iter::once(convert_variant(
663 tcx, variant_did, ctor_did, item.ident, ty::VariantDiscr::Relative(0), def,
664 AdtKind::Struct, def_id,
667 (AdtKind::Struct, variants)
669 ItemKind::Union(ref def, _) => {
670 let variant_did = None;
671 let ctor_did = def.ctor_hir_id()
672 .map(|hir_id| tcx.hir().local_def_id_from_hir_id(hir_id));
674 let variants = std::iter::once(convert_variant(
675 tcx, variant_did, ctor_did, item.ident, ty::VariantDiscr::Relative(0), def,
676 AdtKind::Union, def_id,
679 (AdtKind::Union, variants)
683 tcx.alloc_adt_def(def_id, kind, variants, repr)
686 /// Ensures that the super-predicates of the trait with `DefId`
687 /// trait_def_id are converted and stored. This also ensures that
688 /// the transitive super-predicates are converted;
689 fn super_predicates_of<'a, 'tcx>(
690 tcx: TyCtxt<'a, 'tcx, 'tcx>,
692 ) -> Lrc<ty::GenericPredicates<'tcx>> {
693 debug!("super_predicates(trait_def_id={:?})", trait_def_id);
694 let trait_hir_id = tcx.hir().as_local_hir_id(trait_def_id).unwrap();
696 let item = match tcx.hir().get_by_hir_id(trait_hir_id) {
697 Node::Item(item) => item,
698 _ => bug!("trait_node_id {} is not an item", trait_hir_id),
701 let (generics, bounds) = match item.node {
702 hir::ItemKind::Trait(.., ref generics, ref supertraits, _) => (generics, supertraits),
703 hir::ItemKind::TraitAlias(ref generics, ref supertraits) => (generics, supertraits),
704 _ => span_bug!(item.span, "super_predicates invoked on non-trait"),
707 let icx = ItemCtxt::new(tcx, trait_def_id);
709 // Convert the bounds that follow the colon, e.g., `Bar + Zed` in `trait Foo : Bar + Zed`.
710 let self_param_ty = tcx.mk_self_type();
711 let superbounds1 = compute_bounds(&icx, self_param_ty, bounds, SizedByDefault::No, item.span);
713 let superbounds1 = superbounds1.predicates(tcx, self_param_ty);
715 // Convert any explicit superbounds in the where clause,
716 // e.g., `trait Foo where Self : Bar`.
717 // In the case of trait aliases, however, we include all bounds in the where clause,
718 // so e.g., `trait Foo = where u32: PartialEq<Self>` would include `u32: PartialEq<Self>`
719 // as one of its "superpredicates".
720 let is_trait_alias = tcx.is_trait_alias(trait_def_id);
721 let superbounds2 = icx.type_parameter_bounds_in_generics(
722 generics, item.hir_id, self_param_ty, OnlySelfBounds(!is_trait_alias));
724 // Combine the two lists to form the complete set of superbounds:
725 let superbounds: Vec<_> = superbounds1.into_iter().chain(superbounds2).collect();
727 // Now require that immediate supertraits are converted,
728 // which will, in turn, reach indirect supertraits.
729 for &(pred, span) in &superbounds {
730 debug!("superbound: {:?}", pred);
731 if let ty::Predicate::Trait(bound) = pred {
732 tcx.at(span).super_predicates_of(bound.def_id());
736 Lrc::new(ty::GenericPredicates {
738 predicates: superbounds,
742 fn trait_def<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId) -> &'tcx ty::TraitDef {
743 let hir_id = tcx.hir().as_local_hir_id(def_id).unwrap();
744 let item = tcx.hir().expect_item_by_hir_id(hir_id);
746 let (is_auto, unsafety) = match item.node {
747 hir::ItemKind::Trait(is_auto, unsafety, ..) => (is_auto == hir::IsAuto::Yes, unsafety),
748 hir::ItemKind::TraitAlias(..) => (false, hir::Unsafety::Normal),
749 _ => span_bug!(item.span, "trait_def_of_item invoked on non-trait"),
752 let paren_sugar = tcx.has_attr(def_id, "rustc_paren_sugar");
753 if paren_sugar && !tcx.features().unboxed_closures {
754 let mut err = tcx.sess.struct_span_err(
756 "the `#[rustc_paren_sugar]` attribute is a temporary means of controlling \
757 which traits can use parenthetical notation",
761 "add `#![feature(unboxed_closures)]` to \
762 the crate attributes to use it"
767 let is_marker = tcx.has_attr(def_id, "marker");
768 let def_path_hash = tcx.def_path_hash(def_id);
769 let def = ty::TraitDef::new(def_id, unsafety, paren_sugar, is_auto, is_marker, def_path_hash);
770 tcx.alloc_trait_def(def)
773 fn has_late_bound_regions<'a, 'tcx>(
774 tcx: TyCtxt<'a, 'tcx, 'tcx>,
777 struct LateBoundRegionsDetector<'a, 'tcx: 'a> {
778 tcx: TyCtxt<'a, 'tcx, 'tcx>,
779 outer_index: ty::DebruijnIndex,
780 has_late_bound_regions: Option<Span>,
783 impl<'a, 'tcx> Visitor<'tcx> for LateBoundRegionsDetector<'a, 'tcx> {
784 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
785 NestedVisitorMap::None
788 fn visit_ty(&mut self, ty: &'tcx hir::Ty) {
789 if self.has_late_bound_regions.is_some() {
793 hir::TyKind::BareFn(..) => {
794 self.outer_index.shift_in(1);
795 intravisit::walk_ty(self, ty);
796 self.outer_index.shift_out(1);
798 _ => intravisit::walk_ty(self, ty),
802 fn visit_poly_trait_ref(
804 tr: &'tcx hir::PolyTraitRef,
805 m: hir::TraitBoundModifier,
807 if self.has_late_bound_regions.is_some() {
810 self.outer_index.shift_in(1);
811 intravisit::walk_poly_trait_ref(self, tr, m);
812 self.outer_index.shift_out(1);
815 fn visit_lifetime(&mut self, lt: &'tcx hir::Lifetime) {
816 if self.has_late_bound_regions.is_some() {
820 match self.tcx.named_region(lt.hir_id) {
821 Some(rl::Region::Static) | Some(rl::Region::EarlyBound(..)) => {}
822 Some(rl::Region::LateBound(debruijn, _, _))
823 | Some(rl::Region::LateBoundAnon(debruijn, _)) if debruijn < self.outer_index => {}
824 Some(rl::Region::LateBound(..))
825 | Some(rl::Region::LateBoundAnon(..))
826 | Some(rl::Region::Free(..))
828 self.has_late_bound_regions = Some(lt.span);
834 fn has_late_bound_regions<'a, 'tcx>(
835 tcx: TyCtxt<'a, 'tcx, 'tcx>,
836 generics: &'tcx hir::Generics,
837 decl: &'tcx hir::FnDecl,
839 let mut visitor = LateBoundRegionsDetector {
841 outer_index: ty::INNERMOST,
842 has_late_bound_regions: None,
844 for param in &generics.params {
845 if let GenericParamKind::Lifetime { .. } = param.kind {
846 if tcx.is_late_bound(param.hir_id) {
847 return Some(param.span);
851 visitor.visit_fn_decl(decl);
852 visitor.has_late_bound_regions
856 Node::TraitItem(item) => match item.node {
857 hir::TraitItemKind::Method(ref sig, _) => {
858 has_late_bound_regions(tcx, &item.generics, &sig.decl)
862 Node::ImplItem(item) => match item.node {
863 hir::ImplItemKind::Method(ref sig, _) => {
864 has_late_bound_regions(tcx, &item.generics, &sig.decl)
868 Node::ForeignItem(item) => match item.node {
869 hir::ForeignItemKind::Fn(ref fn_decl, _, ref generics) => {
870 has_late_bound_regions(tcx, generics, fn_decl)
874 Node::Item(item) => match item.node {
875 hir::ItemKind::Fn(ref fn_decl, .., ref generics, _) => {
876 has_late_bound_regions(tcx, generics, fn_decl)
884 fn generics_of<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId) -> &'tcx ty::Generics {
887 let hir_id = tcx.hir().as_local_hir_id(def_id).unwrap();
889 let node = tcx.hir().get_by_hir_id(hir_id);
890 let parent_def_id = match node {
891 Node::ImplItem(_) | Node::TraitItem(_) | Node::Variant(_) |
892 Node::Ctor(..) | Node::Field(_) => {
893 let parent_id = tcx.hir().get_parent_item(hir_id);
894 Some(tcx.hir().local_def_id_from_hir_id(parent_id))
896 Node::Expr(&hir::Expr {
897 node: hir::ExprKind::Closure(..),
899 }) => Some(tcx.closure_base_def_id(def_id)),
900 Node::Item(item) => match item.node {
901 ItemKind::Existential(hir::ExistTy { impl_trait_fn, .. }) => impl_trait_fn,
907 let mut opt_self = None;
908 let mut allow_defaults = false;
910 let no_generics = hir::Generics::empty();
911 let ast_generics = match node {
912 Node::TraitItem(item) => &item.generics,
914 Node::ImplItem(item) => &item.generics,
916 Node::Item(item) => {
918 ItemKind::Fn(.., ref generics, _) | ItemKind::Impl(_, _, _, ref generics, ..) => {
922 ItemKind::Ty(_, ref generics)
923 | ItemKind::Enum(_, ref generics)
924 | ItemKind::Struct(_, ref generics)
925 | ItemKind::Existential(hir::ExistTy { ref generics, .. })
926 | ItemKind::Union(_, ref generics) => {
927 allow_defaults = true;
931 ItemKind::Trait(_, _, ref generics, ..)
932 | ItemKind::TraitAlias(ref generics, ..) => {
933 // Add in the self type parameter.
935 // Something of a hack: use the node id for the trait, also as
936 // the node id for the Self type parameter.
937 let param_id = item.hir_id;
939 opt_self = Some(ty::GenericParamDef {
941 name: keywords::SelfUpper.name().as_interned_str(),
942 def_id: tcx.hir().local_def_id_from_hir_id(param_id),
943 pure_wrt_drop: false,
944 kind: ty::GenericParamDefKind::Type {
946 object_lifetime_default: rl::Set1::Empty,
951 allow_defaults = true;
959 Node::ForeignItem(item) => match item.node {
960 ForeignItemKind::Static(..) => &no_generics,
961 ForeignItemKind::Fn(_, _, ref generics) => generics,
962 ForeignItemKind::Type => &no_generics,
968 let has_self = opt_self.is_some();
969 let mut parent_has_self = false;
970 let mut own_start = has_self as u32;
971 let parent_count = parent_def_id.map_or(0, |def_id| {
972 let generics = tcx.generics_of(def_id);
973 assert_eq!(has_self, false);
974 parent_has_self = generics.has_self;
975 own_start = generics.count() as u32;
976 generics.parent_count + generics.params.len()
979 let mut params: Vec<_> = opt_self.into_iter().collect();
981 let early_lifetimes = early_bound_lifetimes_from_generics(tcx, ast_generics);
985 .map(|(i, param)| ty::GenericParamDef {
986 name: param.name.ident().as_interned_str(),
987 index: own_start + i as u32,
988 def_id: tcx.hir().local_def_id_from_hir_id(param.hir_id),
989 pure_wrt_drop: param.pure_wrt_drop,
990 kind: ty::GenericParamDefKind::Lifetime,
994 let object_lifetime_defaults = tcx.object_lifetime_defaults(hir_id);
996 // Now create the real type parameters.
997 let type_start = own_start - has_self as u32 + params.len() as u32;
1003 .filter_map(|param| {
1004 let kind = match param.kind {
1005 GenericParamKind::Type {
1010 if param.name.ident().name == keywords::SelfUpper.name() {
1013 "`Self` should not be the name of a regular parameter"
1017 if !allow_defaults && default.is_some() {
1018 if !tcx.features().default_type_parameter_fallback {
1020 lint::builtin::INVALID_TYPE_PARAM_DEFAULT,
1024 "defaults for type parameters are only allowed in \
1025 `struct`, `enum`, `type`, or `trait` definitions."
1031 ty::GenericParamDefKind::Type {
1032 has_default: default.is_some(),
1033 object_lifetime_default: object_lifetime_defaults
1035 .map_or(rl::Set1::Empty, |o| o[i]),
1039 GenericParamKind::Const { .. } => {
1040 if param.name.ident().name == keywords::SelfUpper.name() {
1043 "`Self` should not be the name of a regular parameter",
1047 ty::GenericParamDefKind::Const
1052 let param_def = ty::GenericParamDef {
1053 index: type_start + i as u32,
1054 name: param.name.ident().as_interned_str(),
1055 def_id: tcx.hir().local_def_id_from_hir_id(param.hir_id),
1056 pure_wrt_drop: param.pure_wrt_drop,
1064 // provide junk type parameter defs - the only place that
1065 // cares about anything but the length is instantiation,
1066 // and we don't do that for closures.
1067 if let Node::Expr(&hir::Expr {
1068 node: hir::ExprKind::Closure(.., gen),
1072 let dummy_args = if gen.is_some() {
1073 &["<yield_ty>", "<return_ty>", "<witness>"][..]
1075 &["<closure_kind>", "<closure_signature>"][..]
1082 .map(|(i, &arg)| ty::GenericParamDef {
1083 index: type_start + i as u32,
1084 name: Symbol::intern(arg).as_interned_str(),
1086 pure_wrt_drop: false,
1087 kind: ty::GenericParamDefKind::Type {
1089 object_lifetime_default: rl::Set1::Empty,
1095 tcx.with_freevars(hir_id, |fv| {
1096 params.extend(fv.iter().zip((dummy_args.len() as u32)..).map(|(_, i)| {
1097 ty::GenericParamDef {
1098 index: type_start + i,
1099 name: Symbol::intern("<upvar>").as_interned_str(),
1101 pure_wrt_drop: false,
1102 kind: ty::GenericParamDefKind::Type {
1104 object_lifetime_default: rl::Set1::Empty,
1112 let param_def_id_to_index = params
1114 .map(|param| (param.def_id, param.index))
1117 tcx.alloc_generics(ty::Generics {
1118 parent: parent_def_id,
1121 param_def_id_to_index,
1122 has_self: has_self || parent_has_self,
1123 has_late_bound_regions: has_late_bound_regions(tcx, node),
1127 fn report_assoc_ty_on_inherent_impl<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, span: Span) {
1132 "associated types are not yet supported in inherent impls (see #8995)"
1136 fn type_of<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId) -> Ty<'tcx> {
1137 checked_type_of(tcx, def_id, true).unwrap()
1140 /// Same as [`type_of`] but returns [`Option`] instead of failing.
1142 /// If you want to fail anyway, you can set the `fail` parameter to true, but in this case,
1143 /// you'd better just call [`type_of`] directly.
1144 pub fn checked_type_of<'a, 'tcx>(
1145 tcx: TyCtxt<'a, 'tcx, 'tcx>,
1148 ) -> Option<Ty<'tcx>> {
1151 let hir_id = match tcx.hir().as_local_hir_id(def_id) {
1152 Some(hir_id) => hir_id,
1157 bug!("invalid node");
1161 let icx = ItemCtxt::new(tcx, def_id);
1163 Some(match tcx.hir().get_by_hir_id(hir_id) {
1164 Node::TraitItem(item) => match item.node {
1165 TraitItemKind::Method(..) => {
1166 let substs = InternalSubsts::identity_for_item(tcx, def_id);
1167 tcx.mk_fn_def(def_id, substs)
1169 TraitItemKind::Const(ref ty, _) | TraitItemKind::Type(_, Some(ref ty)) => icx.to_ty(ty),
1170 TraitItemKind::Type(_, None) => {
1174 span_bug!(item.span, "associated type missing default");
1178 Node::ImplItem(item) => match item.node {
1179 ImplItemKind::Method(..) => {
1180 let substs = InternalSubsts::identity_for_item(tcx, def_id);
1181 tcx.mk_fn_def(def_id, substs)
1183 ImplItemKind::Const(ref ty, _) => icx.to_ty(ty),
1184 ImplItemKind::Existential(_) => {
1186 .impl_trait_ref(tcx.hir().get_parent_did_by_hir_id(hir_id))
1189 report_assoc_ty_on_inherent_impl(tcx, item.span);
1192 find_existential_constraints(tcx, def_id)
1194 ImplItemKind::Type(ref ty) => {
1196 .impl_trait_ref(tcx.hir().get_parent_did_by_hir_id(hir_id))
1199 report_assoc_ty_on_inherent_impl(tcx, item.span);
1206 Node::Item(item) => {
1208 ItemKind::Static(ref t, ..)
1209 | ItemKind::Const(ref t, _)
1210 | ItemKind::Ty(ref t, _)
1211 | ItemKind::Impl(.., ref t, _) => icx.to_ty(t),
1212 ItemKind::Fn(..) => {
1213 let substs = InternalSubsts::identity_for_item(tcx, def_id);
1214 tcx.mk_fn_def(def_id, substs)
1216 ItemKind::Enum(..) | ItemKind::Struct(..) | ItemKind::Union(..) => {
1217 let def = tcx.adt_def(def_id);
1218 let substs = InternalSubsts::identity_for_item(tcx, def_id);
1219 tcx.mk_adt(def, substs)
1221 ItemKind::Existential(hir::ExistTy {
1222 impl_trait_fn: None,
1224 }) => find_existential_constraints(tcx, def_id),
1225 // existential types desugared from impl Trait
1226 ItemKind::Existential(hir::ExistTy {
1227 impl_trait_fn: Some(owner),
1230 tcx.typeck_tables_of(owner)
1231 .concrete_existential_types
1233 .map(|opaque| opaque.concrete_type)
1234 .unwrap_or_else(|| {
1235 // This can occur if some error in the
1236 // owner fn prevented us from populating
1237 // the `concrete_existential_types` table.
1238 tcx.sess.delay_span_bug(
1241 "owner {:?} has no existential type for {:?} in its tables",
1249 | ItemKind::TraitAlias(..)
1251 | ItemKind::ForeignMod(..)
1252 | ItemKind::GlobalAsm(..)
1253 | ItemKind::ExternCrate(..)
1254 | ItemKind::Use(..) => {
1260 "compute_type_of_item: unexpected item type: {:?}",
1267 Node::ForeignItem(foreign_item) => match foreign_item.node {
1268 ForeignItemKind::Fn(..) => {
1269 let substs = InternalSubsts::identity_for_item(tcx, def_id);
1270 tcx.mk_fn_def(def_id, substs)
1272 ForeignItemKind::Static(ref t, _) => icx.to_ty(t),
1273 ForeignItemKind::Type => tcx.mk_foreign(def_id),
1276 Node::Ctor(&ref def) | Node::Variant(&Spanned {
1277 node: hir::VariantKind { data: ref def, .. },
1280 VariantData::Unit(..) | VariantData::Struct(..) => {
1281 tcx.type_of(tcx.hir().get_parent_did_by_hir_id(hir_id))
1283 VariantData::Tuple(..) => {
1284 let substs = InternalSubsts::identity_for_item(tcx, def_id);
1285 tcx.mk_fn_def(def_id, substs)
1289 Node::Field(field) => icx.to_ty(&field.ty),
1291 Node::Expr(&hir::Expr {
1292 node: hir::ExprKind::Closure(.., gen),
1296 return Some(tcx.typeck_tables_of(def_id).node_type(hir_id));
1299 let substs = ty::ClosureSubsts {
1300 substs: InternalSubsts::identity_for_item(tcx, def_id),
1303 tcx.mk_closure(def_id, substs)
1306 Node::AnonConst(_) => {
1307 let parent_node = tcx.hir().get_by_hir_id(tcx.hir().get_parent_node_by_hir_id(hir_id));
1310 node: hir::TyKind::Array(_, ref constant),
1313 | Node::Ty(&hir::Ty {
1314 node: hir::TyKind::Typeof(ref constant),
1317 | Node::Expr(&hir::Expr {
1318 node: ExprKind::Repeat(_, ref constant),
1320 }) if constant.hir_id == hir_id =>
1325 Node::Variant(&Spanned {
1328 disr_expr: Some(ref e),
1332 }) if e.hir_id == hir_id =>
1334 tcx.adt_def(tcx.hir().get_parent_did_by_hir_id(hir_id))
1340 Node::Ty(&hir::Ty { node: hir::TyKind::Path(_), .. }) |
1341 Node::Expr(&hir::Expr { node: ExprKind::Struct(..), .. }) |
1342 Node::Expr(&hir::Expr { node: ExprKind::Path(_), .. }) => {
1343 let path = match parent_node {
1344 Node::Ty(&hir::Ty { node: hir::TyKind::Path(ref path), .. }) |
1345 Node::Expr(&hir::Expr { node: ExprKind::Path(ref path), .. }) => {
1348 Node::Expr(&hir::Expr { node: ExprKind::Struct(ref path, ..), .. }) => {
1351 _ => unreachable!(),
1355 QPath::Resolved(_, ref path) => {
1356 let mut arg_index = 0;
1357 let mut found_const = false;
1358 for seg in &path.segments {
1359 if let Some(generic_args) = &seg.args {
1360 let args = &generic_args.args;
1362 if let GenericArg::Const(ct) = arg {
1363 if ct.value.hir_id == hir_id {
1372 // Sanity check to make sure everything is as expected.
1377 bug!("no arg matching AnonConst in path")
1380 // We've encountered an `AnonConst` in some path, so we need to
1381 // figure out which generic parameter it corresponds to and return
1382 // the relevant type.
1384 | Def::Union(def_id)
1386 | Def::Fn(def_id) => {
1387 let generics = tcx.generics_of(def_id);
1388 let mut param_index = 0;
1389 for param in &generics.params {
1390 if let ty::GenericParamDefKind::Const = param.kind {
1391 if param_index == arg_index {
1392 return Some(tcx.type_of(param.def_id));
1397 // This is no generic parameter associated with the arg. This is
1398 // probably from an extra arg where one is not needed.
1399 return Some(tcx.types.err);
1401 Def::Err => tcx.types.err,
1406 bug!("unexpected const parent path def {:?}", x);
1414 bug!("unexpected const parent path {:?}", x);
1423 bug!("unexpected const parent in type_of_def_id(): {:?}", x);
1428 Node::GenericParam(param) => match ¶m.kind {
1429 hir::GenericParamKind::Type { default: Some(ref ty), .. } |
1430 hir::GenericParamKind::Const { ref ty, .. } => {
1437 bug!("unexpected non-type Node::GenericParam: {:?}", x)
1445 bug!("unexpected sort of node in type_of_def_id(): {:?}", x);
1450 fn find_existential_constraints<'a, 'tcx>(
1451 tcx: TyCtxt<'a, 'tcx, 'tcx>,
1456 struct ConstraintLocator<'a, 'tcx: 'a> {
1457 tcx: TyCtxt<'a, 'tcx, 'tcx>,
1459 // First found type span, actual type, mapping from the existential type's generic
1460 // parameters to the concrete type's generic parameters
1462 // The mapping is an index for each use site of a generic parameter in the concrete type
1464 // The indices index into the generic parameters on the existential type.
1465 found: Option<(Span, ty::Ty<'tcx>, Vec<usize>)>,
1468 impl<'a, 'tcx> ConstraintLocator<'a, 'tcx> {
1469 fn check(&mut self, def_id: DefId) {
1470 trace!("checking {:?}", def_id);
1471 // don't try to check items that cannot possibly constrain the type
1472 if !self.tcx.has_typeck_tables(def_id) {
1473 trace!("no typeck tables for {:?}", def_id);
1478 .typeck_tables_of(def_id)
1479 .concrete_existential_types
1481 if let Some(ty::ResolvedOpaqueTy { concrete_type, substs }) = ty {
1482 // FIXME(oli-obk): trace the actual span from inference to improve errors
1483 let span = self.tcx.def_span(def_id);
1484 // used to quickly look up the position of a generic parameter
1485 let mut index_map: FxHashMap<ty::ParamTy, usize> = FxHashMap::default();
1486 // skip binder is ok, since we only use this to find generic parameters and their
1488 for (idx, subst) in substs.iter().enumerate() {
1489 if let UnpackedKind::Type(ty) = subst.unpack() {
1490 if let ty::Param(p) = ty.sty {
1491 if index_map.insert(p, idx).is_some() {
1492 // there was already an entry for `p`, meaning a generic parameter
1494 self.tcx.sess.span_err(
1496 &format!("defining existential type use restricts existential \
1497 type by using the generic parameter `{}` twice", p.name),
1502 self.tcx.sess.delay_span_bug(
1505 "non-defining exist ty use in defining scope: {:?}, {:?}",
1506 concrete_type, substs,
1512 // compute the index within the existential type for each generic parameter used in
1513 // the concrete type
1514 let indices = concrete_type
1515 .subst(self.tcx, substs)
1517 .filter_map(|t| match &t.sty {
1518 ty::Param(p) => Some(*index_map.get(p).unwrap()),
1521 let is_param = |ty: ty::Ty<'_>| match ty.sty {
1522 ty::Param(_) => true,
1525 if !substs.types().all(is_param) {
1526 self.tcx.sess.span_err(
1528 "defining existential type use does not fully define existential type",
1530 } else if let Some((prev_span, prev_ty, ref prev_indices)) = self.found {
1531 let mut ty = concrete_type.walk().fuse();
1532 let mut p_ty = prev_ty.walk().fuse();
1533 let iter_eq = (&mut ty).zip(&mut p_ty).all(|(t, p)| match (&t.sty, &p.sty) {
1534 // type parameters are equal to any other type parameter for the purpose of
1535 // concrete type equality, as it is possible to obtain the same type just
1536 // by passing matching parameters to a function.
1537 (ty::Param(_), ty::Param(_)) => true,
1540 if !iter_eq || ty.next().is_some() || p_ty.next().is_some() {
1541 // found different concrete types for the existential type
1542 let mut err = self.tcx.sess.struct_span_err(
1544 "concrete type differs from previous defining existential type use",
1548 format!("expected `{}`, got `{}`", prev_ty, concrete_type),
1550 err.span_note(prev_span, "previous use here");
1552 } else if indices != *prev_indices {
1553 // found "same" concrete types, but the generic parameter order differs
1554 let mut err = self.tcx.sess.struct_span_err(
1556 "concrete type's generic parameters differ from previous defining use",
1558 use std::fmt::Write;
1559 let mut s = String::new();
1560 write!(s, "expected [").unwrap();
1561 let list = |s: &mut String, indices: &Vec<usize>| {
1562 let mut indices = indices.iter().cloned();
1563 if let Some(first) = indices.next() {
1564 write!(s, "`{}`", substs[first]).unwrap();
1566 write!(s, ", `{}`", substs[i]).unwrap();
1570 list(&mut s, prev_indices);
1571 write!(s, "], got [").unwrap();
1572 list(&mut s, &indices);
1573 write!(s, "]").unwrap();
1574 err.span_label(span, s);
1575 err.span_note(prev_span, "previous use here");
1579 self.found = Some((span, concrete_type, indices));
1585 impl<'a, 'tcx> intravisit::Visitor<'tcx> for ConstraintLocator<'a, 'tcx> {
1586 fn nested_visit_map<'this>(&'this mut self) -> intravisit::NestedVisitorMap<'this, 'tcx> {
1587 intravisit::NestedVisitorMap::All(&self.tcx.hir())
1589 fn visit_item(&mut self, it: &'tcx Item) {
1590 let def_id = self.tcx.hir().local_def_id_from_hir_id(it.hir_id);
1591 // the existential type itself or its children are not within its reveal scope
1592 if def_id != self.def_id {
1594 intravisit::walk_item(self, it);
1597 fn visit_impl_item(&mut self, it: &'tcx ImplItem) {
1598 let def_id = self.tcx.hir().local_def_id_from_hir_id(it.hir_id);
1599 // the existential type itself or its children are not within its reveal scope
1600 if def_id != self.def_id {
1602 intravisit::walk_impl_item(self, it);
1605 fn visit_trait_item(&mut self, it: &'tcx TraitItem) {
1606 let def_id = self.tcx.hir().local_def_id_from_hir_id(it.hir_id);
1608 intravisit::walk_trait_item(self, it);
1612 let mut locator = ConstraintLocator {
1617 let hir_id = tcx.hir().as_local_hir_id(def_id).unwrap();
1618 let parent = tcx.hir().get_parent_item(hir_id);
1620 trace!("parent_id: {:?}", parent);
1622 if parent == hir::CRATE_HIR_ID {
1623 intravisit::walk_crate(&mut locator, tcx.hir().krate());
1625 trace!("parent: {:?}", tcx.hir().get_by_hir_id(parent));
1626 match tcx.hir().get_by_hir_id(parent) {
1627 Node::Item(ref it) => intravisit::walk_item(&mut locator, it),
1628 Node::ImplItem(ref it) => intravisit::walk_impl_item(&mut locator, it),
1629 Node::TraitItem(ref it) => intravisit::walk_trait_item(&mut locator, it),
1631 "{:?} is not a valid parent of an existential type item",
1637 match locator.found {
1638 Some((_, ty, _)) => ty,
1640 let span = tcx.def_span(def_id);
1641 tcx.sess.span_err(span, "could not find defining uses");
1647 fn fn_sig<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId) -> ty::PolyFnSig<'tcx> {
1649 use rustc::hir::Node::*;
1651 let hir_id = tcx.hir().as_local_hir_id(def_id).unwrap();
1653 let icx = ItemCtxt::new(tcx, def_id);
1655 match tcx.hir().get_by_hir_id(hir_id) {
1656 TraitItem(hir::TraitItem {
1657 node: TraitItemKind::Method(sig, _),
1660 | ImplItem(hir::ImplItem {
1661 node: ImplItemKind::Method(sig, _),
1663 }) => AstConv::ty_of_fn(&icx, sig.header.unsafety, sig.header.abi, &sig.decl),
1666 node: ItemKind::Fn(decl, header, _, _),
1668 }) => AstConv::ty_of_fn(&icx, header.unsafety, header.abi, decl),
1670 ForeignItem(&hir::ForeignItem {
1671 node: ForeignItemKind::Fn(ref fn_decl, _, _),
1674 let abi = tcx.hir().get_foreign_abi_by_hir_id(hir_id);
1675 compute_sig_of_foreign_fn_decl(tcx, def_id, fn_decl, abi)
1678 Ctor(data) | Variant(Spanned {
1679 node: hir::VariantKind { data, .. },
1681 }) if data.ctor_hir_id().is_some() => {
1682 let ty = tcx.type_of(tcx.hir().get_parent_did_by_hir_id(hir_id));
1683 let inputs = data.fields()
1685 .map(|f| tcx.type_of(tcx.hir().local_def_id_from_hir_id(f.hir_id)));
1686 ty::Binder::bind(tcx.mk_fn_sig(
1690 hir::Unsafety::Normal,
1696 node: hir::ExprKind::Closure(..),
1699 // Closure signatures are not like other function
1700 // signatures and cannot be accessed through `fn_sig`. For
1701 // example, a closure signature excludes the `self`
1702 // argument. In any case they are embedded within the
1703 // closure type as part of the `ClosureSubsts`.
1706 // the signature of a closure, you should use the
1707 // `closure_sig` method on the `ClosureSubsts`:
1709 // closure_substs.closure_sig(def_id, tcx)
1711 // or, inside of an inference context, you can use
1713 // infcx.closure_sig(def_id, closure_substs)
1714 bug!("to get the signature of a closure, use `closure_sig()` not `fn_sig()`");
1718 bug!("unexpected sort of node in fn_sig(): {:?}", x);
1723 fn impl_trait_ref<'a, 'tcx>(
1724 tcx: TyCtxt<'a, 'tcx, 'tcx>,
1726 ) -> Option<ty::TraitRef<'tcx>> {
1727 let icx = ItemCtxt::new(tcx, def_id);
1729 let hir_id = tcx.hir().as_local_hir_id(def_id).unwrap();
1730 match tcx.hir().expect_item_by_hir_id(hir_id).node {
1731 hir::ItemKind::Impl(.., ref opt_trait_ref, _, _) => {
1732 opt_trait_ref.as_ref().map(|ast_trait_ref| {
1733 let selfty = tcx.type_of(def_id);
1734 AstConv::instantiate_mono_trait_ref(&icx, ast_trait_ref, selfty)
1741 fn impl_polarity<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId) -> hir::ImplPolarity {
1742 let hir_id = tcx.hir().as_local_hir_id(def_id).unwrap();
1743 match tcx.hir().expect_item_by_hir_id(hir_id).node {
1744 hir::ItemKind::Impl(_, polarity, ..) => polarity,
1745 ref item => bug!("impl_polarity: {:?} not an impl", item),
1749 // Is it marked with ?Sized
1750 fn is_unsized<'gcx: 'tcx, 'tcx>(
1751 astconv: &dyn AstConv<'gcx, 'tcx>,
1752 ast_bounds: &[hir::GenericBound],
1755 let tcx = astconv.tcx();
1757 // Try to find an unbound in bounds.
1758 let mut unbound = None;
1759 for ab in ast_bounds {
1760 if let &hir::GenericBound::Trait(ref ptr, hir::TraitBoundModifier::Maybe) = ab {
1761 if unbound.is_none() {
1762 unbound = Some(ptr.trait_ref.clone());
1768 "type parameter has more than one relaxed default \
1769 bound, only one is supported"
1775 let kind_id = tcx.lang_items().require(SizedTraitLangItem);
1778 // FIXME(#8559) currently requires the unbound to be built-in.
1779 if let Ok(kind_id) = kind_id {
1780 if tpb.path.def != Def::Trait(kind_id) {
1783 "default bound relaxed for a type parameter, but \
1784 this does nothing because the given bound is not \
1785 a default. Only `?Sized` is supported",
1790 _ if kind_id.is_ok() => {
1793 // No lang item for Sized, so we can't add it as a bound.
1800 /// Returns the early-bound lifetimes declared in this generics
1801 /// listing. For anything other than fns/methods, this is just all
1802 /// the lifetimes that are declared. For fns or methods, we have to
1803 /// screen out those that do not appear in any where-clauses etc using
1804 /// `resolve_lifetime::early_bound_lifetimes`.
1805 fn early_bound_lifetimes_from_generics<'a, 'tcx>(
1806 tcx: TyCtxt<'a, 'tcx, 'tcx>,
1807 generics: &'a hir::Generics,
1808 ) -> impl Iterator<Item = &'a hir::GenericParam> + Captures<'tcx> {
1812 .filter(move |param| match param.kind {
1813 GenericParamKind::Lifetime { .. } => {
1814 !tcx.is_late_bound(param.hir_id)
1820 /// Returns a list of type predicates for the definition with ID `def_id`, including inferred
1821 /// lifetime constraints. This includes all predicates returned by `explicit_predicates_of`, plus
1822 /// inferred constraints concerning which regions outlive other regions.
1823 fn predicates_defined_on<'a, 'tcx>(
1824 tcx: TyCtxt<'a, 'tcx, 'tcx>,
1826 ) -> Lrc<ty::GenericPredicates<'tcx>> {
1827 debug!("predicates_defined_on({:?})", def_id);
1828 let mut result = tcx.explicit_predicates_of(def_id);
1830 "predicates_defined_on: explicit_predicates_of({:?}) = {:?}",
1834 let inferred_outlives = tcx.inferred_outlives_of(def_id);
1835 if !inferred_outlives.is_empty() {
1836 let span = tcx.def_span(def_id);
1838 "predicates_defined_on: inferred_outlives_of({:?}) = {:?}",
1842 Lrc::make_mut(&mut result)
1844 .extend(inferred_outlives.iter().map(|&p| (p, span)));
1846 debug!("predicates_defined_on({:?}) = {:?}", def_id, result);
1850 /// Returns a list of all type predicates (explicit and implicit) for the definition with
1851 /// ID `def_id`. This includes all predicates returned by `predicates_defined_on`, plus
1852 /// `Self: Trait` predicates for traits.
1853 fn predicates_of<'a, 'tcx>(
1854 tcx: TyCtxt<'a, 'tcx, 'tcx>,
1856 ) -> Lrc<ty::GenericPredicates<'tcx>> {
1857 let mut result = tcx.predicates_defined_on(def_id);
1859 if tcx.is_trait(def_id) {
1860 // For traits, add `Self: Trait` predicate. This is
1861 // not part of the predicates that a user writes, but it
1862 // is something that one must prove in order to invoke a
1863 // method or project an associated type.
1865 // In the chalk setup, this predicate is not part of the
1866 // "predicates" for a trait item. But it is useful in
1867 // rustc because if you directly (e.g.) invoke a trait
1868 // method like `Trait::method(...)`, you must naturally
1869 // prove that the trait applies to the types that were
1870 // used, and adding the predicate into this list ensures
1871 // that this is done.
1872 let span = tcx.def_span(def_id);
1873 Lrc::make_mut(&mut result)
1875 .push((ty::TraitRef::identity(tcx, def_id).to_predicate(), span));
1877 debug!("predicates_of(def_id={:?}) = {:?}", def_id, result);
1881 /// Returns a list of user-specified type predicates for the definition with ID `def_id`.
1882 /// N.B., this does not include any implied/inferred constraints.
1883 fn explicit_predicates_of<'a, 'tcx>(
1884 tcx: TyCtxt<'a, 'tcx, 'tcx>,
1886 ) -> Lrc<ty::GenericPredicates<'tcx>> {
1888 use rustc_data_structures::fx::FxHashSet;
1890 debug!("explicit_predicates_of(def_id={:?})", def_id);
1892 /// A data structure with unique elements, which preserves order of insertion.
1893 /// Preserving the order of insertion is important here so as not to break
1894 /// compile-fail UI tests.
1895 struct UniquePredicates<'tcx> {
1896 predicates: Vec<(ty::Predicate<'tcx>, Span)>,
1897 uniques: FxHashSet<(ty::Predicate<'tcx>, Span)>,
1900 impl<'tcx> UniquePredicates<'tcx> {
1904 uniques: FxHashSet::default(),
1908 fn push(&mut self, value: (ty::Predicate<'tcx>, Span)) {
1909 if self.uniques.insert(value) {
1910 self.predicates.push(value);
1914 fn extend<I: IntoIterator<Item = (ty::Predicate<'tcx>, Span)>>(&mut self, iter: I) {
1921 let hir_id = tcx.hir().as_local_hir_id(def_id).unwrap();
1922 let node = tcx.hir().get_by_hir_id(hir_id);
1924 let mut is_trait = None;
1925 let mut is_default_impl_trait = None;
1927 let icx = ItemCtxt::new(tcx, def_id);
1928 let no_generics = hir::Generics::empty();
1929 let empty_trait_items = HirVec::new();
1931 let mut predicates = UniquePredicates::new();
1933 let ast_generics = match node {
1934 Node::TraitItem(item) => &item.generics,
1936 Node::ImplItem(item) => match item.node {
1937 ImplItemKind::Existential(ref bounds) => {
1938 let substs = InternalSubsts::identity_for_item(tcx, def_id);
1939 let opaque_ty = tcx.mk_opaque(def_id, substs);
1941 // Collect the bounds, i.e., the `A+B+'c` in `impl A+B+'c`.
1942 let bounds = compute_bounds(
1946 SizedByDefault::Yes,
1947 tcx.def_span(def_id),
1950 predicates.extend(bounds.predicates(tcx, opaque_ty));
1953 _ => &item.generics,
1956 Node::Item(item) => {
1958 ItemKind::Impl(_, _, defaultness, ref generics, ..) => {
1959 if defaultness.is_default() {
1960 is_default_impl_trait = tcx.impl_trait_ref(def_id);
1964 ItemKind::Fn(.., ref generics, _)
1965 | ItemKind::Ty(_, ref generics)
1966 | ItemKind::Enum(_, ref generics)
1967 | ItemKind::Struct(_, ref generics)
1968 | ItemKind::Union(_, ref generics) => generics,
1970 ItemKind::Trait(_, _, ref generics, .., ref items) => {
1971 is_trait = Some((ty::TraitRef::identity(tcx, def_id), items));
1974 ItemKind::TraitAlias(ref generics, _) => {
1975 is_trait = Some((ty::TraitRef::identity(tcx, def_id), &empty_trait_items));
1978 ItemKind::Existential(ExistTy {
1983 let substs = InternalSubsts::identity_for_item(tcx, def_id);
1984 let opaque_ty = tcx.mk_opaque(def_id, substs);
1986 // Collect the bounds, i.e., the `A+B+'c` in `impl A+B+'c`.
1987 let bounds = compute_bounds(
1991 SizedByDefault::Yes,
1992 tcx.def_span(def_id),
1995 if impl_trait_fn.is_some() {
1997 return Lrc::new(ty::GenericPredicates {
1999 predicates: bounds.predicates(tcx, opaque_ty),
2002 // named existential types
2003 predicates.extend(bounds.predicates(tcx, opaque_ty));
2012 Node::ForeignItem(item) => match item.node {
2013 ForeignItemKind::Static(..) => &no_generics,
2014 ForeignItemKind::Fn(_, _, ref generics) => generics,
2015 ForeignItemKind::Type => &no_generics,
2021 let generics = tcx.generics_of(def_id);
2022 let parent_count = generics.parent_count as u32;
2023 let has_own_self = generics.has_self && parent_count == 0;
2025 // Below we'll consider the bounds on the type parameters (including `Self`)
2026 // and the explicit where-clauses, but to get the full set of predicates
2027 // on a trait we need to add in the supertrait bounds and bounds found on
2028 // associated types.
2029 if let Some((_trait_ref, _)) = is_trait {
2030 predicates.extend(tcx.super_predicates_of(def_id).predicates.iter().cloned());
2033 // In default impls, we can assume that the self type implements
2034 // the trait. So in:
2036 // default impl Foo for Bar { .. }
2038 // we add a default where clause `Foo: Bar`. We do a similar thing for traits
2039 // (see below). Recall that a default impl is not itself an impl, but rather a
2040 // set of defaults that can be incorporated into another impl.
2041 if let Some(trait_ref) = is_default_impl_trait {
2042 predicates.push((trait_ref.to_poly_trait_ref().to_predicate(), tcx.def_span(def_id)));
2045 // Collect the region predicates that were declared inline as
2046 // well. In the case of parameters declared on a fn or method, we
2047 // have to be careful to only iterate over early-bound regions.
2048 let mut index = parent_count + has_own_self as u32;
2049 for param in early_bound_lifetimes_from_generics(tcx, ast_generics) {
2050 let region = tcx.mk_region(ty::ReEarlyBound(ty::EarlyBoundRegion {
2051 def_id: tcx.hir().local_def_id_from_hir_id(param.hir_id),
2053 name: param.name.ident().as_interned_str(),
2058 GenericParamKind::Lifetime { .. } => {
2059 param.bounds.iter().for_each(|bound| match bound {
2060 hir::GenericBound::Outlives(lt) => {
2061 let bound = AstConv::ast_region_to_region(&icx, <, None);
2062 let outlives = ty::Binder::bind(ty::OutlivesPredicate(region, bound));
2063 predicates.push((outlives.to_predicate(), lt.span));
2072 // Collect the predicates that were written inline by the user on each
2073 // type parameter (e.g., `<T:Foo>`).
2074 for param in &ast_generics.params {
2075 if let GenericParamKind::Type { .. } = param.kind {
2076 let name = param.name.ident().as_interned_str();
2077 let param_ty = ty::ParamTy::new(index, name).to_ty(tcx);
2080 let sized = SizedByDefault::Yes;
2081 let bounds = compute_bounds(&icx, param_ty, ¶m.bounds, sized, param.span);
2082 predicates.extend(bounds.predicates(tcx, param_ty));
2086 // Add in the bounds that appear in the where-clause
2087 let where_clause = &ast_generics.where_clause;
2088 for predicate in &where_clause.predicates {
2090 &hir::WherePredicate::BoundPredicate(ref bound_pred) => {
2091 let ty = icx.to_ty(&bound_pred.bounded_ty);
2093 // Keep the type around in a dummy predicate, in case of no bounds.
2094 // That way, `where Ty:` is not a complete noop (see #53696) and `Ty`
2095 // is still checked for WF.
2096 if bound_pred.bounds.is_empty() {
2097 if let ty::Param(_) = ty.sty {
2098 // This is a `where T:`, which can be in the HIR from the
2099 // transformation that moves `?Sized` to `T`'s declaration.
2100 // We can skip the predicate because type parameters are
2101 // trivially WF, but also we *should*, to avoid exposing
2102 // users who never wrote `where Type:,` themselves, to
2103 // compiler/tooling bugs from not handling WF predicates.
2105 let span = bound_pred.bounded_ty.span;
2106 let predicate = ty::OutlivesPredicate(ty, tcx.mk_region(ty::ReEmpty));
2108 (ty::Predicate::TypeOutlives(ty::Binder::dummy(predicate)), span)
2113 for bound in bound_pred.bounds.iter() {
2115 &hir::GenericBound::Trait(ref poly_trait_ref, _) => {
2116 let mut projections = Vec::new();
2118 let (trait_ref, _) = AstConv::instantiate_poly_trait_ref(
2126 iter::once((trait_ref.to_predicate(), poly_trait_ref.span)).chain(
2127 projections.iter().map(|&(p, span)| (p.to_predicate(), span)
2131 &hir::GenericBound::Outlives(ref lifetime) => {
2132 let region = AstConv::ast_region_to_region(&icx, lifetime, None);
2133 let pred = ty::Binder::bind(ty::OutlivesPredicate(ty, region));
2134 predicates.push((ty::Predicate::TypeOutlives(pred), lifetime.span))
2140 &hir::WherePredicate::RegionPredicate(ref region_pred) => {
2141 let r1 = AstConv::ast_region_to_region(&icx, ®ion_pred.lifetime, None);
2142 predicates.extend(region_pred.bounds.iter().map(|bound| {
2143 let (r2, span) = match bound {
2144 hir::GenericBound::Outlives(lt) => {
2145 (AstConv::ast_region_to_region(&icx, lt, None), lt.span)
2149 let pred = ty::Binder::bind(ty::OutlivesPredicate(r1, r2));
2151 (ty::Predicate::RegionOutlives(pred), span)
2155 &hir::WherePredicate::EqPredicate(..) => {
2161 // Add predicates from associated type bounds.
2162 if let Some((self_trait_ref, trait_items)) = is_trait {
2163 predicates.extend(trait_items.iter().flat_map(|trait_item_ref| {
2164 let trait_item = tcx.hir().trait_item(trait_item_ref.id);
2165 let bounds = match trait_item.node {
2166 hir::TraitItemKind::Type(ref bounds, _) => bounds,
2167 _ => return vec![].into_iter()
2171 tcx.mk_projection(tcx.hir().local_def_id_from_hir_id(trait_item.hir_id),
2172 self_trait_ref.substs);
2174 let bounds = compute_bounds(
2175 &ItemCtxt::new(tcx, def_id),
2178 SizedByDefault::Yes,
2182 bounds.predicates(tcx, assoc_ty).into_iter()
2186 let mut predicates = predicates.predicates;
2188 // Subtle: before we store the predicates into the tcx, we
2189 // sort them so that predicates like `T: Foo<Item=U>` come
2190 // before uses of `U`. This avoids false ambiguity errors
2191 // in trait checking. See `setup_constraining_predicates`
2193 if let Node::Item(&Item {
2194 node: ItemKind::Impl(..),
2198 let self_ty = tcx.type_of(def_id);
2199 let trait_ref = tcx.impl_trait_ref(def_id);
2200 ctp::setup_constraining_predicates(
2204 &mut ctp::parameters_for_impl(self_ty, trait_ref),
2208 let result = Lrc::new(ty::GenericPredicates {
2209 parent: generics.parent,
2212 debug!("explicit_predicates_of(def_id={:?}) = {:?}", def_id, result);
2216 pub enum SizedByDefault {
2221 /// Translate the AST's notion of ty param bounds (which are an enum consisting of a newtyped `Ty`
2222 /// or a region) to ty's notion of ty param bounds, which can either be user-defined traits, or the
2223 /// built-in trait `Send`.
2224 pub fn compute_bounds<'gcx: 'tcx, 'tcx>(
2225 astconv: &dyn AstConv<'gcx, 'tcx>,
2227 ast_bounds: &[hir::GenericBound],
2228 sized_by_default: SizedByDefault,
2231 let mut region_bounds = Vec::new();
2232 let mut trait_bounds = Vec::new();
2234 for ast_bound in ast_bounds {
2236 hir::GenericBound::Trait(ref b, hir::TraitBoundModifier::None) => trait_bounds.push(b),
2237 hir::GenericBound::Trait(_, hir::TraitBoundModifier::Maybe) => {}
2238 hir::GenericBound::Outlives(ref l) => region_bounds.push(l),
2242 let mut projection_bounds = Vec::new();
2244 let mut trait_bounds: Vec<_> = trait_bounds.iter().map(|&bound| {
2245 let (poly_trait_ref, _) = astconv.instantiate_poly_trait_ref(
2248 &mut projection_bounds,
2250 (poly_trait_ref, bound.span)
2253 let region_bounds = region_bounds
2255 .map(|r| (astconv.ast_region_to_region(r, None), r.span))
2258 trait_bounds.sort_by_key(|(t, _)| t.def_id());
2260 let implicitly_sized = if let SizedByDefault::Yes = sized_by_default {
2261 if !is_unsized(astconv, ast_bounds, span) {
2278 /// Converts a specific `GenericBound` from the AST into a set of
2279 /// predicates that apply to the self type. A vector is returned
2280 /// because this can be anywhere from zero predicates (`T: ?Sized` adds no
2281 /// predicates) to one (`T: Foo`) to many (`T: Bar<X=i32>` adds `T: Bar`
2282 /// and `<T as Bar>::X == i32`).
2283 fn predicates_from_bound<'tcx>(
2284 astconv: &dyn AstConv<'tcx, 'tcx>,
2286 bound: &hir::GenericBound,
2287 ) -> Vec<(ty::Predicate<'tcx>, Span)> {
2289 hir::GenericBound::Trait(ref tr, hir::TraitBoundModifier::None) => {
2290 let mut projections = Vec::new();
2291 let (pred, _) = astconv.instantiate_poly_trait_ref(tr, param_ty, &mut projections);
2292 iter::once((pred.to_predicate(), tr.span)).chain(
2295 .map(|(p, span)| (p.to_predicate(), span))
2298 hir::GenericBound::Outlives(ref lifetime) => {
2299 let region = astconv.ast_region_to_region(lifetime, None);
2300 let pred = ty::Binder::bind(ty::OutlivesPredicate(param_ty, region));
2301 vec![(ty::Predicate::TypeOutlives(pred), lifetime.span)]
2303 hir::GenericBound::Trait(_, hir::TraitBoundModifier::Maybe) => vec![],
2307 fn compute_sig_of_foreign_fn_decl<'a, 'tcx>(
2308 tcx: TyCtxt<'a, 'tcx, 'tcx>,
2312 ) -> ty::PolyFnSig<'tcx> {
2313 let unsafety = if abi == abi::Abi::RustIntrinsic {
2314 intrisic_operation_unsafety(&*tcx.item_name(def_id).as_str())
2316 hir::Unsafety::Unsafe
2318 let fty = AstConv::ty_of_fn(&ItemCtxt::new(tcx, def_id), unsafety, abi, decl);
2320 // feature gate SIMD types in FFI, since I (huonw) am not sure the
2321 // ABIs are handled at all correctly.
2322 if abi != abi::Abi::RustIntrinsic
2323 && abi != abi::Abi::PlatformIntrinsic
2324 && !tcx.features().simd_ffi
2326 let check = |ast_ty: &hir::Ty, ty: Ty<'_>| {
2332 "use of SIMD type `{}` in FFI is highly experimental and \
2333 may result in invalid code",
2334 tcx.hir().hir_to_pretty_string(ast_ty.hir_id)
2337 .help("add #![feature(simd_ffi)] to the crate attributes to enable")
2341 for (input, ty) in decl.inputs.iter().zip(*fty.inputs().skip_binder()) {
2344 if let hir::Return(ref ty) = decl.output {
2345 check(&ty, *fty.output().skip_binder())
2352 fn is_foreign_item<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId) -> bool {
2353 match tcx.hir().get_if_local(def_id) {
2354 Some(Node::ForeignItem(..)) => true,
2356 _ => bug!("is_foreign_item applied to non-local def-id {:?}", def_id),
2360 fn from_target_feature(
2361 tcx: TyCtxt<'_, '_, '_>,
2363 attr: &ast::Attribute,
2364 whitelist: &FxHashMap<String, Option<String>>,
2365 target_features: &mut Vec<Symbol>,
2367 let list = match attr.meta_item_list() {
2371 let rust_features = tcx.features();
2373 // Only `enable = ...` is accepted in the meta item list
2374 if !item.check_name("enable") {
2375 let msg = "#[target_feature(..)] only accepts sub-keys of `enable` \
2377 tcx.sess.span_err(item.span(), &msg);
2381 // Must be of the form `enable = "..."` ( a string)
2382 let value = match item.value_str() {
2383 Some(value) => value,
2385 let msg = "#[target_feature] attribute must be of the form \
2386 #[target_feature(enable = \"..\")]";
2387 tcx.sess.span_err(item.span(), &msg);
2392 // We allow comma separation to enable multiple features
2393 target_features.extend(value.as_str().split(',').filter_map(|feature| {
2394 // Only allow whitelisted features per platform
2395 let feature_gate = match whitelist.get(feature) {
2399 "the feature named `{}` is not valid for \
2403 let mut err = tcx.sess.struct_span_err(item.span(), &msg);
2405 if feature.starts_with("+") {
2406 let valid = whitelist.contains_key(&feature[1..]);
2408 err.help("consider removing the leading `+` in the feature name");
2416 // Only allow features whose feature gates have been enabled
2417 let allowed = match feature_gate.as_ref().map(|s| &**s) {
2418 Some("arm_target_feature") => rust_features.arm_target_feature,
2419 Some("aarch64_target_feature") => rust_features.aarch64_target_feature,
2420 Some("hexagon_target_feature") => rust_features.hexagon_target_feature,
2421 Some("powerpc_target_feature") => rust_features.powerpc_target_feature,
2422 Some("mips_target_feature") => rust_features.mips_target_feature,
2423 Some("avx512_target_feature") => rust_features.avx512_target_feature,
2424 Some("mmx_target_feature") => rust_features.mmx_target_feature,
2425 Some("sse4a_target_feature") => rust_features.sse4a_target_feature,
2426 Some("tbm_target_feature") => rust_features.tbm_target_feature,
2427 Some("wasm_target_feature") => rust_features.wasm_target_feature,
2428 Some("cmpxchg16b_target_feature") => rust_features.cmpxchg16b_target_feature,
2429 Some("adx_target_feature") => rust_features.adx_target_feature,
2430 Some("movbe_target_feature") => rust_features.movbe_target_feature,
2431 Some(name) => bug!("unknown target feature gate {}", name),
2434 if !allowed && id.is_local() {
2435 feature_gate::emit_feature_err(
2436 &tcx.sess.parse_sess,
2437 feature_gate.as_ref().unwrap(),
2439 feature_gate::GateIssue::Language,
2440 &format!("the target feature `{}` is currently unstable", feature),
2443 Some(Symbol::intern(feature))
2448 fn linkage_by_name<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId, name: &str) -> Linkage {
2449 use rustc::mir::mono::Linkage::*;
2451 // Use the names from src/llvm/docs/LangRef.rst here. Most types are only
2452 // applicable to variable declarations and may not really make sense for
2453 // Rust code in the first place but whitelist them anyway and trust that
2454 // the user knows what s/he's doing. Who knows, unanticipated use cases
2455 // may pop up in the future.
2457 // ghost, dllimport, dllexport and linkonce_odr_autohide are not supported
2458 // and don't have to be, LLVM treats them as no-ops.
2460 "appending" => Appending,
2461 "available_externally" => AvailableExternally,
2463 "extern_weak" => ExternalWeak,
2464 "external" => External,
2465 "internal" => Internal,
2466 "linkonce" => LinkOnceAny,
2467 "linkonce_odr" => LinkOnceODR,
2468 "private" => Private,
2470 "weak_odr" => WeakODR,
2472 let span = tcx.hir().span_if_local(def_id);
2473 if let Some(span) = span {
2474 tcx.sess.span_fatal(span, "invalid linkage specified")
2477 .fatal(&format!("invalid linkage specified: {}", name))
2483 fn codegen_fn_attrs<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, id: DefId) -> CodegenFnAttrs {
2484 let attrs = tcx.get_attrs(id);
2486 let mut codegen_fn_attrs = CodegenFnAttrs::new();
2488 let whitelist = tcx.target_features_whitelist(LOCAL_CRATE);
2490 let mut inline_span = None;
2491 for attr in attrs.iter() {
2492 if attr.check_name("cold") {
2493 codegen_fn_attrs.flags |= CodegenFnAttrFlags::COLD;
2494 } else if attr.check_name("allocator") {
2495 codegen_fn_attrs.flags |= CodegenFnAttrFlags::ALLOCATOR;
2496 } else if attr.check_name("unwind") {
2497 codegen_fn_attrs.flags |= CodegenFnAttrFlags::UNWIND;
2498 } else if attr.check_name("ffi_returns_twice") {
2499 if tcx.is_foreign_item(id) {
2500 codegen_fn_attrs.flags |= CodegenFnAttrFlags::FFI_RETURNS_TWICE;
2502 // `#[ffi_returns_twice]` is only allowed `extern fn`s
2507 "`#[ffi_returns_twice]` may only be used on foreign functions"
2510 } else if attr.check_name("rustc_allocator_nounwind") {
2511 codegen_fn_attrs.flags |= CodegenFnAttrFlags::RUSTC_ALLOCATOR_NOUNWIND;
2512 } else if attr.check_name("naked") {
2513 codegen_fn_attrs.flags |= CodegenFnAttrFlags::NAKED;
2514 } else if attr.check_name("no_mangle") {
2515 codegen_fn_attrs.flags |= CodegenFnAttrFlags::NO_MANGLE;
2516 } else if attr.check_name("rustc_std_internal_symbol") {
2517 codegen_fn_attrs.flags |= CodegenFnAttrFlags::RUSTC_STD_INTERNAL_SYMBOL;
2518 } else if attr.check_name("no_debug") {
2519 codegen_fn_attrs.flags |= CodegenFnAttrFlags::NO_DEBUG;
2520 } else if attr.check_name("used") {
2521 codegen_fn_attrs.flags |= CodegenFnAttrFlags::USED;
2522 } else if attr.check_name("thread_local") {
2523 codegen_fn_attrs.flags |= CodegenFnAttrFlags::THREAD_LOCAL;
2524 } else if attr.check_name("export_name") {
2525 if let Some(s) = attr.value_str() {
2526 if s.as_str().contains("\0") {
2527 // `#[export_name = ...]` will be converted to a null-terminated string,
2528 // so it may not contain any null characters.
2533 "`export_name` may not contain null characters"
2536 codegen_fn_attrs.export_name = Some(s);
2538 } else if attr.check_name("target_feature") {
2539 if tcx.fn_sig(id).unsafety() == Unsafety::Normal {
2540 let msg = "#[target_feature(..)] can only be applied to \
2542 tcx.sess.span_err(attr.span, msg);
2544 from_target_feature(
2549 &mut codegen_fn_attrs.target_features,
2551 } else if attr.check_name("linkage") {
2552 if let Some(val) = attr.value_str() {
2553 codegen_fn_attrs.linkage = Some(linkage_by_name(tcx, id, &val.as_str()));
2555 } else if attr.check_name("link_section") {
2556 if let Some(val) = attr.value_str() {
2557 if val.as_str().bytes().any(|b| b == 0) {
2559 "illegal null byte in link_section \
2563 tcx.sess.span_err(attr.span, &msg);
2565 codegen_fn_attrs.link_section = Some(val);
2568 } else if attr.check_name("link_name") {
2569 codegen_fn_attrs.link_name = attr.value_str();
2573 codegen_fn_attrs.inline = attrs.iter().fold(InlineAttr::None, |ia, attr| {
2574 if attr.path != "inline" {
2577 match attr.meta().map(|i| i.node) {
2578 Some(MetaItemKind::Word) => {
2582 Some(MetaItemKind::List(ref items)) => {
2584 inline_span = Some(attr.span);
2585 if items.len() != 1 {
2587 tcx.sess.diagnostic(),
2590 "expected one argument"
2593 } else if list_contains_name(&items[..], "always") {
2595 } else if list_contains_name(&items[..], "never") {
2599 tcx.sess.diagnostic(),
2608 Some(MetaItemKind::NameValue(_)) => ia,
2613 codegen_fn_attrs.optimize = attrs.iter().fold(OptimizeAttr::None, |ia, attr| {
2614 if attr.path != "optimize" {
2617 let err = |sp, s| span_err!(tcx.sess.diagnostic(), sp, E0722, "{}", s);
2618 match attr.meta().map(|i| i.node) {
2619 Some(MetaItemKind::Word) => {
2620 err(attr.span, "expected one argument");
2623 Some(MetaItemKind::List(ref items)) => {
2625 inline_span = Some(attr.span);
2626 if items.len() != 1 {
2627 err(attr.span, "expected one argument");
2629 } else if list_contains_name(&items[..], "size") {
2631 } else if list_contains_name(&items[..], "speed") {
2634 err(items[0].span(), "invalid argument");
2638 Some(MetaItemKind::NameValue(_)) => ia,
2643 // If a function uses #[target_feature] it can't be inlined into general
2644 // purpose functions as they wouldn't have the right target features
2645 // enabled. For that reason we also forbid #[inline(always)] as it can't be
2647 if codegen_fn_attrs.target_features.len() > 0 {
2648 if codegen_fn_attrs.inline == InlineAttr::Always {
2649 if let Some(span) = inline_span {
2652 "cannot use #[inline(always)] with \
2659 // Weak lang items have the same semantics as "std internal" symbols in the
2660 // sense that they're preserved through all our LTO passes and only
2661 // strippable by the linker.
2663 // Additionally weak lang items have predetermined symbol names.
2664 if tcx.is_weak_lang_item(id) {
2665 codegen_fn_attrs.flags |= CodegenFnAttrFlags::RUSTC_STD_INTERNAL_SYMBOL;
2667 if let Some(name) = weak_lang_items::link_name(&attrs) {
2668 codegen_fn_attrs.export_name = Some(name);
2669 codegen_fn_attrs.link_name = Some(name);
2672 // Internal symbols to the standard library all have no_mangle semantics in
2673 // that they have defined symbol names present in the function name. This
2674 // also applies to weak symbols where they all have known symbol names.
2675 if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::RUSTC_STD_INTERNAL_SYMBOL) {
2676 codegen_fn_attrs.flags |= CodegenFnAttrFlags::NO_MANGLE;