]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_mir/src/const_eval/mod.rs
Auto merge of #77954 - JohnTitor:rollup-bpoy497, r=JohnTitor
[rust.git] / compiler / rustc_mir / src / const_eval / mod.rs
1 // Not in interpret to make sure we do not use private implementation details
2
3 use std::convert::TryFrom;
4
5 use rustc_hir::Mutability;
6 use rustc_middle::mir;
7 use rustc_middle::ty::{self, TyCtxt};
8 use rustc_span::{source_map::DUMMY_SP, symbol::Symbol};
9
10 use crate::interpret::{
11     intern_const_alloc_recursive, ConstValue, InternKind, InterpCx, MemPlaceMeta, Scalar,
12 };
13
14 mod error;
15 mod eval_queries;
16 mod fn_queries;
17 mod machine;
18
19 pub use error::*;
20 pub use eval_queries::*;
21 pub use fn_queries::*;
22 pub use machine::*;
23
24 pub(crate) fn const_caller_location(
25     tcx: TyCtxt<'tcx>,
26     (file, line, col): (Symbol, u32, u32),
27 ) -> ConstValue<'tcx> {
28     trace!("const_caller_location: {}:{}:{}", file, line, col);
29     let mut ecx = mk_eval_cx(tcx, DUMMY_SP, ty::ParamEnv::reveal_all(), false);
30
31     let loc_place = ecx.alloc_caller_location(file, line, col);
32     intern_const_alloc_recursive(&mut ecx, InternKind::Constant, loc_place, false);
33     ConstValue::Scalar(loc_place.ptr)
34 }
35
36 /// This function uses `unwrap` copiously, because an already validated constant
37 /// must have valid fields and can thus never fail outside of compiler bugs. However, it is
38 /// invoked from the pretty printer, where it can receive enums with no variants and e.g.
39 /// `read_discriminant` needs to be able to handle that.
40 pub(crate) fn destructure_const<'tcx>(
41     tcx: TyCtxt<'tcx>,
42     param_env: ty::ParamEnv<'tcx>,
43     val: &'tcx ty::Const<'tcx>,
44 ) -> mir::DestructuredConst<'tcx> {
45     trace!("destructure_const: {:?}", val);
46     let ecx = mk_eval_cx(tcx, DUMMY_SP, param_env, false);
47     let op = ecx.const_to_op(val, None).unwrap();
48
49     // We go to `usize` as we cannot allocate anything bigger anyway.
50     let (field_count, variant, down) = match val.ty.kind() {
51         ty::Array(_, len) => (usize::try_from(len.eval_usize(tcx, param_env)).unwrap(), None, op),
52         ty::Adt(def, _) if def.variants.is_empty() => {
53             return mir::DestructuredConst { variant: None, fields: &[] };
54         }
55         ty::Adt(def, _) => {
56             let variant = ecx.read_discriminant(op).unwrap().1;
57             let down = ecx.operand_downcast(op, variant).unwrap();
58             (def.variants[variant].fields.len(), Some(variant), down)
59         }
60         ty::Tuple(substs) => (substs.len(), None, op),
61         _ => bug!("cannot destructure constant {:?}", val),
62     };
63
64     let fields_iter = (0..field_count).map(|i| {
65         let field_op = ecx.operand_field(down, i).unwrap();
66         let val = op_to_const(&ecx, field_op);
67         ty::Const::from_value(tcx, val, field_op.layout.ty)
68     });
69     let fields = tcx.arena.alloc_from_iter(fields_iter);
70
71     mir::DestructuredConst { variant, fields }
72 }
73
74 pub(crate) fn deref_const<'tcx>(
75     tcx: TyCtxt<'tcx>,
76     param_env: ty::ParamEnv<'tcx>,
77     val: &'tcx ty::Const<'tcx>,
78 ) -> &'tcx ty::Const<'tcx> {
79     trace!("deref_const: {:?}", val);
80     let ecx = mk_eval_cx(tcx, DUMMY_SP, param_env, false);
81     let op = ecx.const_to_op(val, None).unwrap();
82     let mplace = ecx.deref_operand(op).unwrap();
83     if let Scalar::Ptr(ptr) = mplace.ptr {
84         assert_eq!(
85             ecx.memory.get_raw(ptr.alloc_id).unwrap().mutability,
86             Mutability::Not,
87             "deref_const cannot be used with mutable allocations as \
88             that could allow pattern matching to observe mutable statics",
89         );
90     }
91
92     let ty = match mplace.meta {
93         MemPlaceMeta::None => mplace.layout.ty,
94         MemPlaceMeta::Poison => bug!("poison metadata in `deref_const`: {:#?}", mplace),
95         // In case of unsized types, figure out the real type behind.
96         MemPlaceMeta::Meta(scalar) => match mplace.layout.ty.kind() {
97             ty::Str => bug!("there's no sized equivalent of a `str`"),
98             ty::Slice(elem_ty) => tcx.mk_array(elem_ty, scalar.to_machine_usize(&tcx).unwrap()),
99             _ => bug!(
100                 "type {} should not have metadata, but had {:?}",
101                 mplace.layout.ty,
102                 mplace.meta
103             ),
104         },
105     };
106
107     tcx.mk_const(ty::Const { val: ty::ConstKind::Value(op_to_const(&ecx, mplace.into())), ty })
108 }