]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_const_eval/src/const_eval/mod.rs
Rollup merge of #99110 - audunhalland:match_has_guard_from_candidate, r=pnkfelix
[rust.git] / compiler / rustc_const_eval / src / const_eval / mod.rs
1 // Not in interpret to make sure we do not use private implementation details
2
3 use rustc_hir::Mutability;
4 use rustc_middle::mir;
5 use rustc_middle::mir::interpret::{EvalToValTreeResult, GlobalId};
6 use rustc_middle::ty::{self, TyCtxt};
7 use rustc_span::{source_map::DUMMY_SP, symbol::Symbol};
8
9 use crate::interpret::{
10     intern_const_alloc_recursive, ConstValue, InternKind, InterpCx, InterpResult, MemPlaceMeta,
11     Scalar,
12 };
13
14 mod error;
15 mod eval_queries;
16 mod fn_queries;
17 mod machine;
18 mod valtrees;
19
20 pub use error::*;
21 pub use eval_queries::*;
22 pub use fn_queries::*;
23 pub use machine::*;
24 pub(crate) use valtrees::{const_to_valtree_inner, valtree_to_const_value};
25
26 pub(crate) fn const_caller_location(
27     tcx: TyCtxt<'_>,
28     (file, line, col): (Symbol, u32, u32),
29 ) -> ConstValue<'_> {
30     trace!("const_caller_location: {}:{}:{}", file, line, col);
31     let mut ecx = mk_eval_cx(tcx, DUMMY_SP, ty::ParamEnv::reveal_all(), false);
32
33     let loc_place = ecx.alloc_caller_location(file, line, col);
34     if intern_const_alloc_recursive(&mut ecx, InternKind::Constant, &loc_place).is_err() {
35         bug!("intern_const_alloc_recursive should not error in this case")
36     }
37     ConstValue::Scalar(Scalar::from_maybe_pointer(loc_place.ptr, &tcx))
38 }
39
40 // We forbid type-level constants that contain more than `VALTREE_MAX_NODES` nodes.
41 const VALTREE_MAX_NODES: usize = 100000;
42
43 pub(crate) enum ValTreeCreationError {
44     NodesOverflow,
45     NonSupportedType,
46     Other,
47 }
48 pub(crate) type ValTreeCreationResult<'tcx> = Result<ty::ValTree<'tcx>, ValTreeCreationError>;
49
50 /// Evaluates a constant and turns it into a type-level constant value.
51 pub(crate) fn eval_to_valtree<'tcx>(
52     tcx: TyCtxt<'tcx>,
53     param_env: ty::ParamEnv<'tcx>,
54     cid: GlobalId<'tcx>,
55 ) -> EvalToValTreeResult<'tcx> {
56     let const_alloc = tcx.eval_to_allocation_raw(param_env.and(cid))?;
57
58     // FIXME Need to provide a span to `eval_to_valtree`
59     let ecx = mk_eval_cx(
60         tcx, DUMMY_SP, param_env,
61         // It is absolutely crucial for soundness that
62         // we do not read from static items or other mutable memory.
63         false,
64     );
65     let place = ecx.raw_const_to_mplace(const_alloc).unwrap();
66     debug!(?place);
67
68     let mut num_nodes = 0;
69     let valtree_result = const_to_valtree_inner(&ecx, &place, &mut num_nodes);
70
71     match valtree_result {
72         Ok(valtree) => Ok(Some(valtree)),
73         Err(err) => {
74             let did = cid.instance.def_id();
75             let s = cid.display(tcx);
76             match err {
77                 ValTreeCreationError::NodesOverflow => {
78                     let msg = format!("maximum number of nodes exceeded in constant {}", &s);
79                     let mut diag = match tcx.hir().span_if_local(did) {
80                         Some(span) => tcx.sess.struct_span_err(span, &msg),
81                         None => tcx.sess.struct_err(&msg),
82                     };
83                     diag.emit();
84
85                     Ok(None)
86                 }
87                 ValTreeCreationError::NonSupportedType | ValTreeCreationError::Other => Ok(None),
88             }
89         }
90     }
91 }
92
93 #[instrument(skip(tcx), level = "debug")]
94 pub(crate) fn try_destructure_mir_constant<'tcx>(
95     tcx: TyCtxt<'tcx>,
96     param_env: ty::ParamEnv<'tcx>,
97     val: mir::ConstantKind<'tcx>,
98 ) -> InterpResult<'tcx, mir::DestructuredMirConstant<'tcx>> {
99     trace!("destructure_mir_constant: {:?}", val);
100     let ecx = mk_eval_cx(tcx, DUMMY_SP, param_env, false);
101     let op = ecx.mir_const_to_op(&val, None)?;
102
103     // We go to `usize` as we cannot allocate anything bigger anyway.
104     let (field_count, variant, down) = match val.ty().kind() {
105         ty::Array(_, len) => (len.eval_usize(tcx, param_env) as usize, None, op),
106         ty::Adt(def, _) if def.variants().is_empty() => {
107             throw_ub!(Unreachable)
108         }
109         ty::Adt(def, _) => {
110             let variant = ecx.read_discriminant(&op)?.1;
111             let down = ecx.operand_downcast(&op, variant)?;
112             (def.variants()[variant].fields.len(), Some(variant), down)
113         }
114         ty::Tuple(substs) => (substs.len(), None, op),
115         _ => bug!("cannot destructure mir constant {:?}", val),
116     };
117
118     let fields_iter = (0..field_count)
119         .map(|i| {
120             let field_op = ecx.operand_field(&down, i)?;
121             let val = op_to_const(&ecx, &field_op);
122             Ok(mir::ConstantKind::Val(val, field_op.layout.ty))
123         })
124         .collect::<InterpResult<'tcx, Vec<_>>>()?;
125     let fields = tcx.arena.alloc_from_iter(fields_iter);
126
127     Ok(mir::DestructuredMirConstant { variant, fields })
128 }
129
130 #[instrument(skip(tcx), level = "debug")]
131 pub(crate) fn deref_mir_constant<'tcx>(
132     tcx: TyCtxt<'tcx>,
133     param_env: ty::ParamEnv<'tcx>,
134     val: mir::ConstantKind<'tcx>,
135 ) -> mir::ConstantKind<'tcx> {
136     let ecx = mk_eval_cx(tcx, DUMMY_SP, param_env, false);
137     let op = ecx.mir_const_to_op(&val, None).unwrap();
138     let mplace = ecx.deref_operand(&op).unwrap();
139     if let Some(alloc_id) = mplace.ptr.provenance {
140         assert_eq!(
141             tcx.global_alloc(alloc_id).unwrap_memory().0.0.mutability,
142             Mutability::Not,
143             "deref_mir_constant cannot be used with mutable allocations as \
144             that could allow pattern matching to observe mutable statics",
145         );
146     }
147
148     let ty = match mplace.meta {
149         MemPlaceMeta::None => mplace.layout.ty,
150         // In case of unsized types, figure out the real type behind.
151         MemPlaceMeta::Meta(scalar) => match mplace.layout.ty.kind() {
152             ty::Str => bug!("there's no sized equivalent of a `str`"),
153             ty::Slice(elem_ty) => tcx.mk_array(*elem_ty, scalar.to_machine_usize(&tcx).unwrap()),
154             _ => bug!(
155                 "type {} should not have metadata, but had {:?}",
156                 mplace.layout.ty,
157                 mplace.meta
158             ),
159         },
160     };
161
162     mir::ConstantKind::Val(op_to_const(&ecx, &mplace.into()), ty)
163 }