1 //! Check the bodies of `const`s, `static`s and `const fn`s for illegal operations.
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.
7 use rustc::hir::{self, def_id::DefId};
9 use rustc::ty::{self, TyCtxt};
13 pub use self::qualifs::Qualif;
20 /// Information about the item currently being const-checked, as well as a reference to the global
22 pub struct Item<'mir, 'tcx> {
23 pub body: mir::ReadOnlyBodyCache<'mir, 'tcx>,
24 pub tcx: TyCtxt<'tcx>,
26 pub param_env: ty::ParamEnv<'tcx>,
27 pub const_kind: Option<ConstKind>,
30 impl Item<'mir, 'tcx> {
34 body: mir::ReadOnlyBodyCache<'mir, 'tcx>,
36 let param_env = tcx.param_env(def_id);
37 let const_kind = ConstKind::for_item(tcx, def_id);
48 /// Returns the kind of const context this `Item` represents (`const`, `static`, etc.).
50 /// Panics if this `Item` is not const.
51 pub fn const_kind(&self) -> ConstKind {
52 self.const_kind.expect("`const_kind` must not be called on a non-const fn")
56 /// The kinds of items which require compile-time evaluation.
57 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
61 /// A `static mut` item.
63 /// A `const fn` item.
65 /// A `const` item or an anonymous constant (e.g. in array lengths).
70 /// Returns the validation mode for the item with the given `DefId`, or `None` if this item
71 /// does not require validation (e.g. a non-const `fn`).
72 pub fn for_item(tcx: TyCtxt<'tcx>, def_id: DefId) -> Option<Self> {
73 use hir::BodyOwnerKind as HirKind;
75 let hir_id = tcx.hir().as_local_hir_id(def_id).unwrap();
77 let mode = match tcx.hir().body_owner_kind(hir_id) {
78 HirKind::Closure => return None,
80 HirKind::Fn if tcx.is_const_fn(def_id) => ConstKind::ConstFn,
81 HirKind::Fn => return None,
83 HirKind::Const => ConstKind::Const,
85 HirKind::Static(hir::Mutability::Immutable) => ConstKind::Static,
86 HirKind::Static(hir::Mutability::Mutable) => ConstKind::StaticMut,
92 pub fn is_static(self) -> bool {
94 ConstKind::Static | ConstKind::StaticMut => true,
95 ConstKind::ConstFn | ConstKind::Const => false,
100 impl fmt::Display for ConstKind {
101 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
103 ConstKind::Const => write!(f, "constant"),
104 ConstKind::Static | ConstKind::StaticMut => write!(f, "static"),
105 ConstKind::ConstFn => write!(f, "constant function"),
110 /// Returns `true` if this `DefId` points to one of the official `panic` lang items.
111 pub fn is_lang_panic_fn(tcx: TyCtxt<'tcx>, def_id: DefId) -> bool {
112 Some(def_id) == tcx.lang_items().panic_fn() ||
113 Some(def_id) == tcx.lang_items().begin_panic_fn()