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