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