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;
18 use crate::check::intrinsic::intrinsic_operation_unsafety;
21 use rustc_ast::{MetaItemKind, NestedMetaItem};
22 use rustc_attr::{list_contains_name, InlineAttr, InstructionSetAttr, OptimizeAttr};
23 use rustc_data_structures::captures::Captures;
24 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
25 use rustc_errors::{struct_span_err, Applicability, DiagnosticBuilder, ErrorGuaranteed, StashKey};
27 use rustc_hir::def_id::{DefId, LocalDefId, LOCAL_CRATE};
28 use rustc_hir::intravisit::{self, Visitor};
29 use rustc_hir::weak_lang_items::WEAK_LANG_ITEMS;
30 use rustc_hir::{lang_items, GenericParamKind, LangItem, Node};
31 use rustc_middle::hir::nested_filter;
32 use rustc_middle::middle::codegen_fn_attrs::{CodegenFnAttrFlags, CodegenFnAttrs};
33 use rustc_middle::mir::mono::Linkage;
34 use rustc_middle::ty::query::Providers;
35 use rustc_middle::ty::util::{Discr, IntTypeExt};
36 use rustc_middle::ty::{self, AdtKind, Const, DefIdTree, IsSuggestable, Ty, TyCtxt};
37 use rustc_session::lint;
38 use rustc_session::parse::feature_err;
39 use rustc_span::symbol::{kw, sym, Ident, Symbol};
41 use rustc_target::spec::{abi, SanitizerSet};
42 use rustc_trait_selection::traits::error_reporting::suggestions::NextTypeParamName;
51 ///////////////////////////////////////////////////////////////////////////
54 fn collect_mod_item_types(tcx: TyCtxt<'_>, module_def_id: LocalDefId) {
55 tcx.hir().visit_item_likes_in_module(module_def_id, &mut CollectItemTypesVisitor { tcx });
58 pub fn provide(providers: &mut Providers) {
59 lifetimes::provide(providers);
60 *providers = Providers {
61 opt_const_param_of: type_of::opt_const_param_of,
62 type_of: type_of::type_of,
63 item_bounds: item_bounds::item_bounds,
64 explicit_item_bounds: item_bounds::explicit_item_bounds,
65 generics_of: generics_of::generics_of,
66 predicates_of: predicates_of::predicates_of,
67 predicates_defined_on,
68 explicit_predicates_of: predicates_of::explicit_predicates_of,
69 super_predicates_of: predicates_of::super_predicates_of,
70 super_predicates_that_define_assoc_type:
71 predicates_of::super_predicates_that_define_assoc_type,
72 trait_explicit_predicates_and_bounds: predicates_of::trait_explicit_predicates_and_bounds,
73 type_param_predicates: predicates_of::type_param_predicates,
83 collect_mod_item_types,
84 should_inherit_track_caller,
89 ///////////////////////////////////////////////////////////////////////////
91 /// Context specific to some particular item. This is what implements
94 /// # `ItemCtxt` vs `FnCtxt`
96 /// `ItemCtxt` is primarily used to type-check item signatures and lower them
97 /// from HIR to their [`ty::Ty`] representation, which is exposed using [`AstConv`].
98 /// It's also used for the bodies of items like structs where the body (the fields)
99 /// are just signatures.
101 /// This is in contrast to `FnCtxt`, which is used to type-check bodies of
102 /// functions, closures, and `const`s -- anywhere that expressions and statements show up.
104 /// An important thing to note is that `ItemCtxt` does no inference -- it has no [`InferCtxt`] --
105 /// while `FnCtxt` does do inference.
107 /// [`InferCtxt`]: rustc_infer::infer::InferCtxt
109 /// # Trait predicates
111 /// `ItemCtxt` has information about the predicates that are defined
112 /// on the trait. Unfortunately, this predicate information is
113 /// available in various different forms at various points in the
114 /// process. So we can't just store a pointer to e.g., the AST or the
115 /// parsed ty form, we have to be more flexible. To this end, the
116 /// `ItemCtxt` is parameterized by a `DefId` that it uses to satisfy
117 /// `get_type_parameter_bounds` requests, drawing the information from
118 /// the AST (`hir::Generics`), recursively.
119 pub struct ItemCtxt<'tcx> {
124 ///////////////////////////////////////////////////////////////////////////
127 pub(crate) struct HirPlaceholderCollector(pub(crate) Vec<Span>);
129 impl<'v> Visitor<'v> for HirPlaceholderCollector {
130 fn visit_ty(&mut self, t: &'v hir::Ty<'v>) {
131 if let hir::TyKind::Infer = t.kind {
134 intravisit::walk_ty(self, t)
136 fn visit_generic_arg(&mut self, generic_arg: &'v hir::GenericArg<'v>) {
138 hir::GenericArg::Infer(inf) => {
139 self.0.push(inf.span);
140 intravisit::walk_inf(self, inf);
142 hir::GenericArg::Type(t) => self.visit_ty(t),
146 fn visit_array_length(&mut self, length: &'v hir::ArrayLen) {
147 if let &hir::ArrayLen::Infer(_, span) = length {
150 intravisit::walk_array_len(self, length)
154 struct CollectItemTypesVisitor<'tcx> {
158 /// If there are any placeholder types (`_`), emit an error explaining that this is not allowed
159 /// and suggest adding type parameters in the appropriate place, taking into consideration any and
160 /// all already existing generic type parameters to avoid suggesting a name that is already in use.
161 pub(crate) fn placeholder_type_error<'tcx>(
163 generics: Option<&hir::Generics<'_>>,
164 placeholder_types: Vec<Span>,
166 hir_ty: Option<&hir::Ty<'_>>,
169 if placeholder_types.is_empty() {
173 placeholder_type_error_diag(tcx, generics, placeholder_types, vec![], suggest, hir_ty, kind)
177 pub(crate) fn placeholder_type_error_diag<'tcx>(
179 generics: Option<&hir::Generics<'_>>,
180 placeholder_types: Vec<Span>,
181 additional_spans: Vec<Span>,
183 hir_ty: Option<&hir::Ty<'_>>,
185 ) -> DiagnosticBuilder<'tcx, ErrorGuaranteed> {
186 if placeholder_types.is_empty() {
187 return bad_placeholder(tcx, additional_spans, kind);
190 let params = generics.map(|g| g.params).unwrap_or_default();
191 let type_name = params.next_type_param_name(None);
192 let mut sugg: Vec<_> =
193 placeholder_types.iter().map(|sp| (*sp, (*type_name).to_string())).collect();
195 if let Some(generics) = generics {
196 if let Some(arg) = params.iter().find(|arg| {
197 matches!(arg.name, hir::ParamName::Plain(Ident { name: kw::Underscore, .. }))
199 // Account for `_` already present in cases like `struct S<_>(_);` and suggest
200 // `struct S<T>(T);` instead of `struct S<_, T>(T);`.
201 sugg.push((arg.span, (*type_name).to_string()));
202 } else if let Some(span) = generics.span_for_param_suggestion() {
203 // Account for bounds, we want `fn foo<T: E, K>(_: K)` not `fn foo<T, K: E>(_: K)`.
204 sugg.push((span, format!(", {}", type_name)));
206 sugg.push((generics.span, format!("<{}>", type_name)));
211 bad_placeholder(tcx, placeholder_types.into_iter().chain(additional_spans).collect(), kind);
213 // Suggest, but only if it is not a function in const or static
215 let mut is_fn = false;
216 let mut is_const_or_static = false;
218 if let Some(hir_ty) = hir_ty && let hir::TyKind::BareFn(_) = hir_ty.kind {
221 // Check if parent is const or static
222 let parent_id = tcx.hir().get_parent_node(hir_ty.hir_id);
223 let parent_node = tcx.hir().get(parent_id);
225 is_const_or_static = matches!(
227 Node::Item(&hir::Item {
228 kind: hir::ItemKind::Const(..) | hir::ItemKind::Static(..),
230 }) | Node::TraitItem(&hir::TraitItem {
231 kind: hir::TraitItemKind::Const(..),
233 }) | Node::ImplItem(&hir::ImplItem { kind: hir::ImplItemKind::Const(..), .. })
237 // if function is wrapped around a const or static,
238 // then don't show the suggestion
239 if !(is_fn && is_const_or_static) {
240 err.multipart_suggestion(
241 "use type parameters instead",
243 Applicability::HasPlaceholders,
251 fn reject_placeholder_type_signatures_in_item<'tcx>(
253 item: &'tcx hir::Item<'tcx>,
255 let (generics, suggest) = match &item.kind {
256 hir::ItemKind::Union(_, generics)
257 | hir::ItemKind::Enum(_, generics)
258 | hir::ItemKind::TraitAlias(generics, _)
259 | hir::ItemKind::Trait(_, _, generics, ..)
260 | hir::ItemKind::Impl(hir::Impl { generics, .. })
261 | hir::ItemKind::Struct(_, generics) => (generics, true),
262 hir::ItemKind::OpaqueTy(hir::OpaqueTy { generics, .. })
263 | hir::ItemKind::TyAlias(_, generics) => (generics, false),
264 // `static`, `fn` and `const` are handled elsewhere to suggest appropriate type.
268 let mut visitor = HirPlaceholderCollector::default();
269 visitor.visit_item(item);
271 placeholder_type_error(tcx, Some(generics), visitor.0, suggest, None, item.kind.descr());
274 impl<'tcx> Visitor<'tcx> for CollectItemTypesVisitor<'tcx> {
275 type NestedFilter = nested_filter::OnlyBodies;
277 fn nested_visit_map(&mut self) -> Self::Map {
281 fn visit_item(&mut self, item: &'tcx hir::Item<'tcx>) {
282 convert_item(self.tcx, item.item_id());
283 reject_placeholder_type_signatures_in_item(self.tcx, item);
284 intravisit::walk_item(self, item);
287 fn visit_generics(&mut self, generics: &'tcx hir::Generics<'tcx>) {
288 for param in generics.params {
290 hir::GenericParamKind::Lifetime { .. } => {}
291 hir::GenericParamKind::Type { default: Some(_), .. } => {
292 self.tcx.ensure().type_of(param.def_id);
294 hir::GenericParamKind::Type { .. } => {}
295 hir::GenericParamKind::Const { default, .. } => {
296 self.tcx.ensure().type_of(param.def_id);
297 if let Some(default) = default {
298 // need to store default and type of default
299 self.tcx.ensure().type_of(default.def_id);
300 self.tcx.ensure().const_param_default(param.def_id);
305 intravisit::walk_generics(self, generics);
308 fn visit_expr(&mut self, expr: &'tcx hir::Expr<'tcx>) {
309 if let hir::ExprKind::Closure(closure) = expr.kind {
310 self.tcx.ensure().generics_of(closure.def_id);
311 self.tcx.ensure().codegen_fn_attrs(closure.def_id);
312 // We do not call `type_of` for closures here as that
313 // depends on typecheck and would therefore hide
314 // any further errors in case one typeck fails.
316 intravisit::walk_expr(self, expr);
319 fn visit_trait_item(&mut self, trait_item: &'tcx hir::TraitItem<'tcx>) {
320 convert_trait_item(self.tcx, trait_item.trait_item_id());
321 intravisit::walk_trait_item(self, trait_item);
324 fn visit_impl_item(&mut self, impl_item: &'tcx hir::ImplItem<'tcx>) {
325 convert_impl_item(self.tcx, impl_item.impl_item_id());
326 intravisit::walk_impl_item(self, impl_item);
330 ///////////////////////////////////////////////////////////////////////////
331 // Utility types and common code for the above passes.
333 fn bad_placeholder<'tcx>(
335 mut spans: Vec<Span>,
337 ) -> DiagnosticBuilder<'tcx, ErrorGuaranteed> {
338 let kind = if kind.ends_with('s') { format!("{}es", kind) } else { format!("{}s", kind) };
341 let mut err = struct_span_err!(
345 "the placeholder `_` is not allowed within types on item signatures for {}",
349 err.span_label(span, "not allowed in type signatures");
354 impl<'tcx> ItemCtxt<'tcx> {
355 pub fn new(tcx: TyCtxt<'tcx>, item_def_id: DefId) -> ItemCtxt<'tcx> {
356 ItemCtxt { tcx, item_def_id }
359 pub fn to_ty(&self, ast_ty: &hir::Ty<'_>) -> Ty<'tcx> {
360 <dyn AstConv<'_>>::ast_ty_to_ty(self, ast_ty)
363 pub fn hir_id(&self) -> hir::HirId {
364 self.tcx.hir().local_def_id_to_hir_id(self.item_def_id.expect_local())
367 pub fn node(&self) -> hir::Node<'tcx> {
368 self.tcx.hir().get(self.hir_id())
372 impl<'tcx> AstConv<'tcx> for ItemCtxt<'tcx> {
373 fn tcx(&self) -> TyCtxt<'tcx> {
377 fn item_def_id(&self) -> DefId {
381 fn get_type_parameter_bounds(
386 ) -> ty::GenericPredicates<'tcx> {
387 self.tcx.at(span).type_param_predicates((
389 def_id.expect_local(),
394 fn re_infer(&self, _: Option<&ty::GenericParamDef>, _: Span) -> Option<ty::Region<'tcx>> {
398 fn allow_ty_infer(&self) -> bool {
402 fn ty_infer(&self, _: Option<&ty::GenericParamDef>, span: Span) -> Ty<'tcx> {
403 self.tcx().ty_error_with_message(span, "bad placeholder type")
406 fn ct_infer(&self, ty: Ty<'tcx>, _: Option<&ty::GenericParamDef>, span: Span) -> Const<'tcx> {
407 let ty = self.tcx.fold_regions(ty, |r, _| match *r {
408 ty::ReErased => self.tcx.lifetimes.re_static,
411 self.tcx().const_error_with_message(ty, span, "bad placeholder constant")
414 fn projected_ty_from_poly_trait_ref(
418 item_segment: &hir::PathSegment<'_>,
419 poly_trait_ref: ty::PolyTraitRef<'tcx>,
421 if let Some(trait_ref) = poly_trait_ref.no_bound_vars() {
422 let item_substs = <dyn AstConv<'tcx>>::create_substs_for_associated_item(
429 self.tcx().mk_projection(item_def_id, item_substs)
431 // There are no late-bound regions; we can just ignore the binder.
432 let mut err = struct_span_err!(
436 "cannot use the associated type of a trait \
437 with uninferred generic parameters"
441 hir::Node::Field(_) | hir::Node::Ctor(_) | hir::Node::Variant(_) => {
445 .expect_item(self.tcx.hir().get_parent_item(self.hir_id()).def_id);
447 hir::ItemKind::Enum(_, generics)
448 | hir::ItemKind::Struct(_, generics)
449 | hir::ItemKind::Union(_, generics) => {
450 let lt_name = get_new_lifetime_name(self.tcx, poly_trait_ref, generics);
451 let (lt_sp, sugg) = match generics.params {
452 [] => (generics.span, format!("<{}>", lt_name)),
454 (bound.span.shrink_to_lo(), format!("{}, ", lt_name))
457 let suggestions = vec![
460 span.with_hi(item_segment.ident.span.lo()),
463 // Replace the existing lifetimes with a new named lifetime.
464 self.tcx.replace_late_bound_regions_uncached(
467 self.tcx.mk_region(ty::ReEarlyBound(
468 ty::EarlyBoundRegion {
471 name: Symbol::intern(<_name),
479 err.multipart_suggestion(
480 "use a fully qualified path with explicit lifetimes",
482 Applicability::MaybeIncorrect,
488 hir::Node::Item(hir::Item {
490 hir::ItemKind::Struct(..) | hir::ItemKind::Enum(..) | hir::ItemKind::Union(..),
494 | hir::Node::ForeignItem(_)
495 | hir::Node::TraitItem(_)
496 | hir::Node::ImplItem(_) => {
497 err.span_suggestion_verbose(
498 span.with_hi(item_segment.ident.span.lo()),
499 "use a fully qualified path with inferred lifetimes",
502 // Erase named lt, we want `<A as B<'_>::C`, not `<A as B<'a>::C`.
503 self.tcx.anonymize_late_bound_regions(poly_trait_ref).skip_binder(),
505 Applicability::MaybeIncorrect,
510 self.tcx().ty_error_with_guaranteed(err.emit())
514 fn normalize_ty(&self, _span: Span, ty: Ty<'tcx>) -> Ty<'tcx> {
515 // Types in item signatures are not normalized to avoid undue dependencies.
519 fn set_tainted_by_errors(&self, _: ErrorGuaranteed) {
520 // There's no obvious place to track this, so just let it go.
523 fn record_ty(&self, _hir_id: hir::HirId, _ty: Ty<'tcx>, _span: Span) {
524 // There's no place to record types from signatures?
528 /// Synthesize a new lifetime name that doesn't clash with any of the lifetimes already present.
529 fn get_new_lifetime_name<'tcx>(
531 poly_trait_ref: ty::PolyTraitRef<'tcx>,
532 generics: &hir::Generics<'tcx>,
534 let existing_lifetimes = tcx
535 .collect_referenced_late_bound_regions(&poly_trait_ref)
538 if let ty::BoundRegionKind::BrNamed(_, name) = lt {
539 Some(name.as_str().to_string())
544 .chain(generics.params.iter().filter_map(|param| {
545 if let hir::GenericParamKind::Lifetime { .. } = ¶m.kind {
546 Some(param.name.ident().as_str().to_string())
551 .collect::<FxHashSet<String>>();
553 let a_to_z_repeat_n = |n| {
554 (b'a'..=b'z').map(move |c| {
555 let mut s = '\''.to_string();
556 s.extend(std::iter::repeat(char::from(c)).take(n));
561 // If all single char lifetime names are present, we wrap around and double the chars.
562 (1..).flat_map(a_to_z_repeat_n).find(|lt| !existing_lifetimes.contains(lt.as_str())).unwrap()
565 fn convert_item(tcx: TyCtxt<'_>, item_id: hir::ItemId) {
566 let it = tcx.hir().item(item_id);
567 debug!("convert: item {} with id {}", it.ident, it.hir_id());
568 let def_id = item_id.owner_id.def_id;
571 // These don't define types.
572 hir::ItemKind::ExternCrate(_)
573 | hir::ItemKind::Use(..)
574 | hir::ItemKind::Macro(..)
575 | hir::ItemKind::Mod(_)
576 | hir::ItemKind::GlobalAsm(_) => {}
577 hir::ItemKind::ForeignMod { items, .. } => {
579 let item = tcx.hir().foreign_item(item.id);
580 tcx.ensure().generics_of(item.owner_id);
581 tcx.ensure().type_of(item.owner_id);
582 tcx.ensure().predicates_of(item.owner_id);
584 hir::ForeignItemKind::Fn(..) => {
585 tcx.ensure().codegen_fn_attrs(item.owner_id);
586 tcx.ensure().fn_sig(item.owner_id)
588 hir::ForeignItemKind::Static(..) => {
589 tcx.ensure().codegen_fn_attrs(item.owner_id);
590 let mut visitor = HirPlaceholderCollector::default();
591 visitor.visit_foreign_item(item);
592 placeholder_type_error(
605 hir::ItemKind::Enum(..) => {
606 tcx.ensure().generics_of(def_id);
607 tcx.ensure().type_of(def_id);
608 tcx.ensure().predicates_of(def_id);
609 convert_enum_variant_types(tcx, def_id.to_def_id());
611 hir::ItemKind::Impl { .. } => {
612 tcx.ensure().generics_of(def_id);
613 tcx.ensure().type_of(def_id);
614 tcx.ensure().impl_trait_ref(def_id);
615 tcx.ensure().predicates_of(def_id);
617 hir::ItemKind::Trait(..) => {
618 tcx.ensure().generics_of(def_id);
619 tcx.ensure().trait_def(def_id);
620 tcx.at(it.span).super_predicates_of(def_id);
621 tcx.ensure().predicates_of(def_id);
623 hir::ItemKind::TraitAlias(..) => {
624 tcx.ensure().generics_of(def_id);
625 tcx.at(it.span).super_predicates_of(def_id);
626 tcx.ensure().predicates_of(def_id);
628 hir::ItemKind::Struct(ref struct_def, _) | hir::ItemKind::Union(ref struct_def, _) => {
629 tcx.ensure().generics_of(def_id);
630 tcx.ensure().type_of(def_id);
631 tcx.ensure().predicates_of(def_id);
633 for f in struct_def.fields() {
634 tcx.ensure().generics_of(f.def_id);
635 tcx.ensure().type_of(f.def_id);
636 tcx.ensure().predicates_of(f.def_id);
639 if let Some(ctor_def_id) = struct_def.ctor_def_id() {
640 convert_variant_ctor(tcx, ctor_def_id);
644 // Don't call `type_of` on opaque types, since that depends on type
645 // checking function bodies. `check_item_type` ensures that it's called
647 hir::ItemKind::OpaqueTy(..) => {
648 tcx.ensure().generics_of(def_id);
649 tcx.ensure().predicates_of(def_id);
650 tcx.ensure().explicit_item_bounds(def_id);
651 tcx.ensure().item_bounds(def_id);
654 hir::ItemKind::TyAlias(..) => {
655 tcx.ensure().generics_of(def_id);
656 tcx.ensure().type_of(def_id);
657 tcx.ensure().predicates_of(def_id);
660 hir::ItemKind::Static(ty, ..) | hir::ItemKind::Const(ty, ..) => {
661 tcx.ensure().generics_of(def_id);
662 tcx.ensure().type_of(def_id);
663 tcx.ensure().predicates_of(def_id);
664 if !is_suggestable_infer_ty(ty) {
665 let mut visitor = HirPlaceholderCollector::default();
666 visitor.visit_item(it);
667 placeholder_type_error(tcx, None, visitor.0, false, None, it.kind.descr());
671 hir::ItemKind::Fn(..) => {
672 tcx.ensure().generics_of(def_id);
673 tcx.ensure().type_of(def_id);
674 tcx.ensure().predicates_of(def_id);
675 tcx.ensure().fn_sig(def_id);
676 tcx.ensure().codegen_fn_attrs(def_id);
681 fn convert_trait_item(tcx: TyCtxt<'_>, trait_item_id: hir::TraitItemId) {
682 let trait_item = tcx.hir().trait_item(trait_item_id);
683 let def_id = trait_item_id.owner_id;
684 tcx.ensure().generics_of(def_id);
686 match trait_item.kind {
687 hir::TraitItemKind::Fn(..) => {
688 tcx.ensure().codegen_fn_attrs(def_id);
689 tcx.ensure().type_of(def_id);
690 tcx.ensure().fn_sig(def_id);
693 hir::TraitItemKind::Const(.., Some(_)) => {
694 tcx.ensure().type_of(def_id);
697 hir::TraitItemKind::Const(hir_ty, _) => {
698 tcx.ensure().type_of(def_id);
699 // Account for `const C: _;`.
700 let mut visitor = HirPlaceholderCollector::default();
701 visitor.visit_trait_item(trait_item);
702 if !tcx.sess.diagnostic().has_stashed_diagnostic(hir_ty.span, StashKey::ItemNoType) {
703 placeholder_type_error(tcx, None, visitor.0, false, None, "constant");
707 hir::TraitItemKind::Type(_, Some(_)) => {
708 tcx.ensure().item_bounds(def_id);
709 tcx.ensure().type_of(def_id);
710 // Account for `type T = _;`.
711 let mut visitor = HirPlaceholderCollector::default();
712 visitor.visit_trait_item(trait_item);
713 placeholder_type_error(tcx, None, visitor.0, false, None, "associated type");
716 hir::TraitItemKind::Type(_, None) => {
717 tcx.ensure().item_bounds(def_id);
718 // #74612: Visit and try to find bad placeholders
719 // even if there is no concrete type.
720 let mut visitor = HirPlaceholderCollector::default();
721 visitor.visit_trait_item(trait_item);
723 placeholder_type_error(tcx, None, visitor.0, false, None, "associated type");
727 tcx.ensure().predicates_of(def_id);
730 fn convert_impl_item(tcx: TyCtxt<'_>, impl_item_id: hir::ImplItemId) {
731 let def_id = impl_item_id.owner_id;
732 tcx.ensure().generics_of(def_id);
733 tcx.ensure().type_of(def_id);
734 tcx.ensure().predicates_of(def_id);
735 let impl_item = tcx.hir().impl_item(impl_item_id);
736 match impl_item.kind {
737 hir::ImplItemKind::Fn(..) => {
738 tcx.ensure().codegen_fn_attrs(def_id);
739 tcx.ensure().fn_sig(def_id);
741 hir::ImplItemKind::Type(_) => {
742 // Account for `type T = _;`
743 let mut visitor = HirPlaceholderCollector::default();
744 visitor.visit_impl_item(impl_item);
746 placeholder_type_error(tcx, None, visitor.0, false, None, "associated type");
748 hir::ImplItemKind::Const(..) => {}
752 fn convert_variant_ctor(tcx: TyCtxt<'_>, def_id: LocalDefId) {
753 tcx.ensure().generics_of(def_id);
754 tcx.ensure().type_of(def_id);
755 tcx.ensure().predicates_of(def_id);
758 fn convert_enum_variant_types(tcx: TyCtxt<'_>, def_id: DefId) {
759 let def = tcx.adt_def(def_id);
760 let repr_type = def.repr().discr_type();
761 let initial = repr_type.initial_discriminant(tcx);
762 let mut prev_discr = None::<Discr<'_>>;
764 // fill the discriminant values and field types
765 for variant in def.variants() {
766 let wrapped_discr = prev_discr.map_or(initial, |d| d.wrap_incr(tcx));
768 if let ty::VariantDiscr::Explicit(const_def_id) = variant.discr {
769 def.eval_explicit_discr(tcx, const_def_id)
770 } else if let Some(discr) = repr_type.disr_incr(tcx, prev_discr) {
773 let span = tcx.def_span(variant.def_id);
774 struct_span_err!(tcx.sess, span, E0370, "enum discriminant overflowed")
775 .span_label(span, format!("overflowed on value after {}", prev_discr.unwrap()))
777 "explicitly set `{} = {}` if that is desired outcome",
778 tcx.item_name(variant.def_id),
784 .unwrap_or(wrapped_discr),
787 for f in &variant.fields {
788 tcx.ensure().generics_of(f.did);
789 tcx.ensure().type_of(f.did);
790 tcx.ensure().predicates_of(f.did);
793 // Convert the ctor, if any. This also registers the variant as
795 if let Some(ctor_def_id) = variant.ctor_def_id() {
796 convert_variant_ctor(tcx, ctor_def_id.expect_local());
803 variant_did: Option<LocalDefId>,
805 discr: ty::VariantDiscr,
806 def: &hir::VariantData<'_>,
807 adt_kind: ty::AdtKind,
808 parent_did: LocalDefId,
809 ) -> ty::VariantDef {
810 let mut seen_fields: FxHashMap<Ident, Span> = Default::default();
815 let dup_span = seen_fields.get(&f.ident.normalize_to_macros_2_0()).cloned();
816 if let Some(prev_span) = dup_span {
817 tcx.sess.emit_err(errors::FieldAlreadyDeclared {
823 seen_fields.insert(f.ident.normalize_to_macros_2_0(), f.span);
827 did: f.def_id.to_def_id(),
829 vis: tcx.visibility(f.def_id),
833 let recovered = match def {
834 hir::VariantData::Struct(_, r) => *r,
839 variant_did.map(LocalDefId::to_def_id),
840 def.ctor().map(|(kind, _, def_id)| (kind, def_id.to_def_id())),
844 parent_did.to_def_id(),
846 adt_kind == AdtKind::Struct && tcx.has_attr(parent_did.to_def_id(), sym::non_exhaustive)
847 || variant_did.map_or(false, |variant_did| {
848 tcx.has_attr(variant_did.to_def_id(), sym::non_exhaustive)
853 fn adt_def<'tcx>(tcx: TyCtxt<'tcx>, def_id: DefId) -> ty::AdtDef<'tcx> {
856 let def_id = def_id.expect_local();
857 let hir_id = tcx.hir().local_def_id_to_hir_id(def_id);
858 let Node::Item(item) = tcx.hir().get(hir_id) else {
862 let repr = tcx.repr_options_of_def(def_id.to_def_id());
863 let (kind, variants) = match item.kind {
864 ItemKind::Enum(ref def, _) => {
865 let mut distance_from_explicit = 0;
870 let discr = if let Some(ref e) = v.disr_expr {
871 distance_from_explicit = 0;
872 ty::VariantDiscr::Explicit(e.def_id.to_def_id())
874 ty::VariantDiscr::Relative(distance_from_explicit)
876 distance_from_explicit += 1;
890 (AdtKind::Enum, variants)
892 ItemKind::Struct(ref def, _) | ItemKind::Union(ref def, _) => {
893 let adt_kind = match item.kind {
894 ItemKind::Struct(..) => AdtKind::Struct,
897 let variants = std::iter::once(convert_variant(
901 ty::VariantDiscr::Relative(0),
912 tcx.alloc_adt_def(def_id.to_def_id(), kind, variants, repr)
915 fn trait_def(tcx: TyCtxt<'_>, def_id: DefId) -> ty::TraitDef {
916 let item = tcx.hir().expect_item(def_id.expect_local());
918 let (is_auto, unsafety, items) = match item.kind {
919 hir::ItemKind::Trait(is_auto, unsafety, .., items) => {
920 (is_auto == hir::IsAuto::Yes, unsafety, items)
922 hir::ItemKind::TraitAlias(..) => (false, hir::Unsafety::Normal, &[][..]),
923 _ => span_bug!(item.span, "trait_def_of_item invoked on non-trait"),
926 let paren_sugar = tcx.has_attr(def_id, sym::rustc_paren_sugar);
927 if paren_sugar && !tcx.features().unboxed_closures {
931 "the `#[rustc_paren_sugar]` attribute is a temporary means of controlling \
932 which traits can use parenthetical notation",
934 .help("add `#![feature(unboxed_closures)]` to the crate attributes to use it")
938 let is_marker = tcx.has_attr(def_id, sym::marker);
939 let skip_array_during_method_dispatch =
940 tcx.has_attr(def_id, sym::rustc_skip_array_during_method_dispatch);
941 let spec_kind = if tcx.has_attr(def_id, sym::rustc_unsafe_specialization_marker) {
942 ty::trait_def::TraitSpecializationKind::Marker
943 } else if tcx.has_attr(def_id, sym::rustc_specialization_trait) {
944 ty::trait_def::TraitSpecializationKind::AlwaysApplicable
946 ty::trait_def::TraitSpecializationKind::None
948 let must_implement_one_of = tcx
949 .get_attr(def_id, sym::rustc_must_implement_one_of)
950 // Check that there are at least 2 arguments of `#[rustc_must_implement_one_of]`
951 // and that they are all identifiers
952 .and_then(|attr| match attr.meta_item_list() {
953 Some(items) if items.len() < 2 => {
957 "the `#[rustc_must_implement_one_of]` attribute must be \
958 used with at least 2 args",
966 .map(|item| item.ident().ok_or(item.span()))
967 .collect::<Result<Box<[_]>, _>>()
970 .struct_span_err(span, "must be a name of an associated function")
974 .zip(Some(attr.span)),
975 // Error is reported by `rustc_attr!`
978 // Check that all arguments of `#[rustc_must_implement_one_of]` reference
979 // functions in the trait with default implementations
980 .and_then(|(list, attr_span)| {
981 let errors = list.iter().filter_map(|ident| {
982 let item = items.iter().find(|item| item.ident == *ident);
985 Some(item) if matches!(item.kind, hir::AssocItemKind::Fn { .. }) => {
986 if !tcx.impl_defaultness(item.id.owner_id).has_value() {
990 "This function doesn't have a default implementation",
992 .span_note(attr_span, "required by this annotation")
1002 .struct_span_err(item.span, "Not a function")
1003 .span_note(attr_span, "required by this annotation")
1005 "All `#[rustc_must_implement_one_of]` arguments \
1006 must be associated function names",
1012 .struct_span_err(ident.span, "Function not found in this trait")
1020 (errors.count() == 0).then_some(list)
1022 // Check for duplicates
1024 let mut set: FxHashMap<Symbol, Span> = FxHashMap::default();
1025 let mut no_dups = true;
1027 for ident in &*list {
1028 if let Some(dup) = set.insert(ident.name, ident.span) {
1030 .struct_span_err(vec![dup, ident.span], "Functions names are duplicated")
1032 "All `#[rustc_must_implement_one_of]` arguments \
1041 no_dups.then_some(list)
1050 skip_array_during_method_dispatch,
1052 must_implement_one_of,
1056 fn are_suggestable_generic_args(generic_args: &[hir::GenericArg<'_>]) -> bool {
1057 generic_args.iter().any(|arg| match arg {
1058 hir::GenericArg::Type(ty) => is_suggestable_infer_ty(ty),
1059 hir::GenericArg::Infer(_) => true,
1064 /// Whether `ty` is a type with `_` placeholders that can be inferred. Used in diagnostics only to
1065 /// use inference to provide suggestions for the appropriate type if possible.
1066 fn is_suggestable_infer_ty(ty: &hir::Ty<'_>) -> bool {
1071 Slice(ty) => is_suggestable_infer_ty(ty),
1072 Array(ty, length) => {
1073 is_suggestable_infer_ty(ty) || matches!(length, hir::ArrayLen::Infer(_, _))
1075 Tup(tys) => tys.iter().any(is_suggestable_infer_ty),
1076 Ptr(mut_ty) | Rptr(_, mut_ty) => is_suggestable_infer_ty(mut_ty.ty),
1077 OpaqueDef(_, generic_args, _) => are_suggestable_generic_args(generic_args),
1078 Path(hir::QPath::TypeRelative(ty, segment)) => {
1079 is_suggestable_infer_ty(ty) || are_suggestable_generic_args(segment.args().args)
1081 Path(hir::QPath::Resolved(ty_opt, hir::Path { segments, .. })) => {
1082 ty_opt.map_or(false, is_suggestable_infer_ty)
1083 || segments.iter().any(|segment| are_suggestable_generic_args(segment.args().args))
1089 pub fn get_infer_ret_ty<'hir>(output: &'hir hir::FnRetTy<'hir>) -> Option<&'hir hir::Ty<'hir>> {
1090 if let hir::FnRetTy::Return(ty) = output {
1091 if is_suggestable_infer_ty(ty) {
1098 #[instrument(level = "debug", skip(tcx))]
1099 fn fn_sig(tcx: TyCtxt<'_>, def_id: DefId) -> ty::PolyFnSig<'_> {
1100 use rustc_hir::Node::*;
1103 let def_id = def_id.expect_local();
1104 let hir_id = tcx.hir().local_def_id_to_hir_id(def_id);
1106 let icx = ItemCtxt::new(tcx, def_id.to_def_id());
1108 match tcx.hir().get(hir_id) {
1109 TraitItem(hir::TraitItem {
1110 kind: TraitItemKind::Fn(sig, TraitFn::Provided(_)),
1114 | Item(hir::Item { kind: ItemKind::Fn(sig, generics, _), .. }) => {
1115 infer_return_ty_for_fn_sig(tcx, sig, generics, def_id, &icx)
1118 ImplItem(hir::ImplItem { kind: ImplItemKind::Fn(sig, _), generics, .. }) => {
1119 // Do not try to infer the return type for a impl method coming from a trait
1120 if let Item(hir::Item { kind: ItemKind::Impl(i), .. }) =
1121 tcx.hir().get(tcx.hir().get_parent_node(hir_id))
1122 && i.of_trait.is_some()
1124 <dyn AstConv<'_>>::ty_of_fn(
1127 sig.header.unsafety,
1134 infer_return_ty_for_fn_sig(tcx, sig, generics, def_id, &icx)
1138 TraitItem(hir::TraitItem {
1139 kind: TraitItemKind::Fn(FnSig { header, decl, span: _ }, _),
1142 }) => <dyn AstConv<'_>>::ty_of_fn(
1152 ForeignItem(&hir::ForeignItem { kind: ForeignItemKind::Fn(fn_decl, _, _), .. }) => {
1153 let abi = tcx.hir().get_foreign_abi(hir_id);
1154 compute_sig_of_foreign_fn_decl(tcx, def_id.to_def_id(), fn_decl, abi)
1157 Ctor(data) | Variant(hir::Variant { data, .. }) if data.ctor().is_some() => {
1158 let ty = tcx.type_of(tcx.hir().get_parent_item(hir_id));
1159 let inputs = data.fields().iter().map(|f| tcx.type_of(f.def_id));
1160 ty::Binder::dummy(tcx.mk_fn_sig(
1164 hir::Unsafety::Normal,
1169 Expr(&hir::Expr { kind: hir::ExprKind::Closure { .. }, .. }) => {
1170 // Closure signatures are not like other function
1171 // signatures and cannot be accessed through `fn_sig`. For
1172 // example, a closure signature excludes the `self`
1173 // argument. In any case they are embedded within the
1174 // closure type as part of the `ClosureSubsts`.
1176 // To get the signature of a closure, you should use the
1177 // `sig` method on the `ClosureSubsts`:
1179 // substs.as_closure().sig(def_id, tcx)
1181 "to get the signature of a closure, use `substs.as_closure().sig()` not `fn_sig()`",
1186 bug!("unexpected sort of node in fn_sig(): {:?}", x);
1191 fn infer_return_ty_for_fn_sig<'tcx>(
1193 sig: &hir::FnSig<'_>,
1194 generics: &hir::Generics<'_>,
1196 icx: &ItemCtxt<'tcx>,
1197 ) -> ty::PolyFnSig<'tcx> {
1198 let hir_id = tcx.hir().local_def_id_to_hir_id(def_id);
1200 match get_infer_ret_ty(&sig.decl.output) {
1202 let fn_sig = tcx.typeck(def_id).liberated_fn_sigs()[hir_id];
1203 // Typeck doesn't expect erased regions to be returned from `type_of`.
1204 let fn_sig = tcx.fold_regions(fn_sig, |r, _| match *r {
1205 ty::ReErased => tcx.lifetimes.re_static,
1208 let fn_sig = ty::Binder::dummy(fn_sig);
1210 let mut visitor = HirPlaceholderCollector::default();
1211 visitor.visit_ty(ty);
1212 let mut diag = bad_placeholder(tcx, visitor.0, "return type");
1213 let ret_ty = fn_sig.skip_binder().output();
1214 if ret_ty.is_suggestable(tcx, false) {
1215 diag.span_suggestion(
1217 "replace with the correct return type",
1219 Applicability::MachineApplicable,
1221 } else if matches!(ret_ty.kind(), ty::FnDef(..)) {
1222 let fn_sig = ret_ty.fn_sig(tcx);
1227 .all(|t| t.is_suggestable(tcx, false))
1229 diag.span_suggestion(
1231 "replace with the correct return type",
1233 Applicability::MachineApplicable,
1236 } else if ret_ty.is_closure() {
1237 // We're dealing with a closure, so we should suggest using `impl Fn` or trait bounds
1238 // to prevent the user from getting a papercut while trying to use the unique closure
1239 // syntax (e.g. `[closure@src/lib.rs:2:5: 2:9]`).
1240 diag.help("consider using an `Fn`, `FnMut`, or `FnOnce` trait bound");
1241 diag.note("for more information on `Fn` traits and closure types, see https://doc.rust-lang.org/book/ch13-01-closures.html");
1247 None => <dyn AstConv<'_>>::ty_of_fn(
1250 sig.header.unsafety,
1259 fn impl_trait_ref(tcx: TyCtxt<'_>, def_id: DefId) -> Option<ty::TraitRef<'_>> {
1260 let icx = ItemCtxt::new(tcx, def_id);
1261 let item = tcx.hir().expect_item(def_id.expect_local());
1263 hir::ItemKind::Impl(ref impl_) => impl_.of_trait.as_ref().map(|ast_trait_ref| {
1264 let selfty = tcx.type_of(def_id);
1265 <dyn AstConv<'_>>::instantiate_mono_trait_ref(
1269 check_impl_constness(tcx, impl_.constness, ast_trait_ref),
1276 fn check_impl_constness(
1278 constness: hir::Constness,
1279 ast_trait_ref: &hir::TraitRef<'_>,
1280 ) -> ty::BoundConstness {
1282 hir::Constness::Const => {
1283 if let Some(trait_def_id) = ast_trait_ref.trait_def_id() && !tcx.has_attr(trait_def_id, sym::const_trait) {
1284 let trait_name = tcx.item_name(trait_def_id).to_string();
1285 tcx.sess.emit_err(errors::ConstImplForNonConstTrait {
1286 trait_ref_span: ast_trait_ref.path.span,
1288 local_trait_span: trait_def_id.as_local().map(|_| tcx.def_span(trait_def_id).shrink_to_lo()),
1292 ty::BoundConstness::NotConst
1294 ty::BoundConstness::ConstIfConst
1297 hir::Constness::NotConst => ty::BoundConstness::NotConst,
1301 fn impl_polarity(tcx: TyCtxt<'_>, def_id: DefId) -> ty::ImplPolarity {
1302 let is_rustc_reservation = tcx.has_attr(def_id, sym::rustc_reservation_impl);
1303 let item = tcx.hir().expect_item(def_id.expect_local());
1305 hir::ItemKind::Impl(hir::Impl {
1306 polarity: hir::ImplPolarity::Negative(span),
1310 if is_rustc_reservation {
1311 let span = span.to(of_trait.as_ref().map_or(*span, |t| t.path.span));
1312 tcx.sess.span_err(span, "reservation impls can't be negative");
1314 ty::ImplPolarity::Negative
1316 hir::ItemKind::Impl(hir::Impl {
1317 polarity: hir::ImplPolarity::Positive,
1321 if is_rustc_reservation {
1322 tcx.sess.span_err(item.span, "reservation impls can't be inherent");
1324 ty::ImplPolarity::Positive
1326 hir::ItemKind::Impl(hir::Impl {
1327 polarity: hir::ImplPolarity::Positive,
1331 if is_rustc_reservation {
1332 ty::ImplPolarity::Reservation
1334 ty::ImplPolarity::Positive
1337 item => bug!("impl_polarity: {:?} not an impl", item),
1341 /// Returns the early-bound lifetimes declared in this generics
1342 /// listing. For anything other than fns/methods, this is just all
1343 /// the lifetimes that are declared. For fns or methods, we have to
1344 /// screen out those that do not appear in any where-clauses etc using
1345 /// `resolve_lifetime::early_bound_lifetimes`.
1346 fn early_bound_lifetimes_from_generics<'a, 'tcx: 'a>(
1348 generics: &'a hir::Generics<'a>,
1349 ) -> impl Iterator<Item = &'a hir::GenericParam<'a>> + Captures<'tcx> {
1350 generics.params.iter().filter(move |param| match param.kind {
1351 GenericParamKind::Lifetime { .. } => !tcx.is_late_bound(param.hir_id),
1356 /// Returns a list of type predicates for the definition with ID `def_id`, including inferred
1357 /// lifetime constraints. This includes all predicates returned by `explicit_predicates_of`, plus
1358 /// inferred constraints concerning which regions outlive other regions.
1359 #[instrument(level = "debug", skip(tcx))]
1360 fn predicates_defined_on(tcx: TyCtxt<'_>, def_id: DefId) -> ty::GenericPredicates<'_> {
1361 let mut result = tcx.explicit_predicates_of(def_id);
1362 debug!("predicates_defined_on: explicit_predicates_of({:?}) = {:?}", def_id, result,);
1363 let inferred_outlives = tcx.inferred_outlives_of(def_id);
1364 if !inferred_outlives.is_empty() {
1366 "predicates_defined_on: inferred_outlives_of({:?}) = {:?}",
1367 def_id, inferred_outlives,
1369 if result.predicates.is_empty() {
1370 result.predicates = inferred_outlives;
1372 result.predicates = tcx
1374 .alloc_from_iter(result.predicates.iter().chain(inferred_outlives).copied());
1378 debug!("predicates_defined_on({:?}) = {:?}", def_id, result);
1382 fn compute_sig_of_foreign_fn_decl<'tcx>(
1385 decl: &'tcx hir::FnDecl<'tcx>,
1387 ) -> ty::PolyFnSig<'tcx> {
1388 let unsafety = if abi == abi::Abi::RustIntrinsic {
1389 intrinsic_operation_unsafety(tcx, def_id)
1391 hir::Unsafety::Unsafe
1393 let hir_id = tcx.hir().local_def_id_to_hir_id(def_id.expect_local());
1394 let fty = <dyn AstConv<'_>>::ty_of_fn(
1395 &ItemCtxt::new(tcx, def_id),
1404 // Feature gate SIMD types in FFI, since I am not sure that the
1405 // ABIs are handled at all correctly. -huonw
1406 if abi != abi::Abi::RustIntrinsic
1407 && abi != abi::Abi::PlatformIntrinsic
1408 && !tcx.features().simd_ffi
1410 let check = |ast_ty: &hir::Ty<'_>, ty: Ty<'_>| {
1415 .span_to_snippet(ast_ty.span)
1416 .map_or_else(|_| String::new(), |s| format!(" `{}`", s));
1421 "use of SIMD type{} in FFI is highly experimental and \
1422 may result in invalid code",
1426 .help("add `#![feature(simd_ffi)]` to the crate attributes to enable")
1430 for (input, ty) in iter::zip(decl.inputs, fty.inputs().skip_binder()) {
1433 if let hir::FnRetTy::Return(ref ty) = decl.output {
1434 check(ty, fty.output().skip_binder())
1441 fn is_foreign_item(tcx: TyCtxt<'_>, def_id: DefId) -> bool {
1442 match tcx.hir().get_if_local(def_id) {
1443 Some(Node::ForeignItem(..)) => true,
1445 _ => bug!("is_foreign_item applied to non-local def-id {:?}", def_id),
1449 fn generator_kind(tcx: TyCtxt<'_>, def_id: DefId) -> Option<hir::GeneratorKind> {
1450 match tcx.hir().get_if_local(def_id) {
1451 Some(Node::Expr(&rustc_hir::Expr {
1452 kind: rustc_hir::ExprKind::Closure(&rustc_hir::Closure { body, .. }),
1454 })) => tcx.hir().body(body).generator_kind(),
1456 _ => bug!("generator_kind applied to non-local def-id {:?}", def_id),
1460 fn from_target_feature(
1462 attr: &ast::Attribute,
1463 supported_target_features: &FxHashMap<String, Option<Symbol>>,
1464 target_features: &mut Vec<Symbol>,
1466 let Some(list) = attr.meta_item_list() else { return };
1467 let bad_item = |span| {
1468 let msg = "malformed `target_feature` attribute input";
1469 let code = "enable = \"..\"";
1471 .struct_span_err(span, msg)
1472 .span_suggestion(span, "must be of the form", code, Applicability::HasPlaceholders)
1475 let rust_features = tcx.features();
1477 // Only `enable = ...` is accepted in the meta-item list.
1478 if !item.has_name(sym::enable) {
1479 bad_item(item.span());
1483 // Must be of the form `enable = "..."` (a string).
1484 let Some(value) = item.value_str() else {
1485 bad_item(item.span());
1489 // We allow comma separation to enable multiple features.
1490 target_features.extend(value.as_str().split(',').filter_map(|feature| {
1491 let Some(feature_gate) = supported_target_features.get(feature) else {
1493 format!("the feature named `{}` is not valid for this target", feature);
1494 let mut err = tcx.sess.struct_span_err(item.span(), &msg);
1497 format!("`{}` is not valid for this target", feature),
1499 if let Some(stripped) = feature.strip_prefix('+') {
1500 let valid = supported_target_features.contains_key(stripped);
1502 err.help("consider removing the leading `+` in the feature name");
1509 // Only allow features whose feature gates have been enabled.
1510 let allowed = match feature_gate.as_ref().copied() {
1511 Some(sym::arm_target_feature) => rust_features.arm_target_feature,
1512 Some(sym::hexagon_target_feature) => rust_features.hexagon_target_feature,
1513 Some(sym::powerpc_target_feature) => rust_features.powerpc_target_feature,
1514 Some(sym::mips_target_feature) => rust_features.mips_target_feature,
1515 Some(sym::riscv_target_feature) => rust_features.riscv_target_feature,
1516 Some(sym::avx512_target_feature) => rust_features.avx512_target_feature,
1517 Some(sym::sse4a_target_feature) => rust_features.sse4a_target_feature,
1518 Some(sym::tbm_target_feature) => rust_features.tbm_target_feature,
1519 Some(sym::wasm_target_feature) => rust_features.wasm_target_feature,
1520 Some(sym::cmpxchg16b_target_feature) => rust_features.cmpxchg16b_target_feature,
1521 Some(sym::movbe_target_feature) => rust_features.movbe_target_feature,
1522 Some(sym::rtm_target_feature) => rust_features.rtm_target_feature,
1523 Some(sym::f16c_target_feature) => rust_features.f16c_target_feature,
1524 Some(sym::ermsb_target_feature) => rust_features.ermsb_target_feature,
1525 Some(sym::bpf_target_feature) => rust_features.bpf_target_feature,
1526 Some(sym::aarch64_ver_target_feature) => rust_features.aarch64_ver_target_feature,
1527 Some(name) => bug!("unknown target feature gate {}", name),
1532 &tcx.sess.parse_sess,
1533 feature_gate.unwrap(),
1535 &format!("the target feature `{}` is currently unstable", feature),
1539 Some(Symbol::intern(feature))
1544 fn linkage_by_name(tcx: TyCtxt<'_>, def_id: LocalDefId, name: &str) -> Linkage {
1545 use rustc_middle::mir::mono::Linkage::*;
1547 // Use the names from src/llvm/docs/LangRef.rst here. Most types are only
1548 // applicable to variable declarations and may not really make sense for
1549 // Rust code in the first place but allow them anyway and trust that the
1550 // user knows what they're doing. Who knows, unanticipated use cases may pop
1551 // up in the future.
1553 // ghost, dllimport, dllexport and linkonce_odr_autohide are not supported
1554 // and don't have to be, LLVM treats them as no-ops.
1556 "appending" => Appending,
1557 "available_externally" => AvailableExternally,
1559 "extern_weak" => ExternalWeak,
1560 "external" => External,
1561 "internal" => Internal,
1562 "linkonce" => LinkOnceAny,
1563 "linkonce_odr" => LinkOnceODR,
1564 "private" => Private,
1566 "weak_odr" => WeakODR,
1567 _ => tcx.sess.span_fatal(tcx.def_span(def_id), "invalid linkage specified"),
1571 fn codegen_fn_attrs(tcx: TyCtxt<'_>, did: DefId) -> CodegenFnAttrs {
1572 if cfg!(debug_assertions) {
1573 let def_kind = tcx.def_kind(did);
1575 def_kind.has_codegen_attrs(),
1576 "unexpected `def_kind` in `codegen_fn_attrs`: {def_kind:?}",
1580 let did = did.expect_local();
1581 let attrs = tcx.hir().attrs(tcx.hir().local_def_id_to_hir_id(did));
1582 let mut codegen_fn_attrs = CodegenFnAttrs::new();
1583 if tcx.should_inherit_track_caller(did) {
1584 codegen_fn_attrs.flags |= CodegenFnAttrFlags::TRACK_CALLER;
1587 let supported_target_features = tcx.supported_target_features(LOCAL_CRATE);
1589 let mut inline_span = None;
1590 let mut link_ordinal_span = None;
1591 let mut no_sanitize_span = None;
1592 for attr in attrs.iter() {
1593 if attr.has_name(sym::cold) {
1594 codegen_fn_attrs.flags |= CodegenFnAttrFlags::COLD;
1595 } else if attr.has_name(sym::rustc_allocator) {
1596 codegen_fn_attrs.flags |= CodegenFnAttrFlags::ALLOCATOR;
1597 } else if attr.has_name(sym::ffi_returns_twice) {
1598 if tcx.is_foreign_item(did) {
1599 codegen_fn_attrs.flags |= CodegenFnAttrFlags::FFI_RETURNS_TWICE;
1601 // `#[ffi_returns_twice]` is only allowed `extern fn`s.
1606 "`#[ffi_returns_twice]` may only be used on foreign functions"
1610 } else if attr.has_name(sym::ffi_pure) {
1611 if tcx.is_foreign_item(did) {
1612 if attrs.iter().any(|a| a.has_name(sym::ffi_const)) {
1613 // `#[ffi_const]` functions cannot be `#[ffi_pure]`
1618 "`#[ffi_const]` function cannot be `#[ffi_pure]`"
1622 codegen_fn_attrs.flags |= CodegenFnAttrFlags::FFI_PURE;
1625 // `#[ffi_pure]` is only allowed on foreign functions
1630 "`#[ffi_pure]` may only be used on foreign functions"
1634 } else if attr.has_name(sym::ffi_const) {
1635 if tcx.is_foreign_item(did) {
1636 codegen_fn_attrs.flags |= CodegenFnAttrFlags::FFI_CONST;
1638 // `#[ffi_const]` is only allowed on foreign functions
1643 "`#[ffi_const]` may only be used on foreign functions"
1647 } else if attr.has_name(sym::rustc_nounwind) {
1648 codegen_fn_attrs.flags |= CodegenFnAttrFlags::NEVER_UNWIND;
1649 } else if attr.has_name(sym::rustc_reallocator) {
1650 codegen_fn_attrs.flags |= CodegenFnAttrFlags::REALLOCATOR;
1651 } else if attr.has_name(sym::rustc_deallocator) {
1652 codegen_fn_attrs.flags |= CodegenFnAttrFlags::DEALLOCATOR;
1653 } else if attr.has_name(sym::rustc_allocator_zeroed) {
1654 codegen_fn_attrs.flags |= CodegenFnAttrFlags::ALLOCATOR_ZEROED;
1655 } else if attr.has_name(sym::naked) {
1656 codegen_fn_attrs.flags |= CodegenFnAttrFlags::NAKED;
1657 } else if attr.has_name(sym::no_mangle) {
1658 codegen_fn_attrs.flags |= CodegenFnAttrFlags::NO_MANGLE;
1659 } else if attr.has_name(sym::no_coverage) {
1660 codegen_fn_attrs.flags |= CodegenFnAttrFlags::NO_COVERAGE;
1661 } else if attr.has_name(sym::rustc_std_internal_symbol) {
1662 codegen_fn_attrs.flags |= CodegenFnAttrFlags::RUSTC_STD_INTERNAL_SYMBOL;
1663 } else if attr.has_name(sym::used) {
1664 let inner = attr.meta_item_list();
1665 match inner.as_deref() {
1666 Some([item]) if item.has_name(sym::linker) => {
1667 if !tcx.features().used_with_arg {
1669 &tcx.sess.parse_sess,
1672 "`#[used(linker)]` is currently unstable",
1676 codegen_fn_attrs.flags |= CodegenFnAttrFlags::USED_LINKER;
1678 Some([item]) if item.has_name(sym::compiler) => {
1679 if !tcx.features().used_with_arg {
1681 &tcx.sess.parse_sess,
1684 "`#[used(compiler)]` is currently unstable",
1688 codegen_fn_attrs.flags |= CodegenFnAttrFlags::USED;
1691 tcx.sess.emit_err(errors::ExpectedUsedSymbol { span: attr.span });
1694 // Unfortunately, unconditionally using `llvm.used` causes
1695 // issues in handling `.init_array` with the gold linker,
1696 // but using `llvm.compiler.used` caused a nontrival amount
1697 // of unintentional ecosystem breakage -- particularly on
1700 // As a result, we emit `llvm.compiler.used` only on ELF
1701 // targets. This is somewhat ad-hoc, but actually follows
1702 // our pre-LLVM 13 behavior (prior to the ecosystem
1703 // breakage), and seems to match `clang`'s behavior as well
1704 // (both before and after LLVM 13), possibly because they
1705 // have similar compatibility concerns to us. See
1706 // https://github.com/rust-lang/rust/issues/47384#issuecomment-1019080146
1707 // and following comments for some discussion of this, as
1708 // well as the comments in `rustc_codegen_llvm` where these
1709 // flags are handled.
1711 // Anyway, to be clear: this is still up in the air
1712 // somewhat, and is subject to change in the future (which
1713 // is a good thing, because this would ideally be a bit
1715 let is_like_elf = !(tcx.sess.target.is_like_osx
1716 || tcx.sess.target.is_like_windows
1717 || tcx.sess.target.is_like_wasm);
1718 codegen_fn_attrs.flags |= if is_like_elf {
1719 CodegenFnAttrFlags::USED
1721 CodegenFnAttrFlags::USED_LINKER
1725 } else if attr.has_name(sym::cmse_nonsecure_entry) {
1726 if !matches!(tcx.fn_sig(did).abi(), abi::Abi::C { .. }) {
1731 "`#[cmse_nonsecure_entry]` requires C ABI"
1735 if !tcx.sess.target.llvm_target.contains("thumbv8m") {
1736 struct_span_err!(tcx.sess, attr.span, E0775, "`#[cmse_nonsecure_entry]` is only valid for targets with the TrustZone-M extension")
1739 codegen_fn_attrs.flags |= CodegenFnAttrFlags::CMSE_NONSECURE_ENTRY;
1740 } else if attr.has_name(sym::thread_local) {
1741 codegen_fn_attrs.flags |= CodegenFnAttrFlags::THREAD_LOCAL;
1742 } else if attr.has_name(sym::track_caller) {
1743 if !tcx.is_closure(did.to_def_id()) && tcx.fn_sig(did).abi() != abi::Abi::Rust {
1744 struct_span_err!(tcx.sess, attr.span, E0737, "`#[track_caller]` requires Rust ABI")
1747 if tcx.is_closure(did.to_def_id()) && !tcx.features().closure_track_caller {
1749 &tcx.sess.parse_sess,
1750 sym::closure_track_caller,
1752 "`#[track_caller]` on closures is currently unstable",
1756 codegen_fn_attrs.flags |= CodegenFnAttrFlags::TRACK_CALLER;
1757 } else if attr.has_name(sym::export_name) {
1758 if let Some(s) = attr.value_str() {
1759 if s.as_str().contains('\0') {
1760 // `#[export_name = ...]` will be converted to a null-terminated string,
1761 // so it may not contain any null characters.
1766 "`export_name` may not contain null characters"
1770 codegen_fn_attrs.export_name = Some(s);
1772 } else if attr.has_name(sym::target_feature) {
1773 if !tcx.is_closure(did.to_def_id())
1774 && tcx.fn_sig(did).unsafety() == hir::Unsafety::Normal
1776 if tcx.sess.target.is_like_wasm || tcx.sess.opts.actually_rustdoc {
1777 // The `#[target_feature]` attribute is allowed on
1778 // WebAssembly targets on all functions, including safe
1779 // ones. Other targets require that `#[target_feature]` is
1780 // only applied to unsafe functions (pending the
1781 // `target_feature_11` feature) because on most targets
1782 // execution of instructions that are not supported is
1783 // considered undefined behavior. For WebAssembly which is a
1784 // 100% safe target at execution time it's not possible to
1785 // execute undefined instructions, and even if a future
1786 // feature was added in some form for this it would be a
1787 // deterministic trap. There is no undefined behavior when
1788 // executing WebAssembly so `#[target_feature]` is allowed
1789 // on safe functions (but again, only for WebAssembly)
1791 // Note that this is also allowed if `actually_rustdoc` so
1792 // if a target is documenting some wasm-specific code then
1793 // it's not spuriously denied.
1794 } else if !tcx.features().target_feature_11 {
1795 let mut err = feature_err(
1796 &tcx.sess.parse_sess,
1797 sym::target_feature_11,
1799 "`#[target_feature(..)]` can only be applied to `unsafe` functions",
1801 err.span_label(tcx.def_span(did), "not an `unsafe` function");
1804 check_target_feature_trait_unsafe(tcx, did, attr.span);
1807 from_target_feature(
1810 supported_target_features,
1811 &mut codegen_fn_attrs.target_features,
1813 } else if attr.has_name(sym::linkage) {
1814 if let Some(val) = attr.value_str() {
1815 codegen_fn_attrs.linkage = Some(linkage_by_name(tcx, did, val.as_str()));
1817 } else if attr.has_name(sym::link_section) {
1818 if let Some(val) = attr.value_str() {
1819 if val.as_str().bytes().any(|b| b == 0) {
1821 "illegal null byte in link_section \
1825 tcx.sess.span_err(attr.span, &msg);
1827 codegen_fn_attrs.link_section = Some(val);
1830 } else if attr.has_name(sym::link_name) {
1831 codegen_fn_attrs.link_name = attr.value_str();
1832 } else if attr.has_name(sym::link_ordinal) {
1833 link_ordinal_span = Some(attr.span);
1834 if let ordinal @ Some(_) = check_link_ordinal(tcx, attr) {
1835 codegen_fn_attrs.link_ordinal = ordinal;
1837 } else if attr.has_name(sym::no_sanitize) {
1838 no_sanitize_span = Some(attr.span);
1839 if let Some(list) = attr.meta_item_list() {
1840 for item in list.iter() {
1841 if item.has_name(sym::address) {
1842 codegen_fn_attrs.no_sanitize |= SanitizerSet::ADDRESS;
1843 } else if item.has_name(sym::cfi) {
1844 codegen_fn_attrs.no_sanitize |= SanitizerSet::CFI;
1845 } else if item.has_name(sym::memory) {
1846 codegen_fn_attrs.no_sanitize |= SanitizerSet::MEMORY;
1847 } else if item.has_name(sym::memtag) {
1848 codegen_fn_attrs.no_sanitize |= SanitizerSet::MEMTAG;
1849 } else if item.has_name(sym::shadow_call_stack) {
1850 codegen_fn_attrs.no_sanitize |= SanitizerSet::SHADOWCALLSTACK;
1851 } else if item.has_name(sym::thread) {
1852 codegen_fn_attrs.no_sanitize |= SanitizerSet::THREAD;
1853 } else if item.has_name(sym::hwaddress) {
1854 codegen_fn_attrs.no_sanitize |= SanitizerSet::HWADDRESS;
1857 .struct_span_err(item.span(), "invalid argument for `no_sanitize`")
1858 .note("expected one of: `address`, `cfi`, `hwaddress`, `memory`, `memtag`, `shadow-call-stack`, or `thread`")
1863 } else if attr.has_name(sym::instruction_set) {
1864 codegen_fn_attrs.instruction_set = match attr.meta_kind() {
1865 Some(MetaItemKind::List(ref items)) => match items.as_slice() {
1866 [NestedMetaItem::MetaItem(set)] => {
1868 set.path.segments.iter().map(|x| x.ident.name).collect::<Vec<_>>();
1869 match segments.as_slice() {
1870 [sym::arm, sym::a32] | [sym::arm, sym::t32] => {
1871 if !tcx.sess.target.has_thumb_interworking {
1873 tcx.sess.diagnostic(),
1876 "target does not support `#[instruction_set]`"
1880 } else if segments[1] == sym::a32 {
1881 Some(InstructionSetAttr::ArmA32)
1882 } else if segments[1] == sym::t32 {
1883 Some(InstructionSetAttr::ArmT32)
1890 tcx.sess.diagnostic(),
1893 "invalid instruction set specified",
1902 tcx.sess.diagnostic(),
1905 "`#[instruction_set]` requires an argument"
1912 tcx.sess.diagnostic(),
1915 "cannot specify more than one instruction set"
1923 tcx.sess.diagnostic(),
1926 "must specify an instruction set"
1932 } else if attr.has_name(sym::repr) {
1933 codegen_fn_attrs.alignment = match attr.meta_item_list() {
1934 Some(items) => match items.as_slice() {
1935 [item] => match item.name_value_literal() {
1936 Some((sym::align, literal)) => {
1937 let alignment = rustc_attr::parse_alignment(&literal.kind);
1940 Ok(align) => Some(align),
1943 tcx.sess.diagnostic(),
1946 "invalid `repr(align)` attribute: {}",
1965 codegen_fn_attrs.inline = attrs.iter().fold(InlineAttr::None, |ia, attr| {
1966 if !attr.has_name(sym::inline) {
1969 match attr.meta_kind() {
1970 Some(MetaItemKind::Word) => InlineAttr::Hint,
1971 Some(MetaItemKind::List(ref items)) => {
1972 inline_span = Some(attr.span);
1973 if items.len() != 1 {
1975 tcx.sess.diagnostic(),
1978 "expected one argument"
1982 } else if list_contains_name(&items, sym::always) {
1984 } else if list_contains_name(&items, sym::never) {
1988 tcx.sess.diagnostic(),
1993 .help("valid inline arguments are `always` and `never`")
1999 Some(MetaItemKind::NameValue(_)) => ia,
2004 codegen_fn_attrs.optimize = attrs.iter().fold(OptimizeAttr::None, |ia, attr| {
2005 if !attr.has_name(sym::optimize) {
2008 let err = |sp, s| struct_span_err!(tcx.sess.diagnostic(), sp, E0722, "{}", s).emit();
2009 match attr.meta_kind() {
2010 Some(MetaItemKind::Word) => {
2011 err(attr.span, "expected one argument");
2014 Some(MetaItemKind::List(ref items)) => {
2015 inline_span = Some(attr.span);
2016 if items.len() != 1 {
2017 err(attr.span, "expected one argument");
2019 } else if list_contains_name(&items, sym::size) {
2021 } else if list_contains_name(&items, sym::speed) {
2024 err(items[0].span(), "invalid argument");
2028 Some(MetaItemKind::NameValue(_)) => ia,
2033 // #73631: closures inherit `#[target_feature]` annotations
2034 if tcx.features().target_feature_11 && tcx.is_closure(did.to_def_id()) {
2035 let owner_id = tcx.parent(did.to_def_id());
2036 if tcx.def_kind(owner_id).has_codegen_attrs() {
2039 .extend(tcx.codegen_fn_attrs(owner_id).target_features.iter().copied());
2043 // If a function uses #[target_feature] it can't be inlined into general
2044 // purpose functions as they wouldn't have the right target features
2045 // enabled. For that reason we also forbid #[inline(always)] as it can't be
2047 if !codegen_fn_attrs.target_features.is_empty() {
2048 if codegen_fn_attrs.inline == InlineAttr::Always {
2049 if let Some(span) = inline_span {
2052 "cannot use `#[inline(always)]` with \
2053 `#[target_feature]`",
2059 if !codegen_fn_attrs.no_sanitize.is_empty() {
2060 if codegen_fn_attrs.inline == InlineAttr::Always {
2061 if let (Some(no_sanitize_span), Some(inline_span)) = (no_sanitize_span, inline_span) {
2062 let hir_id = tcx.hir().local_def_id_to_hir_id(did);
2063 tcx.struct_span_lint_hir(
2064 lint::builtin::INLINE_NO_SANITIZE,
2067 "`no_sanitize` will have no effect after inlining",
2068 |lint| lint.span_note(inline_span, "inlining requested here"),
2074 // Weak lang items have the same semantics as "std internal" symbols in the
2075 // sense that they're preserved through all our LTO passes and only
2076 // strippable by the linker.
2078 // Additionally weak lang items have predetermined symbol names.
2079 if WEAK_LANG_ITEMS.iter().any(|&l| tcx.lang_items().get(l) == Some(did.to_def_id())) {
2080 codegen_fn_attrs.flags |= CodegenFnAttrFlags::RUSTC_STD_INTERNAL_SYMBOL;
2082 if let Some((name, _)) = lang_items::extract(attrs)
2083 && let Some(lang_item) = LangItem::from_name(name)
2084 && let Some(link_name) = lang_item.link_name()
2086 codegen_fn_attrs.export_name = Some(link_name);
2087 codegen_fn_attrs.link_name = Some(link_name);
2089 check_link_name_xor_ordinal(tcx, &codegen_fn_attrs, link_ordinal_span);
2091 // Internal symbols to the standard library all have no_mangle semantics in
2092 // that they have defined symbol names present in the function name. This
2093 // also applies to weak symbols where they all have known symbol names.
2094 if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::RUSTC_STD_INTERNAL_SYMBOL) {
2095 codegen_fn_attrs.flags |= CodegenFnAttrFlags::NO_MANGLE;
2098 // Any linkage to LLVM intrinsics for now forcibly marks them all as never
2099 // unwinds since LLVM sometimes can't handle codegen which `invoke`s
2100 // intrinsic functions.
2101 if let Some(name) = &codegen_fn_attrs.link_name {
2102 if name.as_str().starts_with("llvm.") {
2103 codegen_fn_attrs.flags |= CodegenFnAttrFlags::NEVER_UNWIND;
2110 /// Computes the set of target features used in a function for the purposes of
2111 /// inline assembly.
2112 fn asm_target_features<'tcx>(tcx: TyCtxt<'tcx>, did: DefId) -> &'tcx FxHashSet<Symbol> {
2113 let mut target_features = tcx.sess.unstable_target_features.clone();
2114 if tcx.def_kind(did).has_codegen_attrs() {
2115 let attrs = tcx.codegen_fn_attrs(did);
2116 target_features.extend(&attrs.target_features);
2117 match attrs.instruction_set {
2119 Some(InstructionSetAttr::ArmA32) => {
2120 target_features.remove(&sym::thumb_mode);
2122 Some(InstructionSetAttr::ArmT32) => {
2123 target_features.insert(sym::thumb_mode);
2128 tcx.arena.alloc(target_features)
2131 /// Checks if the provided DefId is a method in a trait impl for a trait which has track_caller
2132 /// applied to the method prototype.
2133 fn should_inherit_track_caller(tcx: TyCtxt<'_>, def_id: DefId) -> bool {
2134 if let Some(impl_item) = tcx.opt_associated_item(def_id)
2135 && let ty::AssocItemContainer::ImplContainer = impl_item.container
2136 && let Some(trait_item) = impl_item.trait_item_def_id
2139 .codegen_fn_attrs(trait_item)
2141 .intersects(CodegenFnAttrFlags::TRACK_CALLER);
2147 fn check_link_ordinal(tcx: TyCtxt<'_>, attr: &ast::Attribute) -> Option<u16> {
2148 use rustc_ast::{Lit, LitIntType, LitKind};
2149 if !tcx.features().raw_dylib && tcx.sess.target.arch == "x86" {
2151 &tcx.sess.parse_sess,
2154 "`#[link_ordinal]` is unstable on x86",
2158 let meta_item_list = attr.meta_item_list();
2159 let meta_item_list = meta_item_list.as_deref();
2160 let sole_meta_list = match meta_item_list {
2161 Some([item]) => item.literal(),
2164 .struct_span_err(attr.span, "incorrect number of arguments to `#[link_ordinal]`")
2165 .note("the attribute requires exactly one argument")
2171 if let Some(Lit { kind: LitKind::Int(ordinal, LitIntType::Unsuffixed), .. }) = sole_meta_list {
2172 // According to the table at https://docs.microsoft.com/en-us/windows/win32/debug/pe-format#import-header,
2173 // the ordinal must fit into 16 bits. Similarly, the Ordinal field in COFFShortExport (defined
2174 // in llvm/include/llvm/Object/COFFImportFile.h), which we use to communicate import information
2175 // to LLVM for `#[link(kind = "raw-dylib"_])`, is also defined to be uint16_t.
2177 // FIXME: should we allow an ordinal of 0? The MSVC toolchain has inconsistent support for this:
2178 // both LINK.EXE and LIB.EXE signal errors and abort when given a .DEF file that specifies
2179 // a zero ordinal. However, llvm-dlltool is perfectly happy to generate an import library
2180 // for such a .DEF file, and MSVC's LINK.EXE is also perfectly happy to consume an import
2181 // library produced by LLVM with an ordinal of 0, and it generates an .EXE. (I don't know yet
2182 // if the resulting EXE runs, as I haven't yet built the necessary DLL -- see earlier comment
2183 // about LINK.EXE failing.)
2184 if *ordinal <= u16::MAX as u128 {
2185 Some(*ordinal as u16)
2187 let msg = format!("ordinal value in `link_ordinal` is too large: `{}`", &ordinal);
2189 .struct_span_err(attr.span, &msg)
2190 .note("the value may not exceed `u16::MAX`")
2196 .struct_span_err(attr.span, "illegal ordinal format in `link_ordinal`")
2197 .note("an unsuffixed integer value, e.g., `1`, is expected")
2203 fn check_link_name_xor_ordinal(
2205 codegen_fn_attrs: &CodegenFnAttrs,
2206 inline_span: Option<Span>,
2208 if codegen_fn_attrs.link_name.is_none() || codegen_fn_attrs.link_ordinal.is_none() {
2211 let msg = "cannot use `#[link_name]` with `#[link_ordinal]`";
2212 if let Some(span) = inline_span {
2213 tcx.sess.span_err(span, msg);
2219 /// Checks the function annotated with `#[target_feature]` is not a safe
2220 /// trait method implementation, reporting an error if it is.
2221 fn check_target_feature_trait_unsafe(tcx: TyCtxt<'_>, id: LocalDefId, attr_span: Span) {
2222 let hir_id = tcx.hir().local_def_id_to_hir_id(id);
2223 let node = tcx.hir().get(hir_id);
2224 if let Node::ImplItem(hir::ImplItem { kind: hir::ImplItemKind::Fn(..), .. }) = node {
2225 let parent_id = tcx.hir().get_parent_item(hir_id);
2226 let parent_item = tcx.hir().expect_item(parent_id.def_id);
2227 if let hir::ItemKind::Impl(hir::Impl { of_trait: Some(_), .. }) = parent_item.kind {
2231 "`#[target_feature(..)]` cannot be applied to safe trait method",
2233 .span_label(attr_span, "cannot be applied to safe trait method")
2234 .span_label(tcx.def_span(id), "not an `unsafe` function")