]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_hir/src/lang_items.rs
Rollup merge of #85177 - tspiteri:wrapping-bits, r=joshtriplett
[rust.git] / compiler / rustc_hir / src / lang_items.rs
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
10 use crate::def_id::DefId;
11 use crate::{MethodKind, Target};
12
13 use rustc_ast as ast;
14 use rustc_data_structures::fx::FxHashMap;
15 use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
16 use rustc_macros::HashStable_Generic;
17 use rustc_span::symbol::{kw, sym, Symbol};
18 use rustc_span::Span;
19
20 use std::lazy::SyncLazy;
21
22 pub enum LangItemGroup {
23     Op,
24 }
25
26 const NUM_GROUPS: usize = 1;
27
28 macro_rules! expand_group {
29     () => {
30         None
31     };
32     ($group:expr) => {
33         Some($group)
34     };
35 }
36
37 // The actual lang items defined come at the end of this file in one handy table.
38 // So you probably just want to nip down to the end.
39 macro_rules! language_item_table {
40     (
41         $( $(#[$attr:meta])* $variant:ident $($group:expr)?, $module:ident :: $name:ident, $method:ident, $target:expr; )*
42     ) => {
43
44         enum_from_u32! {
45             /// A representation of all the valid language items in Rust.
46             #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash, Encodable, Decodable)]
47             pub enum LangItem {
48                 $(
49                     #[doc = concat!("The `", stringify!($name), "` lang item.")]
50                     ///
51                     $(#[$attr])*
52                     $variant,
53                 )*
54             }
55         }
56
57         impl LangItem {
58             /// Returns the `name` symbol in `#[lang = "$name"]`.
59             /// For example, [`LangItem::PartialEq`]`.name()`
60             /// would result in [`sym::eq`] since it is `#[lang = "eq"]`.
61             pub fn name(self) -> Symbol {
62                 match self {
63                     $( LangItem::$variant => $module::$name, )*
64                 }
65             }
66
67             /// The [group](LangItemGroup) that this lang item belongs to,
68             /// or `None` if it doesn't belong to a group.
69             pub fn group(self) -> Option<LangItemGroup> {
70                 use LangItemGroup::*;
71                 match self {
72                     $( LangItem::$variant => expand_group!($($group)*), )*
73                 }
74             }
75         }
76
77         /// All of the language items, defined or not.
78         /// Defined lang items can come from the current crate or its dependencies.
79         #[derive(HashStable_Generic, Debug)]
80         pub struct LanguageItems {
81             /// Mappings from lang items to their possibly found [`DefId`]s.
82             /// The index corresponds to the order in [`LangItem`].
83             pub items: Vec<Option<DefId>>,
84             /// Lang items that were not found during collection.
85             pub missing: Vec<LangItem>,
86             /// Mapping from [`LangItemGroup`] discriminants to all
87             /// [`DefId`]s of lang items in that group.
88             pub groups: [Vec<DefId>; NUM_GROUPS],
89         }
90
91         impl LanguageItems {
92             /// Construct an empty collection of lang items and no missing ones.
93             pub fn new() -> Self {
94                 fn init_none(_: LangItem) -> Option<DefId> { None }
95
96                 Self {
97                     items: vec![$(init_none(LangItem::$variant)),*],
98                     missing: Vec::new(),
99                     groups: [vec![]; NUM_GROUPS],
100                 }
101             }
102
103             /// Returns the mappings to the possibly found `DefId`s for each lang item.
104             pub fn items(&self) -> &[Option<DefId>] {
105                 &*self.items
106             }
107
108             /// Requires that a given `LangItem` was bound and returns the corresponding `DefId`.
109             /// If it wasn't bound, e.g. due to a missing `#[lang = "<it.name()>"]`,
110             /// returns an error message as a string.
111             pub fn require(&self, it: LangItem) -> Result<DefId, String> {
112                 self.items[it as usize].ok_or_else(|| format!("requires `{}` lang_item", it.name()))
113             }
114
115             /// Returns the [`DefId`]s of all lang items in a group.
116             pub fn group(&self, group: LangItemGroup) -> &[DefId] {
117                 self.groups[group as usize].as_ref()
118             }
119
120             $(
121                 #[doc = concat!("Returns the [`DefId`] of the `", stringify!($name), "` lang item if it is defined.")]
122                 pub fn $method(&self) -> Option<DefId> {
123                     self.items[LangItem::$variant as usize]
124                 }
125             )*
126         }
127
128         /// A mapping from the name of the lang item to its order and the form it must be of.
129         pub static ITEM_REFS: SyncLazy<FxHashMap<Symbol, (usize, Target)>> = SyncLazy::new(|| {
130             let mut item_refs = FxHashMap::default();
131             $( item_refs.insert($module::$name, (LangItem::$variant as usize, $target)); )*
132             item_refs
133         });
134
135 // End of the macro
136     }
137 }
138
139 impl<CTX> HashStable<CTX> for LangItem {
140     fn hash_stable(&self, _: &mut CTX, hasher: &mut StableHasher) {
141         ::std::hash::Hash::hash(self, hasher);
142     }
143 }
144
145 /// Extracts the first `lang = "$name"` out of a list of attributes.
146 /// The attributes `#[panic_handler]` and `#[alloc_error_handler]`
147 /// are also extracted out when found.
148 ///
149 /// About the `check_name` argument: passing in a `Session` would be simpler,
150 /// because then we could call `Session::check_name` directly. But we want to
151 /// avoid the need for `rustc_hir` to depend on `rustc_session`, so we
152 /// use a closure instead.
153 pub fn extract<'a, F>(check_name: F, attrs: &'a [ast::Attribute]) -> Option<(Symbol, Span)>
154 where
155     F: Fn(&'a ast::Attribute, Symbol) -> bool,
156 {
157     attrs.iter().find_map(|attr| {
158         Some(match attr {
159             _ if check_name(attr, sym::lang) => (attr.value_str()?, attr.span),
160             _ if check_name(attr, sym::panic_handler) => (sym::panic_impl, attr.span),
161             _ if check_name(attr, sym::alloc_error_handler) => (sym::oom, attr.span),
162             _ => return None,
163         })
164     })
165 }
166
167 language_item_table! {
168 //  Variant name,            Name,                     Method name,                Target;
169     Bool,                    sym::bool,                bool_impl,                  Target::Impl;
170     Char,                    sym::char,                char_impl,                  Target::Impl;
171     Str,                     sym::str,                 str_impl,                   Target::Impl;
172     Array,                   sym::array,               array_impl,                 Target::Impl;
173     Slice,                   sym::slice,               slice_impl,                 Target::Impl;
174     SliceU8,                 sym::slice_u8,            slice_u8_impl,              Target::Impl;
175     StrAlloc,                sym::str_alloc,           str_alloc_impl,             Target::Impl;
176     SliceAlloc,              sym::slice_alloc,         slice_alloc_impl,           Target::Impl;
177     SliceU8Alloc,            sym::slice_u8_alloc,      slice_u8_alloc_impl,        Target::Impl;
178     ConstPtr,                sym::const_ptr,           const_ptr_impl,             Target::Impl;
179     MutPtr,                  sym::mut_ptr,             mut_ptr_impl,               Target::Impl;
180     ConstSlicePtr,           sym::const_slice_ptr,     const_slice_ptr_impl,       Target::Impl;
181     MutSlicePtr,             sym::mut_slice_ptr,       mut_slice_ptr_impl,         Target::Impl;
182     I8,                      sym::i8,                  i8_impl,                    Target::Impl;
183     I16,                     sym::i16,                 i16_impl,                   Target::Impl;
184     I32,                     sym::i32,                 i32_impl,                   Target::Impl;
185     I64,                     sym::i64,                 i64_impl,                   Target::Impl;
186     I128,                    sym::i128,                i128_impl,                  Target::Impl;
187     Isize,                   sym::isize,               isize_impl,                 Target::Impl;
188     U8,                      sym::u8,                  u8_impl,                    Target::Impl;
189     U16,                     sym::u16,                 u16_impl,                   Target::Impl;
190     U32,                     sym::u32,                 u32_impl,                   Target::Impl;
191     U64,                     sym::u64,                 u64_impl,                   Target::Impl;
192     U128,                    sym::u128,                u128_impl,                  Target::Impl;
193     Usize,                   sym::usize,               usize_impl,                 Target::Impl;
194     F32,                     sym::f32,                 f32_impl,                   Target::Impl;
195     F64,                     sym::f64,                 f64_impl,                   Target::Impl;
196     F32Runtime,              sym::f32_runtime,         f32_runtime_impl,           Target::Impl;
197     F64Runtime,              sym::f64_runtime,         f64_runtime_impl,           Target::Impl;
198
199     Sized,                   sym::sized,               sized_trait,                Target::Trait;
200     Unsize,                  sym::unsize,              unsize_trait,               Target::Trait;
201     /// Trait injected by `#[derive(PartialEq)]`, (i.e. "Partial EQ").
202     StructuralPeq,           sym::structural_peq,      structural_peq_trait,       Target::Trait;
203     /// Trait injected by `#[derive(Eq)]`, (i.e. "Total EQ"; no, I will not apologize).
204     StructuralTeq,           sym::structural_teq,      structural_teq_trait,       Target::Trait;
205     Copy,                    sym::copy,                copy_trait,                 Target::Trait;
206     Clone,                   sym::clone,               clone_trait,                Target::Trait;
207     Sync,                    sym::sync,                sync_trait,                 Target::Trait;
208     DiscriminantKind,        sym::discriminant_kind,   discriminant_kind_trait,    Target::Trait;
209     /// The associated item of the [`DiscriminantKind`] trait.
210     Discriminant,            sym::discriminant_type,   discriminant_type,          Target::AssocTy;
211
212     PointeeTrait,            sym::pointee_trait,       pointee_trait,              Target::Trait;
213     Metadata,                sym::metadata_type,       metadata_type,              Target::AssocTy;
214     DynMetadata,             sym::dyn_metadata,        dyn_metadata,               Target::Struct;
215
216     Freeze,                  sym::freeze,              freeze_trait,               Target::Trait;
217
218     Drop,                    sym::drop,                drop_trait,                 Target::Trait;
219
220     CoerceUnsized,           sym::coerce_unsized,      coerce_unsized_trait,       Target::Trait;
221     DispatchFromDyn,         sym::dispatch_from_dyn,   dispatch_from_dyn_trait,    Target::Trait;
222
223     Add(Op),                 sym::add,                 add_trait,                  Target::Trait;
224     Sub(Op),                 sym::sub,                 sub_trait,                  Target::Trait;
225     Mul(Op),                 sym::mul,                 mul_trait,                  Target::Trait;
226     Div(Op),                 sym::div,                 div_trait,                  Target::Trait;
227     Rem(Op),                 sym::rem,                 rem_trait,                  Target::Trait;
228     Neg(Op),                 sym::neg,                 neg_trait,                  Target::Trait;
229     Not(Op),                 sym::not,                 not_trait,                  Target::Trait;
230     BitXor(Op),              sym::bitxor,              bitxor_trait,               Target::Trait;
231     BitAnd(Op),              sym::bitand,              bitand_trait,               Target::Trait;
232     BitOr(Op),               sym::bitor,               bitor_trait,                Target::Trait;
233     Shl(Op),                 sym::shl,                 shl_trait,                  Target::Trait;
234     Shr(Op),                 sym::shr,                 shr_trait,                  Target::Trait;
235     AddAssign(Op),           sym::add_assign,          add_assign_trait,           Target::Trait;
236     SubAssign(Op),           sym::sub_assign,          sub_assign_trait,           Target::Trait;
237     MulAssign(Op),           sym::mul_assign,          mul_assign_trait,           Target::Trait;
238     DivAssign(Op),           sym::div_assign,          div_assign_trait,           Target::Trait;
239     RemAssign(Op),           sym::rem_assign,          rem_assign_trait,           Target::Trait;
240     BitXorAssign(Op),        sym::bitxor_assign,       bitxor_assign_trait,        Target::Trait;
241     BitAndAssign(Op),        sym::bitand_assign,       bitand_assign_trait,        Target::Trait;
242     BitOrAssign(Op),         sym::bitor_assign,        bitor_assign_trait,         Target::Trait;
243     ShlAssign(Op),           sym::shl_assign,          shl_assign_trait,           Target::Trait;
244     ShrAssign(Op),           sym::shr_assign,          shr_assign_trait,           Target::Trait;
245     Index(Op),               sym::index,               index_trait,                Target::Trait;
246     IndexMut(Op),            sym::index_mut,           index_mut_trait,            Target::Trait;
247
248     UnsafeCell,              sym::unsafe_cell,         unsafe_cell_type,           Target::Struct;
249     VaList,                  sym::va_list,             va_list,                    Target::Struct;
250
251     Deref,                   sym::deref,               deref_trait,                Target::Trait;
252     DerefMut,                sym::deref_mut,           deref_mut_trait,            Target::Trait;
253     DerefTarget,             sym::deref_target,        deref_target,               Target::AssocTy;
254     Receiver,                sym::receiver,            receiver_trait,             Target::Trait;
255
256     Fn,                      kw::Fn,                   fn_trait,                   Target::Trait;
257     FnMut,                   sym::fn_mut,              fn_mut_trait,               Target::Trait;
258     FnOnce,                  sym::fn_once,             fn_once_trait,              Target::Trait;
259
260     FnOnceOutput,            sym::fn_once_output,      fn_once_output,             Target::AssocTy;
261
262     Future,                  sym::future_trait,        future_trait,               Target::Trait;
263     GeneratorState,          sym::generator_state,     gen_state,                  Target::Enum;
264     Generator,               sym::generator,           gen_trait,                  Target::Trait;
265     Unpin,                   sym::unpin,               unpin_trait,                Target::Trait;
266     Pin,                     sym::pin,                 pin_type,                   Target::Struct;
267
268     PartialEq,               sym::eq,                  eq_trait,                   Target::Trait;
269     PartialOrd,              sym::partial_ord,         partial_ord_trait,          Target::Trait;
270
271     // A number of panic-related lang items. The `panic` item corresponds to divide-by-zero and
272     // various panic cases with `match`. The `panic_bounds_check` item is for indexing arrays.
273     //
274     // The `begin_unwind` lang item has a predefined symbol name and is sort of a "weak lang item"
275     // in the sense that a crate is not required to have it defined to use it, but a final product
276     // is required to define it somewhere. Additionally, there are restrictions on crates that use
277     // a weak lang item, but do not have it defined.
278     Panic,                   sym::panic,               panic_fn,                   Target::Fn;
279     PanicStr,                sym::panic_str,           panic_str,                  Target::Fn;
280     PanicBoundsCheck,        sym::panic_bounds_check,  panic_bounds_check_fn,      Target::Fn;
281     PanicInfo,               sym::panic_info,          panic_info,                 Target::Struct;
282     PanicLocation,           sym::panic_location,      panic_location,             Target::Struct;
283     PanicImpl,               sym::panic_impl,          panic_impl,                 Target::Fn;
284     /// libstd panic entry point. Necessary for const eval to be able to catch it
285     BeginPanic,              sym::begin_panic,         begin_panic_fn,             Target::Fn;
286
287     ExchangeMalloc,          sym::exchange_malloc,     exchange_malloc_fn,         Target::Fn;
288     BoxFree,                 sym::box_free,            box_free_fn,                Target::Fn;
289     DropInPlace,             sym::drop_in_place,       drop_in_place_fn,           Target::Fn;
290     Oom,                     sym::oom,                 oom,                        Target::Fn;
291     AllocLayout,             sym::alloc_layout,        alloc_layout,               Target::Struct;
292
293     Start,                   sym::start,               start_fn,                   Target::Fn;
294
295     EhPersonality,           sym::eh_personality,      eh_personality,             Target::Fn;
296     EhCatchTypeinfo,         sym::eh_catch_typeinfo,   eh_catch_typeinfo,          Target::Static;
297
298     OwnedBox,                sym::owned_box,           owned_box,                  Target::Struct;
299
300     PhantomData,             sym::phantom_data,        phantom_data,               Target::Struct;
301
302     ManuallyDrop,            sym::manually_drop,       manually_drop,              Target::Struct;
303
304     MaybeUninit,             sym::maybe_uninit,        maybe_uninit,               Target::Union;
305
306     /// Align offset for stride != 1; must not panic.
307     AlignOffset,             sym::align_offset,        align_offset_fn,            Target::Fn;
308
309     Termination,             sym::termination,         termination,                Target::Trait;
310
311     Try,                     kw::Try,                  try_trait,                  Target::Trait;
312
313     // Language items from AST lowering
314     TryFromError,            sym::from_error,          from_error_fn,              Target::Method(MethodKind::Trait { body: false });
315     TryFromOk,               sym::from_ok,             from_ok_fn,                 Target::Method(MethodKind::Trait { body: false });
316     TryIntoResult,           sym::into_result,         into_result_fn,             Target::Method(MethodKind::Trait { body: false });
317
318     PollReady,               sym::Ready,               poll_ready_variant,         Target::Variant;
319     PollPending,             sym::Pending,             poll_pending_variant,       Target::Variant;
320
321     FromGenerator,           sym::from_generator,      from_generator_fn,          Target::Fn;
322     GetContext,              sym::get_context,         get_context_fn,             Target::Fn;
323
324     FuturePoll,              sym::poll,                future_poll_fn,             Target::Method(MethodKind::Trait { body: false });
325
326     FromFrom,                sym::from,                from_fn,                    Target::Method(MethodKind::Trait { body: false });
327
328     OptionSome,              sym::Some,                option_some_variant,        Target::Variant;
329     OptionNone,              sym::None,                option_none_variant,        Target::Variant;
330
331     ResultOk,                sym::Ok,                  result_ok_variant,          Target::Variant;
332     ResultErr,               sym::Err,                 result_err_variant,         Target::Variant;
333
334     IntoIterIntoIter,        sym::into_iter,           into_iter_fn,               Target::Method(MethodKind::Trait { body: false });
335     IteratorNext,            sym::next,                next_fn,                    Target::Method(MethodKind::Trait { body: false});
336
337     PinNewUnchecked,         sym::new_unchecked,       new_unchecked_fn,           Target::Method(MethodKind::Inherent);
338
339     RangeFrom,               sym::RangeFrom,           range_from_struct,          Target::Struct;
340     RangeFull,               sym::RangeFull,           range_full_struct,          Target::Struct;
341     RangeInclusiveStruct,    sym::RangeInclusive,      range_inclusive_struct,     Target::Struct;
342     RangeInclusiveNew,       sym::range_inclusive_new, range_inclusive_new_method, Target::Method(MethodKind::Inherent);
343     Range,                   sym::Range,               range_struct,               Target::Struct;
344     RangeToInclusive,        sym::RangeToInclusive,    range_to_inclusive_struct,  Target::Struct;
345     RangeTo,                 sym::RangeTo,             range_to_struct,            Target::Struct;
346     Send,                    sym::send,                send_trait,                 Target::Trait;
347     UnwindSafe,              sym::unwind_safe,         unwind_safe_trait,          Target::Trait;
348     RefUnwindSafe,           sym::ref_unwind_safe,     ref_unwind_safe_trait,      Target::Trait;
349 }