]> git.lizzy.rs Git - rust.git/blob - src/librustc_hir/lang_items.rs
Auto merge of #75635 - Aaron1011:fix/incr-fn-param-names, r=eddyb
[rust.git] / src / librustc_hir / 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 pub use self::LangItem::*;
11
12 use crate::def_id::DefId;
13 use crate::{MethodKind, Target};
14
15 use rustc_ast as ast;
16 use rustc_data_structures::fx::FxHashMap;
17 use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
18 use rustc_macros::HashStable_Generic;
19 use rustc_span::symbol::{kw, sym, Symbol};
20 use rustc_span::Span;
21
22 use lazy_static::lazy_static;
23
24 pub enum LangItemGroup {
25     Op,
26 }
27
28 const NUM_GROUPS: usize = 1;
29
30 macro_rules! expand_group {
31     () => {
32         None
33     };
34     ($group:expr) => {
35         Some($group)
36     };
37 }
38
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 {
42     (
43         $( $variant:ident $($group:expr)?, $name:expr, $method:ident, $target:expr; )*
44     ) => {
45
46         enum_from_u32! {
47             /// A representation of all the valid language items in Rust.
48             #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash, Encodable, Decodable)]
49             pub enum LangItem {
50                 $($variant,)*
51             }
52         }
53
54         impl LangItem {
55             /// Returns the `name` symbol in `#[lang = "$name"]`.
56             /// For example, `LangItem::EqTraitLangItem`,
57             /// that is `#[lang = "eq"]` would result in `sym::eq`.
58             pub fn name(self) -> Symbol {
59                 match self {
60                     $( $variant => $name, )*
61                 }
62             }
63
64             pub fn group(self) -> Option<LangItemGroup> {
65                 use LangItemGroup::*;
66                 match self {
67                     $( $variant => expand_group!($($group)*), )*
68                 }
69             }
70         }
71
72         #[derive(HashStable_Generic)]
73         pub struct LanguageItems {
74             /// Mappings from lang items to their possibly found `DefId`s.
75             /// The index corresponds to the order in `LangItem`.
76             pub items: Vec<Option<DefId>>,
77             /// Lang items that were not found during collection.
78             pub missing: Vec<LangItem>,
79             /// Mapping from `LangItemGroup` discriminants to all
80             /// `DefId`s of lang items in that group.
81             pub groups: [Vec<DefId>; NUM_GROUPS],
82         }
83
84         impl LanguageItems {
85             /// Construct an empty collection of lang items and no missing ones.
86             pub fn new() -> Self {
87                 fn init_none(_: LangItem) -> Option<DefId> { None }
88
89                 Self {
90                     items: vec![$(init_none($variant)),*],
91                     missing: Vec::new(),
92                     groups: [vec![]; NUM_GROUPS],
93                 }
94             }
95
96             /// Returns the mappings to the possibly found `DefId`s for each lang item.
97             pub fn items(&self) -> &[Option<DefId>] {
98                 &*self.items
99             }
100
101             /// Requires that a given `LangItem` was bound and returns the corresponding `DefId`.
102             /// If it wasn't bound, e.g. due to a missing `#[lang = "<it.name()>"]`,
103             /// returns an error message as a string.
104             pub fn require(&self, it: LangItem) -> Result<DefId, String> {
105                 self.items[it as usize].ok_or_else(|| format!("requires `{}` lang_item", it.name()))
106             }
107
108             pub fn group(&self, group: LangItemGroup) -> &[DefId] {
109                 self.groups[group as usize].as_ref()
110             }
111
112             $(
113                 /// Returns the corresponding `DefId` for the lang item if it
114                 /// exists.
115                 #[allow(dead_code)]
116                 pub fn $method(&self) -> Option<DefId> {
117                     self.items[$variant as usize]
118                 }
119             )*
120         }
121
122         lazy_static! {
123             /// A mapping from the name of the lang item to its order and the form it must be of.
124             pub static ref ITEM_REFS: FxHashMap<Symbol, (usize, Target)> = {
125                 let mut item_refs = FxHashMap::default();
126                 $( item_refs.insert($name, ($variant as usize, $target)); )*
127                 item_refs
128             };
129         }
130
131 // End of the macro
132     }
133 }
134
135 impl<CTX> HashStable<CTX> for LangItem {
136     fn hash_stable(&self, _: &mut CTX, hasher: &mut StableHasher) {
137         ::std::hash::Hash::hash(self, hasher);
138     }
139 }
140
141 /// Extracts the first `lang = "$name"` out of a list of attributes.
142 /// The attributes `#[panic_handler]` and `#[alloc_error_handler]`
143 /// are also extracted out when found.
144 ///
145 /// About the `check_name` argument: passing in a `Session` would be simpler,
146 /// because then we could call `Session::check_name` directly. But we want to
147 /// avoid the need for `librustc_hir` to depend on `librustc_session`, so we
148 /// use a closure instead.
149 pub fn extract<'a, F>(check_name: F, attrs: &'a [ast::Attribute]) -> Option<(Symbol, Span)>
150 where
151     F: Fn(&'a ast::Attribute, Symbol) -> bool,
152 {
153     attrs.iter().find_map(|attr| {
154         Some(match attr {
155             _ if check_name(attr, sym::lang) => (attr.value_str()?, attr.span),
156             _ if check_name(attr, sym::panic_handler) => (sym::panic_impl, attr.span),
157             _ if check_name(attr, sym::alloc_error_handler) => (sym::oom, attr.span),
158             _ => return None,
159         })
160     })
161 }
162
163 language_item_table! {
164 //  Variant name,                  Name,                    Method name,             Target;
165     BoolImplItem,                  sym::bool,               bool_impl,               Target::Impl;
166     CharImplItem,                  sym::char,               char_impl,               Target::Impl;
167     StrImplItem,                   sym::str,                str_impl,                Target::Impl;
168     ArrayImplItem,                 sym::array,              array_impl,              Target::Impl;
169     SliceImplItem,                 sym::slice,              slice_impl,              Target::Impl;
170     SliceU8ImplItem,               sym::slice_u8,           slice_u8_impl,           Target::Impl;
171     StrAllocImplItem,              sym::str_alloc,          str_alloc_impl,          Target::Impl;
172     SliceAllocImplItem,            sym::slice_alloc,        slice_alloc_impl,        Target::Impl;
173     SliceU8AllocImplItem,          sym::slice_u8_alloc,     slice_u8_alloc_impl,     Target::Impl;
174     ConstPtrImplItem,              sym::const_ptr,          const_ptr_impl,          Target::Impl;
175     MutPtrImplItem,                sym::mut_ptr,            mut_ptr_impl,            Target::Impl;
176     ConstSlicePtrImplItem,         sym::const_slice_ptr,    const_slice_ptr_impl,    Target::Impl;
177     MutSlicePtrImplItem,           sym::mut_slice_ptr,      mut_slice_ptr_impl,      Target::Impl;
178     I8ImplItem,                    sym::i8,                 i8_impl,                 Target::Impl;
179     I16ImplItem,                   sym::i16,                i16_impl,                Target::Impl;
180     I32ImplItem,                   sym::i32,                i32_impl,                Target::Impl;
181     I64ImplItem,                   sym::i64,                i64_impl,                Target::Impl;
182     I128ImplItem,                  sym::i128,               i128_impl,               Target::Impl;
183     IsizeImplItem,                 sym::isize,              isize_impl,              Target::Impl;
184     U8ImplItem,                    sym::u8,                 u8_impl,                 Target::Impl;
185     U16ImplItem,                   sym::u16,                u16_impl,                Target::Impl;
186     U32ImplItem,                   sym::u32,                u32_impl,                Target::Impl;
187     U64ImplItem,                   sym::u64,                u64_impl,                Target::Impl;
188     U128ImplItem,                  sym::u128,               u128_impl,               Target::Impl;
189     UsizeImplItem,                 sym::usize,              usize_impl,              Target::Impl;
190     F32ImplItem,                   sym::f32,                f32_impl,                Target::Impl;
191     F64ImplItem,                   sym::f64,                f64_impl,                Target::Impl;
192     F32RuntimeImplItem,            sym::f32_runtime,        f32_runtime_impl,        Target::Impl;
193     F64RuntimeImplItem,            sym::f64_runtime,        f64_runtime_impl,        Target::Impl;
194
195     SizedTraitLangItem,            sym::sized,              sized_trait,             Target::Trait;
196     UnsizeTraitLangItem,           sym::unsize,             unsize_trait,            Target::Trait;
197     // trait injected by #[derive(PartialEq)], (i.e. "Partial EQ").
198     StructuralPeqTraitLangItem,    sym::structural_peq,     structural_peq_trait,    Target::Trait;
199     // trait injected by #[derive(Eq)], (i.e. "Total EQ"; no, I will not apologize).
200     StructuralTeqTraitLangItem,    sym::structural_teq,     structural_teq_trait,    Target::Trait;
201     CopyTraitLangItem,             sym::copy,               copy_trait,              Target::Trait;
202     CloneTraitLangItem,            sym::clone,              clone_trait,             Target::Trait;
203     SyncTraitLangItem,             sym::sync,               sync_trait,              Target::Trait;
204     DiscriminantKindTraitLangItem, sym::discriminant_kind,  discriminant_kind_trait, Target::Trait;
205     // The associated item of `trait DiscriminantKind`.
206     DiscriminantTypeLangItem,      sym::discriminant_type,  discriminant_type,       Target::AssocTy;
207
208     FreezeTraitLangItem,           sym::freeze,             freeze_trait,            Target::Trait;
209
210     DropTraitLangItem,             sym::drop,               drop_trait,              Target::Trait;
211
212     CoerceUnsizedTraitLangItem,    sym::coerce_unsized,     coerce_unsized_trait,    Target::Trait;
213     DispatchFromDynTraitLangItem,  sym::dispatch_from_dyn,  dispatch_from_dyn_trait, Target::Trait;
214
215     AddTraitLangItem(Op),          sym::add,                add_trait,               Target::Trait;
216     SubTraitLangItem(Op),          sym::sub,                sub_trait,               Target::Trait;
217     MulTraitLangItem(Op),          sym::mul,                mul_trait,               Target::Trait;
218     DivTraitLangItem(Op),          sym::div,                div_trait,               Target::Trait;
219     RemTraitLangItem(Op),          sym::rem,                rem_trait,               Target::Trait;
220     NegTraitLangItem(Op),          sym::neg,                neg_trait,               Target::Trait;
221     NotTraitLangItem(Op),          sym::not,                not_trait,               Target::Trait;
222     BitXorTraitLangItem(Op),       sym::bitxor,             bitxor_trait,            Target::Trait;
223     BitAndTraitLangItem(Op),       sym::bitand,             bitand_trait,            Target::Trait;
224     BitOrTraitLangItem(Op),        sym::bitor,              bitor_trait,             Target::Trait;
225     ShlTraitLangItem(Op),          sym::shl,                shl_trait,               Target::Trait;
226     ShrTraitLangItem(Op),          sym::shr,                shr_trait,               Target::Trait;
227     AddAssignTraitLangItem(Op),    sym::add_assign,         add_assign_trait,        Target::Trait;
228     SubAssignTraitLangItem(Op),    sym::sub_assign,         sub_assign_trait,        Target::Trait;
229     MulAssignTraitLangItem(Op),    sym::mul_assign,         mul_assign_trait,        Target::Trait;
230     DivAssignTraitLangItem(Op),    sym::div_assign,         div_assign_trait,        Target::Trait;
231     RemAssignTraitLangItem(Op),    sym::rem_assign,         rem_assign_trait,        Target::Trait;
232     BitXorAssignTraitLangItem(Op), sym::bitxor_assign,      bitxor_assign_trait,     Target::Trait;
233     BitAndAssignTraitLangItem(Op), sym::bitand_assign,      bitand_assign_trait,     Target::Trait;
234     BitOrAssignTraitLangItem(Op),  sym::bitor_assign,       bitor_assign_trait,      Target::Trait;
235     ShlAssignTraitLangItem(Op),    sym::shl_assign,         shl_assign_trait,        Target::Trait;
236     ShrAssignTraitLangItem(Op),    sym::shr_assign,         shr_assign_trait,        Target::Trait;
237     IndexTraitLangItem(Op),        sym::index,              index_trait,             Target::Trait;
238     IndexMutTraitLangItem(Op),     sym::index_mut,          index_mut_trait,         Target::Trait;
239
240     UnsafeCellTypeLangItem,        sym::unsafe_cell,        unsafe_cell_type,        Target::Struct;
241     VaListTypeLangItem,            sym::va_list,            va_list,                 Target::Struct;
242
243     DerefTraitLangItem,            sym::deref,              deref_trait,             Target::Trait;
244     DerefMutTraitLangItem,         sym::deref_mut,          deref_mut_trait,         Target::Trait;
245     ReceiverTraitLangItem,         sym::receiver,           receiver_trait,          Target::Trait;
246
247     FnTraitLangItem,               kw::Fn,                  fn_trait,                Target::Trait;
248     FnMutTraitLangItem,            sym::fn_mut,             fn_mut_trait,            Target::Trait;
249     FnOnceTraitLangItem,           sym::fn_once,            fn_once_trait,           Target::Trait;
250
251     FnOnceOutputLangItem,          sym::fn_once_output,     fn_once_output,          Target::AssocTy;
252
253     FutureTraitLangItem,           sym::future_trait,       future_trait,            Target::Trait;
254     GeneratorStateLangItem,        sym::generator_state,    gen_state,               Target::Enum;
255     GeneratorTraitLangItem,        sym::generator,          gen_trait,               Target::Trait;
256     UnpinTraitLangItem,            sym::unpin,              unpin_trait,             Target::Trait;
257     PinTypeLangItem,               sym::pin,                pin_type,                Target::Struct;
258
259     // Don't be fooled by the naming here: this lang item denotes `PartialEq`, not `Eq`.
260     EqTraitLangItem,               sym::eq,                 eq_trait,                Target::Trait;
261     PartialOrdTraitLangItem,       sym::partial_ord,        partial_ord_trait,       Target::Trait;
262
263     // A number of panic-related lang items. The `panic` item corresponds to
264     // divide-by-zero and various panic cases with `match`. The
265     // `panic_bounds_check` item is for indexing arrays.
266     //
267     // The `begin_unwind` lang item has a predefined symbol name and is sort of
268     // a "weak lang item" in the sense that a crate is not required to have it
269     // defined to use it, but a final product is required to define it
270     // somewhere. Additionally, there are restrictions on crates that use a weak
271     // lang item, but do not have it defined.
272     PanicFnLangItem,               sym::panic,              panic_fn,                Target::Fn;
273     PanicBoundsCheckFnLangItem,    sym::panic_bounds_check, panic_bounds_check_fn,   Target::Fn;
274     PanicInfoLangItem,             sym::panic_info,         panic_info,              Target::Struct;
275     PanicLocationLangItem,         sym::panic_location,     panic_location,          Target::Struct;
276     PanicImplLangItem,             sym::panic_impl,         panic_impl,              Target::Fn;
277     // Libstd panic entry point. Necessary for const eval to be able to catch it
278     BeginPanicFnLangItem,          sym::begin_panic,        begin_panic_fn,          Target::Fn;
279
280     ExchangeMallocFnLangItem,      sym::exchange_malloc,    exchange_malloc_fn,      Target::Fn;
281     BoxFreeFnLangItem,             sym::box_free,           box_free_fn,             Target::Fn;
282     DropInPlaceFnLangItem,         sym::drop_in_place,      drop_in_place_fn,        Target::Fn;
283     OomLangItem,                   sym::oom,                oom,                     Target::Fn;
284     AllocLayoutLangItem,           sym::alloc_layout,       alloc_layout,            Target::Struct;
285
286     StartFnLangItem,               sym::start,              start_fn,                Target::Fn;
287
288     EhPersonalityLangItem,         sym::eh_personality,     eh_personality,          Target::Fn;
289     EhCatchTypeinfoLangItem,       sym::eh_catch_typeinfo,  eh_catch_typeinfo,       Target::Static;
290
291     OwnedBoxLangItem,              sym::owned_box,          owned_box,               Target::Struct;
292
293     PhantomDataItem,               sym::phantom_data,       phantom_data,            Target::Struct;
294
295     ManuallyDropItem,              sym::manually_drop,      manually_drop,           Target::Struct;
296
297     MaybeUninitLangItem,           sym::maybe_uninit,       maybe_uninit,            Target::Union;
298
299     // Align offset for stride != 1; must not panic.
300     AlignOffsetLangItem,           sym::align_offset,       align_offset_fn,         Target::Fn;
301
302     TerminationTraitLangItem,      sym::termination,        termination,             Target::Trait;
303
304     TryTraitLangItem,              kw::Try,                 try_trait,               Target::Trait;
305
306     // language items related to source code coverage instrumentation (-Zinstrument-coverage)
307     CountCodeRegionFnLangItem,         sym::count_code_region,         count_code_region_fn,         Target::Fn;
308     CoverageCounterAddFnLangItem,      sym::coverage_counter_add,      coverage_counter_add_fn,      Target::Fn;
309     CoverageCounterSubtractFnLangItem, sym::coverage_counter_subtract, coverage_counter_subtract_fn, Target::Fn;
310
311     // Language items from AST lowering
312     TryFromError,                  sym::from_error,         from_error_fn,           Target::Method(MethodKind::Trait { body: false });
313     TryFromOk,                     sym::from_ok,            from_ok_fn,              Target::Method(MethodKind::Trait { body: false });
314     TryIntoResult,                 sym::into_result,        into_result_fn,          Target::Method(MethodKind::Trait { body: false });
315
316     PollReady,                     sym::Ready,              poll_ready_variant,      Target::Variant;
317     PollPending,                   sym::Pending,            poll_pending_variant,    Target::Variant;
318
319     FromGenerator,                 sym::from_generator,     from_generator_fn,       Target::Fn;
320     GetContext,                    sym::get_context,        get_context_fn,          Target::Fn;
321
322     FuturePoll,                    sym::poll,               future_poll_fn,          Target::Method(MethodKind::Trait { body: false });
323
324     FromFrom,                      sym::from,               from_fn,                 Target::Method(MethodKind::Trait { body: false });
325
326     OptionSome,                    sym::Some,               option_some_variant,     Target::Variant;
327     OptionNone,                    sym::None,               option_none_variant,     Target::Variant;
328
329     ResultOk,                      sym::Ok,                 result_ok_variant,       Target::Variant;
330     ResultErr,                     sym::Err,                result_err_variant,      Target::Variant;
331
332     IntoIterIntoIter,              sym::into_iter,          into_iter_fn,            Target::Method(MethodKind::Trait { body: false });
333     IteratorNext,                  sym::next,               next_fn,                 Target::Method(MethodKind::Trait { body: false});
334
335     PinNewUnchecked,               sym::new_unchecked,      new_unchecked_fn,        Target::Method(MethodKind::Inherent);
336
337     RangeFrom,                     sym::RangeFrom,           range_from_struct,          Target::Struct;
338     RangeFull,                     sym::RangeFull,           range_full_struct,          Target::Struct;
339     RangeInclusiveStruct,          sym::RangeInclusive,      range_inclusive_struct,     Target::Struct;
340     RangeInclusiveNew,             sym::range_inclusive_new, range_inclusive_new_method, Target::Method(MethodKind::Inherent);
341     Range,                         sym::Range,               range_struct,               Target::Struct;
342     RangeToInclusive,              sym::RangeToInclusive,    range_to_inclusive_struct,  Target::Struct;
343     RangeTo,                       sym::RangeTo,             range_to_struct,            Target::Struct;
344 }