Skip to main content

rapx/def_ids/
lang_api.rs

1//! Compiler lang-item identities used across RAPx.
2//!
3//! # Agent Rules
4//!
5//! Keep this module limited to identifying rustc lang items and their trait
6//! methods by `DefId`. Do not depend on other RAPx modules.
7
8#[cfg(rapx_has_attr_ir)]
9pub(crate) use rustc_attr_ir::LangItem;
10#[cfg(all(not(rapx_has_attr_ir), not(rapx_ge_100)))]
11pub(crate) use rustc_hir::LangItem;
12#[cfg(all(not(rapx_has_attr_ir), rapx_ge_100))]
13pub(crate) use rustc_hir::attrs::lang_items::LangItem;
14use rustc_hir::def_id::DefId;
15use rustc_middle::ty::TyCtxt;
16
17/// Match a compiler-provided lang item by its `DefId`.
18pub(crate) fn matches(tcx: TyCtxt<'_>, def_id: DefId, item: LangItem) -> bool {
19    tcx.is_lang_item(def_id, item)
20}
21
22/// Whether this is one of the three callable traits.
23pub(crate) fn is_fn_trait(tcx: TyCtxt<'_>, trait_id: DefId) -> bool {
24    matches(tcx, trait_id, LangItem::Fn)
25        || matches(tcx, trait_id, LangItem::FnMut)
26        || matches(tcx, trait_id, LangItem::FnOnce)
27}
28
29/// Whether `did` is the `FnMut::call_mut` trait method.
30pub(crate) fn is_call_mut(tcx: TyCtxt<'_>, did: DefId) -> bool {
31    tcx.opt_associated_item(did)
32        .and_then(|item| item.trait_container(tcx))
33        .is_some_and(|trait_id| matches(tcx, trait_id, LangItem::FnMut))
34        && tcx.item_name(did).as_str() == "call_mut"
35}
36
37/// Whether `did` is a method of the `Clone` trait.
38pub(crate) fn is_clone(tcx: TyCtxt<'_>, did: DefId) -> bool {
39    tcx.opt_associated_item(did)
40        .and_then(|item| item.trait_container(tcx))
41        .is_some_and(|trait_id| matches(tcx, trait_id, LangItem::Clone))
42}
43
44/// The plain `panic!` entry point, which only consumes a static message.
45pub(crate) fn is_panic_exit(tcx: TyCtxt<'_>, callee: DefId) -> bool {
46    matches(tcx, callee, LangItem::Panic)
47}
48
49/// Panic lang items used as diverging exits in MIR.
50pub(crate) fn is_panic_family(tcx: TyCtxt<'_>, callee: DefId) -> bool {
51    is_panic_exit(tcx, callee)
52        || matches(tcx, callee, LangItem::PanicNounwind)
53        || matches(tcx, callee, LangItem::PanicFmt)
54        || matches(tcx, callee, LangItem::PanicDisplay)
55        || matches(tcx, callee, LangItem::ConstPanicFmt)
56        || matches(tcx, callee, LangItem::PanicBoundsCheck)
57        || matches(tcx, callee, LangItem::PanicMisalignedPointerDereference)
58}