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 *inter-procedural* 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, SizedByDefault};
18 use crate::bounds::Bounds;
19 use crate::check::intrinsic::intrinsic_operation_unsafety;
20 use crate::constrained_generic_params as cgp;
22 use crate::middle::resolve_lifetime as rl;
24 use rustc_ast::{MetaItemKind, NestedMetaItem};
25 use rustc_attr::{list_contains_name, InlineAttr, InstructionSetAttr, OptimizeAttr};
26 use rustc_data_structures::captures::Captures;
27 use rustc_data_structures::fx::{FxHashMap, FxHashSet, FxIndexSet};
28 use rustc_errors::{struct_span_err, Applicability};
30 use rustc_hir::def::{CtorKind, DefKind, Res};
31 use rustc_hir::def_id::{DefId, LocalDefId, LOCAL_CRATE};
32 use rustc_hir::intravisit::{self, NestedVisitorMap, Visitor};
33 use rustc_hir::weak_lang_items;
34 use rustc_hir::{GenericParamKind, HirId, Node};
35 use rustc_middle::hir::map::blocks::FnLikeNode;
36 use rustc_middle::hir::map::Map;
37 use rustc_middle::middle::codegen_fn_attrs::{CodegenFnAttrFlags, CodegenFnAttrs};
38 use rustc_middle::mir::mono::Linkage;
39 use rustc_middle::ty::query::Providers;
40 use rustc_middle::ty::subst::InternalSubsts;
41 use rustc_middle::ty::util::Discr;
42 use rustc_middle::ty::util::IntTypeExt;
43 use rustc_middle::ty::{self, AdtKind, Const, DefIdTree, ToPolyTraitRef, Ty, TyCtxt};
44 use rustc_middle::ty::{ReprOptions, ToPredicate, WithConstness};
45 use rustc_session::config::SanitizerSet;
46 use rustc_session::lint;
47 use rustc_session::parse::feature_err;
48 use rustc_span::symbol::{kw, sym, Ident, Symbol};
49 use rustc_span::{Span, DUMMY_SP};
50 use rustc_target::spec::abi;
51 use rustc_trait_selection::traits::error_reporting::suggestions::NextTypeParamName;
56 struct OnlySelfBounds(bool);
58 ///////////////////////////////////////////////////////////////////////////
61 fn collect_mod_item_types(tcx: TyCtxt<'_>, module_def_id: LocalDefId) {
62 tcx.hir().visit_item_likes_in_module(
64 &mut CollectItemTypesVisitor { tcx }.as_deep_visitor(),
68 pub fn provide(providers: &mut Providers) {
69 *providers = Providers {
70 opt_const_param_of: type_of::opt_const_param_of,
71 type_of: type_of::type_of,
72 item_bounds: item_bounds::item_bounds,
73 explicit_item_bounds: item_bounds::explicit_item_bounds,
76 predicates_defined_on,
77 projection_ty_from_predicates,
78 explicit_predicates_of,
80 trait_explicit_predicates_and_bounds,
81 type_param_predicates,
91 collect_mod_item_types,
96 ///////////////////////////////////////////////////////////////////////////
98 /// Context specific to some particular item. This is what implements
99 /// `AstConv`. It has information about the predicates that are defined
100 /// on the trait. Unfortunately, this predicate information is
101 /// available in various different forms at various points in the
102 /// process. So we can't just store a pointer to e.g., the AST or the
103 /// parsed ty form, we have to be more flexible. To this end, the
104 /// `ItemCtxt` is parameterized by a `DefId` that it uses to satisfy
105 /// `get_type_parameter_bounds` requests, drawing the information from
106 /// the AST (`hir::Generics`), recursively.
107 pub struct ItemCtxt<'tcx> {
112 ///////////////////////////////////////////////////////////////////////////
115 crate struct PlaceholderHirTyCollector(crate Vec<Span>);
117 impl<'v> Visitor<'v> for PlaceholderHirTyCollector {
118 type Map = intravisit::ErasedMap<'v>;
120 fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
121 NestedVisitorMap::None
123 fn visit_ty(&mut self, t: &'v hir::Ty<'v>) {
124 if let hir::TyKind::Infer = t.kind {
127 intravisit::walk_ty(self, t)
131 struct CollectItemTypesVisitor<'tcx> {
135 /// If there are any placeholder types (`_`), emit an error explaining that this is not allowed
136 /// and suggest adding type parameters in the appropriate place, taking into consideration any and
137 /// all already existing generic type parameters to avoid suggesting a name that is already in use.
138 crate fn placeholder_type_error(
141 generics: &[hir::GenericParam<'_>],
142 placeholder_types: Vec<Span>,
145 if placeholder_types.is_empty() {
149 let type_name = generics.next_type_param_name(None);
150 let mut sugg: Vec<_> =
151 placeholder_types.iter().map(|sp| (*sp, (*type_name).to_string())).collect();
153 if generics.is_empty() {
154 if let Some(span) = span {
155 sugg.push((span, format!("<{}>", type_name)));
157 } else if let Some(arg) = generics
159 .find(|arg| matches!(arg.name, hir::ParamName::Plain(Ident { name: kw::Underscore, .. })))
161 // Account for `_` already present in cases like `struct S<_>(_);` and suggest
162 // `struct S<T>(T);` instead of `struct S<_, T>(T);`.
163 sugg.push((arg.span, (*type_name).to_string()));
165 let last = generics.iter().last().unwrap();
167 // Account for bounds, we want `fn foo<T: E, K>(_: K)` not `fn foo<T, K: E>(_: K)`.
168 last.bounds_span().unwrap_or(last.span).shrink_to_hi(),
169 format!(", {}", type_name),
173 let mut err = bad_placeholder_type(tcx, placeholder_types);
175 err.multipart_suggestion(
176 "use type parameters instead",
178 Applicability::HasPlaceholders,
184 fn reject_placeholder_type_signatures_in_item(tcx: TyCtxt<'tcx>, item: &'tcx hir::Item<'tcx>) {
185 let (generics, suggest) = match &item.kind {
186 hir::ItemKind::Union(_, generics)
187 | hir::ItemKind::Enum(_, generics)
188 | hir::ItemKind::TraitAlias(generics, _)
189 | hir::ItemKind::Trait(_, _, generics, ..)
190 | hir::ItemKind::Impl(hir::Impl { generics, .. })
191 | hir::ItemKind::Struct(_, generics) => (generics, true),
192 hir::ItemKind::OpaqueTy(hir::OpaqueTy { generics, .. })
193 | hir::ItemKind::TyAlias(_, generics) => (generics, false),
194 // `static`, `fn` and `const` are handled elsewhere to suggest appropriate type.
198 let mut visitor = PlaceholderHirTyCollector::default();
199 visitor.visit_item(item);
201 placeholder_type_error(tcx, Some(generics.span), &generics.params[..], visitor.0, suggest);
204 impl Visitor<'tcx> for CollectItemTypesVisitor<'tcx> {
205 type Map = Map<'tcx>;
207 fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
208 NestedVisitorMap::OnlyBodies(self.tcx.hir())
211 fn visit_item(&mut self, item: &'tcx hir::Item<'tcx>) {
212 convert_item(self.tcx, item.hir_id);
213 reject_placeholder_type_signatures_in_item(self.tcx, item);
214 intravisit::walk_item(self, item);
217 fn visit_generics(&mut self, generics: &'tcx hir::Generics<'tcx>) {
218 for param in generics.params {
220 hir::GenericParamKind::Lifetime { .. } => {}
221 hir::GenericParamKind::Type { default: Some(_), .. } => {
222 let def_id = self.tcx.hir().local_def_id(param.hir_id);
223 self.tcx.ensure().type_of(def_id);
225 hir::GenericParamKind::Type { .. } => {}
226 hir::GenericParamKind::Const { .. } => {
227 let def_id = self.tcx.hir().local_def_id(param.hir_id);
228 self.tcx.ensure().type_of(def_id);
229 // FIXME(const_generics_defaults)
233 intravisit::walk_generics(self, generics);
236 fn visit_expr(&mut self, expr: &'tcx hir::Expr<'tcx>) {
237 if let hir::ExprKind::Closure(..) = expr.kind {
238 let def_id = self.tcx.hir().local_def_id(expr.hir_id);
239 self.tcx.ensure().generics_of(def_id);
240 self.tcx.ensure().type_of(def_id);
242 intravisit::walk_expr(self, expr);
245 fn visit_trait_item(&mut self, trait_item: &'tcx hir::TraitItem<'tcx>) {
246 convert_trait_item(self.tcx, trait_item.hir_id);
247 intravisit::walk_trait_item(self, trait_item);
250 fn visit_impl_item(&mut self, impl_item: &'tcx hir::ImplItem<'tcx>) {
251 convert_impl_item(self.tcx, impl_item.hir_id);
252 intravisit::walk_impl_item(self, impl_item);
256 ///////////////////////////////////////////////////////////////////////////
257 // Utility types and common code for the above passes.
259 fn bad_placeholder_type(
261 mut spans: Vec<Span>,
262 ) -> rustc_errors::DiagnosticBuilder<'tcx> {
264 let mut err = struct_span_err!(
268 "the type placeholder `_` is not allowed within types on item signatures",
271 err.span_label(span, "not allowed in type signatures");
276 impl ItemCtxt<'tcx> {
277 pub fn new(tcx: TyCtxt<'tcx>, item_def_id: DefId) -> ItemCtxt<'tcx> {
278 ItemCtxt { tcx, item_def_id }
281 pub fn to_ty(&self, ast_ty: &'tcx hir::Ty<'tcx>) -> Ty<'tcx> {
282 AstConv::ast_ty_to_ty(self, ast_ty)
285 pub fn hir_id(&self) -> hir::HirId {
286 self.tcx.hir().local_def_id_to_hir_id(self.item_def_id.expect_local())
289 pub fn node(&self) -> hir::Node<'tcx> {
290 self.tcx.hir().get(self.hir_id())
294 impl AstConv<'tcx> for ItemCtxt<'tcx> {
295 fn tcx(&self) -> TyCtxt<'tcx> {
299 fn item_def_id(&self) -> Option<DefId> {
300 Some(self.item_def_id)
303 fn default_constness_for_trait_bounds(&self) -> hir::Constness {
304 if let Some(fn_like) = FnLikeNode::from_node(self.node()) {
307 hir::Constness::NotConst
311 fn get_type_parameter_bounds(&self, span: Span, def_id: DefId) -> ty::GenericPredicates<'tcx> {
312 self.tcx.at(span).type_param_predicates((self.item_def_id, def_id.expect_local()))
315 fn re_infer(&self, _: Option<&ty::GenericParamDef>, _: Span) -> Option<ty::Region<'tcx>> {
319 fn allow_ty_infer(&self) -> bool {
323 fn ty_infer(&self, _: Option<&ty::GenericParamDef>, span: Span) -> Ty<'tcx> {
324 self.tcx().ty_error_with_message(span, "bad_placeholder_type")
330 _: Option<&ty::GenericParamDef>,
332 ) -> &'tcx Const<'tcx> {
333 bad_placeholder_type(self.tcx(), vec![span]).emit();
334 self.tcx().const_error(ty)
337 fn projected_ty_from_poly_trait_ref(
341 item_segment: &hir::PathSegment<'_>,
342 poly_trait_ref: ty::PolyTraitRef<'tcx>,
344 if let Some(trait_ref) = poly_trait_ref.no_bound_vars() {
345 let item_substs = <dyn AstConv<'tcx>>::create_substs_for_associated_item(
353 self.tcx().mk_projection(item_def_id, item_substs)
355 // There are no late-bound regions; we can just ignore the binder.
356 let mut err = struct_span_err!(
360 "cannot use the associated type of a trait \
361 with uninferred generic parameters"
365 hir::Node::Field(_) | hir::Node::Ctor(_) | hir::Node::Variant(_) => {
367 self.tcx.hir().expect_item(self.tcx.hir().get_parent_item(self.hir_id()));
369 hir::ItemKind::Enum(_, generics)
370 | hir::ItemKind::Struct(_, generics)
371 | hir::ItemKind::Union(_, generics) => {
372 let lt_name = get_new_lifetime_name(self.tcx, poly_trait_ref, generics);
373 let (lt_sp, sugg) = match &generics.params[..] {
374 [] => (generics.span, format!("<{}>", lt_name)),
376 (bound.span.shrink_to_lo(), format!("{}, ", lt_name))
379 let suggestions = vec![
385 // Replace the existing lifetimes with a new named lifetime.
387 .replace_late_bound_regions(poly_trait_ref, |_| {
388 self.tcx.mk_region(ty::ReEarlyBound(
389 ty::EarlyBoundRegion {
392 name: Symbol::intern(<_name),
401 err.multipart_suggestion(
402 "use a fully qualified path with explicit lifetimes",
404 Applicability::MaybeIncorrect,
410 hir::Node::Item(hir::Item {
412 hir::ItemKind::Struct(..) | hir::ItemKind::Enum(..) | hir::ItemKind::Union(..),
416 | hir::Node::ForeignItem(_)
417 | hir::Node::TraitItem(_)
418 | hir::Node::ImplItem(_) => {
421 "use a fully qualified path with inferred lifetimes",
424 // Erase named lt, we want `<A as B<'_>::C`, not `<A as B<'a>::C`.
425 self.tcx.anonymize_late_bound_regions(poly_trait_ref).skip_binder(),
428 Applicability::MaybeIncorrect,
434 self.tcx().ty_error()
438 fn normalize_ty(&self, _span: Span, ty: Ty<'tcx>) -> Ty<'tcx> {
439 // Types in item signatures are not normalized to avoid undue dependencies.
443 fn set_tainted_by_errors(&self) {
444 // There's no obvious place to track this, so just let it go.
447 fn record_ty(&self, _hir_id: hir::HirId, _ty: Ty<'tcx>, _span: Span) {
448 // There's no place to record types from signatures?
452 /// Synthesize a new lifetime name that doesn't clash with any of the lifetimes already present.
453 fn get_new_lifetime_name<'tcx>(
455 poly_trait_ref: ty::PolyTraitRef<'tcx>,
456 generics: &hir::Generics<'tcx>,
458 let existing_lifetimes = tcx
459 .collect_referenced_late_bound_regions(&poly_trait_ref)
462 if let ty::BoundRegionKind::BrNamed(_, name) = lt {
463 Some(name.as_str().to_string())
468 .chain(generics.params.iter().filter_map(|param| {
469 if let hir::GenericParamKind::Lifetime { .. } = ¶m.kind {
470 Some(param.name.ident().as_str().to_string())
475 .collect::<FxHashSet<String>>();
477 let a_to_z_repeat_n = |n| {
478 (b'a'..=b'z').map(move |c| {
479 let mut s = '\''.to_string();
480 s.extend(std::iter::repeat(char::from(c)).take(n));
485 // If all single char lifetime names are present, we wrap around and double the chars.
486 (1..).flat_map(a_to_z_repeat_n).find(|lt| !existing_lifetimes.contains(lt.as_str())).unwrap()
489 /// Returns the predicates defined on `item_def_id` of the form
490 /// `X: Foo` where `X` is the type parameter `def_id`.
491 fn type_param_predicates(
493 (item_def_id, def_id): (DefId, LocalDefId),
494 ) -> ty::GenericPredicates<'_> {
497 // In the AST, bounds can derive from two places. Either
498 // written inline like `<T: Foo>` or in a where-clause like
501 let param_id = tcx.hir().local_def_id_to_hir_id(def_id);
502 let param_owner = tcx.hir().ty_param_owner(param_id);
503 let param_owner_def_id = tcx.hir().local_def_id(param_owner);
504 let generics = tcx.generics_of(param_owner_def_id);
505 let index = generics.param_def_id_to_index[&def_id.to_def_id()];
506 let ty = tcx.mk_ty_param(index, tcx.hir().ty_param_name(param_id));
508 // Don't look for bounds where the type parameter isn't in scope.
509 let parent = if item_def_id == param_owner_def_id.to_def_id() {
512 tcx.generics_of(item_def_id).parent
515 let mut result = parent
517 let icx = ItemCtxt::new(tcx, parent);
518 icx.get_type_parameter_bounds(DUMMY_SP, def_id.to_def_id())
520 .unwrap_or_default();
521 let mut extend = None;
523 let item_hir_id = tcx.hir().local_def_id_to_hir_id(item_def_id.expect_local());
524 let ast_generics = match tcx.hir().get(item_hir_id) {
525 Node::TraitItem(item) => &item.generics,
527 Node::ImplItem(item) => &item.generics,
529 Node::Item(item) => {
531 ItemKind::Fn(.., ref generics, _)
532 | ItemKind::Impl(hir::Impl { ref generics, .. })
533 | ItemKind::TyAlias(_, ref generics)
534 | ItemKind::OpaqueTy(OpaqueTy { ref generics, impl_trait_fn: None, .. })
535 | ItemKind::Enum(_, ref generics)
536 | ItemKind::Struct(_, ref generics)
537 | ItemKind::Union(_, ref generics) => generics,
538 ItemKind::Trait(_, _, ref generics, ..) => {
539 // Implied `Self: Trait` and supertrait bounds.
540 if param_id == item_hir_id {
541 let identity_trait_ref = ty::TraitRef::identity(tcx, item_def_id);
543 Some((identity_trait_ref.without_const().to_predicate(tcx), item.span));
551 Node::ForeignItem(item) => match item.kind {
552 ForeignItemKind::Fn(_, _, ref generics) => generics,
559 let icx = ItemCtxt::new(tcx, item_def_id);
560 let extra_predicates = extend.into_iter().chain(
561 icx.type_parameter_bounds_in_generics(ast_generics, param_id, ty, OnlySelfBounds(true))
563 .filter(|(predicate, _)| match predicate.kind().skip_binder() {
564 ty::PredicateKind::Trait(data, _) => data.self_ty().is_param(index),
569 tcx.arena.alloc_from_iter(result.predicates.iter().copied().chain(extra_predicates));
573 impl ItemCtxt<'tcx> {
574 /// Finds bounds from `hir::Generics`. This requires scanning through the
575 /// AST. We do this to avoid having to convert *all* the bounds, which
576 /// would create artificial cycles. Instead, we can only convert the
577 /// bounds for a type parameter `X` if `X::Foo` is used.
578 fn type_parameter_bounds_in_generics(
580 ast_generics: &'tcx hir::Generics<'tcx>,
581 param_id: hir::HirId,
583 only_self_bounds: OnlySelfBounds,
584 ) -> Vec<(ty::Predicate<'tcx>, Span)> {
585 let constness = self.default_constness_for_trait_bounds();
586 let from_ty_params = ast_generics
589 .filter_map(|param| match param.kind {
590 GenericParamKind::Type { .. } if param.hir_id == param_id => Some(¶m.bounds),
593 .flat_map(|bounds| bounds.iter())
594 .flat_map(|b| predicates_from_bound(self, ty, b, constness));
596 let from_where_clauses = ast_generics
600 .filter_map(|wp| match *wp {
601 hir::WherePredicate::BoundPredicate(ref bp) => Some(bp),
605 let bt = if is_param(self.tcx, &bp.bounded_ty, param_id) {
607 } else if !only_self_bounds.0 {
608 Some(self.to_ty(&bp.bounded_ty))
612 bp.bounds.iter().filter_map(move |b| bt.map(|bt| (bt, b)))
614 .flat_map(|(bt, b)| predicates_from_bound(self, bt, b, constness));
616 from_ty_params.chain(from_where_clauses).collect()
620 /// Tests whether this is the AST for a reference to the type
621 /// parameter with ID `param_id`. We use this so as to avoid running
622 /// `ast_ty_to_ty`, because we want to avoid triggering an all-out
623 /// conversion of the type to avoid inducing unnecessary cycles.
624 fn is_param(tcx: TyCtxt<'_>, ast_ty: &hir::Ty<'_>, param_id: hir::HirId) -> bool {
625 if let hir::TyKind::Path(hir::QPath::Resolved(None, ref path)) = ast_ty.kind {
627 Res::SelfTy(Some(def_id), None) | Res::Def(DefKind::TyParam, def_id) => {
628 def_id == tcx.hir().local_def_id(param_id).to_def_id()
637 fn convert_item(tcx: TyCtxt<'_>, item_id: hir::HirId) {
638 let it = tcx.hir().expect_item(item_id);
639 debug!("convert: item {} with id {}", it.ident, it.hir_id);
640 let def_id = tcx.hir().local_def_id(item_id);
642 // These don't define types.
643 hir::ItemKind::ExternCrate(_)
644 | hir::ItemKind::Use(..)
645 | hir::ItemKind::Mod(_)
646 | hir::ItemKind::GlobalAsm(_) => {}
647 hir::ItemKind::ForeignMod { items, .. } => {
649 let item = tcx.hir().foreign_item(item.id);
650 let def_id = tcx.hir().local_def_id(item.hir_id);
651 tcx.ensure().generics_of(def_id);
652 tcx.ensure().type_of(def_id);
653 tcx.ensure().predicates_of(def_id);
654 if let hir::ForeignItemKind::Fn(..) = item.kind {
655 tcx.ensure().fn_sig(def_id);
659 hir::ItemKind::Enum(ref enum_definition, _) => {
660 tcx.ensure().generics_of(def_id);
661 tcx.ensure().type_of(def_id);
662 tcx.ensure().predicates_of(def_id);
663 convert_enum_variant_types(tcx, def_id.to_def_id(), &enum_definition.variants);
665 hir::ItemKind::Impl { .. } => {
666 tcx.ensure().generics_of(def_id);
667 tcx.ensure().type_of(def_id);
668 tcx.ensure().impl_trait_ref(def_id);
669 tcx.ensure().predicates_of(def_id);
671 hir::ItemKind::Trait(..) => {
672 tcx.ensure().generics_of(def_id);
673 tcx.ensure().trait_def(def_id);
674 tcx.at(it.span).super_predicates_of(def_id);
675 tcx.ensure().predicates_of(def_id);
677 hir::ItemKind::TraitAlias(..) => {
678 tcx.ensure().generics_of(def_id);
679 tcx.at(it.span).super_predicates_of(def_id);
680 tcx.ensure().predicates_of(def_id);
682 hir::ItemKind::Struct(ref struct_def, _) | hir::ItemKind::Union(ref struct_def, _) => {
683 tcx.ensure().generics_of(def_id);
684 tcx.ensure().type_of(def_id);
685 tcx.ensure().predicates_of(def_id);
687 for f in struct_def.fields() {
688 let def_id = tcx.hir().local_def_id(f.hir_id);
689 tcx.ensure().generics_of(def_id);
690 tcx.ensure().type_of(def_id);
691 tcx.ensure().predicates_of(def_id);
694 if let Some(ctor_hir_id) = struct_def.ctor_hir_id() {
695 convert_variant_ctor(tcx, ctor_hir_id);
699 // Desugared from `impl Trait`, so visited by the function's return type.
700 hir::ItemKind::OpaqueTy(hir::OpaqueTy { impl_trait_fn: Some(_), .. }) => {}
702 // Don't call `type_of` on opaque types, since that depends on type
703 // checking function bodies. `check_item_type` ensures that it's called
705 hir::ItemKind::OpaqueTy(..) => {
706 tcx.ensure().generics_of(def_id);
707 tcx.ensure().predicates_of(def_id);
708 tcx.ensure().explicit_item_bounds(def_id);
710 hir::ItemKind::TyAlias(..)
711 | hir::ItemKind::Static(..)
712 | hir::ItemKind::Const(..)
713 | hir::ItemKind::Fn(..) => {
714 tcx.ensure().generics_of(def_id);
715 tcx.ensure().type_of(def_id);
716 tcx.ensure().predicates_of(def_id);
718 hir::ItemKind::Fn(..) => tcx.ensure().fn_sig(def_id),
719 hir::ItemKind::OpaqueTy(..) => tcx.ensure().item_bounds(def_id),
726 fn convert_trait_item(tcx: TyCtxt<'_>, trait_item_id: hir::HirId) {
727 let trait_item = tcx.hir().expect_trait_item(trait_item_id);
728 let def_id = tcx.hir().local_def_id(trait_item.hir_id);
729 tcx.ensure().generics_of(def_id);
731 match trait_item.kind {
732 hir::TraitItemKind::Fn(..) => {
733 tcx.ensure().type_of(def_id);
734 tcx.ensure().fn_sig(def_id);
737 hir::TraitItemKind::Const(.., Some(_)) => {
738 tcx.ensure().type_of(def_id);
741 hir::TraitItemKind::Const(..) => {
742 tcx.ensure().type_of(def_id);
743 // Account for `const C: _;`.
744 let mut visitor = PlaceholderHirTyCollector::default();
745 visitor.visit_trait_item(trait_item);
746 placeholder_type_error(tcx, None, &[], visitor.0, false);
749 hir::TraitItemKind::Type(_, Some(_)) => {
750 tcx.ensure().item_bounds(def_id);
751 tcx.ensure().type_of(def_id);
752 // Account for `type T = _;`.
753 let mut visitor = PlaceholderHirTyCollector::default();
754 visitor.visit_trait_item(trait_item);
755 placeholder_type_error(tcx, None, &[], visitor.0, false);
758 hir::TraitItemKind::Type(_, None) => {
759 tcx.ensure().item_bounds(def_id);
760 // #74612: Visit and try to find bad placeholders
761 // even if there is no concrete type.
762 let mut visitor = PlaceholderHirTyCollector::default();
763 visitor.visit_trait_item(trait_item);
764 placeholder_type_error(tcx, None, &[], visitor.0, false);
768 tcx.ensure().predicates_of(def_id);
771 fn convert_impl_item(tcx: TyCtxt<'_>, impl_item_id: hir::HirId) {
772 let def_id = tcx.hir().local_def_id(impl_item_id);
773 tcx.ensure().generics_of(def_id);
774 tcx.ensure().type_of(def_id);
775 tcx.ensure().predicates_of(def_id);
776 let impl_item = tcx.hir().expect_impl_item(impl_item_id);
777 match impl_item.kind {
778 hir::ImplItemKind::Fn(..) => {
779 tcx.ensure().fn_sig(def_id);
781 hir::ImplItemKind::TyAlias(_) => {
782 // Account for `type T = _;`
783 let mut visitor = PlaceholderHirTyCollector::default();
784 visitor.visit_impl_item(impl_item);
785 placeholder_type_error(tcx, None, &[], visitor.0, false);
787 hir::ImplItemKind::Const(..) => {}
791 fn convert_variant_ctor(tcx: TyCtxt<'_>, ctor_id: hir::HirId) {
792 let def_id = tcx.hir().local_def_id(ctor_id);
793 tcx.ensure().generics_of(def_id);
794 tcx.ensure().type_of(def_id);
795 tcx.ensure().predicates_of(def_id);
798 fn convert_enum_variant_types(tcx: TyCtxt<'_>, def_id: DefId, variants: &[hir::Variant<'_>]) {
799 let def = tcx.adt_def(def_id);
800 let repr_type = def.repr.discr_type();
801 let initial = repr_type.initial_discriminant(tcx);
802 let mut prev_discr = None::<Discr<'_>>;
804 // fill the discriminant values and field types
805 for variant in variants {
806 let wrapped_discr = prev_discr.map_or(initial, |d| d.wrap_incr(tcx));
808 if let Some(ref e) = variant.disr_expr {
809 let expr_did = tcx.hir().local_def_id(e.hir_id);
810 def.eval_explicit_discr(tcx, expr_did.to_def_id())
811 } else if let Some(discr) = repr_type.disr_incr(tcx, prev_discr) {
814 struct_span_err!(tcx.sess, variant.span, E0370, "enum discriminant overflowed")
817 format!("overflowed on value after {}", prev_discr.unwrap()),
820 "explicitly set `{} = {}` if that is desired outcome",
821 variant.ident, wrapped_discr
826 .unwrap_or(wrapped_discr),
829 for f in variant.data.fields() {
830 let def_id = tcx.hir().local_def_id(f.hir_id);
831 tcx.ensure().generics_of(def_id);
832 tcx.ensure().type_of(def_id);
833 tcx.ensure().predicates_of(def_id);
836 // Convert the ctor, if any. This also registers the variant as
838 if let Some(ctor_hir_id) = variant.data.ctor_hir_id() {
839 convert_variant_ctor(tcx, ctor_hir_id);
846 variant_did: Option<LocalDefId>,
847 ctor_did: Option<LocalDefId>,
849 discr: ty::VariantDiscr,
850 def: &hir::VariantData<'_>,
851 adt_kind: ty::AdtKind,
852 parent_did: LocalDefId,
853 ) -> ty::VariantDef {
854 let mut seen_fields: FxHashMap<Ident, Span> = Default::default();
859 let fid = tcx.hir().local_def_id(f.hir_id);
860 let dup_span = seen_fields.get(&f.ident.normalize_to_macros_2_0()).cloned();
861 if let Some(prev_span) = dup_span {
862 tcx.sess.emit_err(errors::FieldAlreadyDeclared {
868 seen_fields.insert(f.ident.normalize_to_macros_2_0(), f.span);
871 ty::FieldDef { did: fid.to_def_id(), ident: f.ident, vis: tcx.visibility(fid) }
874 let recovered = match def {
875 hir::VariantData::Struct(_, r) => *r,
880 variant_did.map(LocalDefId::to_def_id),
881 ctor_did.map(LocalDefId::to_def_id),
884 CtorKind::from_hir(def),
886 parent_did.to_def_id(),
888 adt_kind == AdtKind::Struct && tcx.has_attr(parent_did.to_def_id(), sym::non_exhaustive)
889 || variant_did.map_or(false, |variant_did| {
890 tcx.has_attr(variant_did.to_def_id(), sym::non_exhaustive)
895 fn adt_def(tcx: TyCtxt<'_>, def_id: DefId) -> &ty::AdtDef {
898 let def_id = def_id.expect_local();
899 let hir_id = tcx.hir().local_def_id_to_hir_id(def_id);
900 let item = match tcx.hir().get(hir_id) {
901 Node::Item(item) => item,
905 let repr = ReprOptions::new(tcx, def_id.to_def_id());
906 let (kind, variants) = match item.kind {
907 ItemKind::Enum(ref def, _) => {
908 let mut distance_from_explicit = 0;
913 let variant_did = Some(tcx.hir().local_def_id(v.id));
915 v.data.ctor_hir_id().map(|hir_id| tcx.hir().local_def_id(hir_id));
917 let discr = if let Some(ref e) = v.disr_expr {
918 distance_from_explicit = 0;
919 ty::VariantDiscr::Explicit(tcx.hir().local_def_id(e.hir_id).to_def_id())
921 ty::VariantDiscr::Relative(distance_from_explicit)
923 distance_from_explicit += 1;
938 (AdtKind::Enum, variants)
940 ItemKind::Struct(ref def, _) => {
941 let variant_did = None::<LocalDefId>;
942 let ctor_did = def.ctor_hir_id().map(|hir_id| tcx.hir().local_def_id(hir_id));
944 let variants = std::iter::once(convert_variant(
949 ty::VariantDiscr::Relative(0),
956 (AdtKind::Struct, variants)
958 ItemKind::Union(ref def, _) => {
959 let variant_did = None;
960 let ctor_did = def.ctor_hir_id().map(|hir_id| tcx.hir().local_def_id(hir_id));
962 let variants = std::iter::once(convert_variant(
967 ty::VariantDiscr::Relative(0),
974 (AdtKind::Union, variants)
978 tcx.alloc_adt_def(def_id.to_def_id(), kind, variants, repr)
981 /// Ensures that the super-predicates of the trait with a `DefId`
982 /// of `trait_def_id` are converted and stored. This also ensures that
983 /// the transitive super-predicates are converted.
984 fn super_predicates_of(tcx: TyCtxt<'_>, trait_def_id: DefId) -> ty::GenericPredicates<'_> {
985 debug!("super_predicates(trait_def_id={:?})", trait_def_id);
986 let trait_hir_id = tcx.hir().local_def_id_to_hir_id(trait_def_id.expect_local());
988 let item = match tcx.hir().get(trait_hir_id) {
989 Node::Item(item) => item,
990 _ => bug!("trait_node_id {} is not an item", trait_hir_id),
993 let (generics, bounds) = match item.kind {
994 hir::ItemKind::Trait(.., ref generics, ref supertraits, _) => (generics, supertraits),
995 hir::ItemKind::TraitAlias(ref generics, ref supertraits) => (generics, supertraits),
996 _ => span_bug!(item.span, "super_predicates invoked on non-trait"),
999 let icx = ItemCtxt::new(tcx, trait_def_id);
1001 // Convert the bounds that follow the colon, e.g., `Bar + Zed` in `trait Foo: Bar + Zed`.
1002 let self_param_ty = tcx.types.self_param;
1004 AstConv::compute_bounds(&icx, self_param_ty, bounds, SizedByDefault::No, item.span);
1006 let superbounds1 = superbounds1.predicates(tcx, self_param_ty);
1008 // Convert any explicit superbounds in the where-clause,
1009 // e.g., `trait Foo where Self: Bar`.
1010 // In the case of trait aliases, however, we include all bounds in the where-clause,
1011 // so e.g., `trait Foo = where u32: PartialEq<Self>` would include `u32: PartialEq<Self>`
1012 // as one of its "superpredicates".
1013 let is_trait_alias = tcx.is_trait_alias(trait_def_id);
1014 let superbounds2 = icx.type_parameter_bounds_in_generics(
1018 OnlySelfBounds(!is_trait_alias),
1021 // Combine the two lists to form the complete set of superbounds:
1022 let superbounds = &*tcx.arena.alloc_from_iter(superbounds1.into_iter().chain(superbounds2));
1024 // Now require that immediate supertraits are converted,
1025 // which will, in turn, reach indirect supertraits.
1026 for &(pred, span) in superbounds {
1027 debug!("superbound: {:?}", pred);
1028 if let ty::PredicateKind::Trait(bound, _) = pred.kind().skip_binder() {
1029 tcx.at(span).super_predicates_of(bound.def_id());
1033 ty::GenericPredicates { parent: None, predicates: superbounds }
1036 fn trait_def(tcx: TyCtxt<'_>, def_id: DefId) -> ty::TraitDef {
1037 let hir_id = tcx.hir().local_def_id_to_hir_id(def_id.expect_local());
1038 let item = tcx.hir().expect_item(hir_id);
1040 let (is_auto, unsafety) = match item.kind {
1041 hir::ItemKind::Trait(is_auto, unsafety, ..) => (is_auto == hir::IsAuto::Yes, unsafety),
1042 hir::ItemKind::TraitAlias(..) => (false, hir::Unsafety::Normal),
1043 _ => span_bug!(item.span, "trait_def_of_item invoked on non-trait"),
1046 let paren_sugar = tcx.has_attr(def_id, sym::rustc_paren_sugar);
1047 if paren_sugar && !tcx.features().unboxed_closures {
1051 "the `#[rustc_paren_sugar]` attribute is a temporary means of controlling \
1052 which traits can use parenthetical notation",
1054 .help("add `#![feature(unboxed_closures)]` to the crate attributes to use it")
1058 let is_marker = tcx.has_attr(def_id, sym::marker);
1059 let spec_kind = if tcx.has_attr(def_id, sym::rustc_unsafe_specialization_marker) {
1060 ty::trait_def::TraitSpecializationKind::Marker
1061 } else if tcx.has_attr(def_id, sym::rustc_specialization_trait) {
1062 ty::trait_def::TraitSpecializationKind::AlwaysApplicable
1064 ty::trait_def::TraitSpecializationKind::None
1066 let def_path_hash = tcx.def_path_hash(def_id);
1067 ty::TraitDef::new(def_id, unsafety, paren_sugar, is_auto, is_marker, spec_kind, def_path_hash)
1070 fn has_late_bound_regions<'tcx>(tcx: TyCtxt<'tcx>, node: Node<'tcx>) -> Option<Span> {
1071 struct LateBoundRegionsDetector<'tcx> {
1073 outer_index: ty::DebruijnIndex,
1074 has_late_bound_regions: Option<Span>,
1077 impl Visitor<'tcx> for LateBoundRegionsDetector<'tcx> {
1078 type Map = intravisit::ErasedMap<'tcx>;
1080 fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
1081 NestedVisitorMap::None
1084 fn visit_ty(&mut self, ty: &'tcx hir::Ty<'tcx>) {
1085 if self.has_late_bound_regions.is_some() {
1089 hir::TyKind::BareFn(..) => {
1090 self.outer_index.shift_in(1);
1091 intravisit::walk_ty(self, ty);
1092 self.outer_index.shift_out(1);
1094 _ => intravisit::walk_ty(self, ty),
1098 fn visit_poly_trait_ref(
1100 tr: &'tcx hir::PolyTraitRef<'tcx>,
1101 m: hir::TraitBoundModifier,
1103 if self.has_late_bound_regions.is_some() {
1106 self.outer_index.shift_in(1);
1107 intravisit::walk_poly_trait_ref(self, tr, m);
1108 self.outer_index.shift_out(1);
1111 fn visit_lifetime(&mut self, lt: &'tcx hir::Lifetime) {
1112 if self.has_late_bound_regions.is_some() {
1116 match self.tcx.named_region(lt.hir_id) {
1117 Some(rl::Region::Static | rl::Region::EarlyBound(..)) => {}
1119 rl::Region::LateBound(debruijn, _, _) | rl::Region::LateBoundAnon(debruijn, _),
1120 ) if debruijn < self.outer_index => {}
1122 rl::Region::LateBound(..)
1123 | rl::Region::LateBoundAnon(..)
1124 | rl::Region::Free(..),
1127 self.has_late_bound_regions = Some(lt.span);
1133 fn has_late_bound_regions<'tcx>(
1135 generics: &'tcx hir::Generics<'tcx>,
1136 decl: &'tcx hir::FnDecl<'tcx>,
1138 let mut visitor = LateBoundRegionsDetector {
1140 outer_index: ty::INNERMOST,
1141 has_late_bound_regions: None,
1143 for param in generics.params {
1144 if let GenericParamKind::Lifetime { .. } = param.kind {
1145 if tcx.is_late_bound(param.hir_id) {
1146 return Some(param.span);
1150 visitor.visit_fn_decl(decl);
1151 visitor.has_late_bound_regions
1155 Node::TraitItem(item) => match item.kind {
1156 hir::TraitItemKind::Fn(ref sig, _) => {
1157 has_late_bound_regions(tcx, &item.generics, &sig.decl)
1161 Node::ImplItem(item) => match item.kind {
1162 hir::ImplItemKind::Fn(ref sig, _) => {
1163 has_late_bound_regions(tcx, &item.generics, &sig.decl)
1167 Node::ForeignItem(item) => match item.kind {
1168 hir::ForeignItemKind::Fn(ref fn_decl, _, ref generics) => {
1169 has_late_bound_regions(tcx, generics, fn_decl)
1173 Node::Item(item) => match item.kind {
1174 hir::ItemKind::Fn(ref sig, .., ref generics, _) => {
1175 has_late_bound_regions(tcx, generics, &sig.decl)
1183 struct AnonConstInParamListDetector {
1184 in_param_list: bool,
1185 found_anon_const_in_list: bool,
1189 impl<'v> Visitor<'v> for AnonConstInParamListDetector {
1190 type Map = intravisit::ErasedMap<'v>;
1192 fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
1193 NestedVisitorMap::None
1196 fn visit_generic_param(&mut self, p: &'v hir::GenericParam<'v>) {
1197 let prev = self.in_param_list;
1198 self.in_param_list = true;
1199 intravisit::walk_generic_param(self, p);
1200 self.in_param_list = prev;
1203 fn visit_anon_const(&mut self, c: &'v hir::AnonConst) {
1204 if self.in_param_list && self.ct == c.hir_id {
1205 self.found_anon_const_in_list = true;
1207 intravisit::walk_anon_const(self, c)
1212 fn generics_of(tcx: TyCtxt<'_>, def_id: DefId) -> ty::Generics {
1215 let hir_id = tcx.hir().local_def_id_to_hir_id(def_id.expect_local());
1217 let node = tcx.hir().get(hir_id);
1218 let parent_def_id = match node {
1220 | Node::TraitItem(_)
1223 | Node::Field(_) => {
1224 let parent_id = tcx.hir().get_parent_item(hir_id);
1225 Some(tcx.hir().local_def_id(parent_id).to_def_id())
1227 // FIXME(#43408) always enable this once `lazy_normalization` is
1228 // stable enough and does not need a feature gate anymore.
1229 Node::AnonConst(_) => {
1230 let parent_id = tcx.hir().get_parent_item(hir_id);
1231 let parent_def_id = tcx.hir().local_def_id(parent_id);
1233 let mut in_param_list = false;
1234 for (_parent, node) in tcx.hir().parent_iter(hir_id) {
1235 if let Some(generics) = node.generics() {
1236 let mut visitor = AnonConstInParamListDetector {
1237 in_param_list: false,
1238 found_anon_const_in_list: false,
1242 visitor.visit_generics(generics);
1243 in_param_list = visitor.found_anon_const_in_list;
1249 // We do not allow generic parameters in anon consts if we are inside
1252 // This affects both default type bindings, e.g. `struct<T, U = [u8; std::mem::size_of::<T>()]>(T, U)`,
1253 // and the types of const parameters, e.g. `struct V<const N: usize, const M: [u8; N]>();`.
1255 } else if tcx.lazy_normalization() {
1256 // HACK(eddyb) this provides the correct generics when
1257 // `feature(const_generics)` is enabled, so that const expressions
1258 // used with const generics, e.g. `Foo<{N+1}>`, can work at all.
1260 // Note that we do not supply the parent generics when using
1261 // `min_const_generics`.
1262 Some(parent_def_id.to_def_id())
1264 let parent_node = tcx.hir().get(tcx.hir().get_parent_node(hir_id));
1266 // HACK(eddyb) this provides the correct generics for repeat
1267 // expressions' count (i.e. `N` in `[x; N]`), and explicit
1268 // `enum` discriminants (i.e. `D` in `enum Foo { Bar = D }`),
1269 // as they shouldn't be able to cause query cycle errors.
1270 Node::Expr(&Expr { kind: ExprKind::Repeat(_, ref constant), .. })
1271 | Node::Variant(Variant { disr_expr: Some(ref constant), .. })
1272 if constant.hir_id == hir_id =>
1274 Some(parent_def_id.to_def_id())
1281 Node::Expr(&hir::Expr { kind: hir::ExprKind::Closure(..), .. }) => {
1282 Some(tcx.closure_base_def_id(def_id))
1284 Node::Item(item) => match item.kind {
1285 ItemKind::OpaqueTy(hir::OpaqueTy { impl_trait_fn, .. }) => {
1286 impl_trait_fn.or_else(|| {
1287 let parent_id = tcx.hir().get_parent_item(hir_id);
1288 assert!(parent_id != hir_id && parent_id != CRATE_HIR_ID);
1289 debug!("generics_of: parent of opaque ty {:?} is {:?}", def_id, parent_id);
1290 // Opaque types are always nested within another item, and
1291 // inherit the generics of the item.
1292 Some(tcx.hir().local_def_id(parent_id).to_def_id())
1300 let mut opt_self = None;
1301 let mut allow_defaults = false;
1303 let no_generics = hir::Generics::empty();
1304 let ast_generics = match node {
1305 Node::TraitItem(item) => &item.generics,
1307 Node::ImplItem(item) => &item.generics,
1309 Node::Item(item) => {
1311 ItemKind::Fn(.., ref generics, _)
1312 | ItemKind::Impl(hir::Impl { ref generics, .. }) => generics,
1314 ItemKind::TyAlias(_, ref generics)
1315 | ItemKind::Enum(_, ref generics)
1316 | ItemKind::Struct(_, ref generics)
1317 | ItemKind::OpaqueTy(hir::OpaqueTy { ref generics, .. })
1318 | ItemKind::Union(_, ref generics) => {
1319 allow_defaults = true;
1323 ItemKind::Trait(_, _, ref generics, ..)
1324 | ItemKind::TraitAlias(ref generics, ..) => {
1325 // Add in the self type parameter.
1327 // Something of a hack: use the node id for the trait, also as
1328 // the node id for the Self type parameter.
1329 let param_id = item.hir_id;
1331 opt_self = Some(ty::GenericParamDef {
1333 name: kw::SelfUpper,
1334 def_id: tcx.hir().local_def_id(param_id).to_def_id(),
1335 pure_wrt_drop: false,
1336 kind: ty::GenericParamDefKind::Type {
1338 object_lifetime_default: rl::Set1::Empty,
1343 allow_defaults = true;
1351 Node::ForeignItem(item) => match item.kind {
1352 ForeignItemKind::Static(..) => &no_generics,
1353 ForeignItemKind::Fn(_, _, ref generics) => generics,
1354 ForeignItemKind::Type => &no_generics,
1360 let has_self = opt_self.is_some();
1361 let mut parent_has_self = false;
1362 let mut own_start = has_self as u32;
1363 let parent_count = parent_def_id.map_or(0, |def_id| {
1364 let generics = tcx.generics_of(def_id);
1365 assert_eq!(has_self, false);
1366 parent_has_self = generics.has_self;
1367 own_start = generics.count() as u32;
1368 generics.parent_count + generics.params.len()
1371 let mut params: Vec<_> = Vec::with_capacity(ast_generics.params.len() + has_self as usize);
1373 if let Some(opt_self) = opt_self {
1374 params.push(opt_self);
1377 let early_lifetimes = early_bound_lifetimes_from_generics(tcx, ast_generics);
1378 params.extend(early_lifetimes.enumerate().map(|(i, param)| ty::GenericParamDef {
1379 name: param.name.ident().name,
1380 index: own_start + i as u32,
1381 def_id: tcx.hir().local_def_id(param.hir_id).to_def_id(),
1382 pure_wrt_drop: param.pure_wrt_drop,
1383 kind: ty::GenericParamDefKind::Lifetime,
1386 let object_lifetime_defaults = tcx.object_lifetime_defaults(hir_id);
1388 // Now create the real type and const parameters.
1389 let type_start = own_start - has_self as u32 + params.len() as u32;
1392 params.extend(ast_generics.params.iter().filter_map(|param| match param.kind {
1393 GenericParamKind::Lifetime { .. } => None,
1394 GenericParamKind::Type { ref default, synthetic, .. } => {
1395 if !allow_defaults && default.is_some() {
1396 if !tcx.features().default_type_parameter_fallback {
1397 tcx.struct_span_lint_hir(
1398 lint::builtin::INVALID_TYPE_PARAM_DEFAULT,
1403 "defaults for type parameters are only allowed in \
1404 `struct`, `enum`, `type`, or `trait` definitions.",
1412 let kind = ty::GenericParamDefKind::Type {
1413 has_default: default.is_some(),
1414 object_lifetime_default: object_lifetime_defaults
1416 .map_or(rl::Set1::Empty, |o| o[i]),
1420 let param_def = ty::GenericParamDef {
1421 index: type_start + i as u32,
1422 name: param.name.ident().name,
1423 def_id: tcx.hir().local_def_id(param.hir_id).to_def_id(),
1424 pure_wrt_drop: param.pure_wrt_drop,
1430 GenericParamKind::Const { .. } => {
1431 let param_def = ty::GenericParamDef {
1432 index: type_start + i as u32,
1433 name: param.name.ident().name,
1434 def_id: tcx.hir().local_def_id(param.hir_id).to_def_id(),
1435 pure_wrt_drop: param.pure_wrt_drop,
1436 kind: ty::GenericParamDefKind::Const,
1443 // provide junk type parameter defs - the only place that
1444 // cares about anything but the length is instantiation,
1445 // and we don't do that for closures.
1446 if let Node::Expr(&hir::Expr { kind: hir::ExprKind::Closure(.., gen), .. }) = node {
1447 let dummy_args = if gen.is_some() {
1448 &["<resume_ty>", "<yield_ty>", "<return_ty>", "<witness>", "<upvars>"][..]
1450 &["<closure_kind>", "<closure_signature>", "<upvars>"][..]
1453 params.extend(dummy_args.iter().enumerate().map(|(i, &arg)| ty::GenericParamDef {
1454 index: type_start + i as u32,
1455 name: Symbol::intern(arg),
1457 pure_wrt_drop: false,
1458 kind: ty::GenericParamDefKind::Type {
1460 object_lifetime_default: rl::Set1::Empty,
1466 let param_def_id_to_index = params.iter().map(|param| (param.def_id, param.index)).collect();
1469 parent: parent_def_id,
1472 param_def_id_to_index,
1473 has_self: has_self || parent_has_self,
1474 has_late_bound_regions: has_late_bound_regions(tcx, node),
1478 fn are_suggestable_generic_args(generic_args: &[hir::GenericArg<'_>]) -> bool {
1481 .filter_map(|arg| match arg {
1482 hir::GenericArg::Type(ty) => Some(ty),
1485 .any(is_suggestable_infer_ty)
1488 /// Whether `ty` is a type with `_` placeholders that can be inferred. Used in diagnostics only to
1489 /// use inference to provide suggestions for the appropriate type if possible.
1490 fn is_suggestable_infer_ty(ty: &hir::Ty<'_>) -> bool {
1494 Slice(ty) | Array(ty, _) => is_suggestable_infer_ty(ty),
1495 Tup(tys) => tys.iter().any(is_suggestable_infer_ty),
1496 Ptr(mut_ty) | Rptr(_, mut_ty) => is_suggestable_infer_ty(mut_ty.ty),
1497 OpaqueDef(_, generic_args) => are_suggestable_generic_args(generic_args),
1498 Path(hir::QPath::TypeRelative(ty, segment)) => {
1499 is_suggestable_infer_ty(ty) || are_suggestable_generic_args(segment.args().args)
1501 Path(hir::QPath::Resolved(ty_opt, hir::Path { segments, .. })) => {
1502 ty_opt.map_or(false, is_suggestable_infer_ty)
1503 || segments.iter().any(|segment| are_suggestable_generic_args(segment.args().args))
1509 pub fn get_infer_ret_ty(output: &'hir hir::FnRetTy<'hir>) -> Option<&'hir hir::Ty<'hir>> {
1510 if let hir::FnRetTy::Return(ref ty) = output {
1511 if is_suggestable_infer_ty(ty) {
1518 fn fn_sig(tcx: TyCtxt<'_>, def_id: DefId) -> ty::PolyFnSig<'_> {
1519 use rustc_hir::Node::*;
1522 let def_id = def_id.expect_local();
1523 let hir_id = tcx.hir().local_def_id_to_hir_id(def_id);
1525 let icx = ItemCtxt::new(tcx, def_id.to_def_id());
1527 match tcx.hir().get(hir_id) {
1528 TraitItem(hir::TraitItem {
1529 kind: TraitItemKind::Fn(sig, TraitFn::Provided(_)),
1534 | ImplItem(hir::ImplItem { kind: ImplItemKind::Fn(sig, _), ident, generics, .. })
1535 | Item(hir::Item { kind: ItemKind::Fn(sig, generics, _), ident, .. }) => {
1536 match get_infer_ret_ty(&sig.decl.output) {
1538 let fn_sig = tcx.typeck(def_id).liberated_fn_sigs()[hir_id];
1539 let mut visitor = PlaceholderHirTyCollector::default();
1540 visitor.visit_ty(ty);
1541 let mut diag = bad_placeholder_type(tcx, visitor.0);
1542 let ret_ty = fn_sig.output();
1543 if ret_ty != tcx.ty_error() {
1544 if !ret_ty.is_closure() {
1545 let ret_ty_str = match ret_ty.kind() {
1546 // Suggest a function pointer return type instead of a unique function definition
1547 // (e.g. `fn() -> i32` instead of `fn() -> i32 { f }`, the latter of which is invalid
1549 ty::FnDef(..) => ret_ty.fn_sig(tcx).to_string(),
1550 _ => ret_ty.to_string(),
1552 diag.span_suggestion(
1554 "replace with the correct return type",
1556 Applicability::MaybeIncorrect,
1559 // We're dealing with a closure, so we should suggest using `impl Fn` or trait bounds
1560 // to prevent the user from getting a papercut while trying to use the unique closure
1561 // syntax (e.g. `[closure@src/lib.rs:2:5: 2:9]`).
1562 diag.help("consider using an `Fn`, `FnMut`, or `FnOnce` trait bound");
1563 diag.note("for more information on `Fn` traits and closure types, see https://doc.rust-lang.org/book/ch13-01-closures.html");
1567 ty::Binder::bind(fn_sig)
1569 None => AstConv::ty_of_fn(
1571 sig.header.unsafety,
1580 TraitItem(hir::TraitItem {
1581 kind: TraitItemKind::Fn(FnSig { header, decl, span: _ }, _),
1586 AstConv::ty_of_fn(&icx, header.unsafety, header.abi, decl, &generics, Some(ident.span))
1589 ForeignItem(&hir::ForeignItem {
1590 kind: ForeignItemKind::Fn(ref fn_decl, _, _),
1594 let abi = tcx.hir().get_foreign_abi(hir_id);
1595 compute_sig_of_foreign_fn_decl(tcx, def_id.to_def_id(), fn_decl, abi, ident)
1598 Ctor(data) | Variant(hir::Variant { data, .. }) if data.ctor_hir_id().is_some() => {
1599 let ty = tcx.type_of(tcx.hir().get_parent_did(hir_id).to_def_id());
1601 data.fields().iter().map(|f| tcx.type_of(tcx.hir().local_def_id(f.hir_id)));
1602 ty::Binder::bind(tcx.mk_fn_sig(
1606 hir::Unsafety::Normal,
1611 Expr(&hir::Expr { kind: hir::ExprKind::Closure(..), .. }) => {
1612 // Closure signatures are not like other function
1613 // signatures and cannot be accessed through `fn_sig`. For
1614 // example, a closure signature excludes the `self`
1615 // argument. In any case they are embedded within the
1616 // closure type as part of the `ClosureSubsts`.
1618 // To get the signature of a closure, you should use the
1619 // `sig` method on the `ClosureSubsts`:
1621 // substs.as_closure().sig(def_id, tcx)
1623 "to get the signature of a closure, use `substs.as_closure().sig()` not `fn_sig()`",
1628 bug!("unexpected sort of node in fn_sig(): {:?}", x);
1633 fn impl_trait_ref(tcx: TyCtxt<'_>, def_id: DefId) -> Option<ty::TraitRef<'_>> {
1634 let icx = ItemCtxt::new(tcx, def_id);
1636 let hir_id = tcx.hir().local_def_id_to_hir_id(def_id.expect_local());
1637 match tcx.hir().expect_item(hir_id).kind {
1638 hir::ItemKind::Impl(ref impl_) => impl_.of_trait.as_ref().map(|ast_trait_ref| {
1639 let selfty = tcx.type_of(def_id);
1640 AstConv::instantiate_mono_trait_ref(&icx, ast_trait_ref, selfty)
1646 fn impl_polarity(tcx: TyCtxt<'_>, def_id: DefId) -> ty::ImplPolarity {
1647 let hir_id = tcx.hir().local_def_id_to_hir_id(def_id.expect_local());
1648 let is_rustc_reservation = tcx.has_attr(def_id, sym::rustc_reservation_impl);
1649 let item = tcx.hir().expect_item(hir_id);
1651 hir::ItemKind::Impl(hir::Impl {
1652 polarity: hir::ImplPolarity::Negative(span),
1656 if is_rustc_reservation {
1657 let span = span.to(of_trait.as_ref().map_or(*span, |t| t.path.span));
1658 tcx.sess.span_err(span, "reservation impls can't be negative");
1660 ty::ImplPolarity::Negative
1662 hir::ItemKind::Impl(hir::Impl {
1663 polarity: hir::ImplPolarity::Positive,
1667 if is_rustc_reservation {
1668 tcx.sess.span_err(item.span, "reservation impls can't be inherent");
1670 ty::ImplPolarity::Positive
1672 hir::ItemKind::Impl(hir::Impl {
1673 polarity: hir::ImplPolarity::Positive,
1677 if is_rustc_reservation {
1678 ty::ImplPolarity::Reservation
1680 ty::ImplPolarity::Positive
1683 item => bug!("impl_polarity: {:?} not an impl", item),
1687 /// Returns the early-bound lifetimes declared in this generics
1688 /// listing. For anything other than fns/methods, this is just all
1689 /// the lifetimes that are declared. For fns or methods, we have to
1690 /// screen out those that do not appear in any where-clauses etc using
1691 /// `resolve_lifetime::early_bound_lifetimes`.
1692 fn early_bound_lifetimes_from_generics<'a, 'tcx: 'a>(
1694 generics: &'a hir::Generics<'a>,
1695 ) -> impl Iterator<Item = &'a hir::GenericParam<'a>> + Captures<'tcx> {
1696 generics.params.iter().filter(move |param| match param.kind {
1697 GenericParamKind::Lifetime { .. } => !tcx.is_late_bound(param.hir_id),
1702 /// Returns a list of type predicates for the definition with ID `def_id`, including inferred
1703 /// lifetime constraints. This includes all predicates returned by `explicit_predicates_of`, plus
1704 /// inferred constraints concerning which regions outlive other regions.
1705 fn predicates_defined_on(tcx: TyCtxt<'_>, def_id: DefId) -> ty::GenericPredicates<'_> {
1706 debug!("predicates_defined_on({:?})", def_id);
1707 let mut result = tcx.explicit_predicates_of(def_id);
1708 debug!("predicates_defined_on: explicit_predicates_of({:?}) = {:?}", def_id, result,);
1709 let inferred_outlives = tcx.inferred_outlives_of(def_id);
1710 if !inferred_outlives.is_empty() {
1712 "predicates_defined_on: inferred_outlives_of({:?}) = {:?}",
1713 def_id, inferred_outlives,
1715 if result.predicates.is_empty() {
1716 result.predicates = inferred_outlives;
1718 result.predicates = tcx
1720 .alloc_from_iter(result.predicates.iter().chain(inferred_outlives).copied());
1724 debug!("predicates_defined_on({:?}) = {:?}", def_id, result);
1728 /// Returns a list of all type predicates (explicit and implicit) for the definition with
1729 /// ID `def_id`. This includes all predicates returned by `predicates_defined_on`, plus
1730 /// `Self: Trait` predicates for traits.
1731 fn predicates_of(tcx: TyCtxt<'_>, def_id: DefId) -> ty::GenericPredicates<'_> {
1732 let mut result = tcx.predicates_defined_on(def_id);
1734 if tcx.is_trait(def_id) {
1735 // For traits, add `Self: Trait` predicate. This is
1736 // not part of the predicates that a user writes, but it
1737 // is something that one must prove in order to invoke a
1738 // method or project an associated type.
1740 // In the chalk setup, this predicate is not part of the
1741 // "predicates" for a trait item. But it is useful in
1742 // rustc because if you directly (e.g.) invoke a trait
1743 // method like `Trait::method(...)`, you must naturally
1744 // prove that the trait applies to the types that were
1745 // used, and adding the predicate into this list ensures
1746 // that this is done.
1747 let span = tcx.sess.source_map().guess_head_span(tcx.def_span(def_id));
1749 tcx.arena.alloc_from_iter(result.predicates.iter().copied().chain(std::iter::once((
1750 ty::TraitRef::identity(tcx, def_id).without_const().to_predicate(tcx),
1754 debug!("predicates_of(def_id={:?}) = {:?}", def_id, result);
1758 /// Returns a list of user-specified type predicates for the definition with ID `def_id`.
1759 /// N.B., this does not include any implied/inferred constraints.
1760 fn gather_explicit_predicates_of(tcx: TyCtxt<'_>, def_id: DefId) -> ty::GenericPredicates<'_> {
1763 debug!("explicit_predicates_of(def_id={:?})", def_id);
1765 let hir_id = tcx.hir().local_def_id_to_hir_id(def_id.expect_local());
1766 let node = tcx.hir().get(hir_id);
1768 let mut is_trait = None;
1769 let mut is_default_impl_trait = None;
1771 let icx = ItemCtxt::new(tcx, def_id);
1772 let constness = icx.default_constness_for_trait_bounds();
1774 const NO_GENERICS: &hir::Generics<'_> = &hir::Generics::empty();
1776 // We use an `IndexSet` to preserves order of insertion.
1777 // Preserving the order of insertion is important here so as not to break UI tests.
1778 let mut predicates: FxIndexSet<(ty::Predicate<'_>, Span)> = FxIndexSet::default();
1780 let ast_generics = match node {
1781 Node::TraitItem(item) => &item.generics,
1783 Node::ImplItem(item) => &item.generics,
1785 Node::Item(item) => {
1787 ItemKind::Impl(ref impl_) => {
1788 if impl_.defaultness.is_default() {
1789 is_default_impl_trait = tcx.impl_trait_ref(def_id);
1793 ItemKind::Fn(.., ref generics, _)
1794 | ItemKind::TyAlias(_, ref generics)
1795 | ItemKind::Enum(_, ref generics)
1796 | ItemKind::Struct(_, ref generics)
1797 | ItemKind::Union(_, ref generics) => generics,
1799 ItemKind::Trait(_, _, ref generics, ..) => {
1800 is_trait = Some(ty::TraitRef::identity(tcx, def_id));
1803 ItemKind::TraitAlias(ref generics, _) => {
1804 is_trait = Some(ty::TraitRef::identity(tcx, def_id));
1807 ItemKind::OpaqueTy(OpaqueTy {
1813 if impl_trait_fn.is_some() {
1814 // return-position impl trait
1816 // We don't inherit predicates from the parent here:
1817 // If we have, say `fn f<'a, T: 'a>() -> impl Sized {}`
1818 // then the return type is `f::<'static, T>::{{opaque}}`.
1820 // If we inherited the predicates of `f` then we would
1821 // require that `T: 'static` to show that the return
1822 // type is well-formed.
1824 // The only way to have something with this opaque type
1825 // is from the return type of the containing function,
1826 // which will ensure that the function's predicates
1828 return ty::GenericPredicates { parent: None, predicates: &[] };
1830 // type-alias impl trait
1839 Node::ForeignItem(item) => match item.kind {
1840 ForeignItemKind::Static(..) => NO_GENERICS,
1841 ForeignItemKind::Fn(_, _, ref generics) => generics,
1842 ForeignItemKind::Type => NO_GENERICS,
1848 let generics = tcx.generics_of(def_id);
1849 let parent_count = generics.parent_count as u32;
1850 let has_own_self = generics.has_self && parent_count == 0;
1852 // Below we'll consider the bounds on the type parameters (including `Self`)
1853 // and the explicit where-clauses, but to get the full set of predicates
1854 // on a trait we need to add in the supertrait bounds and bounds found on
1855 // associated types.
1856 if let Some(_trait_ref) = is_trait {
1857 predicates.extend(tcx.super_predicates_of(def_id).predicates.iter().cloned());
1860 // In default impls, we can assume that the self type implements
1861 // the trait. So in:
1863 // default impl Foo for Bar { .. }
1865 // we add a default where clause `Foo: Bar`. We do a similar thing for traits
1866 // (see below). Recall that a default impl is not itself an impl, but rather a
1867 // set of defaults that can be incorporated into another impl.
1868 if let Some(trait_ref) = is_default_impl_trait {
1870 trait_ref.to_poly_trait_ref().without_const().to_predicate(tcx),
1871 tcx.def_span(def_id),
1875 // Collect the region predicates that were declared inline as
1876 // well. In the case of parameters declared on a fn or method, we
1877 // have to be careful to only iterate over early-bound regions.
1878 let mut index = parent_count + has_own_self as u32;
1879 for param in early_bound_lifetimes_from_generics(tcx, ast_generics) {
1880 let region = tcx.mk_region(ty::ReEarlyBound(ty::EarlyBoundRegion {
1881 def_id: tcx.hir().local_def_id(param.hir_id).to_def_id(),
1883 name: param.name.ident().name,
1888 GenericParamKind::Lifetime { .. } => {
1889 param.bounds.iter().for_each(|bound| match bound {
1890 hir::GenericBound::Outlives(lt) => {
1891 let bound = AstConv::ast_region_to_region(&icx, <, None);
1892 let outlives = ty::Binder::bind(ty::OutlivesPredicate(region, bound));
1893 predicates.insert((outlives.to_predicate(tcx), lt.span));
1902 // Collect the predicates that were written inline by the user on each
1903 // type parameter (e.g., `<T: Foo>`).
1904 for param in ast_generics.params {
1906 // We already dealt with early bound lifetimes above.
1907 GenericParamKind::Lifetime { .. } => (),
1908 GenericParamKind::Type { .. } => {
1909 let name = param.name.ident().name;
1910 let param_ty = ty::ParamTy::new(index, name).to_ty(tcx);
1913 let sized = SizedByDefault::Yes;
1915 AstConv::compute_bounds(&icx, param_ty, ¶m.bounds, sized, param.span);
1916 predicates.extend(bounds.predicates(tcx, param_ty));
1918 GenericParamKind::Const { .. } => {
1919 // Bounds on const parameters are currently not possible.
1920 debug_assert!(param.bounds.is_empty());
1926 // Add in the bounds that appear in the where-clause.
1927 let where_clause = &ast_generics.where_clause;
1928 for predicate in where_clause.predicates {
1930 hir::WherePredicate::BoundPredicate(bound_pred) => {
1931 let ty = icx.to_ty(&bound_pred.bounded_ty);
1933 // Keep the type around in a dummy predicate, in case of no bounds.
1934 // That way, `where Ty:` is not a complete noop (see #53696) and `Ty`
1935 // is still checked for WF.
1936 if bound_pred.bounds.is_empty() {
1937 if let ty::Param(_) = ty.kind() {
1938 // This is a `where T:`, which can be in the HIR from the
1939 // transformation that moves `?Sized` to `T`'s declaration.
1940 // We can skip the predicate because type parameters are
1941 // trivially WF, but also we *should*, to avoid exposing
1942 // users who never wrote `where Type:,` themselves, to
1943 // compiler/tooling bugs from not handling WF predicates.
1945 let span = bound_pred.bounded_ty.span;
1946 let re_root_empty = tcx.lifetimes.re_root_empty;
1947 let predicate = ty::Binder::bind(ty::PredicateKind::TypeOutlives(
1948 ty::OutlivesPredicate(ty, re_root_empty),
1950 predicates.insert((predicate.to_predicate(tcx), span));
1954 for bound in bound_pred.bounds.iter() {
1956 hir::GenericBound::Trait(poly_trait_ref, modifier) => {
1957 let constness = match modifier {
1958 hir::TraitBoundModifier::MaybeConst => hir::Constness::NotConst,
1959 hir::TraitBoundModifier::None => constness,
1960 hir::TraitBoundModifier::Maybe => bug!("this wasn't handled"),
1963 let mut bounds = Bounds::default();
1964 let _ = AstConv::instantiate_poly_trait_ref(
1971 predicates.extend(bounds.predicates(tcx, ty));
1974 &hir::GenericBound::LangItemTrait(lang_item, span, hir_id, args) => {
1975 let mut bounds = Bounds::default();
1976 AstConv::instantiate_lang_item_trait_ref(
1985 predicates.extend(bounds.predicates(tcx, ty));
1988 hir::GenericBound::Outlives(lifetime) => {
1989 let region = AstConv::ast_region_to_region(&icx, lifetime, None);
1991 ty::Binder::bind(ty::PredicateKind::TypeOutlives(
1992 ty::OutlivesPredicate(ty, region),
2002 hir::WherePredicate::RegionPredicate(region_pred) => {
2003 let r1 = AstConv::ast_region_to_region(&icx, ®ion_pred.lifetime, None);
2004 predicates.extend(region_pred.bounds.iter().map(|bound| {
2005 let (r2, span) = match bound {
2006 hir::GenericBound::Outlives(lt) => {
2007 (AstConv::ast_region_to_region(&icx, lt, None), lt.span)
2011 let pred = ty::PredicateKind::RegionOutlives(ty::OutlivesPredicate(r1, r2))
2012 .to_predicate(icx.tcx);
2018 hir::WherePredicate::EqPredicate(..) => {
2024 if tcx.features().const_evaluatable_checked {
2025 predicates.extend(const_evaluatable_predicates_of(tcx, def_id.expect_local()));
2028 let mut predicates: Vec<_> = predicates.into_iter().collect();
2030 // Subtle: before we store the predicates into the tcx, we
2031 // sort them so that predicates like `T: Foo<Item=U>` come
2032 // before uses of `U`. This avoids false ambiguity errors
2033 // in trait checking. See `setup_constraining_predicates`
2035 if let Node::Item(&Item { kind: ItemKind::Impl { .. }, .. }) = node {
2036 let self_ty = tcx.type_of(def_id);
2037 let trait_ref = tcx.impl_trait_ref(def_id);
2038 cgp::setup_constraining_predicates(
2042 &mut cgp::parameters_for_impl(self_ty, trait_ref),
2046 let result = ty::GenericPredicates {
2047 parent: generics.parent,
2048 predicates: tcx.arena.alloc_from_iter(predicates),
2050 debug!("explicit_predicates_of(def_id={:?}) = {:?}", def_id, result);
2054 fn const_evaluatable_predicates_of<'tcx>(
2057 ) -> FxIndexSet<(ty::Predicate<'tcx>, Span)> {
2058 struct ConstCollector<'tcx> {
2060 preds: FxIndexSet<(ty::Predicate<'tcx>, Span)>,
2063 impl<'tcx> intravisit::Visitor<'tcx> for ConstCollector<'tcx> {
2064 type Map = Map<'tcx>;
2066 fn nested_visit_map(&mut self) -> intravisit::NestedVisitorMap<Self::Map> {
2067 intravisit::NestedVisitorMap::None
2070 fn visit_anon_const(&mut self, c: &'tcx hir::AnonConst) {
2071 let def_id = self.tcx.hir().local_def_id(c.hir_id);
2072 let ct = ty::Const::from_anon_const(self.tcx, def_id);
2073 if let ty::ConstKind::Unevaluated(def, substs, None) = ct.val {
2074 let span = self.tcx.hir().span(c.hir_id);
2076 ty::PredicateKind::ConstEvaluatable(def, substs).to_predicate(self.tcx),
2083 let hir_id = tcx.hir().local_def_id_to_hir_id(def_id);
2084 let node = tcx.hir().get(hir_id);
2086 let mut collector = ConstCollector { tcx, preds: FxIndexSet::default() };
2087 if let hir::Node::Item(item) = node {
2088 if let hir::ItemKind::Impl(ref impl_) = item.kind {
2089 if let Some(of_trait) = &impl_.of_trait {
2090 debug!("const_evaluatable_predicates_of({:?}): visit impl trait_ref", def_id);
2091 collector.visit_trait_ref(of_trait);
2094 debug!("const_evaluatable_predicates_of({:?}): visit_self_ty", def_id);
2095 collector.visit_ty(impl_.self_ty);
2099 if let Some(generics) = node.generics() {
2100 debug!("const_evaluatable_predicates_of({:?}): visit_generics", def_id);
2101 collector.visit_generics(generics);
2104 if let Some(fn_sig) = tcx.hir().fn_sig_by_hir_id(hir_id) {
2105 debug!("const_evaluatable_predicates_of({:?}): visit_fn_decl", def_id);
2106 collector.visit_fn_decl(fn_sig.decl);
2108 debug!("const_evaluatable_predicates_of({:?}) = {:?}", def_id, collector.preds);
2113 fn trait_explicit_predicates_and_bounds(
2116 ) -> ty::GenericPredicates<'_> {
2117 assert_eq!(tcx.def_kind(def_id), DefKind::Trait);
2118 gather_explicit_predicates_of(tcx, def_id.to_def_id())
2121 fn explicit_predicates_of(tcx: TyCtxt<'_>, def_id: DefId) -> ty::GenericPredicates<'_> {
2122 if let DefKind::Trait = tcx.def_kind(def_id) {
2123 // Remove bounds on associated types from the predicates, they will be
2124 // returned by `explicit_item_bounds`.
2125 let predicates_and_bounds = tcx.trait_explicit_predicates_and_bounds(def_id.expect_local());
2126 let trait_identity_substs = InternalSubsts::identity_for_item(tcx, def_id);
2128 let is_assoc_item_ty = |ty: Ty<'_>| {
2129 // For a predicate from a where clause to become a bound on an
2131 // * It must use the identity substs of the item.
2132 // * Since any generic parameters on the item are not in scope,
2133 // this means that the item is not a GAT, and its identity
2134 // substs are the same as the trait's.
2135 // * It must be an associated type for this trait (*not* a
2137 if let ty::Projection(projection) = ty.kind() {
2138 projection.substs == trait_identity_substs
2139 && tcx.associated_item(projection.item_def_id).container.id() == def_id
2145 let predicates: Vec<_> = predicates_and_bounds
2149 .filter(|(pred, _)| match pred.kind().skip_binder() {
2150 ty::PredicateKind::Trait(tr, _) => !is_assoc_item_ty(tr.self_ty()),
2151 ty::PredicateKind::Projection(proj) => {
2152 !is_assoc_item_ty(proj.projection_ty.self_ty())
2154 ty::PredicateKind::TypeOutlives(outlives) => !is_assoc_item_ty(outlives.0),
2158 if predicates.len() == predicates_and_bounds.predicates.len() {
2159 predicates_and_bounds
2161 ty::GenericPredicates {
2162 parent: predicates_and_bounds.parent,
2163 predicates: tcx.arena.alloc_slice(&predicates),
2167 gather_explicit_predicates_of(tcx, def_id)
2171 fn projection_ty_from_predicates(
2176 // def_id of `N` in `<T as Trait>::N`
2179 ) -> Option<ty::ProjectionTy<'tcx>> {
2180 let (ty_def_id, item_def_id) = key;
2181 let mut projection_ty = None;
2182 for (predicate, _) in tcx.predicates_of(ty_def_id).predicates {
2183 if let ty::PredicateKind::Projection(projection_predicate) = predicate.kind().skip_binder()
2185 if item_def_id == projection_predicate.projection_ty.item_def_id {
2186 projection_ty = Some(projection_predicate.projection_ty);
2194 /// Converts a specific `GenericBound` from the AST into a set of
2195 /// predicates that apply to the self type. A vector is returned
2196 /// because this can be anywhere from zero predicates (`T: ?Sized` adds no
2197 /// predicates) to one (`T: Foo`) to many (`T: Bar<X = i32>` adds `T: Bar`
2198 /// and `<T as Bar>::X == i32`).
2199 fn predicates_from_bound<'tcx>(
2200 astconv: &dyn AstConv<'tcx>,
2202 bound: &'tcx hir::GenericBound<'tcx>,
2203 constness: hir::Constness,
2204 ) -> Vec<(ty::Predicate<'tcx>, Span)> {
2206 hir::GenericBound::Trait(ref tr, modifier) => {
2207 let constness = match modifier {
2208 hir::TraitBoundModifier::Maybe => return vec![],
2209 hir::TraitBoundModifier::MaybeConst => hir::Constness::NotConst,
2210 hir::TraitBoundModifier::None => constness,
2213 let mut bounds = Bounds::default();
2214 let _ = astconv.instantiate_poly_trait_ref(tr, constness, param_ty, &mut bounds);
2215 bounds.predicates(astconv.tcx(), param_ty)
2217 hir::GenericBound::LangItemTrait(lang_item, span, hir_id, args) => {
2218 let mut bounds = Bounds::default();
2219 astconv.instantiate_lang_item_trait_ref(
2227 bounds.predicates(astconv.tcx(), param_ty)
2229 hir::GenericBound::Outlives(ref lifetime) => {
2230 let region = astconv.ast_region_to_region(lifetime, None);
2231 let pred = ty::PredicateKind::TypeOutlives(ty::OutlivesPredicate(param_ty, region))
2232 .to_predicate(astconv.tcx());
2233 vec![(pred, lifetime.span)]
2238 fn compute_sig_of_foreign_fn_decl<'tcx>(
2241 decl: &'tcx hir::FnDecl<'tcx>,
2244 ) -> ty::PolyFnSig<'tcx> {
2245 let unsafety = if abi == abi::Abi::RustIntrinsic {
2246 intrinsic_operation_unsafety(tcx.item_name(def_id))
2248 hir::Unsafety::Unsafe
2250 let fty = AstConv::ty_of_fn(
2251 &ItemCtxt::new(tcx, def_id),
2255 &hir::Generics::empty(),
2259 // Feature gate SIMD types in FFI, since I am not sure that the
2260 // ABIs are handled at all correctly. -huonw
2261 if abi != abi::Abi::RustIntrinsic
2262 && abi != abi::Abi::PlatformIntrinsic
2263 && !tcx.features().simd_ffi
2265 let check = |ast_ty: &hir::Ty<'_>, ty: Ty<'_>| {
2270 .span_to_snippet(ast_ty.span)
2271 .map_or(String::new(), |s| format!(" `{}`", s));
2276 "use of SIMD type{} in FFI is highly experimental and \
2277 may result in invalid code",
2281 .help("add `#![feature(simd_ffi)]` to the crate attributes to enable")
2285 for (input, ty) in decl.inputs.iter().zip(fty.inputs().skip_binder()) {
2288 if let hir::FnRetTy::Return(ref ty) = decl.output {
2289 check(&ty, fty.output().skip_binder())
2296 fn is_foreign_item(tcx: TyCtxt<'_>, def_id: DefId) -> bool {
2297 match tcx.hir().get_if_local(def_id) {
2298 Some(Node::ForeignItem(..)) => true,
2300 _ => bug!("is_foreign_item applied to non-local def-id {:?}", def_id),
2304 fn static_mutability(tcx: TyCtxt<'_>, def_id: DefId) -> Option<hir::Mutability> {
2305 match tcx.hir().get_if_local(def_id) {
2307 Node::Item(&hir::Item { kind: hir::ItemKind::Static(_, mutbl, _), .. })
2308 | Node::ForeignItem(&hir::ForeignItem {
2309 kind: hir::ForeignItemKind::Static(_, mutbl),
2314 _ => bug!("static_mutability applied to non-local def-id {:?}", def_id),
2318 fn generator_kind(tcx: TyCtxt<'_>, def_id: DefId) -> Option<hir::GeneratorKind> {
2319 match tcx.hir().get_if_local(def_id) {
2320 Some(Node::Expr(&rustc_hir::Expr {
2321 kind: rustc_hir::ExprKind::Closure(_, _, body_id, _, _),
2323 })) => tcx.hir().body(body_id).generator_kind(),
2325 _ => bug!("generator_kind applied to non-local def-id {:?}", def_id),
2329 fn from_target_feature(
2332 attr: &ast::Attribute,
2333 supported_target_features: &FxHashMap<String, Option<Symbol>>,
2334 target_features: &mut Vec<Symbol>,
2336 let list = match attr.meta_item_list() {
2340 let bad_item = |span| {
2341 let msg = "malformed `target_feature` attribute input";
2342 let code = "enable = \"..\"".to_owned();
2344 .struct_span_err(span, &msg)
2345 .span_suggestion(span, "must be of the form", code, Applicability::HasPlaceholders)
2348 let rust_features = tcx.features();
2350 // Only `enable = ...` is accepted in the meta-item list.
2351 if !item.has_name(sym::enable) {
2352 bad_item(item.span());
2356 // Must be of the form `enable = "..."` (a string).
2357 let value = match item.value_str() {
2358 Some(value) => value,
2360 bad_item(item.span());
2365 // We allow comma separation to enable multiple features.
2366 target_features.extend(value.as_str().split(',').filter_map(|feature| {
2367 let feature_gate = match supported_target_features.get(feature) {
2371 format!("the feature named `{}` is not valid for this target", feature);
2372 let mut err = tcx.sess.struct_span_err(item.span(), &msg);
2375 format!("`{}` is not valid for this target", feature),
2377 if let Some(stripped) = feature.strip_prefix('+') {
2378 let valid = supported_target_features.contains_key(stripped);
2380 err.help("consider removing the leading `+` in the feature name");
2388 // Only allow features whose feature gates have been enabled.
2389 let allowed = match feature_gate.as_ref().copied() {
2390 Some(sym::arm_target_feature) => rust_features.arm_target_feature,
2391 Some(sym::aarch64_target_feature) => rust_features.aarch64_target_feature,
2392 Some(sym::hexagon_target_feature) => rust_features.hexagon_target_feature,
2393 Some(sym::powerpc_target_feature) => rust_features.powerpc_target_feature,
2394 Some(sym::mips_target_feature) => rust_features.mips_target_feature,
2395 Some(sym::riscv_target_feature) => rust_features.riscv_target_feature,
2396 Some(sym::avx512_target_feature) => rust_features.avx512_target_feature,
2397 Some(sym::sse4a_target_feature) => rust_features.sse4a_target_feature,
2398 Some(sym::tbm_target_feature) => rust_features.tbm_target_feature,
2399 Some(sym::wasm_target_feature) => rust_features.wasm_target_feature,
2400 Some(sym::cmpxchg16b_target_feature) => rust_features.cmpxchg16b_target_feature,
2401 Some(sym::adx_target_feature) => rust_features.adx_target_feature,
2402 Some(sym::movbe_target_feature) => rust_features.movbe_target_feature,
2403 Some(sym::rtm_target_feature) => rust_features.rtm_target_feature,
2404 Some(sym::f16c_target_feature) => rust_features.f16c_target_feature,
2405 Some(sym::ermsb_target_feature) => rust_features.ermsb_target_feature,
2406 Some(name) => bug!("unknown target feature gate {}", name),
2409 if !allowed && id.is_local() {
2411 &tcx.sess.parse_sess,
2412 feature_gate.unwrap(),
2414 &format!("the target feature `{}` is currently unstable", feature),
2418 Some(Symbol::intern(feature))
2423 fn linkage_by_name(tcx: TyCtxt<'_>, def_id: DefId, name: &str) -> Linkage {
2424 use rustc_middle::mir::mono::Linkage::*;
2426 // Use the names from src/llvm/docs/LangRef.rst here. Most types are only
2427 // applicable to variable declarations and may not really make sense for
2428 // Rust code in the first place but allow them anyway and trust that the
2429 // user knows what s/he's doing. Who knows, unanticipated use cases may pop
2430 // up in the future.
2432 // ghost, dllimport, dllexport and linkonce_odr_autohide are not supported
2433 // and don't have to be, LLVM treats them as no-ops.
2435 "appending" => Appending,
2436 "available_externally" => AvailableExternally,
2438 "extern_weak" => ExternalWeak,
2439 "external" => External,
2440 "internal" => Internal,
2441 "linkonce" => LinkOnceAny,
2442 "linkonce_odr" => LinkOnceODR,
2443 "private" => Private,
2445 "weak_odr" => WeakODR,
2447 let span = tcx.hir().span_if_local(def_id);
2448 if let Some(span) = span {
2449 tcx.sess.span_fatal(span, "invalid linkage specified")
2451 tcx.sess.fatal(&format!("invalid linkage specified: {}", name))
2457 fn codegen_fn_attrs(tcx: TyCtxt<'_>, id: DefId) -> CodegenFnAttrs {
2458 let attrs = tcx.get_attrs(id);
2460 let mut codegen_fn_attrs = CodegenFnAttrs::new();
2461 if should_inherit_track_caller(tcx, id) {
2462 codegen_fn_attrs.flags |= CodegenFnAttrFlags::TRACK_CALLER;
2465 let supported_target_features = tcx.supported_target_features(LOCAL_CRATE);
2467 let mut inline_span = None;
2468 let mut link_ordinal_span = None;
2469 let mut no_sanitize_span = None;
2470 for attr in attrs.iter() {
2471 if tcx.sess.check_name(attr, sym::cold) {
2472 codegen_fn_attrs.flags |= CodegenFnAttrFlags::COLD;
2473 } else if tcx.sess.check_name(attr, sym::rustc_allocator) {
2474 codegen_fn_attrs.flags |= CodegenFnAttrFlags::ALLOCATOR;
2475 } else if tcx.sess.check_name(attr, sym::unwind) {
2476 codegen_fn_attrs.flags |= CodegenFnAttrFlags::UNWIND;
2477 } else if tcx.sess.check_name(attr, sym::ffi_returns_twice) {
2478 if tcx.is_foreign_item(id) {
2479 codegen_fn_attrs.flags |= CodegenFnAttrFlags::FFI_RETURNS_TWICE;
2481 // `#[ffi_returns_twice]` is only allowed `extern fn`s.
2486 "`#[ffi_returns_twice]` may only be used on foreign functions"
2490 } else if tcx.sess.check_name(attr, sym::ffi_pure) {
2491 if tcx.is_foreign_item(id) {
2492 if attrs.iter().any(|a| tcx.sess.check_name(a, sym::ffi_const)) {
2493 // `#[ffi_const]` functions cannot be `#[ffi_pure]`
2498 "`#[ffi_const]` function cannot be `#[ffi_pure]`"
2502 codegen_fn_attrs.flags |= CodegenFnAttrFlags::FFI_PURE;
2505 // `#[ffi_pure]` is only allowed on foreign functions
2510 "`#[ffi_pure]` may only be used on foreign functions"
2514 } else if tcx.sess.check_name(attr, sym::ffi_const) {
2515 if tcx.is_foreign_item(id) {
2516 codegen_fn_attrs.flags |= CodegenFnAttrFlags::FFI_CONST;
2518 // `#[ffi_const]` is only allowed on foreign functions
2523 "`#[ffi_const]` may only be used on foreign functions"
2527 } else if tcx.sess.check_name(attr, sym::rustc_allocator_nounwind) {
2528 codegen_fn_attrs.flags |= CodegenFnAttrFlags::RUSTC_ALLOCATOR_NOUNWIND;
2529 } else if tcx.sess.check_name(attr, sym::naked) {
2530 codegen_fn_attrs.flags |= CodegenFnAttrFlags::NAKED;
2531 } else if tcx.sess.check_name(attr, sym::no_mangle) {
2532 codegen_fn_attrs.flags |= CodegenFnAttrFlags::NO_MANGLE;
2533 } else if tcx.sess.check_name(attr, sym::rustc_std_internal_symbol) {
2534 codegen_fn_attrs.flags |= CodegenFnAttrFlags::RUSTC_STD_INTERNAL_SYMBOL;
2535 } else if tcx.sess.check_name(attr, sym::used) {
2536 codegen_fn_attrs.flags |= CodegenFnAttrFlags::USED;
2537 } else if tcx.sess.check_name(attr, sym::cmse_nonsecure_entry) {
2538 if tcx.fn_sig(id).abi() != abi::Abi::C {
2543 "`#[cmse_nonsecure_entry]` requires C ABI"
2547 if !tcx.sess.target.llvm_target.contains("thumbv8m") {
2548 struct_span_err!(tcx.sess, attr.span, E0775, "`#[cmse_nonsecure_entry]` is only valid for targets with the TrustZone-M extension")
2551 codegen_fn_attrs.flags |= CodegenFnAttrFlags::CMSE_NONSECURE_ENTRY;
2552 } else if tcx.sess.check_name(attr, sym::thread_local) {
2553 codegen_fn_attrs.flags |= CodegenFnAttrFlags::THREAD_LOCAL;
2554 } else if tcx.sess.check_name(attr, sym::track_caller) {
2555 if tcx.is_closure(id) || tcx.fn_sig(id).abi() != abi::Abi::Rust {
2556 struct_span_err!(tcx.sess, attr.span, E0737, "`#[track_caller]` requires Rust ABI")
2559 codegen_fn_attrs.flags |= CodegenFnAttrFlags::TRACK_CALLER;
2560 } else if tcx.sess.check_name(attr, sym::export_name) {
2561 if let Some(s) = attr.value_str() {
2562 if s.as_str().contains('\0') {
2563 // `#[export_name = ...]` will be converted to a null-terminated string,
2564 // so it may not contain any null characters.
2569 "`export_name` may not contain null characters"
2573 codegen_fn_attrs.export_name = Some(s);
2575 } else if tcx.sess.check_name(attr, sym::target_feature) {
2576 if !tcx.is_closure(id) && tcx.fn_sig(id).unsafety() == hir::Unsafety::Normal {
2577 if !tcx.features().target_feature_11 {
2578 let mut err = feature_err(
2579 &tcx.sess.parse_sess,
2580 sym::target_feature_11,
2582 "`#[target_feature(..)]` can only be applied to `unsafe` functions",
2584 err.span_label(tcx.def_span(id), "not an `unsafe` function");
2586 } else if let Some(local_id) = id.as_local() {
2587 check_target_feature_trait_unsafe(tcx, local_id, attr.span);
2590 from_target_feature(
2594 &supported_target_features,
2595 &mut codegen_fn_attrs.target_features,
2597 } else if tcx.sess.check_name(attr, sym::linkage) {
2598 if let Some(val) = attr.value_str() {
2599 codegen_fn_attrs.linkage = Some(linkage_by_name(tcx, id, &val.as_str()));
2601 } else if tcx.sess.check_name(attr, sym::link_section) {
2602 if let Some(val) = attr.value_str() {
2603 if val.as_str().bytes().any(|b| b == 0) {
2605 "illegal null byte in link_section \
2609 tcx.sess.span_err(attr.span, &msg);
2611 codegen_fn_attrs.link_section = Some(val);
2614 } else if tcx.sess.check_name(attr, sym::link_name) {
2615 codegen_fn_attrs.link_name = attr.value_str();
2616 } else if tcx.sess.check_name(attr, sym::link_ordinal) {
2617 link_ordinal_span = Some(attr.span);
2618 if let ordinal @ Some(_) = check_link_ordinal(tcx, attr) {
2619 codegen_fn_attrs.link_ordinal = ordinal;
2621 } else if tcx.sess.check_name(attr, sym::no_sanitize) {
2622 no_sanitize_span = Some(attr.span);
2623 if let Some(list) = attr.meta_item_list() {
2624 for item in list.iter() {
2625 if item.has_name(sym::address) {
2626 codegen_fn_attrs.no_sanitize |= SanitizerSet::ADDRESS;
2627 } else if item.has_name(sym::memory) {
2628 codegen_fn_attrs.no_sanitize |= SanitizerSet::MEMORY;
2629 } else if item.has_name(sym::thread) {
2630 codegen_fn_attrs.no_sanitize |= SanitizerSet::THREAD;
2633 .struct_span_err(item.span(), "invalid argument for `no_sanitize`")
2634 .note("expected one of: `address`, `memory` or `thread`")
2639 } else if tcx.sess.check_name(attr, sym::instruction_set) {
2640 codegen_fn_attrs.instruction_set = match attr.meta().map(|i| i.kind) {
2641 Some(MetaItemKind::List(ref items)) => match items.as_slice() {
2642 [NestedMetaItem::MetaItem(set)] => {
2644 set.path.segments.iter().map(|x| x.ident.name).collect::<Vec<_>>();
2645 match segments.as_slice() {
2646 [sym::arm, sym::a32] | [sym::arm, sym::t32] => {
2647 if !tcx.sess.target.has_thumb_interworking {
2649 tcx.sess.diagnostic(),
2652 "target does not support `#[instruction_set]`"
2656 } else if segments[1] == sym::a32 {
2657 Some(InstructionSetAttr::ArmA32)
2658 } else if segments[1] == sym::t32 {
2659 Some(InstructionSetAttr::ArmT32)
2666 tcx.sess.diagnostic(),
2669 "invalid instruction set specified",
2678 tcx.sess.diagnostic(),
2681 "`#[instruction_set]` requires an argument"
2688 tcx.sess.diagnostic(),
2691 "cannot specify more than one instruction set"
2699 tcx.sess.diagnostic(),
2702 "must specify an instruction set"
2711 codegen_fn_attrs.inline = attrs.iter().fold(InlineAttr::None, |ia, attr| {
2712 if !attr.has_name(sym::inline) {
2715 match attr.meta().map(|i| i.kind) {
2716 Some(MetaItemKind::Word) => {
2717 tcx.sess.mark_attr_used(attr);
2720 Some(MetaItemKind::List(ref items)) => {
2721 tcx.sess.mark_attr_used(attr);
2722 inline_span = Some(attr.span);
2723 if items.len() != 1 {
2725 tcx.sess.diagnostic(),
2728 "expected one argument"
2732 } else if list_contains_name(&items[..], sym::always) {
2734 } else if list_contains_name(&items[..], sym::never) {
2738 tcx.sess.diagnostic(),
2748 Some(MetaItemKind::NameValue(_)) => ia,
2753 codegen_fn_attrs.optimize = attrs.iter().fold(OptimizeAttr::None, |ia, attr| {
2754 if !attr.has_name(sym::optimize) {
2757 let err = |sp, s| struct_span_err!(tcx.sess.diagnostic(), sp, E0722, "{}", s).emit();
2758 match attr.meta().map(|i| i.kind) {
2759 Some(MetaItemKind::Word) => {
2760 err(attr.span, "expected one argument");
2763 Some(MetaItemKind::List(ref items)) => {
2764 tcx.sess.mark_attr_used(attr);
2765 inline_span = Some(attr.span);
2766 if items.len() != 1 {
2767 err(attr.span, "expected one argument");
2769 } else if list_contains_name(&items[..], sym::size) {
2771 } else if list_contains_name(&items[..], sym::speed) {
2774 err(items[0].span(), "invalid argument");
2778 Some(MetaItemKind::NameValue(_)) => ia,
2783 // #73631: closures inherit `#[target_feature]` annotations
2784 if tcx.features().target_feature_11 && tcx.is_closure(id) {
2785 let owner_id = tcx.parent(id).expect("closure should have a parent");
2788 .extend(tcx.codegen_fn_attrs(owner_id).target_features.iter().copied())
2791 // If a function uses #[target_feature] it can't be inlined into general
2792 // purpose functions as they wouldn't have the right target features
2793 // enabled. For that reason we also forbid #[inline(always)] as it can't be
2795 if !codegen_fn_attrs.target_features.is_empty() {
2796 if codegen_fn_attrs.inline == InlineAttr::Always {
2797 if let Some(span) = inline_span {
2800 "cannot use `#[inline(always)]` with \
2801 `#[target_feature]`",
2807 if !codegen_fn_attrs.no_sanitize.is_empty() {
2808 if codegen_fn_attrs.inline == InlineAttr::Always {
2809 if let (Some(no_sanitize_span), Some(inline_span)) = (no_sanitize_span, inline_span) {
2810 let hir_id = tcx.hir().local_def_id_to_hir_id(id.expect_local());
2811 tcx.struct_span_lint_hir(
2812 lint::builtin::INLINE_NO_SANITIZE,
2816 lint.build("`no_sanitize` will have no effect after inlining")
2817 .span_note(inline_span, "inlining requested here")
2825 // Weak lang items have the same semantics as "std internal" symbols in the
2826 // sense that they're preserved through all our LTO passes and only
2827 // strippable by the linker.
2829 // Additionally weak lang items have predetermined symbol names.
2830 if tcx.is_weak_lang_item(id) {
2831 codegen_fn_attrs.flags |= CodegenFnAttrFlags::RUSTC_STD_INTERNAL_SYMBOL;
2833 let check_name = |attr, sym| tcx.sess.check_name(attr, sym);
2834 if let Some(name) = weak_lang_items::link_name(check_name, &attrs) {
2835 codegen_fn_attrs.export_name = Some(name);
2836 codegen_fn_attrs.link_name = Some(name);
2838 check_link_name_xor_ordinal(tcx, &codegen_fn_attrs, link_ordinal_span);
2840 // Internal symbols to the standard library all have no_mangle semantics in
2841 // that they have defined symbol names present in the function name. This
2842 // also applies to weak symbols where they all have known symbol names.
2843 if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::RUSTC_STD_INTERNAL_SYMBOL) {
2844 codegen_fn_attrs.flags |= CodegenFnAttrFlags::NO_MANGLE;
2850 /// Checks if the provided DefId is a method in a trait impl for a trait which has track_caller
2851 /// applied to the method prototype.
2852 fn should_inherit_track_caller(tcx: TyCtxt<'_>, def_id: DefId) -> bool {
2853 if let Some(impl_item) = tcx.opt_associated_item(def_id) {
2854 if let ty::AssocItemContainer::ImplContainer(impl_def_id) = impl_item.container {
2855 if let Some(trait_def_id) = tcx.trait_id_of_impl(impl_def_id) {
2856 if let Some(trait_item) = tcx
2857 .associated_items(trait_def_id)
2858 .filter_by_name_unhygienic(impl_item.ident.name)
2859 .find(move |trait_item| {
2860 trait_item.kind == ty::AssocKind::Fn
2861 && tcx.hygienic_eq(impl_item.ident, trait_item.ident, trait_def_id)
2865 .codegen_fn_attrs(trait_item.def_id)
2867 .intersects(CodegenFnAttrFlags::TRACK_CALLER);
2876 fn check_link_ordinal(tcx: TyCtxt<'_>, attr: &ast::Attribute) -> Option<usize> {
2877 use rustc_ast::{Lit, LitIntType, LitKind};
2878 let meta_item_list = attr.meta_item_list();
2879 let meta_item_list: Option<&[ast::NestedMetaItem]> = meta_item_list.as_ref().map(Vec::as_ref);
2880 let sole_meta_list = match meta_item_list {
2881 Some([item]) => item.literal(),
2884 if let Some(Lit { kind: LitKind::Int(ordinal, LitIntType::Unsuffixed), .. }) = sole_meta_list {
2885 if *ordinal <= usize::MAX as u128 {
2886 Some(*ordinal as usize)
2888 let msg = format!("ordinal value in `link_ordinal` is too large: `{}`", &ordinal);
2890 .struct_span_err(attr.span, &msg)
2891 .note("the value may not exceed `usize::MAX`")
2897 .struct_span_err(attr.span, "illegal ordinal format in `link_ordinal`")
2898 .note("an unsuffixed integer value, e.g., `1`, is expected")
2904 fn check_link_name_xor_ordinal(
2906 codegen_fn_attrs: &CodegenFnAttrs,
2907 inline_span: Option<Span>,
2909 if codegen_fn_attrs.link_name.is_none() || codegen_fn_attrs.link_ordinal.is_none() {
2912 let msg = "cannot use `#[link_name]` with `#[link_ordinal]`";
2913 if let Some(span) = inline_span {
2914 tcx.sess.span_err(span, msg);
2920 /// Checks the function annotated with `#[target_feature]` is not a safe
2921 /// trait method implementation, reporting an error if it is.
2922 fn check_target_feature_trait_unsafe(tcx: TyCtxt<'_>, id: LocalDefId, attr_span: Span) {
2923 let hir_id = tcx.hir().local_def_id_to_hir_id(id);
2924 let node = tcx.hir().get(hir_id);
2925 if let Node::ImplItem(hir::ImplItem { kind: hir::ImplItemKind::Fn(..), .. }) = node {
2926 let parent_id = tcx.hir().get_parent_item(hir_id);
2927 let parent_item = tcx.hir().expect_item(parent_id);
2928 if let hir::ItemKind::Impl(hir::Impl { of_trait: Some(_), .. }) = parent_item.kind {
2932 "`#[target_feature(..)]` cannot be applied to safe trait method",
2934 .span_label(attr_span, "cannot be applied to safe trait method")
2935 .span_label(tcx.def_span(id), "not an `unsafe` function")