rustc_const_eval/check_consts/
mod.rs

1//! Check the bodies of `const`s, `static`s and `const fn`s for illegal operations.
2//!
3//! This module will eventually replace the parts of `qualify_consts.rs` that check whether a local
4//! has interior mutability or needs to be dropped, as well as the visitor that emits errors when
5//! it finds operations that are invalid in a certain context.
6
7use 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
23/// Information about the item currently being const-checked, as well as a reference to the global
24/// context.
25pub 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    /// Returns the kind of const context this `Item` represents (`const`, `static`, etc.).
48    ///
49    /// Panics if this `Item` is not const.
50    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        // We can skip this if neither `staged_api` nor `-Zforce-unstable-if-unmarked` are enabled,
56        // since in such crates `lookup_const_stability` will always be `None`.
57        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
89/// Returns `true` if the given `def_id` (trait or function) is "safe to expose on stable".
90///
91/// This is relevant within a `staged_api` crate. Unlike with normal features, the use of unstable
92/// const features *recursively* taints the functions that use them. This is to avoid accidentally
93/// exposing e.g. the implementation of an unstable const intrinsic on stable. So we partition the
94/// world into two functions: those that are safe to expose on stable (and hence may not use
95/// unstable features, not even recursively), and those that are not.
96pub fn is_fn_or_trait_safe_to_expose_on_stable(tcx: TyCtxt<'_>, def_id: DefId) -> bool {
97    // A default body in a `#[const_trait]` is const-stable when the trait is const-stable.
98    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            // In a `staged_api` crate, we do enforce recursive const stability for all unmarked
105            // functions, so we can trust local functions. But in another crate we don't know which
106            // rules were applied, so we can't trust that.
107            def_id.is_local() && tcx.features().staged_api()
108        }
109        Some(stab) => {
110            // We consider things safe-to-expose if they are stable or if they are marked as
111            // `const_stable_indirect`.
112            stab.is_const_stable() || stab.const_stable_indirect
113        }
114    }
115}