Skip to main content

rustc_middle/middle/
lang_items.rs

1//! Detecting lang items.
2//!
3//! Language items are items that represent concepts intrinsic to the language
4//! itself. Examples are:
5//!
6//! * Traits that specify "kinds"; e.g., `Sync`, `Send`.
7//! * Traits that represent operators; e.g., `Add`, `Sub`, `Index`.
8//! * Functions called by the compiler itself.
9
10use rustc_attr_ir::lang_items::LangItem;
11use rustc_hir::def_id::DefId;
12use rustc_span::Span;
13use rustc_target::spec::PanicStrategy;
14
15use crate::ty::{self, Asyncness, TyCtxt};
16
17impl<'tcx> TyCtxt<'tcx> {
18    /// Returns the `DefId` for a given `LangItem`.
19    /// If not found, fatally aborts compilation.
20    pub fn require_lang_item(self, lang_item: LangItem, span: Span) -> DefId {
21        self.lang_items().get(lang_item).unwrap_or_else(|| {
22            self.dcx()
23                .emit_fatal(crate::diagnostics::RequiresLangItem { span, name: lang_item.name() });
24        })
25    }
26
27    pub fn is_lang_item(self, def_id: DefId, lang_item: LangItem) -> bool {
28        self.lang_items().get(lang_item) == Some(def_id)
29    }
30
31    pub fn as_lang_item(self, def_id: DefId) -> Option<LangItem> {
32        self.lang_items().from_def_id(def_id)
33    }
34
35    /// Given a [`DefId`] of one of the [`Fn`], [`FnMut`] or [`FnOnce`] traits,
36    /// returns a corresponding [`ty::ClosureKind`].
37    /// For any other [`DefId`] return `None`.
38    pub fn fn_trait_kind_from_def_id(self, id: DefId) -> Option<ty::ClosureKind> {
39        match self.as_lang_item(id)? {
40            LangItem::Fn => Some(ty::ClosureKind::Fn),
41            LangItem::FnMut => Some(ty::ClosureKind::FnMut),
42            LangItem::FnOnce => Some(ty::ClosureKind::FnOnce),
43            _ => None,
44        }
45    }
46
47    /// Given a [`DefId`] of one of the [`Fn`], [`FnMut`], [`FnOnce`], [`AsyncFn`], [`AsyncFnMut`], or [`AsyncFnOnce`] traits,
48    /// returns a corresponding [`ty::ClosureKind`] and [`Asyncness`].
49    /// For any other [`DefId`] return `None`.
50    pub fn maybe_async_fn_trait_kind_from_def_id(
51        self,
52        id: DefId,
53    ) -> Option<(Asyncness, ty::ClosureKind)> {
54        if let Some(kind) = self.fn_trait_kind_from_def_id(id) {
55            Some((Asyncness::No, kind))
56        } else if let Some(kind) = self.async_fn_trait_kind_from_def_id(id) {
57            Some((Asyncness::Yes, kind))
58        } else {
59            return None;
60        }
61    }
62
63    /// Given a [`DefId`] of one of the `AsyncFn`, `AsyncFnMut` or `AsyncFnOnce` traits,
64    /// returns a corresponding [`ty::ClosureKind`].
65    /// For any other [`DefId`] return `None`.
66    pub fn async_fn_trait_kind_from_def_id(self, id: DefId) -> Option<ty::ClosureKind> {
67        match self.as_lang_item(id)? {
68            LangItem::AsyncFn => Some(ty::ClosureKind::Fn),
69            LangItem::AsyncFnMut => Some(ty::ClosureKind::FnMut),
70            LangItem::AsyncFnOnce => Some(ty::ClosureKind::FnOnce),
71            _ => None,
72        }
73    }
74
75    /// Given a [`DefId`], returns whether it is one of the built-in callable
76    /// traits: `Fn`/`FnMut`/`FnOnce` or `AsyncFn`/`AsyncFnMut`/`AsyncFnOnce`.
77    ///
78    /// These built-in callable traits all model their inputs using the
79    /// `rust-call` ABI, which is tupled at the type level.
80    pub fn is_callable_trait(self, id: DefId) -> bool {
81        #[allow(non_exhaustive_omitted_patterns)] match self.as_lang_item(id) {
    Some(LangItem::Fn | LangItem::FnMut | LangItem::FnOnce | LangItem::AsyncFn
        | LangItem::AsyncFnMut | LangItem::AsyncFnOnce) => true,
    _ => false,
}matches!(
82            self.as_lang_item(id),
83            Some(
84                LangItem::Fn
85                    | LangItem::FnMut
86                    | LangItem::FnOnce
87                    | LangItem::AsyncFn
88                    | LangItem::AsyncFnMut
89                    | LangItem::AsyncFnOnce
90            )
91        )
92    }
93
94    /// Given a [`ty::ClosureKind`], get the [`DefId`] of its corresponding `Fn`-family
95    /// trait, if it is defined.
96    pub fn fn_trait_kind_to_def_id(self, kind: ty::ClosureKind) -> Option<DefId> {
97        let items = self.lang_items();
98        match kind {
99            ty::ClosureKind::Fn => items.fn_trait(),
100            ty::ClosureKind::FnMut => items.fn_mut_trait(),
101            ty::ClosureKind::FnOnce => items.fn_once_trait(),
102        }
103    }
104
105    /// Given a [`ty::ClosureKind`], get the [`DefId`] of its corresponding `Fn`-family
106    /// trait, if it is defined.
107    pub fn async_fn_trait_kind_to_def_id(self, kind: ty::ClosureKind) -> Option<DefId> {
108        let items = self.lang_items();
109        match kind {
110            ty::ClosureKind::Fn => items.async_fn_trait(),
111            ty::ClosureKind::FnMut => items.async_fn_mut_trait(),
112            ty::ClosureKind::FnOnce => items.async_fn_once_trait(),
113        }
114    }
115
116    /// Returns `true` if `id` is a `DefId` of [`Fn`], [`FnMut`] or [`FnOnce`] traits.
117    pub fn is_fn_trait(self, id: DefId) -> bool {
118        self.fn_trait_kind_from_def_id(id).is_some()
119    }
120}
121
122/// Returns `true` if the specified `lang_item` must be present for this
123/// compilation.
124///
125/// Not all lang items are always required for each compilation, particularly in
126/// the case of panic=abort. In these situations some lang items are injected by
127/// crates and don't actually need to be defined in libstd.
128pub fn required(tcx: TyCtxt<'_>, lang_item: LangItem) -> bool {
129    // If we're not compiling with unwinding, we won't actually need this
130    // symbol. Other panic runtimes ensure that the relevant symbols are
131    // available to link things together, but they're never exercised.
132    match tcx.sess.panic_strategy() {
133        PanicStrategy::Abort => lang_item != LangItem::EhPersonality,
134        PanicStrategy::Unwind => true,
135        PanicStrategy::ImmediateAbort => false,
136    }
137}