1 //! Defines language items.
3 //! Language items are items that represent concepts intrinsic to the language
4 //! itself. Examples are:
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.
10 use crate::def_id::DefId;
11 use crate::errors::LangItemError;
12 use crate::{MethodKind, Target};
15 use rustc_data_structures::fx::FxIndexMap;
16 use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
17 use rustc_macros::HashStable_Generic;
18 use rustc_span::symbol::{kw, sym, Symbol};
21 use std::sync::LazyLock;
23 pub enum LangItemGroup {
28 const NUM_GROUPS: usize = 2;
30 macro_rules! expand_group {
39 // The actual lang items defined come at the end of this file in one handy table.
40 // So you probably just want to nip down to the end.
41 macro_rules! language_item_table {
43 $( $(#[$attr:meta])* $variant:ident $($group:expr)?, $module:ident :: $name:ident, $method:ident, $target:expr, $generics:expr; )*
47 /// A representation of all the valid language items in Rust.
48 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash, Encodable, Decodable)]
51 #[doc = concat!("The `", stringify!($name), "` lang item.")]
60 /// Returns the `name` symbol in `#[lang = "$name"]`.
61 /// For example, [`LangItem::PartialEq`]`.name()`
62 /// would result in [`sym::eq`] since it is `#[lang = "eq"]`.
63 pub fn name(self) -> Symbol {
65 $( LangItem::$variant => $module::$name, )*
69 /// The [group](LangItemGroup) that this lang item belongs to,
70 /// or `None` if it doesn't belong to a group.
71 pub fn group(self) -> Option<LangItemGroup> {
74 $( LangItem::$variant => expand_group!($($group)*), )*
78 pub fn required_generics(&self) -> GenericRequirement {
80 $( LangItem::$variant => $generics, )*
85 /// All of the language items, defined or not.
86 /// Defined lang items can come from the current crate or its dependencies.
87 #[derive(HashStable_Generic, Debug)]
88 pub struct LanguageItems {
89 /// Mappings from lang items to their possibly found [`DefId`]s.
90 /// The index corresponds to the order in [`LangItem`].
91 pub items: Vec<Option<DefId>>,
92 /// Lang items that were not found during collection.
93 pub missing: Vec<LangItem>,
94 /// Mapping from [`LangItemGroup`] discriminants to all
95 /// [`DefId`]s of lang items in that group.
96 pub groups: [Vec<DefId>; NUM_GROUPS],
100 /// Construct an empty collection of lang items and no missing ones.
101 pub fn new() -> Self {
102 fn init_none(_: LangItem) -> Option<DefId> { None }
103 const EMPTY: Vec<DefId> = Vec::new();
106 items: vec![$(init_none(LangItem::$variant)),*],
108 groups: [EMPTY; NUM_GROUPS],
112 /// Returns the mappings to the possibly found `DefId`s for each lang item.
113 pub fn items(&self) -> &[Option<DefId>] {
117 /// Requires that a given `LangItem` was bound and returns the corresponding `DefId`.
118 /// If it wasn't bound, e.g. due to a missing `#[lang = "<it.name()>"]`,
119 /// returns an error encapsulating the `LangItem`.
120 pub fn require(&self, it: LangItem) -> Result<DefId, LangItemError> {
121 self.items[it as usize].ok_or_else(|| LangItemError(it))
124 /// Returns the [`DefId`]s of all lang items in a group.
125 pub fn group(&self, group: LangItemGroup) -> &[DefId] {
126 self.groups[group as usize].as_ref()
130 #[doc = concat!("Returns the [`DefId`] of the `", stringify!($name), "` lang item if it is defined.")]
131 pub fn $method(&self) -> Option<DefId> {
132 self.items[LangItem::$variant as usize]
137 /// A mapping from the name of the lang item to its order and the form it must be of.
138 pub static ITEM_REFS: LazyLock<FxIndexMap<Symbol, (usize, Target)>> = LazyLock::new(|| {
139 let mut item_refs = FxIndexMap::default();
140 $( item_refs.insert($module::$name, (LangItem::$variant as usize, $target)); )*
148 impl<CTX> HashStable<CTX> for LangItem {
149 fn hash_stable(&self, _: &mut CTX, hasher: &mut StableHasher) {
150 ::std::hash::Hash::hash(self, hasher);
154 /// Extracts the first `lang = "$name"` out of a list of attributes.
155 /// The attributes `#[panic_handler]` and `#[alloc_error_handler]`
156 /// are also extracted out when found.
157 pub fn extract(attrs: &[ast::Attribute]) -> Option<(Symbol, Span)> {
158 attrs.iter().find_map(|attr| {
160 _ if attr.has_name(sym::lang) => (attr.value_str()?, attr.span),
161 _ if attr.has_name(sym::panic_handler) => (sym::panic_impl, attr.span),
162 _ if attr.has_name(sym::alloc_error_handler) => (sym::oom, attr.span),
168 language_item_table! {
169 // Variant name, Name, Method name, Target Generic requirements;
170 Sized, sym::sized, sized_trait, Target::Trait, GenericRequirement::Exact(0);
171 Unsize, sym::unsize, unsize_trait, Target::Trait, GenericRequirement::Minimum(1);
172 /// Trait injected by `#[derive(PartialEq)]`, (i.e. "Partial EQ").
173 StructuralPeq, sym::structural_peq, structural_peq_trait, Target::Trait, GenericRequirement::None;
174 /// Trait injected by `#[derive(Eq)]`, (i.e. "Total EQ"; no, I will not apologize).
175 StructuralTeq, sym::structural_teq, structural_teq_trait, Target::Trait, GenericRequirement::None;
176 Copy, sym::copy, copy_trait, Target::Trait, GenericRequirement::Exact(0);
177 Clone, sym::clone, clone_trait, Target::Trait, GenericRequirement::None;
178 Sync, sym::sync, sync_trait, Target::Trait, GenericRequirement::Exact(0);
179 DiscriminantKind, sym::discriminant_kind, discriminant_kind_trait, Target::Trait, GenericRequirement::None;
180 /// The associated item of the [`DiscriminantKind`] trait.
181 Discriminant, sym::discriminant_type, discriminant_type, Target::AssocTy, GenericRequirement::None;
183 PointeeTrait, sym::pointee_trait, pointee_trait, Target::Trait, GenericRequirement::None;
184 Metadata, sym::metadata_type, metadata_type, Target::AssocTy, GenericRequirement::None;
185 DynMetadata, sym::dyn_metadata, dyn_metadata, Target::Struct, GenericRequirement::None;
187 Freeze, sym::freeze, freeze_trait, Target::Trait, GenericRequirement::Exact(0);
189 Drop, sym::drop, drop_trait, Target::Trait, GenericRequirement::None;
190 Destruct, sym::destruct, destruct_trait, Target::Trait, GenericRequirement::None;
192 CoerceUnsized, sym::coerce_unsized, coerce_unsized_trait, Target::Trait, GenericRequirement::Minimum(1);
193 DispatchFromDyn, sym::dispatch_from_dyn, dispatch_from_dyn_trait, Target::Trait, GenericRequirement::Minimum(1);
195 // language items relating to transmutability
196 TransmuteOpts, sym::transmute_opts, transmute_opts, Target::Struct, GenericRequirement::Exact(0);
197 TransmuteTrait, sym::transmute_trait, transmute_trait, Target::Trait, GenericRequirement::Exact(3);
199 Add(Op), sym::add, add_trait, Target::Trait, GenericRequirement::Exact(1);
200 Sub(Op), sym::sub, sub_trait, Target::Trait, GenericRequirement::Exact(1);
201 Mul(Op), sym::mul, mul_trait, Target::Trait, GenericRequirement::Exact(1);
202 Div(Op), sym::div, div_trait, Target::Trait, GenericRequirement::Exact(1);
203 Rem(Op), sym::rem, rem_trait, Target::Trait, GenericRequirement::Exact(1);
204 Neg(Op), sym::neg, neg_trait, Target::Trait, GenericRequirement::Exact(0);
205 Not(Op), sym::not, not_trait, Target::Trait, GenericRequirement::Exact(0);
206 BitXor(Op), sym::bitxor, bitxor_trait, Target::Trait, GenericRequirement::Exact(1);
207 BitAnd(Op), sym::bitand, bitand_trait, Target::Trait, GenericRequirement::Exact(1);
208 BitOr(Op), sym::bitor, bitor_trait, Target::Trait, GenericRequirement::Exact(1);
209 Shl(Op), sym::shl, shl_trait, Target::Trait, GenericRequirement::Exact(1);
210 Shr(Op), sym::shr, shr_trait, Target::Trait, GenericRequirement::Exact(1);
211 AddAssign(Op), sym::add_assign, add_assign_trait, Target::Trait, GenericRequirement::Exact(1);
212 SubAssign(Op), sym::sub_assign, sub_assign_trait, Target::Trait, GenericRequirement::Exact(1);
213 MulAssign(Op), sym::mul_assign, mul_assign_trait, Target::Trait, GenericRequirement::Exact(1);
214 DivAssign(Op), sym::div_assign, div_assign_trait, Target::Trait, GenericRequirement::Exact(1);
215 RemAssign(Op), sym::rem_assign, rem_assign_trait, Target::Trait, GenericRequirement::Exact(1);
216 BitXorAssign(Op), sym::bitxor_assign, bitxor_assign_trait, Target::Trait, GenericRequirement::Exact(1);
217 BitAndAssign(Op), sym::bitand_assign, bitand_assign_trait, Target::Trait, GenericRequirement::Exact(1);
218 BitOrAssign(Op), sym::bitor_assign, bitor_assign_trait, Target::Trait, GenericRequirement::Exact(1);
219 ShlAssign(Op), sym::shl_assign, shl_assign_trait, Target::Trait, GenericRequirement::Exact(1);
220 ShrAssign(Op), sym::shr_assign, shr_assign_trait, Target::Trait, GenericRequirement::Exact(1);
221 Index(Op), sym::index, index_trait, Target::Trait, GenericRequirement::Exact(1);
222 IndexMut(Op), sym::index_mut, index_mut_trait, Target::Trait, GenericRequirement::Exact(1);
224 UnsafeCell, sym::unsafe_cell, unsafe_cell_type, Target::Struct, GenericRequirement::None;
225 VaList, sym::va_list, va_list, Target::Struct, GenericRequirement::None;
227 Deref, sym::deref, deref_trait, Target::Trait, GenericRequirement::Exact(0);
228 DerefMut, sym::deref_mut, deref_mut_trait, Target::Trait, GenericRequirement::Exact(0);
229 DerefTarget, sym::deref_target, deref_target, Target::AssocTy, GenericRequirement::None;
230 Receiver, sym::receiver, receiver_trait, Target::Trait, GenericRequirement::None;
232 Fn(Fn), kw::Fn, fn_trait, Target::Trait, GenericRequirement::Exact(1);
233 FnMut(Fn), sym::fn_mut, fn_mut_trait, Target::Trait, GenericRequirement::Exact(1);
234 FnOnce(Fn), sym::fn_once, fn_once_trait, Target::Trait, GenericRequirement::Exact(1);
236 FnOnceOutput, sym::fn_once_output, fn_once_output, Target::AssocTy, GenericRequirement::None;
238 Future, sym::future_trait, future_trait, Target::Trait, GenericRequirement::Exact(0);
239 GeneratorState, sym::generator_state, gen_state, Target::Enum, GenericRequirement::None;
240 Generator, sym::generator, gen_trait, Target::Trait, GenericRequirement::Minimum(1);
241 Unpin, sym::unpin, unpin_trait, Target::Trait, GenericRequirement::None;
242 Pin, sym::pin, pin_type, Target::Struct, GenericRequirement::None;
244 PartialEq(Op), sym::eq, eq_trait, Target::Trait, GenericRequirement::Exact(1);
245 PartialOrd(Op), sym::partial_ord, partial_ord_trait, Target::Trait, GenericRequirement::Exact(1);
247 // A number of panic-related lang items. The `panic` item corresponds to divide-by-zero and
248 // various panic cases with `match`. The `panic_bounds_check` item is for indexing arrays.
250 // The `begin_unwind` lang item has a predefined symbol name and is sort of a "weak lang item"
251 // in the sense that a crate is not required to have it defined to use it, but a final product
252 // is required to define it somewhere. Additionally, there are restrictions on crates that use
253 // a weak lang item, but do not have it defined.
254 Panic, sym::panic, panic_fn, Target::Fn, GenericRequirement::Exact(0);
255 PanicFmt, sym::panic_fmt, panic_fmt, Target::Fn, GenericRequirement::None;
256 PanicDisplay, sym::panic_display, panic_display, Target::Fn, GenericRequirement::None;
257 ConstPanicFmt, sym::const_panic_fmt, const_panic_fmt, Target::Fn, GenericRequirement::None;
258 PanicBoundsCheck, sym::panic_bounds_check, panic_bounds_check_fn, Target::Fn, GenericRequirement::Exact(0);
259 PanicInfo, sym::panic_info, panic_info, Target::Struct, GenericRequirement::None;
260 PanicLocation, sym::panic_location, panic_location, Target::Struct, GenericRequirement::None;
261 PanicImpl, sym::panic_impl, panic_impl, Target::Fn, GenericRequirement::None;
262 PanicNoUnwind, sym::panic_no_unwind, panic_no_unwind, Target::Fn, GenericRequirement::Exact(0);
263 /// libstd panic entry point. Necessary for const eval to be able to catch it
264 BeginPanic, sym::begin_panic, begin_panic_fn, Target::Fn, GenericRequirement::None;
266 ExchangeMalloc, sym::exchange_malloc, exchange_malloc_fn, Target::Fn, GenericRequirement::None;
267 BoxFree, sym::box_free, box_free_fn, Target::Fn, GenericRequirement::Minimum(1);
268 DropInPlace, sym::drop_in_place, drop_in_place_fn, Target::Fn, GenericRequirement::Minimum(1);
269 Oom, sym::oom, oom, Target::Fn, GenericRequirement::None;
270 AllocLayout, sym::alloc_layout, alloc_layout, Target::Struct, GenericRequirement::None;
272 Start, sym::start, start_fn, Target::Fn, GenericRequirement::Exact(1);
274 EhPersonality, sym::eh_personality, eh_personality, Target::Fn, GenericRequirement::None;
275 EhCatchTypeinfo, sym::eh_catch_typeinfo, eh_catch_typeinfo, Target::Static, GenericRequirement::None;
277 OwnedBox, sym::owned_box, owned_box, Target::Struct, GenericRequirement::Minimum(1);
279 PhantomData, sym::phantom_data, phantom_data, Target::Struct, GenericRequirement::Exact(1);
281 ManuallyDrop, sym::manually_drop, manually_drop, Target::Struct, GenericRequirement::None;
283 MaybeUninit, sym::maybe_uninit, maybe_uninit, Target::Union, GenericRequirement::None;
285 /// Align offset for stride != 1; must not panic.
286 AlignOffset, sym::align_offset, align_offset_fn, Target::Fn, GenericRequirement::None;
288 Termination, sym::termination, termination, Target::Trait, GenericRequirement::None;
290 Try, sym::Try, try_trait, Target::Trait, GenericRequirement::None;
292 Tuple, sym::tuple_trait, tuple_trait, Target::Trait, GenericRequirement::Exact(0);
294 SliceLen, sym::slice_len_fn, slice_len_fn, Target::Method(MethodKind::Inherent), GenericRequirement::None;
296 // Language items from AST lowering
297 TryTraitFromResidual, sym::from_residual, from_residual_fn, Target::Method(MethodKind::Trait { body: false }), GenericRequirement::None;
298 TryTraitFromOutput, sym::from_output, from_output_fn, Target::Method(MethodKind::Trait { body: false }), GenericRequirement::None;
299 TryTraitBranch, sym::branch, branch_fn, Target::Method(MethodKind::Trait { body: false }), GenericRequirement::None;
300 TryTraitFromYeet, sym::from_yeet, from_yeet_fn, Target::Fn, GenericRequirement::None;
302 PollReady, sym::Ready, poll_ready_variant, Target::Variant, GenericRequirement::None;
303 PollPending, sym::Pending, poll_pending_variant, Target::Variant, GenericRequirement::None;
305 FromGenerator, sym::from_generator, from_generator_fn, Target::Fn, GenericRequirement::None;
306 GetContext, sym::get_context, get_context_fn, Target::Fn, GenericRequirement::None;
308 FuturePoll, sym::poll, future_poll_fn, Target::Method(MethodKind::Trait { body: false }), GenericRequirement::None;
310 FromFrom, sym::from, from_fn, Target::Method(MethodKind::Trait { body: false }), GenericRequirement::None;
312 OptionSome, sym::Some, option_some_variant, Target::Variant, GenericRequirement::None;
313 OptionNone, sym::None, option_none_variant, Target::Variant, GenericRequirement::None;
315 ResultOk, sym::Ok, result_ok_variant, Target::Variant, GenericRequirement::None;
316 ResultErr, sym::Err, result_err_variant, Target::Variant, GenericRequirement::None;
318 ControlFlowContinue, sym::Continue, cf_continue_variant, Target::Variant, GenericRequirement::None;
319 ControlFlowBreak, sym::Break, cf_break_variant, Target::Variant, GenericRequirement::None;
321 IntoFutureIntoFuture, sym::into_future, into_future_fn, Target::Method(MethodKind::Trait { body: false }), GenericRequirement::None;
322 IntoIterIntoIter, sym::into_iter, into_iter_fn, Target::Method(MethodKind::Trait { body: false }), GenericRequirement::None;
323 IteratorNext, sym::next, next_fn, Target::Method(MethodKind::Trait { body: false}), GenericRequirement::None;
325 PinNewUnchecked, sym::new_unchecked, new_unchecked_fn, Target::Method(MethodKind::Inherent), GenericRequirement::None;
327 RangeFrom, sym::RangeFrom, range_from_struct, Target::Struct, GenericRequirement::None;
328 RangeFull, sym::RangeFull, range_full_struct, Target::Struct, GenericRequirement::None;
329 RangeInclusiveStruct, sym::RangeInclusive, range_inclusive_struct, Target::Struct, GenericRequirement::None;
330 RangeInclusiveNew, sym::range_inclusive_new, range_inclusive_new_method, Target::Method(MethodKind::Inherent), GenericRequirement::None;
331 Range, sym::Range, range_struct, Target::Struct, GenericRequirement::None;
332 RangeToInclusive, sym::RangeToInclusive, range_to_inclusive_struct, Target::Struct, GenericRequirement::None;
333 RangeTo, sym::RangeTo, range_to_struct, Target::Struct, GenericRequirement::None;
336 pub enum GenericRequirement {