]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/consts.rs
Merge commit 'bf1c6f9871f430e284b17aa44059e0d0395e28a6' into clippyup
[rust.git] / clippy_lints / src / consts.rs
1 #![allow(clippy::float_cmp)]
2
3 use crate::utils::{clip, higher, sext, unsext};
4 use if_chain::if_chain;
5 use rustc_ast::ast::{FloatTy, LitFloatType, LitKind};
6 use rustc_data_structures::sync::Lrc;
7 use rustc_hir::def::{DefKind, Res};
8 use rustc_hir::{BinOp, BinOpKind, Block, Expr, ExprKind, HirId, QPath, UnOp};
9 use rustc_lint::LateContext;
10 use rustc_middle::ty::subst::{Subst, SubstsRef};
11 use rustc_middle::ty::{self, Ty, TyCtxt};
12 use rustc_middle::{bug, span_bug};
13 use rustc_span::symbol::Symbol;
14 use std::cmp::Ordering::{self, Equal};
15 use std::convert::TryInto;
16 use std::hash::{Hash, Hasher};
17
18 /// A `LitKind`-like enum to fold constant `Expr`s into.
19 #[derive(Debug, Clone)]
20 pub enum Constant {
21     /// A `String` (e.g., "abc").
22     Str(String),
23     /// A binary string (e.g., `b"abc"`).
24     Binary(Lrc<[u8]>),
25     /// A single `char` (e.g., `'a'`).
26     Char(char),
27     /// An integer's bit representation.
28     Int(u128),
29     /// An `f32`.
30     F32(f32),
31     /// An `f64`.
32     F64(f64),
33     /// `true` or `false`.
34     Bool(bool),
35     /// An array of constants.
36     Vec(Vec<Constant>),
37     /// Also an array, but with only one constant, repeated N times.
38     Repeat(Box<Constant>, u64),
39     /// A tuple of constants.
40     Tuple(Vec<Constant>),
41     /// A raw pointer.
42     RawPtr(u128),
43     /// A reference
44     Ref(Box<Constant>),
45     /// A literal with syntax error.
46     Err(Symbol),
47 }
48
49 impl PartialEq for Constant {
50     fn eq(&self, other: &Self) -> bool {
51         match (self, other) {
52             (&Self::Str(ref ls), &Self::Str(ref rs)) => ls == rs,
53             (&Self::Binary(ref l), &Self::Binary(ref r)) => l == r,
54             (&Self::Char(l), &Self::Char(r)) => l == r,
55             (&Self::Int(l), &Self::Int(r)) => l == r,
56             (&Self::F64(l), &Self::F64(r)) => {
57                 // We want `Fw32 == FwAny` and `FwAny == Fw64`, and by transitivity we must have
58                 // `Fw32 == Fw64`, so don’t compare them.
59                 // `to_bits` is required to catch non-matching 0.0, -0.0, and NaNs.
60                 l.to_bits() == r.to_bits()
61             },
62             (&Self::F32(l), &Self::F32(r)) => {
63                 // We want `Fw32 == FwAny` and `FwAny == Fw64`, and by transitivity we must have
64                 // `Fw32 == Fw64`, so don’t compare them.
65                 // `to_bits` is required to catch non-matching 0.0, -0.0, and NaNs.
66                 f64::from(l).to_bits() == f64::from(r).to_bits()
67             },
68             (&Self::Bool(l), &Self::Bool(r)) => l == r,
69             (&Self::Vec(ref l), &Self::Vec(ref r)) | (&Self::Tuple(ref l), &Self::Tuple(ref r)) => l == r,
70             (&Self::Repeat(ref lv, ref ls), &Self::Repeat(ref rv, ref rs)) => ls == rs && lv == rv,
71             (&Self::Ref(ref lb), &Self::Ref(ref rb)) => *lb == *rb,
72             // TODO: are there inter-type equalities?
73             _ => false,
74         }
75     }
76 }
77
78 impl Hash for Constant {
79     fn hash<H>(&self, state: &mut H)
80     where
81         H: Hasher,
82     {
83         std::mem::discriminant(self).hash(state);
84         match *self {
85             Self::Str(ref s) => {
86                 s.hash(state);
87             },
88             Self::Binary(ref b) => {
89                 b.hash(state);
90             },
91             Self::Char(c) => {
92                 c.hash(state);
93             },
94             Self::Int(i) => {
95                 i.hash(state);
96             },
97             Self::F32(f) => {
98                 f64::from(f).to_bits().hash(state);
99             },
100             Self::F64(f) => {
101                 f.to_bits().hash(state);
102             },
103             Self::Bool(b) => {
104                 b.hash(state);
105             },
106             Self::Vec(ref v) | Self::Tuple(ref v) => {
107                 v.hash(state);
108             },
109             Self::Repeat(ref c, l) => {
110                 c.hash(state);
111                 l.hash(state);
112             },
113             Self::RawPtr(u) => {
114                 u.hash(state);
115             },
116             Self::Ref(ref r) => {
117                 r.hash(state);
118             },
119             Self::Err(ref s) => {
120                 s.hash(state);
121             },
122         }
123     }
124 }
125
126 impl Constant {
127     pub fn partial_cmp(tcx: TyCtxt<'_>, cmp_type: Ty<'_>, left: &Self, right: &Self) -> Option<Ordering> {
128         match (left, right) {
129             (&Self::Str(ref ls), &Self::Str(ref rs)) => Some(ls.cmp(rs)),
130             (&Self::Char(ref l), &Self::Char(ref r)) => Some(l.cmp(r)),
131             (&Self::Int(l), &Self::Int(r)) => {
132                 if let ty::Int(int_ty) = *cmp_type.kind() {
133                     Some(sext(tcx, l, int_ty).cmp(&sext(tcx, r, int_ty)))
134                 } else {
135                     Some(l.cmp(&r))
136                 }
137             },
138             (&Self::F64(l), &Self::F64(r)) => l.partial_cmp(&r),
139             (&Self::F32(l), &Self::F32(r)) => l.partial_cmp(&r),
140             (&Self::Bool(ref l), &Self::Bool(ref r)) => Some(l.cmp(r)),
141             (&Self::Tuple(ref l), &Self::Tuple(ref r)) | (&Self::Vec(ref l), &Self::Vec(ref r)) => l
142                 .iter()
143                 .zip(r.iter())
144                 .map(|(li, ri)| Self::partial_cmp(tcx, cmp_type, li, ri))
145                 .find(|r| r.map_or(true, |o| o != Ordering::Equal))
146                 .unwrap_or_else(|| Some(l.len().cmp(&r.len()))),
147             (&Self::Repeat(ref lv, ref ls), &Self::Repeat(ref rv, ref rs)) => {
148                 match Self::partial_cmp(tcx, cmp_type, lv, rv) {
149                     Some(Equal) => Some(ls.cmp(rs)),
150                     x => x,
151                 }
152             },
153             (&Self::Ref(ref lb), &Self::Ref(ref rb)) => Self::partial_cmp(tcx, cmp_type, lb, rb),
154             // TODO: are there any useful inter-type orderings?
155             _ => None,
156         }
157     }
158 }
159
160 /// Parses a `LitKind` to a `Constant`.
161 pub fn lit_to_constant(lit: &LitKind, ty: Option<Ty<'_>>) -> Constant {
162     match *lit {
163         LitKind::Str(ref is, _) => Constant::Str(is.to_string()),
164         LitKind::Byte(b) => Constant::Int(u128::from(b)),
165         LitKind::ByteStr(ref s) => Constant::Binary(Lrc::clone(s)),
166         LitKind::Char(c) => Constant::Char(c),
167         LitKind::Int(n, _) => Constant::Int(n),
168         LitKind::Float(ref is, LitFloatType::Suffixed(fty)) => match fty {
169             FloatTy::F32 => Constant::F32(is.as_str().parse().unwrap()),
170             FloatTy::F64 => Constant::F64(is.as_str().parse().unwrap()),
171         },
172         LitKind::Float(ref is, LitFloatType::Unsuffixed) => match ty.expect("type of float is known").kind() {
173             ty::Float(FloatTy::F32) => Constant::F32(is.as_str().parse().unwrap()),
174             ty::Float(FloatTy::F64) => Constant::F64(is.as_str().parse().unwrap()),
175             _ => bug!(),
176         },
177         LitKind::Bool(b) => Constant::Bool(b),
178         LitKind::Err(s) => Constant::Err(s),
179     }
180 }
181
182 pub fn constant<'tcx>(
183     lcx: &LateContext<'tcx>,
184     typeck_results: &ty::TypeckResults<'tcx>,
185     e: &Expr<'_>,
186 ) -> Option<(Constant, bool)> {
187     let mut cx = ConstEvalLateContext {
188         lcx,
189         typeck_results,
190         param_env: lcx.param_env,
191         needed_resolution: false,
192         substs: lcx.tcx.intern_substs(&[]),
193     };
194     cx.expr(e).map(|cst| (cst, cx.needed_resolution))
195 }
196
197 pub fn constant_simple<'tcx>(
198     lcx: &LateContext<'tcx>,
199     typeck_results: &ty::TypeckResults<'tcx>,
200     e: &Expr<'_>,
201 ) -> Option<Constant> {
202     constant(lcx, typeck_results, e).and_then(|(cst, res)| if res { None } else { Some(cst) })
203 }
204
205 /// Creates a `ConstEvalLateContext` from the given `LateContext` and `TypeckResults`.
206 pub fn constant_context<'a, 'tcx>(
207     lcx: &'a LateContext<'tcx>,
208     typeck_results: &'a ty::TypeckResults<'tcx>,
209 ) -> ConstEvalLateContext<'a, 'tcx> {
210     ConstEvalLateContext {
211         lcx,
212         typeck_results,
213         param_env: lcx.param_env,
214         needed_resolution: false,
215         substs: lcx.tcx.intern_substs(&[]),
216     }
217 }
218
219 pub struct ConstEvalLateContext<'a, 'tcx> {
220     lcx: &'a LateContext<'tcx>,
221     typeck_results: &'a ty::TypeckResults<'tcx>,
222     param_env: ty::ParamEnv<'tcx>,
223     needed_resolution: bool,
224     substs: SubstsRef<'tcx>,
225 }
226
227 impl<'a, 'tcx> ConstEvalLateContext<'a, 'tcx> {
228     /// Simple constant folding: Insert an expression, get a constant or none.
229     pub fn expr(&mut self, e: &Expr<'_>) -> Option<Constant> {
230         if let Some((ref cond, ref then, otherwise)) = higher::if_block(&e) {
231             return self.ifthenelse(cond, then, otherwise);
232         }
233         match e.kind {
234             ExprKind::Path(ref qpath) => self.fetch_path(qpath, e.hir_id, self.typeck_results.expr_ty(e)),
235             ExprKind::Block(ref block, _) => self.block(block),
236             ExprKind::Lit(ref lit) => Some(lit_to_constant(&lit.node, self.typeck_results.expr_ty_opt(e))),
237             ExprKind::Array(ref vec) => self.multi(vec).map(Constant::Vec),
238             ExprKind::Tup(ref tup) => self.multi(tup).map(Constant::Tuple),
239             ExprKind::Repeat(ref value, _) => {
240                 let n = match self.typeck_results.expr_ty(e).kind() {
241                     ty::Array(_, n) => n.try_eval_usize(self.lcx.tcx, self.lcx.param_env)?,
242                     _ => span_bug!(e.span, "typeck error"),
243                 };
244                 self.expr(value).map(|v| Constant::Repeat(Box::new(v), n))
245             },
246             ExprKind::Unary(op, ref operand) => self.expr(operand).and_then(|o| match op {
247                 UnOp::UnNot => self.constant_not(&o, self.typeck_results.expr_ty(e)),
248                 UnOp::UnNeg => self.constant_negate(&o, self.typeck_results.expr_ty(e)),
249                 UnOp::UnDeref => Some(if let Constant::Ref(r) = o { *r } else { o }),
250             }),
251             ExprKind::Binary(op, ref left, ref right) => self.binop(op, left, right),
252             ExprKind::Call(ref callee, ref args) => {
253                 // We only handle a few const functions for now.
254                 if_chain! {
255                     if args.is_empty();
256                     if let ExprKind::Path(qpath) = &callee.kind;
257                     let res = self.typeck_results.qpath_res(qpath, callee.hir_id);
258                     if let Some(def_id) = res.opt_def_id();
259                     let def_path: Vec<_> = self.lcx.get_def_path(def_id).into_iter().map(Symbol::as_str).collect();
260                     let def_path: Vec<&str> = def_path.iter().take(4).map(|s| &**s).collect();
261                     if let ["core", "num", int_impl, "max_value"] = *def_path;
262                     then {
263                        let value = match int_impl {
264                            "<impl i8>" => i8::MAX as u128,
265                            "<impl i16>" => i16::MAX as u128,
266                            "<impl i32>" => i32::MAX as u128,
267                            "<impl i64>" => i64::MAX as u128,
268                            "<impl i128>" => i128::MAX as u128,
269                            _ => return None,
270                        };
271                        Some(Constant::Int(value))
272                     }
273                     else {
274                         None
275                     }
276                 }
277             },
278             ExprKind::Index(ref arr, ref index) => self.index(arr, index),
279             ExprKind::AddrOf(_, _, ref inner) => self.expr(inner).map(|r| Constant::Ref(Box::new(r))),
280             // TODO: add other expressions.
281             _ => None,
282         }
283     }
284
285     #[allow(clippy::cast_possible_wrap)]
286     fn constant_not(&self, o: &Constant, ty: Ty<'_>) -> Option<Constant> {
287         use self::Constant::{Bool, Int};
288         match *o {
289             Bool(b) => Some(Bool(!b)),
290             Int(value) => {
291                 let value = !value;
292                 match *ty.kind() {
293                     ty::Int(ity) => Some(Int(unsext(self.lcx.tcx, value as i128, ity))),
294                     ty::Uint(ity) => Some(Int(clip(self.lcx.tcx, value, ity))),
295                     _ => None,
296                 }
297             },
298             _ => None,
299         }
300     }
301
302     fn constant_negate(&self, o: &Constant, ty: Ty<'_>) -> Option<Constant> {
303         use self::Constant::{Int, F32, F64};
304         match *o {
305             Int(value) => {
306                 let ity = match *ty.kind() {
307                     ty::Int(ity) => ity,
308                     _ => return None,
309                 };
310                 // sign extend
311                 let value = sext(self.lcx.tcx, value, ity);
312                 let value = value.checked_neg()?;
313                 // clear unused bits
314                 Some(Int(unsext(self.lcx.tcx, value, ity)))
315             },
316             F32(f) => Some(F32(-f)),
317             F64(f) => Some(F64(-f)),
318             _ => None,
319         }
320     }
321
322     /// Create `Some(Vec![..])` of all constants, unless there is any
323     /// non-constant part.
324     fn multi(&mut self, vec: &[Expr<'_>]) -> Option<Vec<Constant>> {
325         vec.iter().map(|elem| self.expr(elem)).collect::<Option<_>>()
326     }
327
328     /// Lookup a possibly constant expression from a `ExprKind::Path`.
329     fn fetch_path(&mut self, qpath: &QPath<'_>, id: HirId, ty: Ty<'tcx>) -> Option<Constant> {
330         let res = self.typeck_results.qpath_res(qpath, id);
331         match res {
332             Res::Def(DefKind::Const | DefKind::AssocConst, def_id) => {
333                 let substs = self.typeck_results.node_substs(id);
334                 let substs = if self.substs.is_empty() {
335                     substs
336                 } else {
337                     substs.subst(self.lcx.tcx, self.substs)
338                 };
339
340                 let result = self
341                     .lcx
342                     .tcx
343                     .const_eval_resolve(
344                         self.param_env,
345                         ty::WithOptConstParam::unknown(def_id),
346                         substs,
347                         None,
348                         None,
349                     )
350                     .ok()
351                     .map(|val| rustc_middle::ty::Const::from_value(self.lcx.tcx, val, ty))?;
352                 let result = miri_to_const(&result);
353                 if result.is_some() {
354                     self.needed_resolution = true;
355                 }
356                 result
357             },
358             // FIXME: cover all usable cases.
359             _ => None,
360         }
361     }
362
363     fn index(&mut self, lhs: &'_ Expr<'_>, index: &'_ Expr<'_>) -> Option<Constant> {
364         let lhs = self.expr(lhs);
365         let index = self.expr(index);
366
367         match (lhs, index) {
368             (Some(Constant::Vec(vec)), Some(Constant::Int(index))) => match vec.get(index as usize) {
369                 Some(Constant::F32(x)) => Some(Constant::F32(*x)),
370                 Some(Constant::F64(x)) => Some(Constant::F64(*x)),
371                 _ => None,
372             },
373             (Some(Constant::Vec(vec)), _) => {
374                 if !vec.is_empty() && vec.iter().all(|x| *x == vec[0]) {
375                     match vec.get(0) {
376                         Some(Constant::F32(x)) => Some(Constant::F32(*x)),
377                         Some(Constant::F64(x)) => Some(Constant::F64(*x)),
378                         _ => None,
379                     }
380                 } else {
381                     None
382                 }
383             },
384             _ => None,
385         }
386     }
387
388     /// A block can only yield a constant if it only has one constant expression.
389     fn block(&mut self, block: &Block<'_>) -> Option<Constant> {
390         if block.stmts.is_empty() {
391             block.expr.as_ref().and_then(|b| self.expr(b))
392         } else {
393             None
394         }
395     }
396
397     fn ifthenelse(&mut self, cond: &Expr<'_>, then: &Expr<'_>, otherwise: Option<&Expr<'_>>) -> Option<Constant> {
398         if let Some(Constant::Bool(b)) = self.expr(cond) {
399             if b {
400                 self.expr(&*then)
401             } else {
402                 otherwise.as_ref().and_then(|expr| self.expr(expr))
403             }
404         } else {
405             None
406         }
407     }
408
409     fn binop(&mut self, op: BinOp, left: &Expr<'_>, right: &Expr<'_>) -> Option<Constant> {
410         let l = self.expr(left)?;
411         let r = self.expr(right);
412         match (l, r) {
413             (Constant::Int(l), Some(Constant::Int(r))) => match *self.typeck_results.expr_ty_opt(left)?.kind() {
414                 ty::Int(ity) => {
415                     let l = sext(self.lcx.tcx, l, ity);
416                     let r = sext(self.lcx.tcx, r, ity);
417                     let zext = |n: i128| Constant::Int(unsext(self.lcx.tcx, n, ity));
418                     match op.node {
419                         BinOpKind::Add => l.checked_add(r).map(zext),
420                         BinOpKind::Sub => l.checked_sub(r).map(zext),
421                         BinOpKind::Mul => l.checked_mul(r).map(zext),
422                         BinOpKind::Div if r != 0 => l.checked_div(r).map(zext),
423                         BinOpKind::Rem if r != 0 => l.checked_rem(r).map(zext),
424                         BinOpKind::Shr => l.checked_shr(r.try_into().expect("invalid shift")).map(zext),
425                         BinOpKind::Shl => l.checked_shl(r.try_into().expect("invalid shift")).map(zext),
426                         BinOpKind::BitXor => Some(zext(l ^ r)),
427                         BinOpKind::BitOr => Some(zext(l | r)),
428                         BinOpKind::BitAnd => Some(zext(l & r)),
429                         BinOpKind::Eq => Some(Constant::Bool(l == r)),
430                         BinOpKind::Ne => Some(Constant::Bool(l != r)),
431                         BinOpKind::Lt => Some(Constant::Bool(l < r)),
432                         BinOpKind::Le => Some(Constant::Bool(l <= r)),
433                         BinOpKind::Ge => Some(Constant::Bool(l >= r)),
434                         BinOpKind::Gt => Some(Constant::Bool(l > r)),
435                         _ => None,
436                     }
437                 },
438                 ty::Uint(_) => match op.node {
439                     BinOpKind::Add => l.checked_add(r).map(Constant::Int),
440                     BinOpKind::Sub => l.checked_sub(r).map(Constant::Int),
441                     BinOpKind::Mul => l.checked_mul(r).map(Constant::Int),
442                     BinOpKind::Div => l.checked_div(r).map(Constant::Int),
443                     BinOpKind::Rem => l.checked_rem(r).map(Constant::Int),
444                     BinOpKind::Shr => l.checked_shr(r.try_into().expect("shift too large")).map(Constant::Int),
445                     BinOpKind::Shl => l.checked_shl(r.try_into().expect("shift too large")).map(Constant::Int),
446                     BinOpKind::BitXor => Some(Constant::Int(l ^ r)),
447                     BinOpKind::BitOr => Some(Constant::Int(l | r)),
448                     BinOpKind::BitAnd => Some(Constant::Int(l & r)),
449                     BinOpKind::Eq => Some(Constant::Bool(l == r)),
450                     BinOpKind::Ne => Some(Constant::Bool(l != r)),
451                     BinOpKind::Lt => Some(Constant::Bool(l < r)),
452                     BinOpKind::Le => Some(Constant::Bool(l <= r)),
453                     BinOpKind::Ge => Some(Constant::Bool(l >= r)),
454                     BinOpKind::Gt => Some(Constant::Bool(l > r)),
455                     _ => None,
456                 },
457                 _ => None,
458             },
459             (Constant::F32(l), Some(Constant::F32(r))) => match op.node {
460                 BinOpKind::Add => Some(Constant::F32(l + r)),
461                 BinOpKind::Sub => Some(Constant::F32(l - r)),
462                 BinOpKind::Mul => Some(Constant::F32(l * r)),
463                 BinOpKind::Div => Some(Constant::F32(l / r)),
464                 BinOpKind::Rem => Some(Constant::F32(l % r)),
465                 BinOpKind::Eq => Some(Constant::Bool(l == r)),
466                 BinOpKind::Ne => Some(Constant::Bool(l != r)),
467                 BinOpKind::Lt => Some(Constant::Bool(l < r)),
468                 BinOpKind::Le => Some(Constant::Bool(l <= r)),
469                 BinOpKind::Ge => Some(Constant::Bool(l >= r)),
470                 BinOpKind::Gt => Some(Constant::Bool(l > r)),
471                 _ => None,
472             },
473             (Constant::F64(l), Some(Constant::F64(r))) => match op.node {
474                 BinOpKind::Add => Some(Constant::F64(l + r)),
475                 BinOpKind::Sub => Some(Constant::F64(l - r)),
476                 BinOpKind::Mul => Some(Constant::F64(l * r)),
477                 BinOpKind::Div => Some(Constant::F64(l / r)),
478                 BinOpKind::Rem => Some(Constant::F64(l % r)),
479                 BinOpKind::Eq => Some(Constant::Bool(l == r)),
480                 BinOpKind::Ne => Some(Constant::Bool(l != r)),
481                 BinOpKind::Lt => Some(Constant::Bool(l < r)),
482                 BinOpKind::Le => Some(Constant::Bool(l <= r)),
483                 BinOpKind::Ge => Some(Constant::Bool(l >= r)),
484                 BinOpKind::Gt => Some(Constant::Bool(l > r)),
485                 _ => None,
486             },
487             (l, r) => match (op.node, l, r) {
488                 (BinOpKind::And, Constant::Bool(false), _) => Some(Constant::Bool(false)),
489                 (BinOpKind::Or, Constant::Bool(true), _) => Some(Constant::Bool(true)),
490                 (BinOpKind::And, Constant::Bool(true), Some(r)) | (BinOpKind::Or, Constant::Bool(false), Some(r)) => {
491                     Some(r)
492                 },
493                 (BinOpKind::BitXor, Constant::Bool(l), Some(Constant::Bool(r))) => Some(Constant::Bool(l ^ r)),
494                 (BinOpKind::BitAnd, Constant::Bool(l), Some(Constant::Bool(r))) => Some(Constant::Bool(l & r)),
495                 (BinOpKind::BitOr, Constant::Bool(l), Some(Constant::Bool(r))) => Some(Constant::Bool(l | r)),
496                 _ => None,
497             },
498         }
499     }
500 }
501
502 pub fn miri_to_const(result: &ty::Const<'_>) -> Option<Constant> {
503     use rustc_middle::mir::interpret::{ConstValue, Scalar};
504     match result.val {
505         ty::ConstKind::Value(ConstValue::Scalar(Scalar::Raw { data: d, .. })) => {
506             match result.ty.kind() {
507                 ty::Bool => Some(Constant::Bool(d == 1)),
508                 ty::Uint(_) | ty::Int(_) => Some(Constant::Int(d)),
509                 ty::Float(FloatTy::F32) => Some(Constant::F32(f32::from_bits(
510                     d.try_into().expect("invalid f32 bit representation"),
511                 ))),
512                 ty::Float(FloatTy::F64) => Some(Constant::F64(f64::from_bits(
513                     d.try_into().expect("invalid f64 bit representation"),
514                 ))),
515                 ty::RawPtr(type_and_mut) => {
516                     if let ty::Uint(_) = type_and_mut.ty.kind() {
517                         return Some(Constant::RawPtr(d));
518                     }
519                     None
520                 },
521                 // FIXME: implement other conversions.
522                 _ => None,
523             }
524         },
525         ty::ConstKind::Value(ConstValue::Slice { data, start, end }) => match result.ty.kind() {
526             ty::Ref(_, tam, _) => match tam.kind() {
527                 ty::Str => String::from_utf8(
528                     data.inspect_with_uninit_and_ptr_outside_interpreter(start..end)
529                         .to_owned(),
530                 )
531                 .ok()
532                 .map(Constant::Str),
533                 _ => None,
534             },
535             _ => None,
536         },
537         ty::ConstKind::Value(ConstValue::ByRef { alloc, offset: _ }) => match result.ty.kind() {
538             ty::Array(sub_type, len) => match sub_type.kind() {
539                 ty::Float(FloatTy::F32) => match miri_to_const(len) {
540                     Some(Constant::Int(len)) => alloc
541                         .inspect_with_uninit_and_ptr_outside_interpreter(0..(4 * len as usize))
542                         .to_owned()
543                         .chunks(4)
544                         .map(|chunk| {
545                             Some(Constant::F32(f32::from_le_bytes(
546                                 chunk.try_into().expect("this shouldn't happen"),
547                             )))
548                         })
549                         .collect::<Option<Vec<Constant>>>()
550                         .map(Constant::Vec),
551                     _ => None,
552                 },
553                 ty::Float(FloatTy::F64) => match miri_to_const(len) {
554                     Some(Constant::Int(len)) => alloc
555                         .inspect_with_uninit_and_ptr_outside_interpreter(0..(8 * len as usize))
556                         .to_owned()
557                         .chunks(8)
558                         .map(|chunk| {
559                             Some(Constant::F64(f64::from_le_bytes(
560                                 chunk.try_into().expect("this shouldn't happen"),
561                             )))
562                         })
563                         .collect::<Option<Vec<Constant>>>()
564                         .map(Constant::Vec),
565                     _ => None,
566                 },
567                 // FIXME: implement other array type conversions.
568                 _ => None,
569             },
570             _ => None,
571         },
572         // FIXME: implement other conversions.
573         _ => None,
574     }
575 }