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