rustc_hir/
lang_items.rs

1//! Defines 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_ast::attr::AttributeExt;
11use rustc_data_structures::fx::FxIndexMap;
12use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
13use rustc_macros::{Decodable, Encodable, HashStable_Generic};
14use rustc_span::{Span, Symbol, kw, sym};
15
16use crate::def_id::DefId;
17use crate::{MethodKind, Target};
18
19/// All of the lang items, defined or not.
20/// Defined lang items can come from the current crate or its dependencies.
21#[derive(HashStable_Generic, Debug)]
22pub struct LanguageItems {
23    /// Mappings from lang items to their possibly found [`DefId`]s.
24    /// The index corresponds to the order in [`LangItem`].
25    items: [Option<DefId>; std::mem::variant_count::<LangItem>()],
26    reverse_items: FxIndexMap<DefId, LangItem>,
27    /// Lang items that were not found during collection.
28    pub missing: Vec<LangItem>,
29}
30
31impl LanguageItems {
32    /// Construct an empty collection of lang items and no missing ones.
33    pub fn new() -> Self {
34        Self {
35            items: [None; std::mem::variant_count::<LangItem>()],
36            reverse_items: FxIndexMap::default(),
37            missing: Vec::new(),
38        }
39    }
40
41    pub fn get(&self, item: LangItem) -> Option<DefId> {
42        self.items[item as usize]
43    }
44
45    pub fn set(&mut self, item: LangItem, def_id: DefId) {
46        self.items[item as usize] = Some(def_id);
47        let preexisting = self.reverse_items.insert(def_id, item);
48
49        // This needs to be a bijection.
50        if let Some(preexisting) = preexisting {
51            panic!(
52                "For the bijection of LangItem <=> DefId to work,\
53                one item DefId may only be assigned one LangItem. \
54                Separate the LangItem definitions for {item:?} and {preexisting:?}."
55            );
56        }
57    }
58
59    pub fn from_def_id(&self, def_id: DefId) -> Option<LangItem> {
60        self.reverse_items.get(&def_id).copied()
61    }
62
63    pub fn iter(&self) -> impl Iterator<Item = (LangItem, DefId)> {
64        self.items
65            .iter()
66            .enumerate()
67            .filter_map(|(i, id)| id.map(|id| (LangItem::from_u32(i as u32).unwrap(), id)))
68    }
69}
70
71// The actual lang items defined come at the end of this file in one handy table.
72// So you probably just want to nip down to the end.
73macro_rules! language_item_table {
74    (
75        $( $(#[$attr:meta])* $variant:ident, $module:ident :: $name:ident, $method:ident, $target:expr, $generics:expr; )*
76    ) => {
77        /// A representation of all the valid lang items in Rust.
78        #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash, Encodable, Decodable)]
79        pub enum LangItem {
80            $(
81                #[doc = concat!("The `", stringify!($name), "` lang item.")]
82                $(#[$attr])*
83                $variant,
84            )*
85        }
86
87        impl LangItem {
88            fn from_u32(u: u32) -> Option<LangItem> {
89                // This implementation is clumsy, but makes no assumptions
90                // about how discriminant tags are allocated within the
91                // range `0 .. std::mem::variant_count::<LangItem>()`.
92                $(if u == LangItem::$variant as u32 {
93                    return Some(LangItem::$variant)
94                })*
95                None
96            }
97
98            /// Returns the `name` symbol in `#[lang = "$name"]`.
99            /// For example, [`LangItem::PartialEq`]`.name()`
100            /// would result in [`sym::eq`] since it is `#[lang = "eq"]`.
101            pub fn name(self) -> Symbol {
102                match self {
103                    $( LangItem::$variant => $module::$name, )*
104                }
105            }
106
107            /// Opposite of [`LangItem::name`]
108            pub fn from_name(name: Symbol) -> Option<Self> {
109                match name {
110                    $( $module::$name => Some(LangItem::$variant), )*
111                    _ => None,
112                }
113            }
114
115            /// Returns the name of the `LangItem` enum variant.
116            // This method is used by Clippy for internal lints.
117            pub fn variant_name(self) -> &'static str {
118                match self {
119                    $( LangItem::$variant => stringify!($variant), )*
120                }
121            }
122
123            pub fn target(self) -> Target {
124                match self {
125                    $( LangItem::$variant => $target, )*
126                }
127            }
128
129            pub fn required_generics(&self) -> GenericRequirement {
130                match self {
131                    $( LangItem::$variant => $generics, )*
132                }
133            }
134        }
135
136        impl LanguageItems {
137            $(
138                #[doc = concat!("Returns the [`DefId`] of the `", stringify!($name), "` lang item if it is defined.")]
139                pub fn $method(&self) -> Option<DefId> {
140                    self.items[LangItem::$variant as usize]
141                }
142            )*
143        }
144    }
145}
146
147impl<CTX> HashStable<CTX> for LangItem {
148    fn hash_stable(&self, _: &mut CTX, hasher: &mut StableHasher) {
149        ::std::hash::Hash::hash(self, hasher);
150    }
151}
152
153/// Extracts the first `lang = "$name"` out of a list of attributes.
154/// The `#[panic_handler]` attribute is also extracted out when found.
155pub fn extract(attrs: &[impl AttributeExt]) -> Option<(Symbol, Span)> {
156    attrs.iter().find_map(|attr| {
157        Some(match attr {
158            _ if attr.has_name(sym::lang) => (attr.value_str()?, attr.span()),
159            _ if attr.has_name(sym::panic_handler) => (sym::panic_impl, attr.span()),
160            _ => return None,
161        })
162    })
163}
164
165language_item_table! {
166//  Variant name,            Name,                     Getter method name,         Target                  Generic requirements;
167    Sized,                   sym::sized,               sized_trait,                Target::Trait,          GenericRequirement::Exact(0);
168    MetaSized,               sym::meta_sized,          meta_sized_trait,           Target::Trait,          GenericRequirement::Exact(0);
169    PointeeSized,            sym::pointee_sized,       pointee_sized_trait,        Target::Trait,          GenericRequirement::Exact(0);
170    Unsize,                  sym::unsize,              unsize_trait,               Target::Trait,          GenericRequirement::Minimum(1);
171    /// Trait injected by `#[derive(PartialEq)]`, (i.e. "Partial EQ").
172    StructuralPeq,           sym::structural_peq,      structural_peq_trait,       Target::Trait,          GenericRequirement::None;
173    Copy,                    sym::copy,                copy_trait,                 Target::Trait,          GenericRequirement::Exact(0);
174    Clone,                   sym::clone,               clone_trait,                Target::Trait,          GenericRequirement::None;
175    CloneFn,                 sym::clone_fn,            clone_fn,                   Target::Method(MethodKind::Trait { body: false }), GenericRequirement::None;
176    UseCloned,               sym::use_cloned,          use_cloned_trait,           Target::Trait,          GenericRequirement::None;
177    Sync,                    sym::sync,                sync_trait,                 Target::Trait,          GenericRequirement::Exact(0);
178    DiscriminantKind,        sym::discriminant_kind,   discriminant_kind_trait,    Target::Trait,          GenericRequirement::None;
179    /// The associated item of the `DiscriminantKind` trait.
180    Discriminant,            sym::discriminant_type,   discriminant_type,          Target::AssocTy,        GenericRequirement::None;
181
182    PointeeTrait,            sym::pointee_trait,       pointee_trait,              Target::Trait,          GenericRequirement::None;
183    Metadata,                sym::metadata_type,       metadata_type,              Target::AssocTy,        GenericRequirement::None;
184    DynMetadata,             sym::dyn_metadata,        dyn_metadata,               Target::Struct,         GenericRequirement::None;
185
186    Freeze,                  sym::freeze,              freeze_trait,               Target::Trait,          GenericRequirement::Exact(0);
187    UnsafeUnpin,             sym::unsafe_unpin,        unsafe_unpin_trait,         Target::Trait,          GenericRequirement::Exact(0);
188
189    FnPtrTrait,              sym::fn_ptr_trait,        fn_ptr_trait,               Target::Trait,          GenericRequirement::Exact(0);
190    FnPtrAddr,               sym::fn_ptr_addr,         fn_ptr_addr,                Target::Method(MethodKind::Trait { body: false }), GenericRequirement::None;
191
192    Drop,                    sym::drop,                drop_trait,                 Target::Trait,          GenericRequirement::None;
193    Destruct,                sym::destruct,            destruct_trait,             Target::Trait,          GenericRequirement::None;
194    AsyncDrop,               sym::async_drop,          async_drop_trait,           Target::Trait,          GenericRequirement::None;
195    AsyncDropInPlace,        sym::async_drop_in_place, async_drop_in_place_fn,     Target::Fn,             GenericRequirement::Exact(1);
196
197    CoerceUnsized,           sym::coerce_unsized,      coerce_unsized_trait,       Target::Trait,          GenericRequirement::Minimum(1);
198    DispatchFromDyn,         sym::dispatch_from_dyn,   dispatch_from_dyn_trait,    Target::Trait,          GenericRequirement::Minimum(1);
199
200    // lang items relating to transmutability
201    TransmuteOpts,           sym::transmute_opts,      transmute_opts,             Target::Struct,         GenericRequirement::Exact(0);
202    TransmuteTrait,          sym::transmute_trait,     transmute_trait,            Target::Trait,          GenericRequirement::Exact(2);
203
204    Add,                     sym::add,                 add_trait,                  Target::Trait,          GenericRequirement::Exact(1);
205    Sub,                     sym::sub,                 sub_trait,                  Target::Trait,          GenericRequirement::Exact(1);
206    Mul,                     sym::mul,                 mul_trait,                  Target::Trait,          GenericRequirement::Exact(1);
207    Div,                     sym::div,                 div_trait,                  Target::Trait,          GenericRequirement::Exact(1);
208    Rem,                     sym::rem,                 rem_trait,                  Target::Trait,          GenericRequirement::Exact(1);
209    Neg,                     sym::neg,                 neg_trait,                  Target::Trait,          GenericRequirement::Exact(0);
210    Not,                     sym::not,                 not_trait,                  Target::Trait,          GenericRequirement::Exact(0);
211    BitXor,                  sym::bitxor,              bitxor_trait,               Target::Trait,          GenericRequirement::Exact(1);
212    BitAnd,                  sym::bitand,              bitand_trait,               Target::Trait,          GenericRequirement::Exact(1);
213    BitOr,                   sym::bitor,               bitor_trait,                Target::Trait,          GenericRequirement::Exact(1);
214    Shl,                     sym::shl,                 shl_trait,                  Target::Trait,          GenericRequirement::Exact(1);
215    Shr,                     sym::shr,                 shr_trait,                  Target::Trait,          GenericRequirement::Exact(1);
216    AddAssign,               sym::add_assign,          add_assign_trait,           Target::Trait,          GenericRequirement::Exact(1);
217    SubAssign,               sym::sub_assign,          sub_assign_trait,           Target::Trait,          GenericRequirement::Exact(1);
218    MulAssign,               sym::mul_assign,          mul_assign_trait,           Target::Trait,          GenericRequirement::Exact(1);
219    DivAssign,               sym::div_assign,          div_assign_trait,           Target::Trait,          GenericRequirement::Exact(1);
220    RemAssign,               sym::rem_assign,          rem_assign_trait,           Target::Trait,          GenericRequirement::Exact(1);
221    BitXorAssign,            sym::bitxor_assign,       bitxor_assign_trait,        Target::Trait,          GenericRequirement::Exact(1);
222    BitAndAssign,            sym::bitand_assign,       bitand_assign_trait,        Target::Trait,          GenericRequirement::Exact(1);
223    BitOrAssign,             sym::bitor_assign,        bitor_assign_trait,         Target::Trait,          GenericRequirement::Exact(1);
224    ShlAssign,               sym::shl_assign,          shl_assign_trait,           Target::Trait,          GenericRequirement::Exact(1);
225    ShrAssign,               sym::shr_assign,          shr_assign_trait,           Target::Trait,          GenericRequirement::Exact(1);
226    Index,                   sym::index,               index_trait,                Target::Trait,          GenericRequirement::Exact(1);
227    IndexMut,                sym::index_mut,           index_mut_trait,            Target::Trait,          GenericRequirement::Exact(1);
228
229    UnsafeCell,              sym::unsafe_cell,         unsafe_cell_type,           Target::Struct,         GenericRequirement::None;
230    UnsafePinned,            sym::unsafe_pinned,       unsafe_pinned_type,         Target::Struct,         GenericRequirement::None;
231
232    VaList,                  sym::va_list,             va_list,                    Target::Struct,         GenericRequirement::None;
233
234    Deref,                   sym::deref,               deref_trait,                Target::Trait,          GenericRequirement::Exact(0);
235    DerefMut,                sym::deref_mut,           deref_mut_trait,            Target::Trait,          GenericRequirement::Exact(0);
236    DerefPure,               sym::deref_pure,          deref_pure_trait,           Target::Trait,          GenericRequirement::Exact(0);
237    DerefTarget,             sym::deref_target,        deref_target,               Target::AssocTy,        GenericRequirement::None;
238    Receiver,                sym::receiver,            receiver_trait,             Target::Trait,          GenericRequirement::None;
239    ReceiverTarget,          sym::receiver_target,     receiver_target,            Target::AssocTy,        GenericRequirement::None;
240    LegacyReceiver,          sym::legacy_receiver,     legacy_receiver_trait,      Target::Trait,          GenericRequirement::None;
241
242    Fn,                      kw::Fn,                   fn_trait,                   Target::Trait,          GenericRequirement::Exact(1);
243    FnMut,                   sym::fn_mut,              fn_mut_trait,               Target::Trait,          GenericRequirement::Exact(1);
244    FnOnce,                  sym::fn_once,             fn_once_trait,              Target::Trait,          GenericRequirement::Exact(1);
245
246    AsyncFn,                 sym::async_fn,            async_fn_trait,             Target::Trait,          GenericRequirement::Exact(1);
247    AsyncFnMut,              sym::async_fn_mut,        async_fn_mut_trait,         Target::Trait,          GenericRequirement::Exact(1);
248    AsyncFnOnce,             sym::async_fn_once,       async_fn_once_trait,        Target::Trait,          GenericRequirement::Exact(1);
249    AsyncFnOnceOutput,       sym::async_fn_once_output, async_fn_once_output,       Target::AssocTy,        GenericRequirement::Exact(1);
250    CallOnceFuture,          sym::call_once_future,    call_once_future,           Target::AssocTy,        GenericRequirement::Exact(1);
251    CallRefFuture,           sym::call_ref_future,     call_ref_future,            Target::AssocTy,        GenericRequirement::Exact(2);
252    AsyncFnKindHelper,       sym::async_fn_kind_helper, async_fn_kind_helper,      Target::Trait,          GenericRequirement::Exact(1);
253    AsyncFnKindUpvars,       sym::async_fn_kind_upvars, async_fn_kind_upvars,      Target::AssocTy,          GenericRequirement::Exact(5);
254
255    FnOnceOutput,            sym::fn_once_output,      fn_once_output,             Target::AssocTy,        GenericRequirement::None;
256
257    Iterator,                sym::iterator,            iterator_trait,             Target::Trait,          GenericRequirement::Exact(0);
258    FusedIterator,           sym::fused_iterator,      fused_iterator_trait,       Target::Trait,          GenericRequirement::Exact(0);
259    Future,                  sym::future_trait,        future_trait,               Target::Trait,          GenericRequirement::Exact(0);
260    FutureOutput,            sym::future_output,       future_output,              Target::AssocTy,        GenericRequirement::Exact(0);
261    AsyncIterator,           sym::async_iterator,      async_iterator_trait,       Target::Trait,          GenericRequirement::Exact(0);
262
263    CoroutineState,          sym::coroutine_state,     coroutine_state,            Target::Enum,           GenericRequirement::None;
264    Coroutine,               sym::coroutine,           coroutine_trait,            Target::Trait,          GenericRequirement::Exact(1);
265    CoroutineReturn,         sym::coroutine_return,    coroutine_return,           Target::AssocTy,        GenericRequirement::Exact(1);
266    CoroutineYield,          sym::coroutine_yield,     coroutine_yield,            Target::AssocTy,        GenericRequirement::Exact(1);
267    CoroutineResume,         sym::coroutine_resume,    coroutine_resume,           Target::Method(MethodKind::Trait { body: false }), GenericRequirement::None;
268
269    Unpin,                   sym::unpin,               unpin_trait,                Target::Trait,          GenericRequirement::None;
270    Pin,                     sym::pin,                 pin_type,                   Target::Struct,         GenericRequirement::None;
271
272    OrderingEnum,            sym::Ordering,            ordering_enum,              Target::Enum,           GenericRequirement::Exact(0);
273    PartialEq,               sym::eq,                  eq_trait,                   Target::Trait,          GenericRequirement::Exact(1);
274    PartialOrd,              sym::partial_ord,         partial_ord_trait,          Target::Trait,          GenericRequirement::Exact(1);
275    CVoid,                   sym::c_void,              c_void,                     Target::Enum,           GenericRequirement::None;
276
277    // A number of panic-related lang items. The `panic` item corresponds to divide-by-zero and
278    // various panic cases with `match`. The `panic_bounds_check` item is for indexing arrays.
279    //
280    // The `begin_unwind` lang item has a predefined symbol name and is sort of a "weak lang item"
281    // in the sense that a crate is not required to have it defined to use it, but a final product
282    // is required to define it somewhere. Additionally, there are restrictions on crates that use
283    // a weak lang item, but do not have it defined.
284    Panic,                   sym::panic,               panic_fn,                   Target::Fn,             GenericRequirement::Exact(0);
285    PanicNounwind,           sym::panic_nounwind,      panic_nounwind,             Target::Fn,             GenericRequirement::Exact(0);
286    PanicFmt,                sym::panic_fmt,           panic_fmt,                  Target::Fn,             GenericRequirement::None;
287    ConstPanicFmt,           sym::const_panic_fmt,     const_panic_fmt,            Target::Fn,             GenericRequirement::None;
288    PanicBoundsCheck,        sym::panic_bounds_check,  panic_bounds_check_fn,      Target::Fn,             GenericRequirement::Exact(0);
289    PanicMisalignedPointerDereference, sym::panic_misaligned_pointer_dereference, panic_misaligned_pointer_dereference_fn, Target::Fn, GenericRequirement::Exact(0);
290    PanicInfo,               sym::panic_info,          panic_info,                 Target::Struct,         GenericRequirement::None;
291    PanicLocation,           sym::panic_location,      panic_location,             Target::Struct,         GenericRequirement::None;
292    PanicImpl,               sym::panic_impl,          panic_impl,                 Target::Fn,             GenericRequirement::None;
293    PanicCannotUnwind,       sym::panic_cannot_unwind, panic_cannot_unwind,        Target::Fn,             GenericRequirement::Exact(0);
294    PanicInCleanup,          sym::panic_in_cleanup,    panic_in_cleanup,           Target::Fn,             GenericRequirement::Exact(0);
295    /// Constant panic messages, used for codegen of MIR asserts.
296    PanicAddOverflow,        sym::panic_const_add_overflow, panic_const_add_overflow, Target::Fn, GenericRequirement::None;
297    PanicSubOverflow,        sym::panic_const_sub_overflow, panic_const_sub_overflow, Target::Fn, GenericRequirement::None;
298    PanicMulOverflow,        sym::panic_const_mul_overflow, panic_const_mul_overflow, Target::Fn, GenericRequirement::None;
299    PanicDivOverflow,        sym::panic_const_div_overflow, panic_const_div_overflow, Target::Fn, GenericRequirement::None;
300    PanicRemOverflow,        sym::panic_const_rem_overflow, panic_const_rem_overflow, Target::Fn, GenericRequirement::None;
301    PanicNegOverflow,        sym::panic_const_neg_overflow, panic_const_neg_overflow, Target::Fn, GenericRequirement::None;
302    PanicShrOverflow,        sym::panic_const_shr_overflow, panic_const_shr_overflow, Target::Fn, GenericRequirement::None;
303    PanicShlOverflow,        sym::panic_const_shl_overflow, panic_const_shl_overflow, Target::Fn, GenericRequirement::None;
304    PanicDivZero,            sym::panic_const_div_by_zero, panic_const_div_by_zero, Target::Fn, GenericRequirement::None;
305    PanicRemZero,            sym::panic_const_rem_by_zero, panic_const_rem_by_zero, Target::Fn, GenericRequirement::None;
306    PanicCoroutineResumed, sym::panic_const_coroutine_resumed, panic_const_coroutine_resumed, Target::Fn, GenericRequirement::None;
307    PanicAsyncFnResumed, sym::panic_const_async_fn_resumed, panic_const_async_fn_resumed, Target::Fn, GenericRequirement::None;
308    PanicAsyncGenFnResumed, sym::panic_const_async_gen_fn_resumed, panic_const_async_gen_fn_resumed, Target::Fn, GenericRequirement::None;
309    PanicGenFnNone, sym::panic_const_gen_fn_none, panic_const_gen_fn_none, Target::Fn, GenericRequirement::None;
310    PanicCoroutineResumedPanic, sym::panic_const_coroutine_resumed_panic, panic_const_coroutine_resumed_panic, Target::Fn, GenericRequirement::None;
311    PanicAsyncFnResumedPanic, sym::panic_const_async_fn_resumed_panic, panic_const_async_fn_resumed_panic, Target::Fn, GenericRequirement::None;
312    PanicAsyncGenFnResumedPanic, sym::panic_const_async_gen_fn_resumed_panic, panic_const_async_gen_fn_resumed_panic, Target::Fn, GenericRequirement::None;
313    PanicGenFnNonePanic, sym::panic_const_gen_fn_none_panic, panic_const_gen_fn_none_panic, Target::Fn, GenericRequirement::None;
314    PanicNullPointerDereference, sym::panic_null_pointer_dereference, panic_null_pointer_dereference, Target::Fn, GenericRequirement::None;
315    PanicCoroutineResumedDrop, sym::panic_const_coroutine_resumed_drop, panic_const_coroutine_resumed_drop, Target::Fn, GenericRequirement::None;
316    PanicAsyncFnResumedDrop, sym::panic_const_async_fn_resumed_drop, panic_const_async_fn_resumed_drop, Target::Fn, GenericRequirement::None;
317    PanicAsyncGenFnResumedDrop, sym::panic_const_async_gen_fn_resumed_drop, panic_const_async_gen_fn_resumed_drop, Target::Fn, GenericRequirement::None;
318    PanicGenFnNoneDrop, sym::panic_const_gen_fn_none_drop, panic_const_gen_fn_none_drop, Target::Fn, GenericRequirement::None;
319    /// libstd panic entry point. Necessary for const eval to be able to catch it
320    BeginPanic,              sym::begin_panic,         begin_panic_fn,             Target::Fn,             GenericRequirement::None;
321
322    // Lang items needed for `format_args!()`.
323    FormatArgument,          sym::format_argument,     format_argument,            Target::Struct,         GenericRequirement::None;
324    FormatArguments,         sym::format_arguments,    format_arguments,           Target::Struct,         GenericRequirement::None;
325    FormatCount,             sym::format_count,        format_count,               Target::Enum,           GenericRequirement::None;
326    FormatPlaceholder,       sym::format_placeholder,  format_placeholder,         Target::Struct,         GenericRequirement::None;
327    FormatUnsafeArg,         sym::format_unsafe_arg,   format_unsafe_arg,          Target::Struct,         GenericRequirement::None;
328
329    ExchangeMalloc,          sym::exchange_malloc,     exchange_malloc_fn,         Target::Fn,             GenericRequirement::None;
330    DropInPlace,             sym::drop_in_place,       drop_in_place_fn,           Target::Fn,             GenericRequirement::Minimum(1);
331    AllocLayout,             sym::alloc_layout,        alloc_layout,               Target::Struct,         GenericRequirement::None;
332
333    /// For all binary crates without `#![no_main]`, Rust will generate a "main" function.
334    /// The exact name and signature are target-dependent. The "main" function will invoke
335    /// this lang item, passing it the `argc` and `argv` (or null, if those don't exist
336    /// on the current target) as well as the user-defined `fn main` from the binary crate.
337    Start,                   sym::start,               start_fn,                   Target::Fn,             GenericRequirement::Exact(1);
338
339    EhPersonality,           sym::eh_personality,      eh_personality,             Target::Fn,             GenericRequirement::None;
340    EhCatchTypeinfo,         sym::eh_catch_typeinfo,   eh_catch_typeinfo,          Target::Static,         GenericRequirement::None;
341
342    OwnedBox,                sym::owned_box,           owned_box,                  Target::Struct,         GenericRequirement::Minimum(1);
343    GlobalAlloc,             sym::global_alloc_ty,     global_alloc_ty,            Target::Struct,         GenericRequirement::None;
344
345    // Experimental lang item for Miri
346    PtrUnique,               sym::ptr_unique,          ptr_unique,                 Target::Struct,         GenericRequirement::Exact(1);
347
348    PhantomData,             sym::phantom_data,        phantom_data,               Target::Struct,         GenericRequirement::Exact(1);
349
350    ManuallyDrop,            sym::manually_drop,       manually_drop,              Target::Struct,         GenericRequirement::None;
351    BikeshedGuaranteedNoDrop, sym::bikeshed_guaranteed_no_drop, bikeshed_guaranteed_no_drop, Target::Trait, GenericRequirement::Exact(0);
352
353    MaybeUninit,             sym::maybe_uninit,        maybe_uninit,               Target::Union,          GenericRequirement::None;
354
355    Termination,             sym::termination,         termination,                Target::Trait,          GenericRequirement::None;
356
357    Try,                     sym::Try,                 try_trait,                  Target::Trait,          GenericRequirement::None;
358
359    Tuple,                   sym::tuple_trait,         tuple_trait,                Target::Trait,          GenericRequirement::Exact(0);
360
361    SliceLen,                sym::slice_len_fn,        slice_len_fn,               Target::Method(MethodKind::Inherent), GenericRequirement::None;
362
363    // Language items from AST lowering
364    TryTraitFromResidual,    sym::from_residual,       from_residual_fn,           Target::Method(MethodKind::Trait { body: false }), GenericRequirement::None;
365    TryTraitFromOutput,      sym::from_output,         from_output_fn,             Target::Method(MethodKind::Trait { body: false }), GenericRequirement::None;
366    TryTraitBranch,          sym::branch,              branch_fn,                  Target::Method(MethodKind::Trait { body: false }), GenericRequirement::None;
367    TryTraitFromYeet,        sym::from_yeet,           from_yeet_fn,               Target::Fn,             GenericRequirement::None;
368
369    PointerLike,             sym::pointer_like,        pointer_like,               Target::Trait,          GenericRequirement::Exact(0);
370
371    CoercePointeeValidated, sym::coerce_pointee_validated, coerce_pointee_validated_trait, Target::Trait,     GenericRequirement::Exact(0);
372
373    ConstParamTy,            sym::const_param_ty,      const_param_ty_trait,       Target::Trait,          GenericRequirement::Exact(0);
374    UnsizedConstParamTy,     sym::unsized_const_param_ty, unsized_const_param_ty_trait, Target::Trait, GenericRequirement::Exact(0);
375
376    Poll,                    sym::Poll,                poll,                       Target::Enum,           GenericRequirement::None;
377    PollReady,               sym::Ready,               poll_ready_variant,         Target::Variant,        GenericRequirement::None;
378    PollPending,             sym::Pending,             poll_pending_variant,       Target::Variant,        GenericRequirement::None;
379
380    AsyncGenReady,           sym::AsyncGenReady,       async_gen_ready,            Target::Method(MethodKind::Inherent), GenericRequirement::Exact(1);
381    AsyncGenPending,         sym::AsyncGenPending,     async_gen_pending,          Target::AssocConst,     GenericRequirement::Exact(1);
382    AsyncGenFinished,        sym::AsyncGenFinished,    async_gen_finished,         Target::AssocConst,     GenericRequirement::Exact(1);
383
384    // FIXME(swatinem): the following lang items are used for async lowering and
385    // should become obsolete eventually.
386    ResumeTy,                sym::ResumeTy,            resume_ty,                  Target::Struct,         GenericRequirement::None;
387    GetContext,              sym::get_context,         get_context_fn,             Target::Fn,             GenericRequirement::None;
388
389    Context,                 sym::Context,             context,                    Target::Struct,         GenericRequirement::None;
390    FuturePoll,              sym::poll,                future_poll_fn,             Target::Method(MethodKind::Trait { body: false }), GenericRequirement::None;
391
392    AsyncIteratorPollNext,   sym::async_iterator_poll_next, async_iterator_poll_next, Target::Method(MethodKind::Trait { body: false }), GenericRequirement::Exact(0);
393    IntoAsyncIterIntoIter,   sym::into_async_iter_into_iter, into_async_iter_into_iter, Target::Method(MethodKind::Trait { body: false }), GenericRequirement::Exact(0);
394
395    Option,                  sym::Option,              option_type,                Target::Enum,           GenericRequirement::None;
396    OptionSome,              sym::Some,                option_some_variant,        Target::Variant,        GenericRequirement::None;
397    OptionNone,              sym::None,                option_none_variant,        Target::Variant,        GenericRequirement::None;
398
399    ResultOk,                sym::Ok,                  result_ok_variant,          Target::Variant,        GenericRequirement::None;
400    ResultErr,               sym::Err,                 result_err_variant,         Target::Variant,        GenericRequirement::None;
401
402    ControlFlowContinue,     sym::Continue,            cf_continue_variant,        Target::Variant,        GenericRequirement::None;
403    ControlFlowBreak,        sym::Break,               cf_break_variant,           Target::Variant,        GenericRequirement::None;
404
405    IntoFutureIntoFuture,    sym::into_future,         into_future_fn,             Target::Method(MethodKind::Trait { body: false }), GenericRequirement::None;
406    IntoIterIntoIter,        sym::into_iter,           into_iter_fn,               Target::Method(MethodKind::Trait { body: false }), GenericRequirement::None;
407    IteratorNext,            sym::next,                next_fn,                    Target::Method(MethodKind::Trait { body: false}), GenericRequirement::None;
408
409    PinNewUnchecked,         sym::new_unchecked,       new_unchecked_fn,           Target::Method(MethodKind::Inherent), GenericRequirement::None;
410
411    RangeFrom,               sym::RangeFrom,           range_from_struct,          Target::Struct,         GenericRequirement::None;
412    RangeFull,               sym::RangeFull,           range_full_struct,          Target::Struct,         GenericRequirement::None;
413    RangeInclusiveStruct,    sym::RangeInclusive,      range_inclusive_struct,     Target::Struct,         GenericRequirement::None;
414    RangeInclusiveNew,       sym::range_inclusive_new, range_inclusive_new_method, Target::Method(MethodKind::Inherent), GenericRequirement::None;
415    Range,                   sym::Range,               range_struct,               Target::Struct,         GenericRequirement::None;
416    RangeToInclusive,        sym::RangeToInclusive,    range_to_inclusive_struct,  Target::Struct,         GenericRequirement::None;
417    RangeTo,                 sym::RangeTo,             range_to_struct,            Target::Struct,         GenericRequirement::None;
418    RangeMax,                sym::RangeMax,            range_max,                  Target::AssocConst,     GenericRequirement::Exact(0);
419    RangeMin,                sym::RangeMin,            range_min,                  Target::AssocConst,     GenericRequirement::Exact(0);
420    RangeSub,                sym::RangeSub,            range_sub,                  Target::Method(MethodKind::Trait { body: false }),     GenericRequirement::Exact(0);
421
422    // `new_range` types that are `Copy + IntoIterator`
423    RangeFromCopy,           sym::RangeFromCopy,       range_from_copy_struct,     Target::Struct,         GenericRequirement::None;
424    RangeCopy,               sym::RangeCopy,           range_copy_struct,          Target::Struct,         GenericRequirement::None;
425    RangeInclusiveCopy,      sym::RangeInclusiveCopy,  range_inclusive_copy_struct, Target::Struct,         GenericRequirement::None;
426
427    String,                  sym::String,              string,                     Target::Struct,         GenericRequirement::None;
428    CStr,                    sym::CStr,                c_str,                      Target::Struct,         GenericRequirement::None;
429
430    // Experimental lang items for implementing contract pre- and post-condition checking.
431    ContractBuildCheckEnsures, sym::contract_build_check_ensures, contract_build_check_ensures_fn, Target::Fn, GenericRequirement::None;
432    ContractCheckRequires,     sym::contract_check_requires,      contract_check_requires_fn,      Target::Fn, GenericRequirement::None;
433
434    // Experimental lang items for `MCP: Low level components for async drop`(https://github.com/rust-lang/compiler-team/issues/727)
435    DefaultTrait4,           sym::default_trait4,      default_trait4_trait,       Target::Trait,          GenericRequirement::None;
436    DefaultTrait3,           sym::default_trait3,      default_trait3_trait,       Target::Trait,          GenericRequirement::None;
437    DefaultTrait2,           sym::default_trait2,      default_trait2_trait,       Target::Trait,          GenericRequirement::None;
438    DefaultTrait1,           sym::default_trait1,      default_trait1_trait,       Target::Trait,          GenericRequirement::None;
439
440    ContractCheckEnsures,     sym::contract_check_ensures,      contract_check_ensures_fn,      Target::Fn, GenericRequirement::None;
441}
442
443/// The requirement imposed on the generics of a lang item
444pub enum GenericRequirement {
445    /// No restriction on the generics
446    None,
447    /// A minimum number of generics that is demanded on a lang item
448    Minimum(usize),
449    /// The number of generics must match precisely as stipulated
450    Exact(usize),
451}
452
453pub static FN_TRAITS: &'static [LangItem] = &[LangItem::Fn, LangItem::FnMut, LangItem::FnOnce];
454
455pub static OPERATORS: &'static [LangItem] = &[
456    LangItem::Add,
457    LangItem::Sub,
458    LangItem::Mul,
459    LangItem::Div,
460    LangItem::Rem,
461    LangItem::Neg,
462    LangItem::Not,
463    LangItem::BitXor,
464    LangItem::BitAnd,
465    LangItem::BitOr,
466    LangItem::Shl,
467    LangItem::Shr,
468    LangItem::AddAssign,
469    LangItem::SubAssign,
470    LangItem::MulAssign,
471    LangItem::DivAssign,
472    LangItem::RemAssign,
473    LangItem::BitXorAssign,
474    LangItem::BitAndAssign,
475    LangItem::BitOrAssign,
476    LangItem::ShlAssign,
477    LangItem::ShrAssign,
478    LangItem::Index,
479    LangItem::IndexMut,
480    LangItem::PartialEq,
481    LangItem::PartialOrd,
482];
483
484pub static BINARY_OPERATORS: &'static [LangItem] = &[
485    LangItem::Add,
486    LangItem::Sub,
487    LangItem::Mul,
488    LangItem::Div,
489    LangItem::Rem,
490    LangItem::BitXor,
491    LangItem::BitAnd,
492    LangItem::BitOr,
493    LangItem::Shl,
494    LangItem::Shr,
495    LangItem::AddAssign,
496    LangItem::SubAssign,
497    LangItem::MulAssign,
498    LangItem::DivAssign,
499    LangItem::RemAssign,
500    LangItem::BitXorAssign,
501    LangItem::BitAndAssign,
502    LangItem::BitOrAssign,
503    LangItem::ShlAssign,
504    LangItem::ShrAssign,
505    LangItem::Index,
506    LangItem::IndexMut,
507    LangItem::PartialEq,
508    LangItem::PartialOrd,
509];