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_errors::DiagCtxtHandle;
8use rustc_hir::def_id::{DefId, LocalDefId};
9use rustc_middle::ty::{self, PolyFnSig, TyCtxt};
10use rustc_middle::{bug, mir};
11use rustc_span::Symbol;
12use {rustc_attr_parsing as attr, rustc_hir as hir};
13
14pub use self::qualifs::Qualif;
15
16pub mod check;
17mod ops;
18pub mod post_drop_elaboration;
19pub mod qualifs;
20mod resolver;
21
22/// Information about the item currently being const-checked, as well as a reference to the global
23/// context.
24pub struct ConstCx<'mir, 'tcx> {
25    pub body: &'mir mir::Body<'tcx>,
26    pub tcx: TyCtxt<'tcx>,
27    pub typing_env: ty::TypingEnv<'tcx>,
28    pub const_kind: Option<hir::ConstContext>,
29}
30
31impl<'mir, 'tcx> ConstCx<'mir, 'tcx> {
32    pub fn new(tcx: TyCtxt<'tcx>, body: &'mir mir::Body<'tcx>) -> Self {
33        let typing_env = body.typing_env(tcx);
34        let const_kind = tcx.hir().body_const_context(body.source.def_id().expect_local());
35        ConstCx { body, tcx, typing_env, const_kind }
36    }
37
38    pub(crate) fn dcx(&self) -> DiagCtxtHandle<'tcx> {
39        self.tcx.dcx()
40    }
41
42    pub fn def_id(&self) -> LocalDefId {
43        self.body.source.def_id().expect_local()
44    }
45
46    /// Returns the kind of const context this `Item` represents (`const`, `static`, etc.).
47    ///
48    /// Panics if this `Item` is not const.
49    pub fn const_kind(&self) -> hir::ConstContext {
50        self.const_kind.expect("`const_kind` must not be called on a non-const fn")
51    }
52
53    pub fn enforce_recursive_const_stability(&self) -> bool {
54        // We can skip this if neither `staged_api` nor `-Zforce-unstable-if-unmarked` are enabled,
55        // since in such crates `lookup_const_stability` will always be `None`.
56        self.const_kind == Some(hir::ConstContext::ConstFn)
57            && (self.tcx.features().staged_api()
58                || self.tcx.sess.opts.unstable_opts.force_unstable_if_unmarked)
59            && is_fn_or_trait_safe_to_expose_on_stable(self.tcx, self.def_id().to_def_id())
60    }
61
62    fn is_async(&self) -> bool {
63        self.tcx.asyncness(self.def_id()).is_async()
64    }
65
66    pub fn fn_sig(&self) -> PolyFnSig<'tcx> {
67        let did = self.def_id().to_def_id();
68        if self.tcx.is_closure_like(did) {
69            let ty = self.tcx.type_of(did).instantiate_identity();
70            let ty::Closure(_, args) = ty.kind() else { bug!("type_of closure not ty::Closure") };
71            args.as_closure().sig()
72        } else {
73            self.tcx.fn_sig(did).instantiate_identity()
74        }
75    }
76}
77
78pub fn rustc_allow_const_fn_unstable(
79    tcx: TyCtxt<'_>,
80    def_id: LocalDefId,
81    feature_gate: Symbol,
82) -> bool {
83    let attrs = tcx.hir().attrs(tcx.local_def_id_to_hir_id(def_id));
84    attr::rustc_allow_const_fn_unstable(tcx.sess, attrs).any(|name| name == feature_gate)
85}
86
87/// Returns `true` if the given `def_id` (trait or function) is "safe to expose on stable".
88///
89/// This is relevant within a `staged_api` crate. Unlike with normal features, the use of unstable
90/// const features *recursively* taints the functions that use them. This is to avoid accidentally
91/// exposing e.g. the implementation of an unstable const intrinsic on stable. So we partition the
92/// world into two functions: those that are safe to expose on stable (and hence may not use
93/// unstable features, not even recursively), and those that are not.
94pub fn is_fn_or_trait_safe_to_expose_on_stable(tcx: TyCtxt<'_>, def_id: DefId) -> bool {
95    match tcx.lookup_const_stability(def_id) {
96        None => {
97            // In a `staged_api` crate, we do enforce recursive const stability for all unmarked
98            // functions, so we can trust local functions. But in another crate we don't know which
99            // rules were applied, so we can't trust that.
100            def_id.is_local() && tcx.features().staged_api()
101        }
102        Some(stab) => {
103            // We consider things safe-to-expose if they are stable or if they are marked as
104            // `const_stable_indirect`.
105            stab.is_const_stable() || stab.const_stable_indirect
106        }
107    }
108}