]> git.proxmox.com Git - rustc.git/blame - compiler/rustc_hir/src/lang_items.rs
New upstream version 1.68.2+dfsg1
[rustc.git] / compiler / rustc_hir / src / lang_items.rs
CommitLineData
74b04a01
XL
1//! Defines language 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
74b04a01 10use crate::def_id::DefId;
f2b60f7d 11use crate::errors::LangItemError;
3dfed10e 12use crate::{MethodKind, Target};
74b04a01 13
3dfed10e 14use rustc_ast as ast;
74b04a01
XL
15use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
16use rustc_macros::HashStable_Generic;
3dfed10e 17use rustc_span::symbol::{kw, sym, Symbol};
74b04a01
XL
18use rustc_span::Span;
19
487cf647
FG
20/// All of the language items, defined or not.
21/// Defined lang items can come from the current crate or its dependencies.
22#[derive(HashStable_Generic, Debug)]
23pub struct LanguageItems {
24 /// Mappings from lang items to their possibly found [`DefId`]s.
25 /// The index corresponds to the order in [`LangItem`].
26 items: [Option<DefId>; std::mem::variant_count::<LangItem>()],
27 /// Lang items that were not found during collection.
28 pub missing: Vec<LangItem>,
f035d41b
XL
29}
30
487cf647
FG
31impl LanguageItems {
32 /// Construct an empty collection of lang items and no missing ones.
33 pub fn new() -> Self {
34 Self { items: [None; std::mem::variant_count::<LangItem>()], missing: Vec::new() }
35 }
36
37 pub fn get(&self, item: LangItem) -> Option<DefId> {
38 self.items[item as usize]
39 }
40
41 pub fn set(&mut self, item: LangItem, def_id: DefId) {
42 self.items[item as usize] = Some(def_id);
43 }
44
45 /// Requires that a given `LangItem` was bound and returns the corresponding `DefId`.
46 /// If it wasn't bound, e.g. due to a missing `#[lang = "<it.name()>"]`,
47 /// returns an error encapsulating the `LangItem`.
48 pub fn require(&self, it: LangItem) -> Result<DefId, LangItemError> {
49 self.get(it).ok_or_else(|| LangItemError(it))
50 }
f035d41b 51
487cf647
FG
52 pub fn iter<'a>(&'a self) -> impl Iterator<Item = (LangItem, DefId)> + 'a {
53 self.items
54 .iter()
55 .enumerate()
56 .filter_map(|(i, id)| id.map(|id| (LangItem::from_u32(i as u32).unwrap(), id)))
57 }
f035d41b
XL
58}
59
74b04a01
XL
60// The actual lang items defined come at the end of this file in one handy table.
61// So you probably just want to nip down to the end.
62macro_rules! language_item_table {
63 (
487cf647 64 $( $(#[$attr:meta])* $variant:ident, $module:ident :: $name:ident, $method:ident, $target:expr, $generics:expr; )*
74b04a01
XL
65 ) => {
66
67 enum_from_u32! {
68 /// A representation of all the valid language items in Rust.
3dfed10e 69 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash, Encodable, Decodable)]
74b04a01 70 pub enum LangItem {
6a06907d
XL
71 $(
72 #[doc = concat!("The `", stringify!($name), "` lang item.")]
73 ///
74 $(#[$attr])*
75 $variant,
76 )*
74b04a01
XL
77 }
78 }
79
80 impl LangItem {
3dfed10e 81 /// Returns the `name` symbol in `#[lang = "$name"]`.
6a06907d
XL
82 /// For example, [`LangItem::PartialEq`]`.name()`
83 /// would result in [`sym::eq`] since it is `#[lang = "eq"]`.
3dfed10e 84 pub fn name(self) -> Symbol {
74b04a01 85 match self {
6a06907d 86 $( LangItem::$variant => $module::$name, )*
74b04a01
XL
87 }
88 }
f035d41b 89
487cf647
FG
90 /// Opposite of [`LangItem::name`]
91 pub fn from_name(name: Symbol) -> Option<Self> {
92 match name {
93 $( $module::$name => Some(LangItem::$variant), )*
94 _ => None,
f035d41b
XL
95 }
96 }
94222f64 97
487cf647
FG
98 /// Returns the name of the `LangItem` enum variant.
99 // This method is used by Clippy for internal lints.
100 pub fn variant_name(self) -> &'static str {
94222f64 101 match self {
487cf647 102 $( LangItem::$variant => stringify!($variant), )*
94222f64
XL
103 }
104 }
74b04a01 105
487cf647
FG
106 pub fn target(self) -> Target {
107 match self {
108 $( LangItem::$variant => $target, )*
74b04a01
XL
109 }
110 }
111
487cf647
FG
112 pub fn required_generics(&self) -> GenericRequirement {
113 match self {
114 $( LangItem::$variant => $generics, )*
115 }
f035d41b 116 }
487cf647 117 }
f035d41b 118
487cf647 119 impl LanguageItems {
74b04a01 120 $(
6a06907d 121 #[doc = concat!("Returns the [`DefId`] of the `", stringify!($name), "` lang item if it is defined.")]
74b04a01 122 pub fn $method(&self) -> Option<DefId> {
3dfed10e 123 self.items[LangItem::$variant as usize]
74b04a01
XL
124 }
125 )*
126 }
74b04a01
XL
127 }
128}
129
130impl<CTX> HashStable<CTX> for LangItem {
131 fn hash_stable(&self, _: &mut CTX, hasher: &mut StableHasher) {
132 ::std::hash::Hash::hash(self, hasher);
133 }
134}
135
136/// Extracts the first `lang = "$name"` out of a list of attributes.
487cf647 137/// The `#[panic_handler]` attribute is also extracted out when found.
5099ac24 138pub fn extract(attrs: &[ast::Attribute]) -> Option<(Symbol, Span)> {
74b04a01
XL
139 attrs.iter().find_map(|attr| {
140 Some(match attr {
5099ac24
FG
141 _ if attr.has_name(sym::lang) => (attr.value_str()?, attr.span),
142 _ if attr.has_name(sym::panic_handler) => (sym::panic_impl, attr.span),
74b04a01
XL
143 _ => return None,
144 })
145 })
146}
147
148language_item_table! {
9c376795 149// Variant name, Name, Getter method name, Target Generic requirements;
94222f64
XL
150 Sized, sym::sized, sized_trait, Target::Trait, GenericRequirement::Exact(0);
151 Unsize, sym::unsize, unsize_trait, Target::Trait, GenericRequirement::Minimum(1);
6a06907d 152 /// Trait injected by `#[derive(PartialEq)]`, (i.e. "Partial EQ").
94222f64 153 StructuralPeq, sym::structural_peq, structural_peq_trait, Target::Trait, GenericRequirement::None;
6a06907d 154 /// Trait injected by `#[derive(Eq)]`, (i.e. "Total EQ"; no, I will not apologize).
94222f64
XL
155 StructuralTeq, sym::structural_teq, structural_teq_trait, Target::Trait, GenericRequirement::None;
156 Copy, sym::copy, copy_trait, Target::Trait, GenericRequirement::Exact(0);
157 Clone, sym::clone, clone_trait, Target::Trait, GenericRequirement::None;
158 Sync, sym::sync, sync_trait, Target::Trait, GenericRequirement::Exact(0);
159 DiscriminantKind, sym::discriminant_kind, discriminant_kind_trait, Target::Trait, GenericRequirement::None;
6a06907d 160 /// The associated item of the [`DiscriminantKind`] trait.
94222f64
XL
161 Discriminant, sym::discriminant_type, discriminant_type, Target::AssocTy, GenericRequirement::None;
162
163 PointeeTrait, sym::pointee_trait, pointee_trait, Target::Trait, GenericRequirement::None;
164 Metadata, sym::metadata_type, metadata_type, Target::AssocTy, GenericRequirement::None;
165 DynMetadata, sym::dyn_metadata, dyn_metadata, Target::Struct, GenericRequirement::None;
166
167 Freeze, sym::freeze, freeze_trait, Target::Trait, GenericRequirement::Exact(0);
168
169 Drop, sym::drop, drop_trait, Target::Trait, GenericRequirement::None;
5e7ed085 170 Destruct, sym::destruct, destruct_trait, Target::Trait, GenericRequirement::None;
94222f64
XL
171
172 CoerceUnsized, sym::coerce_unsized, coerce_unsized_trait, Target::Trait, GenericRequirement::Minimum(1);
173 DispatchFromDyn, sym::dispatch_from_dyn, dispatch_from_dyn_trait, Target::Trait, GenericRequirement::Minimum(1);
174
064997fb 175 // language items relating to transmutability
f2b60f7d
FG
176 TransmuteOpts, sym::transmute_opts, transmute_opts, Target::Struct, GenericRequirement::Exact(0);
177 TransmuteTrait, sym::transmute_trait, transmute_trait, Target::Trait, GenericRequirement::Exact(3);
064997fb 178
487cf647
FG
179 Add, sym::add, add_trait, Target::Trait, GenericRequirement::Exact(1);
180 Sub, sym::sub, sub_trait, Target::Trait, GenericRequirement::Exact(1);
181 Mul, sym::mul, mul_trait, Target::Trait, GenericRequirement::Exact(1);
182 Div, sym::div, div_trait, Target::Trait, GenericRequirement::Exact(1);
183 Rem, sym::rem, rem_trait, Target::Trait, GenericRequirement::Exact(1);
184 Neg, sym::neg, neg_trait, Target::Trait, GenericRequirement::Exact(0);
185 Not, sym::not, not_trait, Target::Trait, GenericRequirement::Exact(0);
186 BitXor, sym::bitxor, bitxor_trait, Target::Trait, GenericRequirement::Exact(1);
187 BitAnd, sym::bitand, bitand_trait, Target::Trait, GenericRequirement::Exact(1);
188 BitOr, sym::bitor, bitor_trait, Target::Trait, GenericRequirement::Exact(1);
189 Shl, sym::shl, shl_trait, Target::Trait, GenericRequirement::Exact(1);
190 Shr, sym::shr, shr_trait, Target::Trait, GenericRequirement::Exact(1);
191 AddAssign, sym::add_assign, add_assign_trait, Target::Trait, GenericRequirement::Exact(1);
192 SubAssign, sym::sub_assign, sub_assign_trait, Target::Trait, GenericRequirement::Exact(1);
193 MulAssign, sym::mul_assign, mul_assign_trait, Target::Trait, GenericRequirement::Exact(1);
194 DivAssign, sym::div_assign, div_assign_trait, Target::Trait, GenericRequirement::Exact(1);
195 RemAssign, sym::rem_assign, rem_assign_trait, Target::Trait, GenericRequirement::Exact(1);
196 BitXorAssign, sym::bitxor_assign, bitxor_assign_trait, Target::Trait, GenericRequirement::Exact(1);
197 BitAndAssign, sym::bitand_assign, bitand_assign_trait, Target::Trait, GenericRequirement::Exact(1);
198 BitOrAssign, sym::bitor_assign, bitor_assign_trait, Target::Trait, GenericRequirement::Exact(1);
199 ShlAssign, sym::shl_assign, shl_assign_trait, Target::Trait, GenericRequirement::Exact(1);
200 ShrAssign, sym::shr_assign, shr_assign_trait, Target::Trait, GenericRequirement::Exact(1);
201 Index, sym::index, index_trait, Target::Trait, GenericRequirement::Exact(1);
202 IndexMut, sym::index_mut, index_mut_trait, Target::Trait, GenericRequirement::Exact(1);
94222f64
XL
203
204 UnsafeCell, sym::unsafe_cell, unsafe_cell_type, Target::Struct, GenericRequirement::None;
205 VaList, sym::va_list, va_list, Target::Struct, GenericRequirement::None;
206
207 Deref, sym::deref, deref_trait, Target::Trait, GenericRequirement::Exact(0);
208 DerefMut, sym::deref_mut, deref_mut_trait, Target::Trait, GenericRequirement::Exact(0);
209 DerefTarget, sym::deref_target, deref_target, Target::AssocTy, GenericRequirement::None;
210 Receiver, sym::receiver, receiver_trait, Target::Trait, GenericRequirement::None;
211
487cf647
FG
212 Fn, kw::Fn, fn_trait, Target::Trait, GenericRequirement::Exact(1);
213 FnMut, sym::fn_mut, fn_mut_trait, Target::Trait, GenericRequirement::Exact(1);
214 FnOnce, sym::fn_once, fn_once_trait, Target::Trait, GenericRequirement::Exact(1);
94222f64
XL
215
216 FnOnceOutput, sym::fn_once_output, fn_once_output, Target::AssocTy, GenericRequirement::None;
217
218 Future, sym::future_trait, future_trait, Target::Trait, GenericRequirement::Exact(0);
219 GeneratorState, sym::generator_state, gen_state, Target::Enum, GenericRequirement::None;
220 Generator, sym::generator, gen_trait, Target::Trait, GenericRequirement::Minimum(1);
221 Unpin, sym::unpin, unpin_trait, Target::Trait, GenericRequirement::None;
222 Pin, sym::pin, pin_type, Target::Struct, GenericRequirement::None;
223
487cf647
FG
224 PartialEq, sym::eq, eq_trait, Target::Trait, GenericRequirement::Exact(1);
225 PartialOrd, sym::partial_ord, partial_ord_trait, Target::Trait, GenericRequirement::Exact(1);
3dfed10e
XL
226
227 // A number of panic-related lang items. The `panic` item corresponds to divide-by-zero and
228 // various panic cases with `match`. The `panic_bounds_check` item is for indexing arrays.
74b04a01 229 //
3dfed10e
XL
230 // The `begin_unwind` lang item has a predefined symbol name and is sort of a "weak lang item"
231 // in the sense that a crate is not required to have it defined to use it, but a final product
232 // is required to define it somewhere. Additionally, there are restrictions on crates that use
233 // a weak lang item, but do not have it defined.
3c0e092e 234 Panic, sym::panic, panic_fn, Target::Fn, GenericRequirement::Exact(0);
9c376795 235 PanicNounwind, sym::panic_nounwind, panic_nounwind, Target::Fn, GenericRequirement::Exact(0);
94222f64 236 PanicFmt, sym::panic_fmt, panic_fmt, Target::Fn, GenericRequirement::None;
c295e0f8 237 PanicDisplay, sym::panic_display, panic_display, Target::Fn, GenericRequirement::None;
94222f64 238 ConstPanicFmt, sym::const_panic_fmt, const_panic_fmt, Target::Fn, GenericRequirement::None;
3c0e092e 239 PanicBoundsCheck, sym::panic_bounds_check, panic_bounds_check_fn, Target::Fn, GenericRequirement::Exact(0);
94222f64
XL
240 PanicInfo, sym::panic_info, panic_info, Target::Struct, GenericRequirement::None;
241 PanicLocation, sym::panic_location, panic_location, Target::Struct, GenericRequirement::None;
242 PanicImpl, sym::panic_impl, panic_impl, Target::Fn, GenericRequirement::None;
9c376795 243 PanicCannotUnwind, sym::panic_cannot_unwind, panic_cannot_unwind, Target::Fn, GenericRequirement::Exact(0);
6a06907d 244 /// libstd panic entry point. Necessary for const eval to be able to catch it
94222f64 245 BeginPanic, sym::begin_panic, begin_panic_fn, Target::Fn, GenericRequirement::None;
74b04a01 246
94222f64
XL
247 ExchangeMalloc, sym::exchange_malloc, exchange_malloc_fn, Target::Fn, GenericRequirement::None;
248 BoxFree, sym::box_free, box_free_fn, Target::Fn, GenericRequirement::Minimum(1);
249 DropInPlace, sym::drop_in_place, drop_in_place_fn, Target::Fn, GenericRequirement::Minimum(1);
94222f64 250 AllocLayout, sym::alloc_layout, alloc_layout, Target::Struct, GenericRequirement::None;
74b04a01 251
c295e0f8 252 Start, sym::start, start_fn, Target::Fn, GenericRequirement::Exact(1);
f035d41b 253
94222f64
XL
254 EhPersonality, sym::eh_personality, eh_personality, Target::Fn, GenericRequirement::None;
255 EhCatchTypeinfo, sym::eh_catch_typeinfo, eh_catch_typeinfo, Target::Static, GenericRequirement::None;
74b04a01 256
94222f64 257 OwnedBox, sym::owned_box, owned_box, Target::Struct, GenericRequirement::Minimum(1);
74b04a01 258
94222f64 259 PhantomData, sym::phantom_data, phantom_data, Target::Struct, GenericRequirement::Exact(1);
74b04a01 260
94222f64 261 ManuallyDrop, sym::manually_drop, manually_drop, Target::Struct, GenericRequirement::None;
74b04a01 262
94222f64 263 MaybeUninit, sym::maybe_uninit, maybe_uninit, Target::Union, GenericRequirement::None;
74b04a01 264
6a06907d 265 /// Align offset for stride != 1; must not panic.
94222f64 266 AlignOffset, sym::align_offset, align_offset_fn, Target::Fn, GenericRequirement::None;
3dfed10e 267
94222f64 268 Termination, sym::termination, termination, Target::Trait, GenericRequirement::None;
3dfed10e 269
94222f64 270 Try, sym::Try, try_trait, Target::Trait, GenericRequirement::None;
3dfed10e 271
f2b60f7d
FG
272 Tuple, sym::tuple_trait, tuple_trait, Target::Trait, GenericRequirement::Exact(0);
273
94222f64 274 SliceLen, sym::slice_len_fn, slice_len_fn, Target::Method(MethodKind::Inherent), GenericRequirement::None;
136023e0 275
3dfed10e 276 // Language items from AST lowering
94222f64
XL
277 TryTraitFromResidual, sym::from_residual, from_residual_fn, Target::Method(MethodKind::Trait { body: false }), GenericRequirement::None;
278 TryTraitFromOutput, sym::from_output, from_output_fn, Target::Method(MethodKind::Trait { body: false }), GenericRequirement::None;
279 TryTraitBranch, sym::branch, branch_fn, Target::Method(MethodKind::Trait { body: false }), GenericRequirement::None;
04454e1e 280 TryTraitFromYeet, sym::from_yeet, from_yeet_fn, Target::Fn, GenericRequirement::None;
94222f64 281
487cf647
FG
282 PointerSized, sym::pointer_sized, pointer_sized, Target::Trait, GenericRequirement::Exact(0);
283
284 Poll, sym::Poll, poll, Target::Enum, GenericRequirement::None;
94222f64
XL
285 PollReady, sym::Ready, poll_ready_variant, Target::Variant, GenericRequirement::None;
286 PollPending, sym::Pending, poll_pending_variant, Target::Variant, GenericRequirement::None;
3dfed10e 287
487cf647
FG
288 // FIXME(swatinem): the following lang items are used for async lowering and
289 // should become obsolete eventually.
290 ResumeTy, sym::ResumeTy, resume_ty, Target::Struct, GenericRequirement::None;
291 IdentityFuture, sym::identity_future, identity_future_fn, Target::Fn, GenericRequirement::None;
94222f64 292 GetContext, sym::get_context, get_context_fn, Target::Fn, GenericRequirement::None;
3dfed10e 293
9c376795 294 Context, sym::Context, context, Target::Struct, GenericRequirement::None;
94222f64 295 FuturePoll, sym::poll, future_poll_fn, Target::Method(MethodKind::Trait { body: false }), GenericRequirement::None;
3dfed10e 296
94222f64 297 FromFrom, sym::from, from_fn, Target::Method(MethodKind::Trait { body: false }), GenericRequirement::None;
3dfed10e 298
94222f64
XL
299 OptionSome, sym::Some, option_some_variant, Target::Variant, GenericRequirement::None;
300 OptionNone, sym::None, option_none_variant, Target::Variant, GenericRequirement::None;
3dfed10e 301
94222f64
XL
302 ResultOk, sym::Ok, result_ok_variant, Target::Variant, GenericRequirement::None;
303 ResultErr, sym::Err, result_err_variant, Target::Variant, GenericRequirement::None;
3dfed10e 304
94222f64
XL
305 ControlFlowContinue, sym::Continue, cf_continue_variant, Target::Variant, GenericRequirement::None;
306 ControlFlowBreak, sym::Break, cf_break_variant, Target::Variant, GenericRequirement::None;
3dfed10e 307
a2a8927a 308 IntoFutureIntoFuture, sym::into_future, into_future_fn, Target::Method(MethodKind::Trait { body: false }), GenericRequirement::None;
94222f64
XL
309 IntoIterIntoIter, sym::into_iter, into_iter_fn, Target::Method(MethodKind::Trait { body: false }), GenericRequirement::None;
310 IteratorNext, sym::next, next_fn, Target::Method(MethodKind::Trait { body: false}), GenericRequirement::None;
17df50a5 311
94222f64 312 PinNewUnchecked, sym::new_unchecked, new_unchecked_fn, Target::Method(MethodKind::Inherent), GenericRequirement::None;
74b04a01 313
94222f64
XL
314 RangeFrom, sym::RangeFrom, range_from_struct, Target::Struct, GenericRequirement::None;
315 RangeFull, sym::RangeFull, range_full_struct, Target::Struct, GenericRequirement::None;
316 RangeInclusiveStruct, sym::RangeInclusive, range_inclusive_struct, Target::Struct, GenericRequirement::None;
317 RangeInclusiveNew, sym::range_inclusive_new, range_inclusive_new_method, Target::Method(MethodKind::Inherent), GenericRequirement::None;
318 Range, sym::Range, range_struct, Target::Struct, GenericRequirement::None;
319 RangeToInclusive, sym::RangeToInclusive, range_to_inclusive_struct, Target::Struct, GenericRequirement::None;
320 RangeTo, sym::RangeTo, range_to_struct, Target::Struct, GenericRequirement::None;
487cf647
FG
321
322 String, sym::String, string, Target::Struct, GenericRequirement::None;
94222f64 323}
f9f354fc 324
94222f64
XL
325pub enum GenericRequirement {
326 None,
327 Minimum(usize),
328 Exact(usize),
74b04a01 329}
487cf647
FG
330
331pub static FN_TRAITS: &'static [LangItem] = &[LangItem::Fn, LangItem::FnMut, LangItem::FnOnce];
332
333pub static OPERATORS: &'static [LangItem] = &[
334 LangItem::Add,
335 LangItem::Sub,
336 LangItem::Mul,
337 LangItem::Div,
338 LangItem::Rem,
339 LangItem::Neg,
340 LangItem::Not,
341 LangItem::BitXor,
342 LangItem::BitAnd,
343 LangItem::BitOr,
344 LangItem::Shl,
345 LangItem::Shr,
346 LangItem::AddAssign,
347 LangItem::SubAssign,
348 LangItem::MulAssign,
349 LangItem::DivAssign,
350 LangItem::RemAssign,
351 LangItem::BitXorAssign,
352 LangItem::BitAndAssign,
353 LangItem::BitOrAssign,
354 LangItem::ShlAssign,
355 LangItem::ShrAssign,
356 LangItem::Index,
357 LangItem::IndexMut,
358 LangItem::PartialEq,
359 LangItem::PartialOrd,
360];