rustc_const_eval/const_eval/
fn_queries.rs1use rustc_hir::def_id::{DefId, LocalDefId};
2use rustc_hir::{
3 Constness, ExprKind, ForeignItemKind, ImplItem, ImplItemImplKind, ImplItemKind, Item, ItemKind,
4 Node, TraitItem, TraitItemKind, VariantData, find_attr,
5};
6use rustc_middle::query::Providers;
7use rustc_middle::ty::TyCtxt;
8
9fn constness(tcx: TyCtxt<'_>, def_id: LocalDefId) -> Constness {
11 let node = tcx.hir_node_by_def_id(def_id);
12
13 match node {
14 Node::Ctor(VariantData::Tuple(..)) => Constness::Const,
15 Node::ForeignItem(item) if let ForeignItemKind::Fn(..) = item.kind => {
16 Constness::NotConst
18 }
19 Node::Expr(e) if let ExprKind::Closure(c) = e.kind => c.constness,
20 Node::Item(i) if let ItemKind::Impl(impl_) = i.kind => impl_.constness,
22 Node::Item(Item { kind: ItemKind::Fn { sig, .. }, .. }) => sig.header.constness,
23 Node::ImplItem(ImplItem {
24 impl_kind: ImplItemImplKind::Trait { .. },
25 kind: ImplItemKind::Fn(..),
26 ..
27 }) => tcx.impl_trait_header(tcx.local_parent(def_id)).constness,
28 Node::ImplItem(ImplItem {
29 impl_kind: ImplItemImplKind::Inherent { .. },
30 kind: ImplItemKind::Fn(sig, _),
31 ..
32 }) => {
33 match sig.header.constness {
34 Constness::Const => Constness::Const,
35 Constness::NotConst => tcx.constness(tcx.local_parent(def_id)),
37 }
38 }
39 Node::TraitItem(ti @ TraitItem { kind: TraitItemKind::Fn(..), .. }) => {
40 if {
{
'done:
{
for i in tcx.hir_attrs(ti.hir_id()) {
#[allow(unused_imports)]
use rustc_hir::attrs::AttributeKind::*;
let i: &rustc_hir::Attribute = i;
match i {
rustc_hir::Attribute::Parsed(RustcNonConstTraitMethod) => {
break 'done Some(());
}
rustc_hir::Attribute::Unparsed(..) =>
{}
#[deny(unreachable_patterns)]
_ => {}
}
}
None
}
}.is_some()
}find_attr!(tcx.hir_attrs(ti.hir_id()), RustcNonConstTraitMethod) {
41 Constness::NotConst
42 } else {
43 tcx.trait_def(tcx.local_parent(def_id)).constness
44 }
45 }
46 _ => {
47 tcx.dcx().span_bug(
48 tcx.def_span(def_id),
49 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("should not be requesting the constness of items that can\'t be const: {1:#?}: {0:?}",
tcx.def_kind(def_id), node))
})format!("should not be requesting the constness of items that can't be const: {node:#?}: {:?}", tcx.def_kind(def_id))
50 )
51 }
52 }
53}
54
55fn is_promotable_const_fn(tcx: TyCtxt<'_>, def_id: DefId) -> bool {
56 tcx.is_const_fn(def_id)
57 && match tcx.lookup_const_stability(def_id) {
58 Some(stab) => {
59 if truecfg!(debug_assertions) && stab.promotable {
60 let sig = tcx.fn_sig(def_id);
61 if !sig.skip_binder().safety().is_safe() {
{
::core::panicking::panic_fmt(format_args!("don\'t mark const unsafe fns as promotable"));
}
};assert!(
62 sig.skip_binder().safety().is_safe(),
63 "don't mark const unsafe fns as promotable",
64 );
66 }
67 stab.promotable
68 }
69 None => false,
70 }
71}
72
73pub fn provide(providers: &mut Providers) {
74 *providers = Providers { constness, is_promotable_const_fn, ..*providers };
75}