rustc_middle/middle/
lang_items.rs
1use rustc_hir::LangItem;
11use rustc_hir::def_id::DefId;
12use rustc_span::Span;
13use rustc_target::spec::PanicStrategy;
14
15use crate::ty::{self, TyCtxt};
16
17impl<'tcx> TyCtxt<'tcx> {
18 pub fn require_lang_item(self, lang_item: LangItem, span: Option<Span>) -> DefId {
21 self.lang_items().get(lang_item).unwrap_or_else(|| {
22 self.dcx().emit_fatal(crate::error::RequiresLangItem { span, name: lang_item.name() });
23 })
24 }
25
26 pub fn is_lang_item(self, def_id: DefId, lang_item: LangItem) -> bool {
27 self.lang_items().get(lang_item) == Some(def_id)
28 }
29
30 pub fn as_lang_item(self, def_id: DefId) -> Option<LangItem> {
31 self.lang_items().from_def_id(def_id)
32 }
33
34 pub fn fn_trait_kind_from_def_id(self, id: DefId) -> Option<ty::ClosureKind> {
38 let items = self.lang_items();
39 match Some(id) {
40 x if x == items.fn_trait() => Some(ty::ClosureKind::Fn),
41 x if x == items.fn_mut_trait() => Some(ty::ClosureKind::FnMut),
42 x if x == items.fn_once_trait() => Some(ty::ClosureKind::FnOnce),
43 _ => None,
44 }
45 }
46
47 pub fn async_fn_trait_kind_from_def_id(self, id: DefId) -> Option<ty::ClosureKind> {
51 let items = self.lang_items();
52 match Some(id) {
53 x if x == items.async_fn_trait() => Some(ty::ClosureKind::Fn),
54 x if x == items.async_fn_mut_trait() => Some(ty::ClosureKind::FnMut),
55 x if x == items.async_fn_once_trait() => Some(ty::ClosureKind::FnOnce),
56 _ => None,
57 }
58 }
59
60 pub fn fn_trait_kind_to_def_id(self, kind: ty::ClosureKind) -> Option<DefId> {
63 let items = self.lang_items();
64 match kind {
65 ty::ClosureKind::Fn => items.fn_trait(),
66 ty::ClosureKind::FnMut => items.fn_mut_trait(),
67 ty::ClosureKind::FnOnce => items.fn_once_trait(),
68 }
69 }
70
71 pub fn async_fn_trait_kind_to_def_id(self, kind: ty::ClosureKind) -> Option<DefId> {
74 let items = self.lang_items();
75 match kind {
76 ty::ClosureKind::Fn => items.async_fn_trait(),
77 ty::ClosureKind::FnMut => items.async_fn_mut_trait(),
78 ty::ClosureKind::FnOnce => items.async_fn_once_trait(),
79 }
80 }
81
82 pub fn is_fn_trait(self, id: DefId) -> bool {
84 self.fn_trait_kind_from_def_id(id).is_some()
85 }
86}
87
88pub fn required(tcx: TyCtxt<'_>, lang_item: LangItem) -> bool {
95 match tcx.sess.panic_strategy() {
99 PanicStrategy::Abort => {
100 lang_item != LangItem::EhPersonality && lang_item != LangItem::EhCatchTypeinfo
101 }
102 PanicStrategy::Unwind => true,
103 }
104}