rustc_const_eval/check_consts/
mod.rs
1use rustc_attr_parsing::{AttributeKind, find_attr};
8use rustc_errors::DiagCtxtHandle;
9use rustc_hir as hir;
10use rustc_hir::def_id::{DefId, LocalDefId};
11use rustc_middle::ty::{self, PolyFnSig, TyCtxt};
12use rustc_middle::{bug, mir};
13use rustc_span::Symbol;
14
15pub use self::qualifs::Qualif;
16
17pub mod check;
18mod ops;
19pub mod post_drop_elaboration;
20pub mod qualifs;
21mod resolver;
22
23pub struct ConstCx<'mir, 'tcx> {
26 pub body: &'mir mir::Body<'tcx>,
27 pub tcx: TyCtxt<'tcx>,
28 pub typing_env: ty::TypingEnv<'tcx>,
29 pub const_kind: Option<hir::ConstContext>,
30}
31
32impl<'mir, 'tcx> ConstCx<'mir, 'tcx> {
33 pub fn new(tcx: TyCtxt<'tcx>, body: &'mir mir::Body<'tcx>) -> Self {
34 let typing_env = body.typing_env(tcx);
35 let const_kind = tcx.hir_body_const_context(body.source.def_id().expect_local());
36 ConstCx { body, tcx, typing_env, const_kind }
37 }
38
39 pub(crate) fn dcx(&self) -> DiagCtxtHandle<'tcx> {
40 self.tcx.dcx()
41 }
42
43 pub fn def_id(&self) -> LocalDefId {
44 self.body.source.def_id().expect_local()
45 }
46
47 pub fn const_kind(&self) -> hir::ConstContext {
51 self.const_kind.expect("`const_kind` must not be called on a non-const fn")
52 }
53
54 pub fn enforce_recursive_const_stability(&self) -> bool {
55 self.const_kind == Some(hir::ConstContext::ConstFn)
58 && (self.tcx.features().staged_api()
59 || self.tcx.sess.opts.unstable_opts.force_unstable_if_unmarked)
60 && is_fn_or_trait_safe_to_expose_on_stable(self.tcx, self.def_id().to_def_id())
61 }
62
63 fn is_async(&self) -> bool {
64 self.tcx.asyncness(self.def_id()).is_async()
65 }
66
67 pub fn fn_sig(&self) -> PolyFnSig<'tcx> {
68 let did = self.def_id().to_def_id();
69 if self.tcx.is_closure_like(did) {
70 let ty = self.tcx.type_of(did).instantiate_identity();
71 let ty::Closure(_, args) = ty.kind() else { bug!("type_of closure not ty::Closure") };
72 args.as_closure().sig()
73 } else {
74 self.tcx.fn_sig(did).instantiate_identity()
75 }
76 }
77}
78
79pub fn rustc_allow_const_fn_unstable(
80 tcx: TyCtxt<'_>,
81 def_id: LocalDefId,
82 feature_gate: Symbol,
83) -> bool {
84 let attrs = tcx.hir_attrs(tcx.local_def_id_to_hir_id(def_id));
85
86 find_attr!(attrs, AttributeKind::AllowConstFnUnstable(syms) if syms.contains(&feature_gate))
87}
88
89pub fn is_fn_or_trait_safe_to_expose_on_stable(tcx: TyCtxt<'_>, def_id: DefId) -> bool {
97 if tcx.is_const_default_method(def_id) {
99 return is_fn_or_trait_safe_to_expose_on_stable(tcx, tcx.parent(def_id));
100 }
101
102 match tcx.lookup_const_stability(def_id) {
103 None => {
104 def_id.is_local() && tcx.features().staged_api()
108 }
109 Some(stab) => {
110 stab.is_const_stable() || stab.const_stable_indirect
113 }
114 }
115}