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;
53 use std::ops::ControlFlow;
58 struct OnlySelfBounds(bool);
60 ///////////////////////////////////////////////////////////////////////////
63 fn collect_mod_item_types(tcx: TyCtxt<'_>, module_def_id: LocalDefId) {
64 tcx.hir().visit_item_likes_in_module(
66 &mut CollectItemTypesVisitor { tcx }.as_deep_visitor(),
70 pub fn provide(providers: &mut Providers) {
71 *providers = Providers {
72 opt_const_param_of: type_of::opt_const_param_of,
73 type_of: type_of::type_of,
74 item_bounds: item_bounds::item_bounds,
75 explicit_item_bounds: item_bounds::explicit_item_bounds,
78 predicates_defined_on,
79 projection_ty_from_predicates,
80 explicit_predicates_of,
82 trait_explicit_predicates_and_bounds,
83 type_param_predicates,
93 collect_mod_item_types,
98 ///////////////////////////////////////////////////////////////////////////
100 /// Context specific to some particular item. This is what implements
101 /// `AstConv`. It has information about the predicates that are defined
102 /// on the trait. Unfortunately, this predicate information is
103 /// available in various different forms at various points in the
104 /// process. So we can't just store a pointer to e.g., the AST or the
105 /// parsed ty form, we have to be more flexible. To this end, the
106 /// `ItemCtxt` is parameterized by a `DefId` that it uses to satisfy
107 /// `get_type_parameter_bounds` requests, drawing the information from
108 /// the AST (`hir::Generics`), recursively.
109 pub struct ItemCtxt<'tcx> {
114 ///////////////////////////////////////////////////////////////////////////
117 crate struct PlaceholderHirTyCollector(crate Vec<Span>);
119 impl<'v> Visitor<'v> for PlaceholderHirTyCollector {
120 type Map = intravisit::ErasedMap<'v>;
122 fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
123 NestedVisitorMap::None
125 fn visit_ty(&mut self, t: &'v hir::Ty<'v>) {
126 if let hir::TyKind::Infer = t.kind {
129 intravisit::walk_ty(self, t)
133 struct CollectItemTypesVisitor<'tcx> {
137 /// If there are any placeholder types (`_`), emit an error explaining that this is not allowed
138 /// and suggest adding type parameters in the appropriate place, taking into consideration any and
139 /// all already existing generic type parameters to avoid suggesting a name that is already in use.
140 crate fn placeholder_type_error(
143 generics: &[hir::GenericParam<'_>],
144 placeholder_types: Vec<Span>,
147 if placeholder_types.is_empty() {
151 let type_name = generics.next_type_param_name(None);
152 let mut sugg: Vec<_> =
153 placeholder_types.iter().map(|sp| (*sp, (*type_name).to_string())).collect();
155 if generics.is_empty() {
156 if let Some(span) = span {
157 sugg.push((span, format!("<{}>", type_name)));
159 } else if let Some(arg) = generics.iter().find(|arg| match arg.name {
160 hir::ParamName::Plain(Ident { name: kw::Underscore, .. }) => true,
163 // Account for `_` already present in cases like `struct S<_>(_);` and suggest
164 // `struct S<T>(T);` instead of `struct S<_, T>(T);`.
165 sugg.push((arg.span, (*type_name).to_string()));
167 let last = generics.iter().last().unwrap();
169 // Account for bounds, we want `fn foo<T: E, K>(_: K)` not `fn foo<T, K: E>(_: K)`.
170 last.bounds_span().unwrap_or(last.span).shrink_to_hi(),
171 format!(", {}", type_name),
175 let mut err = bad_placeholder_type(tcx, placeholder_types);
177 err.multipart_suggestion(
178 "use type parameters instead",
180 Applicability::HasPlaceholders,
186 fn reject_placeholder_type_signatures_in_item(tcx: TyCtxt<'tcx>, item: &'tcx hir::Item<'tcx>) {
187 let (generics, suggest) = match &item.kind {
188 hir::ItemKind::Union(_, generics)
189 | hir::ItemKind::Enum(_, generics)
190 | hir::ItemKind::TraitAlias(generics, _)
191 | hir::ItemKind::Trait(_, _, generics, ..)
192 | hir::ItemKind::Impl { generics, .. }
193 | hir::ItemKind::Struct(_, generics) => (generics, true),
194 hir::ItemKind::OpaqueTy(hir::OpaqueTy { generics, .. })
195 | hir::ItemKind::TyAlias(_, generics) => (generics, false),
196 // `static`, `fn` and `const` are handled elsewhere to suggest appropriate type.
200 let mut visitor = PlaceholderHirTyCollector::default();
201 visitor.visit_item(item);
203 placeholder_type_error(tcx, Some(generics.span), &generics.params[..], visitor.0, suggest);
206 impl Visitor<'tcx> for CollectItemTypesVisitor<'tcx> {
207 type Map = Map<'tcx>;
209 fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
210 NestedVisitorMap::OnlyBodies(self.tcx.hir())
213 fn visit_item(&mut self, item: &'tcx hir::Item<'tcx>) {
214 convert_item(self.tcx, item.hir_id);
215 reject_placeholder_type_signatures_in_item(self.tcx, item);
216 intravisit::walk_item(self, item);
219 fn visit_generics(&mut self, generics: &'tcx hir::Generics<'tcx>) {
220 for param in generics.params {
222 hir::GenericParamKind::Lifetime { .. } => {}
223 hir::GenericParamKind::Type { default: Some(_), .. } => {
224 let def_id = self.tcx.hir().local_def_id(param.hir_id);
225 self.tcx.ensure().type_of(def_id);
227 hir::GenericParamKind::Type { .. } => {}
228 hir::GenericParamKind::Const { .. } => {
229 let def_id = self.tcx.hir().local_def_id(param.hir_id);
230 self.tcx.ensure().type_of(def_id);
231 // FIXME(const_generics:defaults)
235 intravisit::walk_generics(self, generics);
238 fn visit_expr(&mut self, expr: &'tcx hir::Expr<'tcx>) {
239 if let hir::ExprKind::Closure(..) = expr.kind {
240 let def_id = self.tcx.hir().local_def_id(expr.hir_id);
241 self.tcx.ensure().generics_of(def_id);
242 self.tcx.ensure().type_of(def_id);
244 intravisit::walk_expr(self, expr);
247 fn visit_trait_item(&mut self, trait_item: &'tcx hir::TraitItem<'tcx>) {
248 convert_trait_item(self.tcx, trait_item.hir_id);
249 intravisit::walk_trait_item(self, trait_item);
252 fn visit_impl_item(&mut self, impl_item: &'tcx hir::ImplItem<'tcx>) {
253 convert_impl_item(self.tcx, impl_item.hir_id);
254 intravisit::walk_impl_item(self, impl_item);
258 ///////////////////////////////////////////////////////////////////////////
259 // Utility types and common code for the above passes.
261 fn bad_placeholder_type(
263 mut spans: Vec<Span>,
264 ) -> rustc_errors::DiagnosticBuilder<'tcx> {
266 let mut err = struct_span_err!(
270 "the type placeholder `_` is not allowed within types on item signatures",
273 err.span_label(span, "not allowed in type signatures");
278 impl ItemCtxt<'tcx> {
279 pub fn new(tcx: TyCtxt<'tcx>, item_def_id: DefId) -> ItemCtxt<'tcx> {
280 ItemCtxt { tcx, item_def_id }
283 pub fn to_ty(&self, ast_ty: &'tcx hir::Ty<'tcx>) -> Ty<'tcx> {
284 AstConv::ast_ty_to_ty(self, ast_ty)
287 pub fn hir_id(&self) -> hir::HirId {
288 self.tcx.hir().local_def_id_to_hir_id(self.item_def_id.expect_local())
291 pub fn node(&self) -> hir::Node<'tcx> {
292 self.tcx.hir().get(self.hir_id())
296 impl AstConv<'tcx> for ItemCtxt<'tcx> {
297 fn tcx(&self) -> TyCtxt<'tcx> {
301 fn item_def_id(&self) -> Option<DefId> {
302 Some(self.item_def_id)
305 fn default_constness_for_trait_bounds(&self) -> hir::Constness {
306 if let Some(fn_like) = FnLikeNode::from_node(self.node()) {
309 hir::Constness::NotConst
313 fn get_type_parameter_bounds(&self, span: Span, def_id: DefId) -> ty::GenericPredicates<'tcx> {
314 self.tcx.at(span).type_param_predicates((self.item_def_id, def_id.expect_local()))
317 fn re_infer(&self, _: Option<&ty::GenericParamDef>, _: Span) -> Option<ty::Region<'tcx>> {
321 fn allow_ty_infer(&self) -> bool {
325 fn ty_infer(&self, _: Option<&ty::GenericParamDef>, span: Span) -> Ty<'tcx> {
326 self.tcx().ty_error_with_message(span, "bad_placeholder_type")
332 _: Option<&ty::GenericParamDef>,
334 ) -> &'tcx Const<'tcx> {
335 bad_placeholder_type(self.tcx(), vec![span]).emit();
336 self.tcx().const_error(ty)
339 fn projected_ty_from_poly_trait_ref(
343 item_segment: &hir::PathSegment<'_>,
344 poly_trait_ref: ty::PolyTraitRef<'tcx>,
346 if let Some(trait_ref) = poly_trait_ref.no_bound_vars() {
347 let item_substs = <dyn AstConv<'tcx>>::create_substs_for_associated_item(
355 self.tcx().mk_projection(item_def_id, item_substs)
357 // There are no late-bound regions; we can just ignore the binder.
358 let mut err = struct_span_err!(
362 "cannot use the associated type of a trait \
363 with uninferred generic parameters"
367 hir::Node::Field(_) | hir::Node::Ctor(_) | hir::Node::Variant(_) => {
369 self.tcx.hir().expect_item(self.tcx.hir().get_parent_item(self.hir_id()));
371 hir::ItemKind::Enum(_, generics)
372 | hir::ItemKind::Struct(_, generics)
373 | hir::ItemKind::Union(_, generics) => {
374 let lt_name = get_new_lifetime_name(self.tcx, poly_trait_ref, generics);
375 let (lt_sp, sugg) = match &generics.params[..] {
376 [] => (generics.span, format!("<{}>", lt_name)),
378 (bound.span.shrink_to_lo(), format!("{}, ", lt_name))
381 let suggestions = vec![
387 // Replace the existing lifetimes with a new named lifetime.
389 .replace_late_bound_regions(poly_trait_ref, |_| {
390 self.tcx.mk_region(ty::ReEarlyBound(
391 ty::EarlyBoundRegion {
394 name: Symbol::intern(<_name),
403 err.multipart_suggestion(
404 "use a fully qualified path with explicit lifetimes",
406 Applicability::MaybeIncorrect,
412 hir::Node::Item(hir::Item {
414 hir::ItemKind::Struct(..) | hir::ItemKind::Enum(..) | hir::ItemKind::Union(..),
418 | hir::Node::ForeignItem(_)
419 | hir::Node::TraitItem(_)
420 | hir::Node::ImplItem(_) => {
423 "use a fully qualified path with inferred lifetimes",
426 // Erase named lt, we want `<A as B<'_>::C`, not `<A as B<'a>::C`.
427 self.tcx.anonymize_late_bound_regions(poly_trait_ref).skip_binder(),
430 Applicability::MaybeIncorrect,
436 self.tcx().ty_error()
440 fn normalize_ty(&self, _span: Span, ty: Ty<'tcx>) -> Ty<'tcx> {
441 // Types in item signatures are not normalized to avoid undue dependencies.
445 fn set_tainted_by_errors(&self) {
446 // There's no obvious place to track this, so just let it go.
449 fn record_ty(&self, _hir_id: hir::HirId, _ty: Ty<'tcx>, _span: Span) {
450 // There's no place to record types from signatures?
454 /// Synthesize a new lifetime name that doesn't clash with any of the lifetimes already present.
455 fn get_new_lifetime_name<'tcx>(
457 poly_trait_ref: ty::PolyTraitRef<'tcx>,
458 generics: &hir::Generics<'tcx>,
460 let existing_lifetimes = tcx
461 .collect_referenced_late_bound_regions(&poly_trait_ref)
464 if let ty::BoundRegionKind::BrNamed(_, name) = lt {
465 Some(name.as_str().to_string())
470 .chain(generics.params.iter().filter_map(|param| {
471 if let hir::GenericParamKind::Lifetime { .. } = ¶m.kind {
472 Some(param.name.ident().as_str().to_string())
477 .collect::<FxHashSet<String>>();
479 let a_to_z_repeat_n = |n| {
480 (b'a'..=b'z').map(move |c| {
481 let mut s = '\''.to_string();
482 s.extend(std::iter::repeat(char::from(c)).take(n));
487 // If all single char lifetime names are present, we wrap around and double the chars.
488 (1..).flat_map(a_to_z_repeat_n).find(|lt| !existing_lifetimes.contains(lt.as_str())).unwrap()
491 /// Returns the predicates defined on `item_def_id` of the form
492 /// `X: Foo` where `X` is the type parameter `def_id`.
493 fn type_param_predicates(
495 (item_def_id, def_id): (DefId, LocalDefId),
496 ) -> ty::GenericPredicates<'_> {
499 // In the AST, bounds can derive from two places. Either
500 // written inline like `<T: Foo>` or in a where-clause like
503 let param_id = tcx.hir().local_def_id_to_hir_id(def_id);
504 let param_owner = tcx.hir().ty_param_owner(param_id);
505 let param_owner_def_id = tcx.hir().local_def_id(param_owner);
506 let generics = tcx.generics_of(param_owner_def_id);
507 let index = generics.param_def_id_to_index[&def_id.to_def_id()];
508 let ty = tcx.mk_ty_param(index, tcx.hir().ty_param_name(param_id));
510 // Don't look for bounds where the type parameter isn't in scope.
511 let parent = if item_def_id == param_owner_def_id.to_def_id() {
514 tcx.generics_of(item_def_id).parent
517 let mut result = parent
519 let icx = ItemCtxt::new(tcx, parent);
520 icx.get_type_parameter_bounds(DUMMY_SP, def_id.to_def_id())
522 .unwrap_or_default();
523 let mut extend = None;
525 let item_hir_id = tcx.hir().local_def_id_to_hir_id(item_def_id.expect_local());
526 let ast_generics = match tcx.hir().get(item_hir_id) {
527 Node::TraitItem(item) => &item.generics,
529 Node::ImplItem(item) => &item.generics,
531 Node::Item(item) => {
533 ItemKind::Fn(.., ref generics, _)
534 | ItemKind::Impl { ref generics, .. }
535 | ItemKind::TyAlias(_, ref generics)
536 | ItemKind::OpaqueTy(OpaqueTy { ref generics, impl_trait_fn: None, .. })
537 | ItemKind::Enum(_, ref generics)
538 | ItemKind::Struct(_, ref generics)
539 | ItemKind::Union(_, ref generics) => generics,
540 ItemKind::Trait(_, _, ref generics, ..) => {
541 // Implied `Self: Trait` and supertrait bounds.
542 if param_id == item_hir_id {
543 let identity_trait_ref = ty::TraitRef::identity(tcx, item_def_id);
545 Some((identity_trait_ref.without_const().to_predicate(tcx), item.span));
553 Node::ForeignItem(item) => match item.kind {
554 ForeignItemKind::Fn(_, _, ref generics) => generics,
561 let icx = ItemCtxt::new(tcx, item_def_id);
562 let extra_predicates = extend.into_iter().chain(
563 icx.type_parameter_bounds_in_generics(ast_generics, param_id, ty, OnlySelfBounds(true))
565 .filter(|(predicate, _)| match predicate.skip_binders() {
566 ty::PredicateAtom::Trait(data, _) => data.self_ty().is_param(index),
571 tcx.arena.alloc_from_iter(result.predicates.iter().copied().chain(extra_predicates));
575 impl ItemCtxt<'tcx> {
576 /// Finds bounds from `hir::Generics`. This requires scanning through the
577 /// AST. We do this to avoid having to convert *all* the bounds, which
578 /// would create artificial cycles. Instead, we can only convert the
579 /// bounds for a type parameter `X` if `X::Foo` is used.
580 fn type_parameter_bounds_in_generics(
582 ast_generics: &'tcx hir::Generics<'tcx>,
583 param_id: hir::HirId,
585 only_self_bounds: OnlySelfBounds,
586 ) -> Vec<(ty::Predicate<'tcx>, Span)> {
587 let constness = self.default_constness_for_trait_bounds();
588 let from_ty_params = ast_generics
591 .filter_map(|param| match param.kind {
592 GenericParamKind::Type { .. } if param.hir_id == param_id => Some(¶m.bounds),
595 .flat_map(|bounds| bounds.iter())
596 .flat_map(|b| predicates_from_bound(self, ty, b, constness));
598 let from_where_clauses = ast_generics
602 .filter_map(|wp| match *wp {
603 hir::WherePredicate::BoundPredicate(ref bp) => Some(bp),
607 let bt = if is_param(self.tcx, &bp.bounded_ty, param_id) {
609 } else if !only_self_bounds.0 {
610 Some(self.to_ty(&bp.bounded_ty))
614 bp.bounds.iter().filter_map(move |b| bt.map(|bt| (bt, b)))
616 .flat_map(|(bt, b)| predicates_from_bound(self, bt, b, constness));
618 from_ty_params.chain(from_where_clauses).collect()
622 /// Tests whether this is the AST for a reference to the type
623 /// parameter with ID `param_id`. We use this so as to avoid running
624 /// `ast_ty_to_ty`, because we want to avoid triggering an all-out
625 /// conversion of the type to avoid inducing unnecessary cycles.
626 fn is_param(tcx: TyCtxt<'_>, ast_ty: &hir::Ty<'_>, param_id: hir::HirId) -> bool {
627 if let hir::TyKind::Path(hir::QPath::Resolved(None, ref path)) = ast_ty.kind {
629 Res::SelfTy(Some(def_id), None) | Res::Def(DefKind::TyParam, def_id) => {
630 def_id == tcx.hir().local_def_id(param_id).to_def_id()
639 fn convert_item(tcx: TyCtxt<'_>, item_id: hir::HirId) {
640 let it = tcx.hir().expect_item(item_id);
641 debug!("convert: item {} with id {}", it.ident, it.hir_id);
642 let def_id = tcx.hir().local_def_id(item_id);
644 // These don't define types.
645 hir::ItemKind::ExternCrate(_)
646 | hir::ItemKind::Use(..)
647 | hir::ItemKind::Mod(_)
648 | hir::ItemKind::GlobalAsm(_) => {}
649 hir::ItemKind::ForeignMod { items, .. } => {
651 let item = tcx.hir().foreign_item(item.id);
652 let def_id = tcx.hir().local_def_id(item.hir_id);
653 tcx.ensure().generics_of(def_id);
654 tcx.ensure().type_of(def_id);
655 tcx.ensure().predicates_of(def_id);
656 if let hir::ForeignItemKind::Fn(..) = item.kind {
657 tcx.ensure().fn_sig(def_id);
661 hir::ItemKind::Enum(ref enum_definition, _) => {
662 tcx.ensure().generics_of(def_id);
663 tcx.ensure().type_of(def_id);
664 tcx.ensure().predicates_of(def_id);
665 convert_enum_variant_types(tcx, def_id.to_def_id(), &enum_definition.variants);
667 hir::ItemKind::Impl { .. } => {
668 tcx.ensure().generics_of(def_id);
669 tcx.ensure().type_of(def_id);
670 tcx.ensure().impl_trait_ref(def_id);
671 tcx.ensure().predicates_of(def_id);
673 hir::ItemKind::Trait(..) => {
674 tcx.ensure().generics_of(def_id);
675 tcx.ensure().trait_def(def_id);
676 tcx.at(it.span).super_predicates_of(def_id);
677 tcx.ensure().predicates_of(def_id);
679 hir::ItemKind::TraitAlias(..) => {
680 tcx.ensure().generics_of(def_id);
681 tcx.at(it.span).super_predicates_of(def_id);
682 tcx.ensure().predicates_of(def_id);
684 hir::ItemKind::Struct(ref struct_def, _) | hir::ItemKind::Union(ref struct_def, _) => {
685 tcx.ensure().generics_of(def_id);
686 tcx.ensure().type_of(def_id);
687 tcx.ensure().predicates_of(def_id);
689 for f in struct_def.fields() {
690 let def_id = tcx.hir().local_def_id(f.hir_id);
691 tcx.ensure().generics_of(def_id);
692 tcx.ensure().type_of(def_id);
693 tcx.ensure().predicates_of(def_id);
696 if let Some(ctor_hir_id) = struct_def.ctor_hir_id() {
697 convert_variant_ctor(tcx, ctor_hir_id);
701 // Desugared from `impl Trait`, so visited by the function's return type.
702 hir::ItemKind::OpaqueTy(hir::OpaqueTy { impl_trait_fn: Some(_), .. }) => {}
704 // Don't call `type_of` on opaque types, since that depends on type
705 // checking function bodies. `check_item_type` ensures that it's called
707 hir::ItemKind::OpaqueTy(..) => {
708 tcx.ensure().generics_of(def_id);
709 tcx.ensure().predicates_of(def_id);
710 tcx.ensure().explicit_item_bounds(def_id);
712 hir::ItemKind::TyAlias(..)
713 | hir::ItemKind::Static(..)
714 | hir::ItemKind::Const(..)
715 | hir::ItemKind::Fn(..) => {
716 tcx.ensure().generics_of(def_id);
717 tcx.ensure().type_of(def_id);
718 tcx.ensure().predicates_of(def_id);
720 hir::ItemKind::Fn(..) => tcx.ensure().fn_sig(def_id),
721 hir::ItemKind::OpaqueTy(..) => tcx.ensure().item_bounds(def_id),
728 fn convert_trait_item(tcx: TyCtxt<'_>, trait_item_id: hir::HirId) {
729 let trait_item = tcx.hir().expect_trait_item(trait_item_id);
730 let def_id = tcx.hir().local_def_id(trait_item.hir_id);
731 tcx.ensure().generics_of(def_id);
733 match trait_item.kind {
734 hir::TraitItemKind::Fn(..) => {
735 tcx.ensure().type_of(def_id);
736 tcx.ensure().fn_sig(def_id);
739 hir::TraitItemKind::Const(.., Some(_)) => {
740 tcx.ensure().type_of(def_id);
743 hir::TraitItemKind::Const(..) => {
744 tcx.ensure().type_of(def_id);
745 // Account for `const C: _;`.
746 let mut visitor = PlaceholderHirTyCollector::default();
747 visitor.visit_trait_item(trait_item);
748 placeholder_type_error(tcx, None, &[], visitor.0, false);
751 hir::TraitItemKind::Type(_, Some(_)) => {
752 tcx.ensure().item_bounds(def_id);
753 tcx.ensure().type_of(def_id);
754 // Account for `type T = _;`.
755 let mut visitor = PlaceholderHirTyCollector::default();
756 visitor.visit_trait_item(trait_item);
757 placeholder_type_error(tcx, None, &[], visitor.0, false);
760 hir::TraitItemKind::Type(_, None) => {
761 tcx.ensure().item_bounds(def_id);
762 // #74612: Visit and try to find bad placeholders
763 // even if there is no concrete type.
764 let mut visitor = PlaceholderHirTyCollector::default();
765 visitor.visit_trait_item(trait_item);
766 placeholder_type_error(tcx, None, &[], visitor.0, false);
770 tcx.ensure().predicates_of(def_id);
773 fn convert_impl_item(tcx: TyCtxt<'_>, impl_item_id: hir::HirId) {
774 let def_id = tcx.hir().local_def_id(impl_item_id);
775 tcx.ensure().generics_of(def_id);
776 tcx.ensure().type_of(def_id);
777 tcx.ensure().predicates_of(def_id);
778 let impl_item = tcx.hir().expect_impl_item(impl_item_id);
779 match impl_item.kind {
780 hir::ImplItemKind::Fn(..) => {
781 tcx.ensure().fn_sig(def_id);
783 hir::ImplItemKind::TyAlias(_) => {
784 // Account for `type T = _;`
785 let mut visitor = PlaceholderHirTyCollector::default();
786 visitor.visit_impl_item(impl_item);
787 placeholder_type_error(tcx, None, &[], visitor.0, false);
789 hir::ImplItemKind::Const(..) => {}
793 fn convert_variant_ctor(tcx: TyCtxt<'_>, ctor_id: hir::HirId) {
794 let def_id = tcx.hir().local_def_id(ctor_id);
795 tcx.ensure().generics_of(def_id);
796 tcx.ensure().type_of(def_id);
797 tcx.ensure().predicates_of(def_id);
800 fn convert_enum_variant_types(tcx: TyCtxt<'_>, def_id: DefId, variants: &[hir::Variant<'_>]) {
801 let def = tcx.adt_def(def_id);
802 let repr_type = def.repr.discr_type();
803 let initial = repr_type.initial_discriminant(tcx);
804 let mut prev_discr = None::<Discr<'_>>;
806 // fill the discriminant values and field types
807 for variant in variants {
808 let wrapped_discr = prev_discr.map_or(initial, |d| d.wrap_incr(tcx));
810 if let Some(ref e) = variant.disr_expr {
811 let expr_did = tcx.hir().local_def_id(e.hir_id);
812 def.eval_explicit_discr(tcx, expr_did.to_def_id())
813 } else if let Some(discr) = repr_type.disr_incr(tcx, prev_discr) {
816 struct_span_err!(tcx.sess, variant.span, E0370, "enum discriminant overflowed")
819 format!("overflowed on value after {}", prev_discr.unwrap()),
822 "explicitly set `{} = {}` if that is desired outcome",
823 variant.ident, wrapped_discr
828 .unwrap_or(wrapped_discr),
831 for f in variant.data.fields() {
832 let def_id = tcx.hir().local_def_id(f.hir_id);
833 tcx.ensure().generics_of(def_id);
834 tcx.ensure().type_of(def_id);
835 tcx.ensure().predicates_of(def_id);
838 // Convert the ctor, if any. This also registers the variant as
840 if let Some(ctor_hir_id) = variant.data.ctor_hir_id() {
841 convert_variant_ctor(tcx, ctor_hir_id);
848 variant_did: Option<LocalDefId>,
849 ctor_did: Option<LocalDefId>,
851 discr: ty::VariantDiscr,
852 def: &hir::VariantData<'_>,
853 adt_kind: ty::AdtKind,
854 parent_did: LocalDefId,
855 ) -> ty::VariantDef {
856 let mut seen_fields: FxHashMap<Ident, Span> = Default::default();
861 let fid = tcx.hir().local_def_id(f.hir_id);
862 let dup_span = seen_fields.get(&f.ident.normalize_to_macros_2_0()).cloned();
863 if let Some(prev_span) = dup_span {
864 tcx.sess.emit_err(errors::FieldAlreadyDeclared {
870 seen_fields.insert(f.ident.normalize_to_macros_2_0(), f.span);
873 ty::FieldDef { did: fid.to_def_id(), ident: f.ident, vis: tcx.visibility(fid) }
876 let recovered = match def {
877 hir::VariantData::Struct(_, r) => *r,
882 variant_did.map(LocalDefId::to_def_id),
883 ctor_did.map(LocalDefId::to_def_id),
886 CtorKind::from_hir(def),
888 parent_did.to_def_id(),
890 adt_kind == AdtKind::Struct && tcx.has_attr(parent_did.to_def_id(), sym::non_exhaustive)
891 || variant_did.map_or(false, |variant_did| {
892 tcx.has_attr(variant_did.to_def_id(), sym::non_exhaustive)
897 fn adt_def(tcx: TyCtxt<'_>, def_id: DefId) -> &ty::AdtDef {
900 let def_id = def_id.expect_local();
901 let hir_id = tcx.hir().local_def_id_to_hir_id(def_id);
902 let item = match tcx.hir().get(hir_id) {
903 Node::Item(item) => item,
907 let repr = ReprOptions::new(tcx, def_id.to_def_id());
908 let (kind, variants) = match item.kind {
909 ItemKind::Enum(ref def, _) => {
910 let mut distance_from_explicit = 0;
915 let variant_did = Some(tcx.hir().local_def_id(v.id));
917 v.data.ctor_hir_id().map(|hir_id| tcx.hir().local_def_id(hir_id));
919 let discr = if let Some(ref e) = v.disr_expr {
920 distance_from_explicit = 0;
921 ty::VariantDiscr::Explicit(tcx.hir().local_def_id(e.hir_id).to_def_id())
923 ty::VariantDiscr::Relative(distance_from_explicit)
925 distance_from_explicit += 1;
940 (AdtKind::Enum, variants)
942 ItemKind::Struct(ref def, _) => {
943 let variant_did = None::<LocalDefId>;
944 let ctor_did = def.ctor_hir_id().map(|hir_id| tcx.hir().local_def_id(hir_id));
946 let variants = std::iter::once(convert_variant(
951 ty::VariantDiscr::Relative(0),
958 (AdtKind::Struct, variants)
960 ItemKind::Union(ref def, _) => {
961 let variant_did = None;
962 let ctor_did = def.ctor_hir_id().map(|hir_id| tcx.hir().local_def_id(hir_id));
964 let variants = std::iter::once(convert_variant(
969 ty::VariantDiscr::Relative(0),
976 (AdtKind::Union, variants)
980 tcx.alloc_adt_def(def_id.to_def_id(), kind, variants, repr)
983 /// Ensures that the super-predicates of the trait with a `DefId`
984 /// of `trait_def_id` are converted and stored. This also ensures that
985 /// the transitive super-predicates are converted.
986 fn super_predicates_of(tcx: TyCtxt<'_>, trait_def_id: DefId) -> ty::GenericPredicates<'_> {
987 debug!("super_predicates(trait_def_id={:?})", trait_def_id);
988 let trait_hir_id = tcx.hir().local_def_id_to_hir_id(trait_def_id.expect_local());
990 let item = match tcx.hir().get(trait_hir_id) {
991 Node::Item(item) => item,
992 _ => bug!("trait_node_id {} is not an item", trait_hir_id),
995 let (generics, bounds) = match item.kind {
996 hir::ItemKind::Trait(.., ref generics, ref supertraits, _) => (generics, supertraits),
997 hir::ItemKind::TraitAlias(ref generics, ref supertraits) => (generics, supertraits),
998 _ => span_bug!(item.span, "super_predicates invoked on non-trait"),
1001 let icx = ItemCtxt::new(tcx, trait_def_id);
1003 // Convert the bounds that follow the colon, e.g., `Bar + Zed` in `trait Foo: Bar + Zed`.
1004 let self_param_ty = tcx.types.self_param;
1006 AstConv::compute_bounds(&icx, self_param_ty, bounds, SizedByDefault::No, item.span);
1008 let superbounds1 = superbounds1.predicates(tcx, self_param_ty);
1010 // Convert any explicit superbounds in the where-clause,
1011 // e.g., `trait Foo where Self: Bar`.
1012 // In the case of trait aliases, however, we include all bounds in the where-clause,
1013 // so e.g., `trait Foo = where u32: PartialEq<Self>` would include `u32: PartialEq<Self>`
1014 // as one of its "superpredicates".
1015 let is_trait_alias = tcx.is_trait_alias(trait_def_id);
1016 let superbounds2 = icx.type_parameter_bounds_in_generics(
1020 OnlySelfBounds(!is_trait_alias),
1023 // Combine the two lists to form the complete set of superbounds:
1024 let superbounds = &*tcx.arena.alloc_from_iter(superbounds1.into_iter().chain(superbounds2));
1026 // Now require that immediate supertraits are converted,
1027 // which will, in turn, reach indirect supertraits.
1028 for &(pred, span) in superbounds {
1029 debug!("superbound: {:?}", pred);
1030 if let ty::PredicateAtom::Trait(bound, _) = pred.skip_binders() {
1031 tcx.at(span).super_predicates_of(bound.def_id());
1035 ty::GenericPredicates { parent: None, predicates: superbounds }
1038 fn trait_def(tcx: TyCtxt<'_>, def_id: DefId) -> ty::TraitDef {
1039 let hir_id = tcx.hir().local_def_id_to_hir_id(def_id.expect_local());
1040 let item = tcx.hir().expect_item(hir_id);
1042 let (is_auto, unsafety) = match item.kind {
1043 hir::ItemKind::Trait(is_auto, unsafety, ..) => (is_auto == hir::IsAuto::Yes, unsafety),
1044 hir::ItemKind::TraitAlias(..) => (false, hir::Unsafety::Normal),
1045 _ => span_bug!(item.span, "trait_def_of_item invoked on non-trait"),
1048 let paren_sugar = tcx.has_attr(def_id, sym::rustc_paren_sugar);
1049 if paren_sugar && !tcx.features().unboxed_closures {
1053 "the `#[rustc_paren_sugar]` attribute is a temporary means of controlling \
1054 which traits can use parenthetical notation",
1056 .help("add `#![feature(unboxed_closures)]` to the crate attributes to use it")
1060 let is_marker = tcx.has_attr(def_id, sym::marker);
1061 let spec_kind = if tcx.has_attr(def_id, sym::rustc_unsafe_specialization_marker) {
1062 ty::trait_def::TraitSpecializationKind::Marker
1063 } else if tcx.has_attr(def_id, sym::rustc_specialization_trait) {
1064 ty::trait_def::TraitSpecializationKind::AlwaysApplicable
1066 ty::trait_def::TraitSpecializationKind::None
1068 let def_path_hash = tcx.def_path_hash(def_id);
1069 ty::TraitDef::new(def_id, unsafety, paren_sugar, is_auto, is_marker, spec_kind, def_path_hash)
1072 fn has_late_bound_regions<'tcx>(tcx: TyCtxt<'tcx>, node: Node<'tcx>) -> Option<Span> {
1073 struct LateBoundRegionsDetector<'tcx> {
1075 outer_index: ty::DebruijnIndex,
1076 has_late_bound_regions: Option<Span>,
1079 impl Visitor<'tcx> for LateBoundRegionsDetector<'tcx> {
1080 type Map = intravisit::ErasedMap<'tcx>;
1082 fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
1083 NestedVisitorMap::None
1086 fn visit_ty(&mut self, ty: &'tcx hir::Ty<'tcx>) {
1087 if self.has_late_bound_regions.is_some() {
1091 hir::TyKind::BareFn(..) => {
1092 self.outer_index.shift_in(1);
1093 intravisit::walk_ty(self, ty);
1094 self.outer_index.shift_out(1);
1096 _ => intravisit::walk_ty(self, ty),
1100 fn visit_poly_trait_ref(
1102 tr: &'tcx hir::PolyTraitRef<'tcx>,
1103 m: hir::TraitBoundModifier,
1105 if self.has_late_bound_regions.is_some() {
1108 self.outer_index.shift_in(1);
1109 intravisit::walk_poly_trait_ref(self, tr, m);
1110 self.outer_index.shift_out(1);
1113 fn visit_lifetime(&mut self, lt: &'tcx hir::Lifetime) {
1114 if self.has_late_bound_regions.is_some() {
1118 match self.tcx.named_region(lt.hir_id) {
1119 Some(rl::Region::Static | rl::Region::EarlyBound(..)) => {}
1121 rl::Region::LateBound(debruijn, _, _) | rl::Region::LateBoundAnon(debruijn, _),
1122 ) if debruijn < self.outer_index => {}
1124 rl::Region::LateBound(..)
1125 | rl::Region::LateBoundAnon(..)
1126 | rl::Region::Free(..),
1129 self.has_late_bound_regions = Some(lt.span);
1135 fn has_late_bound_regions<'tcx>(
1137 generics: &'tcx hir::Generics<'tcx>,
1138 decl: &'tcx hir::FnDecl<'tcx>,
1140 let mut visitor = LateBoundRegionsDetector {
1142 outer_index: ty::INNERMOST,
1143 has_late_bound_regions: None,
1145 for param in generics.params {
1146 if let GenericParamKind::Lifetime { .. } = param.kind {
1147 if tcx.is_late_bound(param.hir_id) {
1148 return Some(param.span);
1152 visitor.visit_fn_decl(decl);
1153 visitor.has_late_bound_regions
1157 Node::TraitItem(item) => match item.kind {
1158 hir::TraitItemKind::Fn(ref sig, _) => {
1159 has_late_bound_regions(tcx, &item.generics, &sig.decl)
1163 Node::ImplItem(item) => match item.kind {
1164 hir::ImplItemKind::Fn(ref sig, _) => {
1165 has_late_bound_regions(tcx, &item.generics, &sig.decl)
1169 Node::ForeignItem(item) => match item.kind {
1170 hir::ForeignItemKind::Fn(ref fn_decl, _, ref generics) => {
1171 has_late_bound_regions(tcx, generics, fn_decl)
1175 Node::Item(item) => match item.kind {
1176 hir::ItemKind::Fn(ref sig, .., ref generics, _) => {
1177 has_late_bound_regions(tcx, generics, &sig.decl)
1185 struct AnonConstInParamListDetector {
1186 in_param_list: bool,
1187 found_anon_const_in_list: bool,
1191 impl<'v> Visitor<'v> for AnonConstInParamListDetector {
1192 type Map = intravisit::ErasedMap<'v>;
1194 fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
1195 NestedVisitorMap::None
1198 fn visit_generic_param(&mut self, p: &'v hir::GenericParam<'v>) {
1199 let prev = self.in_param_list;
1200 self.in_param_list = true;
1201 intravisit::walk_generic_param(self, p);
1202 self.in_param_list = prev;
1205 fn visit_anon_const(&mut self, c: &'v hir::AnonConst) {
1206 if self.in_param_list && self.ct == c.hir_id {
1207 self.found_anon_const_in_list = true;
1209 intravisit::walk_anon_const(self, c)
1214 fn generics_of(tcx: TyCtxt<'_>, def_id: DefId) -> ty::Generics {
1217 let hir_id = tcx.hir().local_def_id_to_hir_id(def_id.expect_local());
1219 let node = tcx.hir().get(hir_id);
1220 let parent_def_id = match node {
1222 | Node::TraitItem(_)
1225 | Node::Field(_) => {
1226 let parent_id = tcx.hir().get_parent_item(hir_id);
1227 Some(tcx.hir().local_def_id(parent_id).to_def_id())
1229 // FIXME(#43408) always enable this once `lazy_normalization` is
1230 // stable enough and does not need a feature gate anymore.
1231 Node::AnonConst(_) => {
1232 let parent_id = tcx.hir().get_parent_item(hir_id);
1233 let parent_def_id = tcx.hir().local_def_id(parent_id);
1235 let mut in_param_list = false;
1236 for (_parent, node) in tcx.hir().parent_iter(hir_id) {
1237 if let Some(generics) = node.generics() {
1238 let mut visitor = AnonConstInParamListDetector {
1239 in_param_list: false,
1240 found_anon_const_in_list: false,
1244 visitor.visit_generics(generics);
1245 in_param_list = visitor.found_anon_const_in_list;
1251 // We do not allow generic parameters in anon consts if we are inside
1254 // This affects both default type bindings, e.g. `struct<T, U = [u8; std::mem::size_of::<T>()]>(T, U)`,
1255 // and the types of const parameters, e.g. `struct V<const N: usize, const M: [u8; N]>();`.
1257 } else if tcx.lazy_normalization() {
1258 // HACK(eddyb) this provides the correct generics when
1259 // `feature(const_generics)` is enabled, so that const expressions
1260 // used with const generics, e.g. `Foo<{N+1}>`, can work at all.
1262 // Note that we do not supply the parent generics when using
1263 // `feature(min_const_generics)`.
1264 Some(parent_def_id.to_def_id())
1266 let parent_node = tcx.hir().get(tcx.hir().get_parent_node(hir_id));
1268 // HACK(eddyb) this provides the correct generics for repeat
1269 // expressions' count (i.e. `N` in `[x; N]`), and explicit
1270 // `enum` discriminants (i.e. `D` in `enum Foo { Bar = D }`),
1271 // as they shouldn't be able to cause query cycle errors.
1272 Node::Expr(&Expr { kind: ExprKind::Repeat(_, ref constant), .. })
1273 | Node::Variant(Variant { disr_expr: Some(ref constant), .. })
1274 if constant.hir_id == hir_id =>
1276 Some(parent_def_id.to_def_id())
1283 Node::Expr(&hir::Expr { kind: hir::ExprKind::Closure(..), .. }) => {
1284 Some(tcx.closure_base_def_id(def_id))
1286 Node::Item(item) => match item.kind {
1287 ItemKind::OpaqueTy(hir::OpaqueTy { impl_trait_fn, .. }) => {
1288 impl_trait_fn.or_else(|| {
1289 let parent_id = tcx.hir().get_parent_item(hir_id);
1290 assert!(parent_id != hir_id && parent_id != CRATE_HIR_ID);
1291 debug!("generics_of: parent of opaque ty {:?} is {:?}", def_id, parent_id);
1292 // Opaque types are always nested within another item, and
1293 // inherit the generics of the item.
1294 Some(tcx.hir().local_def_id(parent_id).to_def_id())
1302 let mut opt_self = None;
1303 let mut allow_defaults = false;
1305 let no_generics = hir::Generics::empty();
1306 let ast_generics = match node {
1307 Node::TraitItem(item) => &item.generics,
1309 Node::ImplItem(item) => &item.generics,
1311 Node::Item(item) => {
1313 ItemKind::Fn(.., ref generics, _) | ItemKind::Impl { ref generics, .. } => generics,
1315 ItemKind::TyAlias(_, ref generics)
1316 | ItemKind::Enum(_, ref generics)
1317 | ItemKind::Struct(_, ref generics)
1318 | ItemKind::OpaqueTy(hir::OpaqueTy { ref generics, .. })
1319 | ItemKind::Union(_, ref generics) => {
1320 allow_defaults = true;
1324 ItemKind::Trait(_, _, ref generics, ..)
1325 | ItemKind::TraitAlias(ref generics, ..) => {
1326 // Add in the self type parameter.
1328 // Something of a hack: use the node id for the trait, also as
1329 // the node id for the Self type parameter.
1330 let param_id = item.hir_id;
1332 opt_self = Some(ty::GenericParamDef {
1334 name: kw::SelfUpper,
1335 def_id: tcx.hir().local_def_id(param_id).to_def_id(),
1336 pure_wrt_drop: false,
1337 kind: ty::GenericParamDefKind::Type {
1339 object_lifetime_default: rl::Set1::Empty,
1344 allow_defaults = true;
1352 Node::ForeignItem(item) => match item.kind {
1353 ForeignItemKind::Static(..) => &no_generics,
1354 ForeignItemKind::Fn(_, _, ref generics) => generics,
1355 ForeignItemKind::Type => &no_generics,
1361 let has_self = opt_self.is_some();
1362 let mut parent_has_self = false;
1363 let mut own_start = has_self as u32;
1364 let parent_count = parent_def_id.map_or(0, |def_id| {
1365 let generics = tcx.generics_of(def_id);
1366 assert_eq!(has_self, false);
1367 parent_has_self = generics.has_self;
1368 own_start = generics.count() as u32;
1369 generics.parent_count + generics.params.len()
1372 let mut params: Vec<_> = opt_self.into_iter().collect();
1374 let early_lifetimes = early_bound_lifetimes_from_generics(tcx, ast_generics);
1375 params.extend(early_lifetimes.enumerate().map(|(i, param)| ty::GenericParamDef {
1376 name: param.name.ident().name,
1377 index: own_start + i as u32,
1378 def_id: tcx.hir().local_def_id(param.hir_id).to_def_id(),
1379 pure_wrt_drop: param.pure_wrt_drop,
1380 kind: ty::GenericParamDefKind::Lifetime,
1383 let object_lifetime_defaults = tcx.object_lifetime_defaults(hir_id);
1385 // Now create the real type and const parameters.
1386 let type_start = own_start - has_self as u32 + params.len() as u32;
1389 params.extend(ast_generics.params.iter().filter_map(|param| match param.kind {
1390 GenericParamKind::Lifetime { .. } => None,
1391 GenericParamKind::Type { ref default, synthetic, .. } => {
1392 if !allow_defaults && default.is_some() {
1393 if !tcx.features().default_type_parameter_fallback {
1394 tcx.struct_span_lint_hir(
1395 lint::builtin::INVALID_TYPE_PARAM_DEFAULT,
1400 "defaults for type parameters are only allowed in \
1401 `struct`, `enum`, `type`, or `trait` definitions.",
1409 let kind = ty::GenericParamDefKind::Type {
1410 has_default: default.is_some(),
1411 object_lifetime_default: object_lifetime_defaults
1413 .map_or(rl::Set1::Empty, |o| o[i]),
1417 let param_def = ty::GenericParamDef {
1418 index: type_start + i as u32,
1419 name: param.name.ident().name,
1420 def_id: tcx.hir().local_def_id(param.hir_id).to_def_id(),
1421 pure_wrt_drop: param.pure_wrt_drop,
1427 GenericParamKind::Const { .. } => {
1428 let param_def = ty::GenericParamDef {
1429 index: type_start + i as u32,
1430 name: param.name.ident().name,
1431 def_id: tcx.hir().local_def_id(param.hir_id).to_def_id(),
1432 pure_wrt_drop: param.pure_wrt_drop,
1433 kind: ty::GenericParamDefKind::Const,
1440 // provide junk type parameter defs - the only place that
1441 // cares about anything but the length is instantiation,
1442 // and we don't do that for closures.
1443 if let Node::Expr(&hir::Expr { kind: hir::ExprKind::Closure(.., gen), .. }) = node {
1444 let dummy_args = if gen.is_some() {
1445 &["<resume_ty>", "<yield_ty>", "<return_ty>", "<witness>", "<upvars>"][..]
1447 &["<closure_kind>", "<closure_signature>", "<upvars>"][..]
1450 params.extend(dummy_args.iter().enumerate().map(|(i, &arg)| ty::GenericParamDef {
1451 index: type_start + i as u32,
1452 name: Symbol::intern(arg),
1454 pure_wrt_drop: false,
1455 kind: ty::GenericParamDefKind::Type {
1457 object_lifetime_default: rl::Set1::Empty,
1463 let param_def_id_to_index = params.iter().map(|param| (param.def_id, param.index)).collect();
1466 parent: parent_def_id,
1469 param_def_id_to_index,
1470 has_self: has_self || parent_has_self,
1471 has_late_bound_regions: has_late_bound_regions(tcx, node),
1475 fn are_suggestable_generic_args(generic_args: &[hir::GenericArg<'_>]) -> bool {
1478 .filter_map(|arg| match arg {
1479 hir::GenericArg::Type(ty) => Some(ty),
1482 .any(is_suggestable_infer_ty)
1485 /// Whether `ty` is a type with `_` placeholders that can be inferred. Used in diagnostics only to
1486 /// use inference to provide suggestions for the appropriate type if possible.
1487 fn is_suggestable_infer_ty(ty: &hir::Ty<'_>) -> bool {
1491 Slice(ty) | Array(ty, _) => is_suggestable_infer_ty(ty),
1492 Tup(tys) => tys.iter().any(is_suggestable_infer_ty),
1493 Ptr(mut_ty) | Rptr(_, mut_ty) => is_suggestable_infer_ty(mut_ty.ty),
1494 OpaqueDef(_, generic_args) => are_suggestable_generic_args(generic_args),
1495 Path(hir::QPath::TypeRelative(ty, segment)) => {
1496 is_suggestable_infer_ty(ty) || are_suggestable_generic_args(segment.generic_args().args)
1498 Path(hir::QPath::Resolved(ty_opt, hir::Path { segments, .. })) => {
1499 ty_opt.map_or(false, is_suggestable_infer_ty)
1502 .any(|segment| are_suggestable_generic_args(segment.generic_args().args))
1508 pub fn get_infer_ret_ty(output: &'hir hir::FnRetTy<'hir>) -> Option<&'hir hir::Ty<'hir>> {
1509 if let hir::FnRetTy::Return(ref ty) = output {
1510 if is_suggestable_infer_ty(ty) {
1517 fn fn_sig(tcx: TyCtxt<'_>, def_id: DefId) -> ty::PolyFnSig<'_> {
1518 use rustc_hir::Node::*;
1521 let def_id = def_id.expect_local();
1522 let hir_id = tcx.hir().local_def_id_to_hir_id(def_id);
1524 let icx = ItemCtxt::new(tcx, def_id.to_def_id());
1526 match tcx.hir().get(hir_id) {
1527 TraitItem(hir::TraitItem {
1528 kind: TraitItemKind::Fn(sig, TraitFn::Provided(_)),
1533 | ImplItem(hir::ImplItem { kind: ImplItemKind::Fn(sig, _), ident, generics, .. })
1534 | Item(hir::Item { kind: ItemKind::Fn(sig, generics, _), ident, .. }) => {
1535 match get_infer_ret_ty(&sig.decl.output) {
1537 let fn_sig = tcx.typeck(def_id).liberated_fn_sigs()[hir_id];
1538 let mut visitor = PlaceholderHirTyCollector::default();
1539 visitor.visit_ty(ty);
1540 let mut diag = bad_placeholder_type(tcx, visitor.0);
1541 let ret_ty = fn_sig.output();
1542 if ret_ty != tcx.ty_error() {
1543 diag.span_suggestion(
1545 "replace with the correct return type",
1547 Applicability::MaybeIncorrect,
1551 ty::Binder::bind(fn_sig)
1553 None => AstConv::ty_of_fn(
1555 sig.header.unsafety,
1564 TraitItem(hir::TraitItem {
1565 kind: TraitItemKind::Fn(FnSig { header, decl, span: _ }, _),
1570 AstConv::ty_of_fn(&icx, header.unsafety, header.abi, decl, &generics, Some(ident.span))
1573 ForeignItem(&hir::ForeignItem {
1574 kind: ForeignItemKind::Fn(ref fn_decl, _, _),
1578 let abi = tcx.hir().get_foreign_abi(hir_id);
1579 compute_sig_of_foreign_fn_decl(tcx, def_id.to_def_id(), fn_decl, abi, ident)
1582 Ctor(data) | Variant(hir::Variant { data, .. }) if data.ctor_hir_id().is_some() => {
1583 let ty = tcx.type_of(tcx.hir().get_parent_did(hir_id).to_def_id());
1585 data.fields().iter().map(|f| tcx.type_of(tcx.hir().local_def_id(f.hir_id)));
1586 ty::Binder::bind(tcx.mk_fn_sig(
1590 hir::Unsafety::Normal,
1595 Expr(&hir::Expr { kind: hir::ExprKind::Closure(..), .. }) => {
1596 // Closure signatures are not like other function
1597 // signatures and cannot be accessed through `fn_sig`. For
1598 // example, a closure signature excludes the `self`
1599 // argument. In any case they are embedded within the
1600 // closure type as part of the `ClosureSubsts`.
1602 // To get the signature of a closure, you should use the
1603 // `sig` method on the `ClosureSubsts`:
1605 // substs.as_closure().sig(def_id, tcx)
1607 "to get the signature of a closure, use `substs.as_closure().sig()` not `fn_sig()`",
1612 bug!("unexpected sort of node in fn_sig(): {:?}", x);
1617 fn impl_trait_ref(tcx: TyCtxt<'_>, def_id: DefId) -> Option<ty::TraitRef<'_>> {
1618 let icx = ItemCtxt::new(tcx, def_id);
1620 let hir_id = tcx.hir().local_def_id_to_hir_id(def_id.expect_local());
1621 match tcx.hir().expect_item(hir_id).kind {
1622 hir::ItemKind::Impl { ref of_trait, .. } => of_trait.as_ref().map(|ast_trait_ref| {
1623 let selfty = tcx.type_of(def_id);
1624 AstConv::instantiate_mono_trait_ref(&icx, ast_trait_ref, selfty)
1630 fn impl_polarity(tcx: TyCtxt<'_>, def_id: DefId) -> ty::ImplPolarity {
1631 let hir_id = tcx.hir().local_def_id_to_hir_id(def_id.expect_local());
1632 let is_rustc_reservation = tcx.has_attr(def_id, sym::rustc_reservation_impl);
1633 let item = tcx.hir().expect_item(hir_id);
1635 hir::ItemKind::Impl { polarity: hir::ImplPolarity::Negative(span), of_trait, .. } => {
1636 if is_rustc_reservation {
1637 let span = span.to(of_trait.as_ref().map(|t| t.path.span).unwrap_or(*span));
1638 tcx.sess.span_err(span, "reservation impls can't be negative");
1640 ty::ImplPolarity::Negative
1642 hir::ItemKind::Impl { polarity: hir::ImplPolarity::Positive, of_trait: None, .. } => {
1643 if is_rustc_reservation {
1644 tcx.sess.span_err(item.span, "reservation impls can't be inherent");
1646 ty::ImplPolarity::Positive
1648 hir::ItemKind::Impl {
1649 polarity: hir::ImplPolarity::Positive, of_trait: Some(_), ..
1651 if is_rustc_reservation {
1652 ty::ImplPolarity::Reservation
1654 ty::ImplPolarity::Positive
1657 ref item => bug!("impl_polarity: {:?} not an impl", item),
1661 /// Returns the early-bound lifetimes declared in this generics
1662 /// listing. For anything other than fns/methods, this is just all
1663 /// the lifetimes that are declared. For fns or methods, we have to
1664 /// screen out those that do not appear in any where-clauses etc using
1665 /// `resolve_lifetime::early_bound_lifetimes`.
1666 fn early_bound_lifetimes_from_generics<'a, 'tcx: 'a>(
1668 generics: &'a hir::Generics<'a>,
1669 ) -> impl Iterator<Item = &'a hir::GenericParam<'a>> + Captures<'tcx> {
1670 generics.params.iter().filter(move |param| match param.kind {
1671 GenericParamKind::Lifetime { .. } => !tcx.is_late_bound(param.hir_id),
1676 /// Returns a list of type predicates for the definition with ID `def_id`, including inferred
1677 /// lifetime constraints. This includes all predicates returned by `explicit_predicates_of`, plus
1678 /// inferred constraints concerning which regions outlive other regions.
1679 fn predicates_defined_on(tcx: TyCtxt<'_>, def_id: DefId) -> ty::GenericPredicates<'_> {
1680 debug!("predicates_defined_on({:?})", def_id);
1681 let mut result = tcx.explicit_predicates_of(def_id);
1682 debug!("predicates_defined_on: explicit_predicates_of({:?}) = {:?}", def_id, result,);
1683 let inferred_outlives = tcx.inferred_outlives_of(def_id);
1684 if !inferred_outlives.is_empty() {
1686 "predicates_defined_on: inferred_outlives_of({:?}) = {:?}",
1687 def_id, inferred_outlives,
1689 if result.predicates.is_empty() {
1690 result.predicates = inferred_outlives;
1692 result.predicates = tcx
1694 .alloc_from_iter(result.predicates.iter().chain(inferred_outlives).copied());
1698 debug!("predicates_defined_on({:?}) = {:?}", def_id, result);
1702 /// Returns a list of all type predicates (explicit and implicit) for the definition with
1703 /// ID `def_id`. This includes all predicates returned by `predicates_defined_on`, plus
1704 /// `Self: Trait` predicates for traits.
1705 fn predicates_of(tcx: TyCtxt<'_>, def_id: DefId) -> ty::GenericPredicates<'_> {
1706 let mut result = tcx.predicates_defined_on(def_id);
1708 if tcx.is_trait(def_id) {
1709 // For traits, add `Self: Trait` predicate. This is
1710 // not part of the predicates that a user writes, but it
1711 // is something that one must prove in order to invoke a
1712 // method or project an associated type.
1714 // In the chalk setup, this predicate is not part of the
1715 // "predicates" for a trait item. But it is useful in
1716 // rustc because if you directly (e.g.) invoke a trait
1717 // method like `Trait::method(...)`, you must naturally
1718 // prove that the trait applies to the types that were
1719 // used, and adding the predicate into this list ensures
1720 // that this is done.
1721 let span = tcx.sess.source_map().guess_head_span(tcx.def_span(def_id));
1723 tcx.arena.alloc_from_iter(result.predicates.iter().copied().chain(std::iter::once((
1724 ty::TraitRef::identity(tcx, def_id).without_const().to_predicate(tcx),
1728 debug!("predicates_of(def_id={:?}) = {:?}", def_id, result);
1732 /// Returns a list of user-specified type predicates for the definition with ID `def_id`.
1733 /// N.B., this does not include any implied/inferred constraints.
1734 fn gather_explicit_predicates_of(tcx: TyCtxt<'_>, def_id: DefId) -> ty::GenericPredicates<'_> {
1737 debug!("explicit_predicates_of(def_id={:?})", def_id);
1739 let hir_id = tcx.hir().local_def_id_to_hir_id(def_id.expect_local());
1740 let node = tcx.hir().get(hir_id);
1742 let mut is_trait = None;
1743 let mut is_default_impl_trait = None;
1745 let icx = ItemCtxt::new(tcx, def_id);
1746 let constness = icx.default_constness_for_trait_bounds();
1748 const NO_GENERICS: &hir::Generics<'_> = &hir::Generics::empty();
1750 // We use an `IndexSet` to preserves order of insertion.
1751 // Preserving the order of insertion is important here so as not to break
1752 // compile-fail UI tests.
1753 let mut predicates: FxIndexSet<(ty::Predicate<'_>, Span)> = FxIndexSet::default();
1755 let ast_generics = match node {
1756 Node::TraitItem(item) => &item.generics,
1758 Node::ImplItem(item) => &item.generics,
1760 Node::Item(item) => {
1762 ItemKind::Impl { defaultness, ref generics, .. } => {
1763 if defaultness.is_default() {
1764 is_default_impl_trait = tcx.impl_trait_ref(def_id);
1768 ItemKind::Fn(.., ref generics, _)
1769 | ItemKind::TyAlias(_, ref generics)
1770 | ItemKind::Enum(_, ref generics)
1771 | ItemKind::Struct(_, ref generics)
1772 | ItemKind::Union(_, ref generics) => generics,
1774 ItemKind::Trait(_, _, ref generics, ..) => {
1775 is_trait = Some(ty::TraitRef::identity(tcx, def_id));
1778 ItemKind::TraitAlias(ref generics, _) => {
1779 is_trait = Some(ty::TraitRef::identity(tcx, def_id));
1782 ItemKind::OpaqueTy(OpaqueTy {
1788 if impl_trait_fn.is_some() {
1789 // return-position impl trait
1791 // We don't inherit predicates from the parent here:
1792 // If we have, say `fn f<'a, T: 'a>() -> impl Sized {}`
1793 // then the return type is `f::<'static, T>::{{opaque}}`.
1795 // If we inherited the predicates of `f` then we would
1796 // require that `T: 'static` to show that the return
1797 // type is well-formed.
1799 // The only way to have something with this opaque type
1800 // is from the return type of the containing function,
1801 // which will ensure that the function's predicates
1803 return ty::GenericPredicates { parent: None, predicates: &[] };
1805 // type-alias impl trait
1814 Node::ForeignItem(item) => match item.kind {
1815 ForeignItemKind::Static(..) => NO_GENERICS,
1816 ForeignItemKind::Fn(_, _, ref generics) => generics,
1817 ForeignItemKind::Type => NO_GENERICS,
1823 let generics = tcx.generics_of(def_id);
1824 let parent_count = generics.parent_count as u32;
1825 let has_own_self = generics.has_self && parent_count == 0;
1827 // Below we'll consider the bounds on the type parameters (including `Self`)
1828 // and the explicit where-clauses, but to get the full set of predicates
1829 // on a trait we need to add in the supertrait bounds and bounds found on
1830 // associated types.
1831 if let Some(_trait_ref) = is_trait {
1832 predicates.extend(tcx.super_predicates_of(def_id).predicates.iter().cloned());
1835 // In default impls, we can assume that the self type implements
1836 // the trait. So in:
1838 // default impl Foo for Bar { .. }
1840 // we add a default where clause `Foo: Bar`. We do a similar thing for traits
1841 // (see below). Recall that a default impl is not itself an impl, but rather a
1842 // set of defaults that can be incorporated into another impl.
1843 if let Some(trait_ref) = is_default_impl_trait {
1845 trait_ref.to_poly_trait_ref().without_const().to_predicate(tcx),
1846 tcx.def_span(def_id),
1850 // Collect the region predicates that were declared inline as
1851 // well. In the case of parameters declared on a fn or method, we
1852 // have to be careful to only iterate over early-bound regions.
1853 let mut index = parent_count + has_own_self as u32;
1854 for param in early_bound_lifetimes_from_generics(tcx, ast_generics) {
1855 let region = tcx.mk_region(ty::ReEarlyBound(ty::EarlyBoundRegion {
1856 def_id: tcx.hir().local_def_id(param.hir_id).to_def_id(),
1858 name: param.name.ident().name,
1863 GenericParamKind::Lifetime { .. } => {
1864 param.bounds.iter().for_each(|bound| match bound {
1865 hir::GenericBound::Outlives(lt) => {
1866 let bound = AstConv::ast_region_to_region(&icx, <, None);
1867 let outlives = ty::Binder::bind(ty::OutlivesPredicate(region, bound));
1868 predicates.insert((outlives.to_predicate(tcx), lt.span));
1877 // Collect the predicates that were written inline by the user on each
1878 // type parameter (e.g., `<T: Foo>`).
1879 for param in ast_generics.params {
1881 // We already dealt with early bound lifetimes above.
1882 GenericParamKind::Lifetime { .. } => (),
1883 GenericParamKind::Type { .. } => {
1884 let name = param.name.ident().name;
1885 let param_ty = ty::ParamTy::new(index, name).to_ty(tcx);
1888 let sized = SizedByDefault::Yes;
1890 AstConv::compute_bounds(&icx, param_ty, ¶m.bounds, sized, param.span);
1891 predicates.extend(bounds.predicates(tcx, param_ty));
1893 GenericParamKind::Const { .. } => {
1894 // Bounds on const parameters are currently not possible.
1895 debug_assert!(param.bounds.is_empty());
1901 // Add in the bounds that appear in the where-clause.
1902 let where_clause = &ast_generics.where_clause;
1903 for predicate in where_clause.predicates {
1905 &hir::WherePredicate::BoundPredicate(ref bound_pred) => {
1906 let ty = icx.to_ty(&bound_pred.bounded_ty);
1908 // Keep the type around in a dummy predicate, in case of no bounds.
1909 // That way, `where Ty:` is not a complete noop (see #53696) and `Ty`
1910 // is still checked for WF.
1911 if bound_pred.bounds.is_empty() {
1912 if let ty::Param(_) = ty.kind() {
1913 // This is a `where T:`, which can be in the HIR from the
1914 // transformation that moves `?Sized` to `T`'s declaration.
1915 // We can skip the predicate because type parameters are
1916 // trivially WF, but also we *should*, to avoid exposing
1917 // users who never wrote `where Type:,` themselves, to
1918 // compiler/tooling bugs from not handling WF predicates.
1920 let span = bound_pred.bounded_ty.span;
1921 let re_root_empty = tcx.lifetimes.re_root_empty;
1922 let predicate = ty::Binder::bind(ty::PredicateAtom::TypeOutlives(
1923 ty::OutlivesPredicate(ty, re_root_empty),
1926 predicate.potentially_quantified(tcx, ty::PredicateKind::ForAll),
1932 for bound in bound_pred.bounds.iter() {
1934 &hir::GenericBound::Trait(ref poly_trait_ref, modifier) => {
1935 let constness = match modifier {
1936 hir::TraitBoundModifier::MaybeConst => hir::Constness::NotConst,
1937 hir::TraitBoundModifier::None => constness,
1938 hir::TraitBoundModifier::Maybe => bug!("this wasn't handled"),
1941 let mut bounds = Bounds::default();
1942 let _ = AstConv::instantiate_poly_trait_ref(
1949 predicates.extend(bounds.predicates(tcx, ty));
1952 &hir::GenericBound::LangItemTrait(lang_item, span, hir_id, args) => {
1953 let mut bounds = Bounds::default();
1954 AstConv::instantiate_lang_item_trait_ref(
1963 predicates.extend(bounds.predicates(tcx, ty));
1966 &hir::GenericBound::Outlives(ref lifetime) => {
1967 let region = AstConv::ast_region_to_region(&icx, lifetime, None);
1969 ty::Binder::bind(ty::PredicateAtom::TypeOutlives(
1970 ty::OutlivesPredicate(ty, region),
1972 .potentially_quantified(tcx, ty::PredicateKind::ForAll),
1980 &hir::WherePredicate::RegionPredicate(ref region_pred) => {
1981 let r1 = AstConv::ast_region_to_region(&icx, ®ion_pred.lifetime, None);
1982 predicates.extend(region_pred.bounds.iter().map(|bound| {
1983 let (r2, span) = match bound {
1984 hir::GenericBound::Outlives(lt) => {
1985 (AstConv::ast_region_to_region(&icx, lt, None), lt.span)
1989 let pred = ty::PredicateAtom::RegionOutlives(ty::OutlivesPredicate(r1, r2))
1990 .to_predicate(icx.tcx);
1996 &hir::WherePredicate::EqPredicate(..) => {
2002 if tcx.features().const_evaluatable_checked {
2003 predicates.extend(const_evaluatable_predicates_of(tcx, def_id.expect_local()));
2006 let mut predicates: Vec<_> = predicates.into_iter().collect();
2008 // Subtle: before we store the predicates into the tcx, we
2009 // sort them so that predicates like `T: Foo<Item=U>` come
2010 // before uses of `U`. This avoids false ambiguity errors
2011 // in trait checking. See `setup_constraining_predicates`
2013 if let Node::Item(&Item { kind: ItemKind::Impl { .. }, .. }) = node {
2014 let self_ty = tcx.type_of(def_id);
2015 let trait_ref = tcx.impl_trait_ref(def_id);
2016 cgp::setup_constraining_predicates(
2020 &mut cgp::parameters_for_impl(self_ty, trait_ref),
2024 let result = ty::GenericPredicates {
2025 parent: generics.parent,
2026 predicates: tcx.arena.alloc_from_iter(predicates),
2028 debug!("explicit_predicates_of(def_id={:?}) = {:?}", def_id, result);
2032 fn const_evaluatable_predicates_of<'tcx>(
2035 ) -> FxIndexSet<(ty::Predicate<'tcx>, Span)> {
2036 struct ConstCollector<'tcx> {
2038 preds: FxIndexSet<(ty::Predicate<'tcx>, Span)>,
2041 impl<'tcx> intravisit::Visitor<'tcx> for ConstCollector<'tcx> {
2042 type Map = Map<'tcx>;
2044 fn nested_visit_map(&mut self) -> intravisit::NestedVisitorMap<Self::Map> {
2045 intravisit::NestedVisitorMap::None
2048 fn visit_anon_const(&mut self, c: &'tcx hir::AnonConst) {
2049 let def_id = self.tcx.hir().local_def_id(c.hir_id);
2050 let ct = ty::Const::from_anon_const(self.tcx, def_id);
2051 if let ty::ConstKind::Unevaluated(def, substs, None) = ct.val {
2052 let span = self.tcx.hir().span(c.hir_id);
2054 ty::PredicateAtom::ConstEvaluatable(def, substs).to_predicate(self.tcx),
2060 // Look into `TyAlias`.
2061 fn visit_ty(&mut self, ty: &'tcx hir::Ty<'tcx>) {
2062 use ty::fold::{TypeFoldable, TypeVisitor};
2063 struct TyAliasVisitor<'a, 'tcx> {
2065 preds: &'a mut FxIndexSet<(ty::Predicate<'tcx>, Span)>,
2069 impl<'a, 'tcx> TypeVisitor<'tcx> for TyAliasVisitor<'a, 'tcx> {
2070 fn visit_const(&mut self, ct: &'tcx Const<'tcx>) -> ControlFlow<Self::BreakTy> {
2071 if let ty::ConstKind::Unevaluated(def, substs, None) = ct.val {
2073 ty::PredicateAtom::ConstEvaluatable(def, substs).to_predicate(self.tcx),
2077 ControlFlow::CONTINUE
2081 if let hir::TyKind::Path(hir::QPath::Resolved(None, path)) = ty.kind {
2082 if let Res::Def(DefKind::TyAlias, def_id) = path.res {
2084 TyAliasVisitor { tcx: self.tcx, preds: &mut self.preds, span: path.span };
2085 self.tcx.type_of(def_id).visit_with(&mut visitor);
2089 intravisit::walk_ty(self, ty)
2093 let hir_id = tcx.hir().local_def_id_to_hir_id(def_id);
2094 let node = tcx.hir().get(hir_id);
2096 let mut collector = ConstCollector { tcx, preds: FxIndexSet::default() };
2097 if let hir::Node::Item(item) = node {
2098 if let hir::ItemKind::Impl { ref of_trait, ref self_ty, .. } = item.kind {
2099 if let Some(of_trait) = of_trait {
2100 debug!("const_evaluatable_predicates_of({:?}): visit impl trait_ref", def_id);
2101 collector.visit_trait_ref(of_trait);
2104 debug!("const_evaluatable_predicates_of({:?}): visit_self_ty", def_id);
2105 collector.visit_ty(self_ty);
2109 if let Some(generics) = node.generics() {
2110 debug!("const_evaluatable_predicates_of({:?}): visit_generics", def_id);
2111 collector.visit_generics(generics);
2114 if let Some(fn_sig) = tcx.hir().fn_sig_by_hir_id(hir_id) {
2115 debug!("const_evaluatable_predicates_of({:?}): visit_fn_decl", def_id);
2116 collector.visit_fn_decl(fn_sig.decl);
2118 debug!("const_evaluatable_predicates_of({:?}) = {:?}", def_id, collector.preds);
2123 fn trait_explicit_predicates_and_bounds(
2126 ) -> ty::GenericPredicates<'_> {
2127 assert_eq!(tcx.def_kind(def_id), DefKind::Trait);
2128 gather_explicit_predicates_of(tcx, def_id.to_def_id())
2131 fn explicit_predicates_of(tcx: TyCtxt<'_>, def_id: DefId) -> ty::GenericPredicates<'_> {
2132 if let DefKind::Trait = tcx.def_kind(def_id) {
2133 // Remove bounds on associated types from the predicates, they will be
2134 // returned by `explicit_item_bounds`.
2135 let predicates_and_bounds = tcx.trait_explicit_predicates_and_bounds(def_id.expect_local());
2136 let trait_identity_substs = InternalSubsts::identity_for_item(tcx, def_id);
2138 let is_assoc_item_ty = |ty: Ty<'_>| {
2139 // For a predicate from a where clause to become a bound on an
2141 // * It must use the identity substs of the item.
2142 // * Since any generic parameters on the item are not in scope,
2143 // this means that the item is not a GAT, and its identity
2144 // substs are the same as the trait's.
2145 // * It must be an associated type for this trait (*not* a
2147 if let ty::Projection(projection) = ty.kind() {
2148 projection.substs == trait_identity_substs
2149 && tcx.associated_item(projection.item_def_id).container.id() == def_id
2155 let predicates: Vec<_> = predicates_and_bounds
2159 .filter(|(pred, _)| match pred.skip_binders() {
2160 ty::PredicateAtom::Trait(tr, _) => !is_assoc_item_ty(tr.self_ty()),
2161 ty::PredicateAtom::Projection(proj) => {
2162 !is_assoc_item_ty(proj.projection_ty.self_ty())
2164 ty::PredicateAtom::TypeOutlives(outlives) => !is_assoc_item_ty(outlives.0),
2168 if predicates.len() == predicates_and_bounds.predicates.len() {
2169 predicates_and_bounds
2171 ty::GenericPredicates {
2172 parent: predicates_and_bounds.parent,
2173 predicates: tcx.arena.alloc_slice(&predicates),
2177 gather_explicit_predicates_of(tcx, def_id)
2181 fn projection_ty_from_predicates(
2186 // def_id of `N` in `<T as Trait>::N`
2189 ) -> Option<ty::ProjectionTy<'tcx>> {
2190 let (ty_def_id, item_def_id) = key;
2191 let mut projection_ty = None;
2192 for (predicate, _) in tcx.predicates_of(ty_def_id).predicates {
2193 if let ty::PredicateAtom::Projection(projection_predicate) = predicate.skip_binders() {
2194 if item_def_id == projection_predicate.projection_ty.item_def_id {
2195 projection_ty = Some(projection_predicate.projection_ty);
2203 /// Converts a specific `GenericBound` from the AST into a set of
2204 /// predicates that apply to the self type. A vector is returned
2205 /// because this can be anywhere from zero predicates (`T: ?Sized` adds no
2206 /// predicates) to one (`T: Foo`) to many (`T: Bar<X = i32>` adds `T: Bar`
2207 /// and `<T as Bar>::X == i32`).
2208 fn predicates_from_bound<'tcx>(
2209 astconv: &dyn AstConv<'tcx>,
2211 bound: &'tcx hir::GenericBound<'tcx>,
2212 constness: hir::Constness,
2213 ) -> Vec<(ty::Predicate<'tcx>, Span)> {
2215 hir::GenericBound::Trait(ref tr, modifier) => {
2216 let constness = match modifier {
2217 hir::TraitBoundModifier::Maybe => return vec![],
2218 hir::TraitBoundModifier::MaybeConst => hir::Constness::NotConst,
2219 hir::TraitBoundModifier::None => constness,
2222 let mut bounds = Bounds::default();
2223 let _ = astconv.instantiate_poly_trait_ref(tr, constness, param_ty, &mut bounds);
2224 bounds.predicates(astconv.tcx(), param_ty)
2226 hir::GenericBound::LangItemTrait(lang_item, span, hir_id, args) => {
2227 let mut bounds = Bounds::default();
2228 astconv.instantiate_lang_item_trait_ref(
2236 bounds.predicates(astconv.tcx(), param_ty)
2238 hir::GenericBound::Outlives(ref lifetime) => {
2239 let region = astconv.ast_region_to_region(lifetime, None);
2240 let pred = ty::PredicateAtom::TypeOutlives(ty::OutlivesPredicate(param_ty, region))
2241 .to_predicate(astconv.tcx());
2242 vec![(pred, lifetime.span)]
2247 fn compute_sig_of_foreign_fn_decl<'tcx>(
2250 decl: &'tcx hir::FnDecl<'tcx>,
2253 ) -> ty::PolyFnSig<'tcx> {
2254 let unsafety = if abi == abi::Abi::RustIntrinsic {
2255 intrinsic_operation_unsafety(tcx.item_name(def_id))
2257 hir::Unsafety::Unsafe
2259 let fty = AstConv::ty_of_fn(
2260 &ItemCtxt::new(tcx, def_id),
2264 &hir::Generics::empty(),
2268 // Feature gate SIMD types in FFI, since I am not sure that the
2269 // ABIs are handled at all correctly. -huonw
2270 if abi != abi::Abi::RustIntrinsic
2271 && abi != abi::Abi::PlatformIntrinsic
2272 && !tcx.features().simd_ffi
2274 let check = |ast_ty: &hir::Ty<'_>, ty: Ty<'_>| {
2279 .span_to_snippet(ast_ty.span)
2280 .map_or(String::new(), |s| format!(" `{}`", s));
2285 "use of SIMD type{} in FFI is highly experimental and \
2286 may result in invalid code",
2290 .help("add `#![feature(simd_ffi)]` to the crate attributes to enable")
2294 for (input, ty) in decl.inputs.iter().zip(fty.inputs().skip_binder()) {
2297 if let hir::FnRetTy::Return(ref ty) = decl.output {
2298 check(&ty, fty.output().skip_binder())
2305 fn is_foreign_item(tcx: TyCtxt<'_>, def_id: DefId) -> bool {
2306 match tcx.hir().get_if_local(def_id) {
2307 Some(Node::ForeignItem(..)) => true,
2309 _ => bug!("is_foreign_item applied to non-local def-id {:?}", def_id),
2313 fn static_mutability(tcx: TyCtxt<'_>, def_id: DefId) -> Option<hir::Mutability> {
2314 match tcx.hir().get_if_local(def_id) {
2316 Node::Item(&hir::Item { kind: hir::ItemKind::Static(_, mutbl, _), .. })
2317 | Node::ForeignItem(&hir::ForeignItem {
2318 kind: hir::ForeignItemKind::Static(_, mutbl),
2323 _ => bug!("static_mutability applied to non-local def-id {:?}", def_id),
2327 fn generator_kind(tcx: TyCtxt<'_>, def_id: DefId) -> Option<hir::GeneratorKind> {
2328 match tcx.hir().get_if_local(def_id) {
2329 Some(Node::Expr(&rustc_hir::Expr {
2330 kind: rustc_hir::ExprKind::Closure(_, _, body_id, _, _),
2332 })) => tcx.hir().body(body_id).generator_kind(),
2334 _ => bug!("generator_kind applied to non-local def-id {:?}", def_id),
2338 fn from_target_feature(
2341 attr: &ast::Attribute,
2342 supported_target_features: &FxHashMap<String, Option<Symbol>>,
2343 target_features: &mut Vec<Symbol>,
2345 let list = match attr.meta_item_list() {
2349 let bad_item = |span| {
2350 let msg = "malformed `target_feature` attribute input";
2351 let code = "enable = \"..\"".to_owned();
2353 .struct_span_err(span, &msg)
2354 .span_suggestion(span, "must be of the form", code, Applicability::HasPlaceholders)
2357 let rust_features = tcx.features();
2359 // Only `enable = ...` is accepted in the meta-item list.
2360 if !item.has_name(sym::enable) {
2361 bad_item(item.span());
2365 // Must be of the form `enable = "..."` (a string).
2366 let value = match item.value_str() {
2367 Some(value) => value,
2369 bad_item(item.span());
2374 // We allow comma separation to enable multiple features.
2375 target_features.extend(value.as_str().split(',').filter_map(|feature| {
2376 let feature_gate = match supported_target_features.get(feature) {
2380 format!("the feature named `{}` is not valid for this target", feature);
2381 let mut err = tcx.sess.struct_span_err(item.span(), &msg);
2384 format!("`{}` is not valid for this target", feature),
2386 if let Some(stripped) = feature.strip_prefix('+') {
2387 let valid = supported_target_features.contains_key(stripped);
2389 err.help("consider removing the leading `+` in the feature name");
2397 // Only allow features whose feature gates have been enabled.
2398 let allowed = match feature_gate.as_ref().copied() {
2399 Some(sym::arm_target_feature) => rust_features.arm_target_feature,
2400 Some(sym::aarch64_target_feature) => rust_features.aarch64_target_feature,
2401 Some(sym::hexagon_target_feature) => rust_features.hexagon_target_feature,
2402 Some(sym::powerpc_target_feature) => rust_features.powerpc_target_feature,
2403 Some(sym::mips_target_feature) => rust_features.mips_target_feature,
2404 Some(sym::riscv_target_feature) => rust_features.riscv_target_feature,
2405 Some(sym::avx512_target_feature) => rust_features.avx512_target_feature,
2406 Some(sym::sse4a_target_feature) => rust_features.sse4a_target_feature,
2407 Some(sym::tbm_target_feature) => rust_features.tbm_target_feature,
2408 Some(sym::wasm_target_feature) => rust_features.wasm_target_feature,
2409 Some(sym::cmpxchg16b_target_feature) => rust_features.cmpxchg16b_target_feature,
2410 Some(sym::adx_target_feature) => rust_features.adx_target_feature,
2411 Some(sym::movbe_target_feature) => rust_features.movbe_target_feature,
2412 Some(sym::rtm_target_feature) => rust_features.rtm_target_feature,
2413 Some(sym::f16c_target_feature) => rust_features.f16c_target_feature,
2414 Some(sym::ermsb_target_feature) => rust_features.ermsb_target_feature,
2415 Some(name) => bug!("unknown target feature gate {}", name),
2418 if !allowed && id.is_local() {
2420 &tcx.sess.parse_sess,
2421 feature_gate.unwrap(),
2423 &format!("the target feature `{}` is currently unstable", feature),
2427 Some(Symbol::intern(feature))
2432 fn linkage_by_name(tcx: TyCtxt<'_>, def_id: DefId, name: &str) -> Linkage {
2433 use rustc_middle::mir::mono::Linkage::*;
2435 // Use the names from src/llvm/docs/LangRef.rst here. Most types are only
2436 // applicable to variable declarations and may not really make sense for
2437 // Rust code in the first place but allow them anyway and trust that the
2438 // user knows what s/he's doing. Who knows, unanticipated use cases may pop
2439 // up in the future.
2441 // ghost, dllimport, dllexport and linkonce_odr_autohide are not supported
2442 // and don't have to be, LLVM treats them as no-ops.
2444 "appending" => Appending,
2445 "available_externally" => AvailableExternally,
2447 "extern_weak" => ExternalWeak,
2448 "external" => External,
2449 "internal" => Internal,
2450 "linkonce" => LinkOnceAny,
2451 "linkonce_odr" => LinkOnceODR,
2452 "private" => Private,
2454 "weak_odr" => WeakODR,
2456 let span = tcx.hir().span_if_local(def_id);
2457 if let Some(span) = span {
2458 tcx.sess.span_fatal(span, "invalid linkage specified")
2460 tcx.sess.fatal(&format!("invalid linkage specified: {}", name))
2466 fn codegen_fn_attrs(tcx: TyCtxt<'_>, id: DefId) -> CodegenFnAttrs {
2467 let attrs = tcx.get_attrs(id);
2469 let mut codegen_fn_attrs = CodegenFnAttrs::new();
2470 if should_inherit_track_caller(tcx, id) {
2471 codegen_fn_attrs.flags |= CodegenFnAttrFlags::TRACK_CALLER;
2474 let supported_target_features = tcx.supported_target_features(LOCAL_CRATE);
2476 let mut inline_span = None;
2477 let mut link_ordinal_span = None;
2478 let mut no_sanitize_span = None;
2479 for attr in attrs.iter() {
2480 if tcx.sess.check_name(attr, sym::cold) {
2481 codegen_fn_attrs.flags |= CodegenFnAttrFlags::COLD;
2482 } else if tcx.sess.check_name(attr, sym::rustc_allocator) {
2483 codegen_fn_attrs.flags |= CodegenFnAttrFlags::ALLOCATOR;
2484 } else if tcx.sess.check_name(attr, sym::unwind) {
2485 codegen_fn_attrs.flags |= CodegenFnAttrFlags::UNWIND;
2486 } else if tcx.sess.check_name(attr, sym::ffi_returns_twice) {
2487 if tcx.is_foreign_item(id) {
2488 codegen_fn_attrs.flags |= CodegenFnAttrFlags::FFI_RETURNS_TWICE;
2490 // `#[ffi_returns_twice]` is only allowed `extern fn`s.
2495 "`#[ffi_returns_twice]` may only be used on foreign functions"
2499 } else if tcx.sess.check_name(attr, sym::ffi_pure) {
2500 if tcx.is_foreign_item(id) {
2501 if attrs.iter().any(|a| tcx.sess.check_name(a, sym::ffi_const)) {
2502 // `#[ffi_const]` functions cannot be `#[ffi_pure]`
2507 "`#[ffi_const]` function cannot be `#[ffi_pure]`"
2511 codegen_fn_attrs.flags |= CodegenFnAttrFlags::FFI_PURE;
2514 // `#[ffi_pure]` is only allowed on foreign functions
2519 "`#[ffi_pure]` may only be used on foreign functions"
2523 } else if tcx.sess.check_name(attr, sym::ffi_const) {
2524 if tcx.is_foreign_item(id) {
2525 codegen_fn_attrs.flags |= CodegenFnAttrFlags::FFI_CONST;
2527 // `#[ffi_const]` is only allowed on foreign functions
2532 "`#[ffi_const]` may only be used on foreign functions"
2536 } else if tcx.sess.check_name(attr, sym::rustc_allocator_nounwind) {
2537 codegen_fn_attrs.flags |= CodegenFnAttrFlags::RUSTC_ALLOCATOR_NOUNWIND;
2538 } else if tcx.sess.check_name(attr, sym::naked) {
2539 codegen_fn_attrs.flags |= CodegenFnAttrFlags::NAKED;
2540 } else if tcx.sess.check_name(attr, sym::no_mangle) {
2541 codegen_fn_attrs.flags |= CodegenFnAttrFlags::NO_MANGLE;
2542 } else if tcx.sess.check_name(attr, sym::rustc_std_internal_symbol) {
2543 codegen_fn_attrs.flags |= CodegenFnAttrFlags::RUSTC_STD_INTERNAL_SYMBOL;
2544 } else if tcx.sess.check_name(attr, sym::used) {
2545 codegen_fn_attrs.flags |= CodegenFnAttrFlags::USED;
2546 } else if tcx.sess.check_name(attr, sym::cmse_nonsecure_entry) {
2547 if tcx.fn_sig(id).abi() != abi::Abi::C {
2552 "`#[cmse_nonsecure_entry]` requires C ABI"
2556 if !tcx.sess.target.llvm_target.contains("thumbv8m") {
2557 struct_span_err!(tcx.sess, attr.span, E0775, "`#[cmse_nonsecure_entry]` is only valid for targets with the TrustZone-M extension")
2560 codegen_fn_attrs.flags |= CodegenFnAttrFlags::CMSE_NONSECURE_ENTRY;
2561 } else if tcx.sess.check_name(attr, sym::thread_local) {
2562 codegen_fn_attrs.flags |= CodegenFnAttrFlags::THREAD_LOCAL;
2563 } else if tcx.sess.check_name(attr, sym::track_caller) {
2564 if tcx.is_closure(id) || tcx.fn_sig(id).abi() != abi::Abi::Rust {
2565 struct_span_err!(tcx.sess, attr.span, E0737, "`#[track_caller]` requires Rust ABI")
2568 codegen_fn_attrs.flags |= CodegenFnAttrFlags::TRACK_CALLER;
2569 } else if tcx.sess.check_name(attr, sym::export_name) {
2570 if let Some(s) = attr.value_str() {
2571 if s.as_str().contains('\0') {
2572 // `#[export_name = ...]` will be converted to a null-terminated string,
2573 // so it may not contain any null characters.
2578 "`export_name` may not contain null characters"
2582 codegen_fn_attrs.export_name = Some(s);
2584 } else if tcx.sess.check_name(attr, sym::target_feature) {
2585 if !tcx.is_closure(id) && tcx.fn_sig(id).unsafety() == hir::Unsafety::Normal {
2586 if !tcx.features().target_feature_11 {
2587 let mut err = feature_err(
2588 &tcx.sess.parse_sess,
2589 sym::target_feature_11,
2591 "`#[target_feature(..)]` can only be applied to `unsafe` functions",
2593 err.span_label(tcx.def_span(id), "not an `unsafe` function");
2595 } else if let Some(local_id) = id.as_local() {
2596 check_target_feature_trait_unsafe(tcx, local_id, attr.span);
2599 from_target_feature(
2603 &supported_target_features,
2604 &mut codegen_fn_attrs.target_features,
2606 } else if tcx.sess.check_name(attr, sym::linkage) {
2607 if let Some(val) = attr.value_str() {
2608 codegen_fn_attrs.linkage = Some(linkage_by_name(tcx, id, &val.as_str()));
2610 } else if tcx.sess.check_name(attr, sym::link_section) {
2611 if let Some(val) = attr.value_str() {
2612 if val.as_str().bytes().any(|b| b == 0) {
2614 "illegal null byte in link_section \
2618 tcx.sess.span_err(attr.span, &msg);
2620 codegen_fn_attrs.link_section = Some(val);
2623 } else if tcx.sess.check_name(attr, sym::link_name) {
2624 codegen_fn_attrs.link_name = attr.value_str();
2625 } else if tcx.sess.check_name(attr, sym::link_ordinal) {
2626 link_ordinal_span = Some(attr.span);
2627 if let ordinal @ Some(_) = check_link_ordinal(tcx, attr) {
2628 codegen_fn_attrs.link_ordinal = ordinal;
2630 } else if tcx.sess.check_name(attr, sym::no_sanitize) {
2631 no_sanitize_span = Some(attr.span);
2632 if let Some(list) = attr.meta_item_list() {
2633 for item in list.iter() {
2634 if item.has_name(sym::address) {
2635 codegen_fn_attrs.no_sanitize |= SanitizerSet::ADDRESS;
2636 } else if item.has_name(sym::memory) {
2637 codegen_fn_attrs.no_sanitize |= SanitizerSet::MEMORY;
2638 } else if item.has_name(sym::thread) {
2639 codegen_fn_attrs.no_sanitize |= SanitizerSet::THREAD;
2642 .struct_span_err(item.span(), "invalid argument for `no_sanitize`")
2643 .note("expected one of: `address`, `memory` or `thread`")
2648 } else if tcx.sess.check_name(attr, sym::instruction_set) {
2649 codegen_fn_attrs.instruction_set = match attr.meta().map(|i| i.kind) {
2650 Some(MetaItemKind::List(ref items)) => match items.as_slice() {
2651 [NestedMetaItem::MetaItem(set)] => {
2653 set.path.segments.iter().map(|x| x.ident.name).collect::<Vec<_>>();
2654 match segments.as_slice() {
2655 [sym::arm, sym::a32] | [sym::arm, sym::t32] => {
2656 if !tcx.sess.target.has_thumb_interworking {
2658 tcx.sess.diagnostic(),
2661 "target does not support `#[instruction_set]`"
2665 } else if segments[1] == sym::a32 {
2666 Some(InstructionSetAttr::ArmA32)
2667 } else if segments[1] == sym::t32 {
2668 Some(InstructionSetAttr::ArmT32)
2675 tcx.sess.diagnostic(),
2678 "invalid instruction set specified",
2687 tcx.sess.diagnostic(),
2690 "`#[instruction_set]` requires an argument"
2697 tcx.sess.diagnostic(),
2700 "cannot specify more than one instruction set"
2708 tcx.sess.diagnostic(),
2711 "must specify an instruction set"
2720 codegen_fn_attrs.inline = attrs.iter().fold(InlineAttr::None, |ia, attr| {
2721 if !attr.has_name(sym::inline) {
2724 match attr.meta().map(|i| i.kind) {
2725 Some(MetaItemKind::Word) => {
2726 tcx.sess.mark_attr_used(attr);
2729 Some(MetaItemKind::List(ref items)) => {
2730 tcx.sess.mark_attr_used(attr);
2731 inline_span = Some(attr.span);
2732 if items.len() != 1 {
2734 tcx.sess.diagnostic(),
2737 "expected one argument"
2741 } else if list_contains_name(&items[..], sym::always) {
2743 } else if list_contains_name(&items[..], sym::never) {
2747 tcx.sess.diagnostic(),
2757 Some(MetaItemKind::NameValue(_)) => ia,
2762 codegen_fn_attrs.optimize = attrs.iter().fold(OptimizeAttr::None, |ia, attr| {
2763 if !attr.has_name(sym::optimize) {
2766 let err = |sp, s| struct_span_err!(tcx.sess.diagnostic(), sp, E0722, "{}", s).emit();
2767 match attr.meta().map(|i| i.kind) {
2768 Some(MetaItemKind::Word) => {
2769 err(attr.span, "expected one argument");
2772 Some(MetaItemKind::List(ref items)) => {
2773 tcx.sess.mark_attr_used(attr);
2774 inline_span = Some(attr.span);
2775 if items.len() != 1 {
2776 err(attr.span, "expected one argument");
2778 } else if list_contains_name(&items[..], sym::size) {
2780 } else if list_contains_name(&items[..], sym::speed) {
2783 err(items[0].span(), "invalid argument");
2787 Some(MetaItemKind::NameValue(_)) => ia,
2792 // #73631: closures inherit `#[target_feature]` annotations
2793 if tcx.features().target_feature_11 && tcx.is_closure(id) {
2794 let owner_id = tcx.parent(id).expect("closure should have a parent");
2797 .extend(tcx.codegen_fn_attrs(owner_id).target_features.iter().copied())
2800 // If a function uses #[target_feature] it can't be inlined into general
2801 // purpose functions as they wouldn't have the right target features
2802 // enabled. For that reason we also forbid #[inline(always)] as it can't be
2804 if !codegen_fn_attrs.target_features.is_empty() {
2805 if codegen_fn_attrs.inline == InlineAttr::Always {
2806 if let Some(span) = inline_span {
2809 "cannot use `#[inline(always)]` with \
2810 `#[target_feature]`",
2816 if !codegen_fn_attrs.no_sanitize.is_empty() {
2817 if codegen_fn_attrs.inline == InlineAttr::Always {
2818 if let (Some(no_sanitize_span), Some(inline_span)) = (no_sanitize_span, inline_span) {
2819 let hir_id = tcx.hir().local_def_id_to_hir_id(id.expect_local());
2820 tcx.struct_span_lint_hir(
2821 lint::builtin::INLINE_NO_SANITIZE,
2825 lint.build("`no_sanitize` will have no effect after inlining")
2826 .span_note(inline_span, "inlining requested here")
2834 // Weak lang items have the same semantics as "std internal" symbols in the
2835 // sense that they're preserved through all our LTO passes and only
2836 // strippable by the linker.
2838 // Additionally weak lang items have predetermined symbol names.
2839 if tcx.is_weak_lang_item(id) {
2840 codegen_fn_attrs.flags |= CodegenFnAttrFlags::RUSTC_STD_INTERNAL_SYMBOL;
2842 let check_name = |attr, sym| tcx.sess.check_name(attr, sym);
2843 if let Some(name) = weak_lang_items::link_name(check_name, &attrs) {
2844 codegen_fn_attrs.export_name = Some(name);
2845 codegen_fn_attrs.link_name = Some(name);
2847 check_link_name_xor_ordinal(tcx, &codegen_fn_attrs, link_ordinal_span);
2849 // Internal symbols to the standard library all have no_mangle semantics in
2850 // that they have defined symbol names present in the function name. This
2851 // also applies to weak symbols where they all have known symbol names.
2852 if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::RUSTC_STD_INTERNAL_SYMBOL) {
2853 codegen_fn_attrs.flags |= CodegenFnAttrFlags::NO_MANGLE;
2859 /// Checks if the provided DefId is a method in a trait impl for a trait which has track_caller
2860 /// applied to the method prototype.
2861 fn should_inherit_track_caller(tcx: TyCtxt<'_>, def_id: DefId) -> bool {
2862 if let Some(impl_item) = tcx.opt_associated_item(def_id) {
2863 if let ty::AssocItemContainer::ImplContainer(impl_def_id) = impl_item.container {
2864 if let Some(trait_def_id) = tcx.trait_id_of_impl(impl_def_id) {
2865 if let Some(trait_item) = tcx
2866 .associated_items(trait_def_id)
2867 .filter_by_name_unhygienic(impl_item.ident.name)
2868 .find(move |trait_item| {
2869 trait_item.kind == ty::AssocKind::Fn
2870 && tcx.hygienic_eq(impl_item.ident, trait_item.ident, trait_def_id)
2874 .codegen_fn_attrs(trait_item.def_id)
2876 .intersects(CodegenFnAttrFlags::TRACK_CALLER);
2885 fn check_link_ordinal(tcx: TyCtxt<'_>, attr: &ast::Attribute) -> Option<usize> {
2886 use rustc_ast::{Lit, LitIntType, LitKind};
2887 let meta_item_list = attr.meta_item_list();
2888 let meta_item_list: Option<&[ast::NestedMetaItem]> = meta_item_list.as_ref().map(Vec::as_ref);
2889 let sole_meta_list = match meta_item_list {
2890 Some([item]) => item.literal(),
2893 if let Some(Lit { kind: LitKind::Int(ordinal, LitIntType::Unsuffixed), .. }) = sole_meta_list {
2894 if *ordinal <= usize::MAX as u128 {
2895 Some(*ordinal as usize)
2897 let msg = format!("ordinal value in `link_ordinal` is too large: `{}`", &ordinal);
2899 .struct_span_err(attr.span, &msg)
2900 .note("the value may not exceed `usize::MAX`")
2906 .struct_span_err(attr.span, "illegal ordinal format in `link_ordinal`")
2907 .note("an unsuffixed integer value, e.g., `1`, is expected")
2913 fn check_link_name_xor_ordinal(
2915 codegen_fn_attrs: &CodegenFnAttrs,
2916 inline_span: Option<Span>,
2918 if codegen_fn_attrs.link_name.is_none() || codegen_fn_attrs.link_ordinal.is_none() {
2921 let msg = "cannot use `#[link_name]` with `#[link_ordinal]`";
2922 if let Some(span) = inline_span {
2923 tcx.sess.span_err(span, msg);
2929 /// Checks the function annotated with `#[target_feature]` is not a safe
2930 /// trait method implementation, reporting an error if it is.
2931 fn check_target_feature_trait_unsafe(tcx: TyCtxt<'_>, id: LocalDefId, attr_span: Span) {
2932 let hir_id = tcx.hir().local_def_id_to_hir_id(id);
2933 let node = tcx.hir().get(hir_id);
2934 if let Node::ImplItem(hir::ImplItem { kind: hir::ImplItemKind::Fn(..), .. }) = node {
2935 let parent_id = tcx.hir().get_parent_item(hir_id);
2936 let parent_item = tcx.hir().expect_item(parent_id);
2937 if let hir::ItemKind::Impl { of_trait: Some(_), .. } = parent_item.kind {
2941 "`#[target_feature(..)]` cannot be applied to safe trait method",
2943 .span_label(attr_span, "cannot be applied to safe trait method")
2944 .span_label(tcx.def_span(id), "not an `unsafe` function")