Skip to main content

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_hir::{self as hir, find_attr};
10use rustc_middle::ty::{self, PolyFnSig, TyCtxt};
11use rustc_middle::{bug, mir};
12use rustc_span::Symbol;
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 { ::rustc_middle::util::bug::bug_fmt(format_args!("type_of closure not ty::Closure"))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    {

        #[allow(deprecated)]
        {
            {
                'done:
                    {
                    for i in tcx.get_all_attrs(def_id) {
                        #[allow(unused_imports)]
                        use rustc_hir::attrs::AttributeKind::*;
                        let i: &rustc_hir::Attribute = i;
                        match i {
                            rustc_hir::Attribute::Parsed(RustcAllowConstFnUnstable(syms,
                                _)) if syms.contains(&feature_gate) => {
                                break 'done Some(());
                            }
                            rustc_hir::Attribute::Unparsed(..) =>
                                {}
                                #[deny(unreachable_patterns)]
                                _ => {}
                        }
                    }
                    None
                }
            }
        }
    }.is_some()find_attr!(tcx, def_id, RustcAllowConstFnUnstable(syms, _) if syms.contains(&feature_gate))
84}
85
86/// Returns `true` if the given `def_id` (trait or function) is "safe to expose on stable".
87///
88/// This is relevant within a `staged_api` crate. Unlike with normal features, the use of unstable
89/// const features *recursively* taints the functions that use them. This is to avoid accidentally
90/// exposing e.g. the implementation of an unstable const intrinsic on stable. So we partition the
91/// world into two functions: those that are safe to expose on stable (and hence may not use
92/// unstable features, not even recursively), and those that are not.
93pub fn is_fn_or_trait_safe_to_expose_on_stable(tcx: TyCtxt<'_>, def_id: DefId) -> bool {
94    // A default body in a `const trait` is const-stable when the trait is const-stable.
95    if let Some(trait_id) = tcx.trait_of_assoc(def_id)
96        && tcx.is_const_trait(trait_id)
97    {
98        return is_fn_or_trait_safe_to_expose_on_stable(tcx, trait_id);
99    }
100
101    match tcx.lookup_const_stability(def_id) {
102        None => {
103            // In a `staged_api` crate, we do enforce recursive const stability for all unmarked
104            // functions, so we can trust local functions. But in another crate we don't know which
105            // rules were applied, so we can't trust that.
106            def_id.is_local() && tcx.features().staged_api()
107        }
108        Some(stab) => {
109            // We consider things safe-to-expose if they are stable or if they are marked as
110            // `const_stable_indirect`.
111            stab.is_const_stable() || stab.const_stable_indirect
112        }
113    }
114}