]> git.lizzy.rs Git - rust.git/blob - src/tools/clippy/clippy_utils/src/consts.rs
implement valtrees as the type-system representation for constant values
[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::ty::subst::{Subst, SubstsRef};
11 use rustc_middle::ty::{self, EarlyBinder, FloatTy, ScalarInt, 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::hash::{Hash, Hasher};
16 use std::iter;
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)) => 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(ref l), &Self::Bool(ref r)) => Some(l.cmp(r)),
139             (&Self::Tuple(ref l), &Self::Tuple(ref r)) | (&Self::Vec(ref l), &Self::Vec(ref r)) => iter::zip(l, r)
140                 .map(|(li, ri)| Self::partial_cmp(tcx, cmp_type, li, ri))
141                 .find(|r| r.map_or(true, |o| o != Ordering::Equal))
142                 .unwrap_or_else(|| Some(l.len().cmp(&r.len()))),
143             (&Self::Repeat(ref lv, ref ls), &Self::Repeat(ref rv, ref rs)) => {
144                 match Self::partial_cmp(tcx, cmp_type, lv, rv) {
145                     Some(Equal) => Some(ls.cmp(rs)),
146                     x => x,
147                 }
148             },
149             (&Self::Ref(ref lb), &Self::Ref(ref rb)) => Self::partial_cmp(tcx, cmp_type, lb, rb),
150             // TODO: are there any useful inter-type orderings?
151             _ => None,
152         }
153     }
154
155     /// Returns the integer value or `None` if `self` or `val_type` is not integer type.
156     pub fn int_value(&self, cx: &LateContext<'_>, val_type: Ty<'_>) -> Option<FullInt> {
157         if let Constant::Int(const_int) = *self {
158             match *val_type.kind() {
159                 ty::Int(ity) => Some(FullInt::S(sext(cx.tcx, const_int, ity))),
160                 ty::Uint(_) => Some(FullInt::U(const_int)),
161                 _ => None,
162             }
163         } else {
164             None
165         }
166     }
167
168     #[must_use]
169     pub fn peel_refs(mut self) -> Self {
170         while let Constant::Ref(r) = self {
171             self = *r;
172         }
173         self
174     }
175 }
176
177 /// Parses a `LitKind` to a `Constant`.
178 pub fn lit_to_mir_constant(lit: &LitKind, ty: Option<Ty<'_>>) -> Constant {
179     match *lit {
180         LitKind::Str(ref is, _) => Constant::Str(is.to_string()),
181         LitKind::Byte(b) => Constant::Int(u128::from(b)),
182         LitKind::ByteStr(ref s) => Constant::Binary(Lrc::clone(s)),
183         LitKind::Char(c) => Constant::Char(c),
184         LitKind::Int(n, _) => Constant::Int(n),
185         LitKind::Float(ref is, LitFloatType::Suffixed(fty)) => match fty {
186             ast::FloatTy::F32 => Constant::F32(is.as_str().parse().unwrap()),
187             ast::FloatTy::F64 => Constant::F64(is.as_str().parse().unwrap()),
188         },
189         LitKind::Float(ref is, LitFloatType::Unsuffixed) => match ty.expect("type of float is known").kind() {
190             ty::Float(FloatTy::F32) => Constant::F32(is.as_str().parse().unwrap()),
191             ty::Float(FloatTy::F64) => Constant::F64(is.as_str().parse().unwrap()),
192             _ => bug!(),
193         },
194         LitKind::Bool(b) => Constant::Bool(b),
195         LitKind::Err(s) => Constant::Err(s),
196     }
197 }
198
199 pub fn constant<'tcx>(
200     lcx: &LateContext<'tcx>,
201     typeck_results: &ty::TypeckResults<'tcx>,
202     e: &Expr<'_>,
203 ) -> Option<(Constant, bool)> {
204     let mut cx = ConstEvalLateContext {
205         lcx,
206         typeck_results,
207         param_env: lcx.param_env,
208         needed_resolution: false,
209         substs: lcx.tcx.intern_substs(&[]),
210     };
211     cx.expr(e).map(|cst| (cst, cx.needed_resolution))
212 }
213
214 pub fn constant_simple<'tcx>(
215     lcx: &LateContext<'tcx>,
216     typeck_results: &ty::TypeckResults<'tcx>,
217     e: &Expr<'_>,
218 ) -> Option<Constant> {
219     constant(lcx, typeck_results, e).and_then(|(cst, res)| if res { None } else { Some(cst) })
220 }
221
222 pub fn constant_full_int<'tcx>(
223     lcx: &LateContext<'tcx>,
224     typeck_results: &ty::TypeckResults<'tcx>,
225     e: &Expr<'_>,
226 ) -> Option<FullInt> {
227     constant_simple(lcx, typeck_results, e)?.int_value(lcx, typeck_results.expr_ty(e))
228 }
229
230 #[derive(Copy, Clone, Debug, Eq)]
231 pub enum FullInt {
232     S(i128),
233     U(u128),
234 }
235
236 impl PartialEq for FullInt {
237     #[must_use]
238     fn eq(&self, other: &Self) -> bool {
239         self.cmp(other) == Ordering::Equal
240     }
241 }
242
243 impl PartialOrd for FullInt {
244     #[must_use]
245     fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
246         Some(self.cmp(other))
247     }
248 }
249
250 impl Ord for FullInt {
251     #[must_use]
252     fn cmp(&self, other: &Self) -> Ordering {
253         use FullInt::{S, U};
254
255         fn cmp_s_u(s: i128, u: u128) -> Ordering {
256             u128::try_from(s).map_or(Ordering::Less, |x| x.cmp(&u))
257         }
258
259         match (*self, *other) {
260             (S(s), S(o)) => s.cmp(&o),
261             (U(s), U(o)) => s.cmp(&o),
262             (S(s), U(o)) => cmp_s_u(s, o),
263             (U(s), S(o)) => cmp_s_u(o, s).reverse(),
264         }
265     }
266 }
267
268 /// Creates a `ConstEvalLateContext` from the given `LateContext` and `TypeckResults`.
269 pub fn constant_context<'a, 'tcx>(
270     lcx: &'a LateContext<'tcx>,
271     typeck_results: &'a ty::TypeckResults<'tcx>,
272 ) -> ConstEvalLateContext<'a, 'tcx> {
273     ConstEvalLateContext {
274         lcx,
275         typeck_results,
276         param_env: lcx.param_env,
277         needed_resolution: false,
278         substs: lcx.tcx.intern_substs(&[]),
279     }
280 }
281
282 pub struct ConstEvalLateContext<'a, 'tcx> {
283     lcx: &'a LateContext<'tcx>,
284     typeck_results: &'a ty::TypeckResults<'tcx>,
285     param_env: ty::ParamEnv<'tcx>,
286     needed_resolution: bool,
287     substs: SubstsRef<'tcx>,
288 }
289
290 impl<'a, 'tcx> ConstEvalLateContext<'a, 'tcx> {
291     /// Simple constant folding: Insert an expression, get a constant or none.
292     pub fn expr(&mut self, e: &Expr<'_>) -> Option<Constant> {
293         match e.kind {
294             ExprKind::Path(ref qpath) => self.fetch_path(qpath, e.hir_id, self.typeck_results.expr_ty(e)),
295             ExprKind::Block(block, _) => self.block(block),
296             ExprKind::Lit(ref lit) => {
297                 if is_direct_expn_of(e.span, "cfg").is_some() {
298                     None
299                 } else {
300                     Some(lit_to_mir_constant(&lit.node, self.typeck_results.expr_ty_opt(e)))
301                 }
302             },
303             ExprKind::Array(vec) => self.multi(vec).map(Constant::Vec),
304             ExprKind::Tup(tup) => self.multi(tup).map(Constant::Tuple),
305             ExprKind::Repeat(value, _) => {
306                 let n = match self.typeck_results.expr_ty(e).kind() {
307                     ty::Array(_, n) => n.try_eval_usize(self.lcx.tcx, self.lcx.param_env)?,
308                     _ => span_bug!(e.span, "typeck error"),
309                 };
310                 self.expr(value).map(|v| Constant::Repeat(Box::new(v), n))
311             },
312             ExprKind::Unary(op, operand) => self.expr(operand).and_then(|o| match op {
313                 UnOp::Not => self.constant_not(&o, self.typeck_results.expr_ty(e)),
314                 UnOp::Neg => self.constant_negate(&o, self.typeck_results.expr_ty(e)),
315                 UnOp::Deref => Some(if let Constant::Ref(r) = o { *r } else { o }),
316             }),
317             ExprKind::If(cond, then, ref otherwise) => self.ifthenelse(cond, then, *otherwise),
318             ExprKind::Binary(op, left, right) => self.binop(op, left, right),
319             ExprKind::Call(callee, args) => {
320                 // We only handle a few const functions for now.
321                 if_chain! {
322                     if args.is_empty();
323                     if let ExprKind::Path(qpath) = &callee.kind;
324                     let res = self.typeck_results.qpath_res(qpath, callee.hir_id);
325                     if let Some(def_id) = res.opt_def_id();
326                     let def_path = self.lcx.get_def_path(def_id);
327                     let def_path: Vec<&str> = def_path.iter().take(4).map(Symbol::as_str).collect();
328                     if let ["core", "num", int_impl, "max_value"] = *def_path;
329                     then {
330                         let value = match int_impl {
331                             "<impl i8>" => i8::MAX as u128,
332                             "<impl i16>" => i16::MAX as u128,
333                             "<impl i32>" => i32::MAX as u128,
334                             "<impl i64>" => i64::MAX as u128,
335                             "<impl i128>" => i128::MAX as u128,
336                             _ => return None,
337                         };
338                         Some(Constant::Int(value))
339                     } else {
340                         None
341                     }
342                 }
343             },
344             ExprKind::Index(arr, index) => self.index(arr, index),
345             ExprKind::AddrOf(_, _, inner) => self.expr(inner).map(|r| Constant::Ref(Box::new(r))),
346             // TODO: add other expressions.
347             _ => None,
348         }
349     }
350
351     #[expect(clippy::cast_possible_wrap)]
352     fn constant_not(&self, o: &Constant, ty: Ty<'_>) -> Option<Constant> {
353         use self::Constant::{Bool, Int};
354         match *o {
355             Bool(b) => Some(Bool(!b)),
356             Int(value) => {
357                 let value = !value;
358                 match *ty.kind() {
359                     ty::Int(ity) => Some(Int(unsext(self.lcx.tcx, value as i128, ity))),
360                     ty::Uint(ity) => Some(Int(clip(self.lcx.tcx, value, ity))),
361                     _ => None,
362                 }
363             },
364             _ => None,
365         }
366     }
367
368     fn constant_negate(&self, o: &Constant, ty: Ty<'_>) -> Option<Constant> {
369         use self::Constant::{Int, F32, F64};
370         match *o {
371             Int(value) => {
372                 let ity = match *ty.kind() {
373                     ty::Int(ity) => ity,
374                     _ => return None,
375                 };
376                 // sign extend
377                 let value = sext(self.lcx.tcx, value, ity);
378                 let value = value.checked_neg()?;
379                 // clear unused bits
380                 Some(Int(unsext(self.lcx.tcx, value, ity)))
381             },
382             F32(f) => Some(F32(-f)),
383             F64(f) => Some(F64(-f)),
384             _ => None,
385         }
386     }
387
388     /// Create `Some(Vec![..])` of all constants, unless there is any
389     /// non-constant part.
390     fn multi(&mut self, vec: &[Expr<'_>]) -> Option<Vec<Constant>> {
391         vec.iter().map(|elem| self.expr(elem)).collect::<Option<_>>()
392     }
393
394     /// Lookup a possibly constant expression from an `ExprKind::Path`.
395     fn fetch_path(&mut self, qpath: &QPath<'_>, id: HirId, ty: Ty<'tcx>) -> Option<Constant> {
396         let res = self.typeck_results.qpath_res(qpath, id);
397         match res {
398             Res::Def(DefKind::Const | DefKind::AssocConst, def_id) => {
399                 // Check if this constant is based on `cfg!(..)`,
400                 // which is NOT constant for our purposes.
401                 if let Some(node) = self.lcx.tcx.hir().get_if_local(def_id) &&
402                 let Node::Item(&Item {
403                     kind: ItemKind::Const(_, body_id),
404                     ..
405                 }) = node &&
406                 let Node::Expr(&Expr {
407                     kind: ExprKind::Lit(_),
408                     span,
409                     ..
410                 }) = self.lcx.tcx.hir().get(body_id.hir_id) &&
411                 is_direct_expn_of(span, "cfg").is_some() {
412                     return None;
413                 }
414
415                 let substs = self.typeck_results.node_substs(id);
416                 let substs = if self.substs.is_empty() {
417                     substs
418                 } else {
419                     EarlyBinder(substs).subst(self.lcx.tcx, self.substs)
420                 };
421
422                 let result = self
423                     .lcx
424                     .tcx
425                     .const_eval_resolve_for_typeck(
426                         self.param_env,
427                         ty::Unevaluated::new(ty::WithOptConstParam::unknown(def_id), substs),
428                         None,
429                     )
430                     .ok()
431                     .and_then(|val| val.map(|val| rustc_middle::ty::Const::from_value(self.lcx.tcx, val, ty)))?;
432                 let result = miri_to_const(self.lcx.tcx, result);
433                 if result.is_some() {
434                     self.needed_resolution = true;
435                 }
436                 result
437             },
438             // FIXME: cover all usable cases.
439             _ => None,
440         }
441     }
442
443     fn index(&mut self, lhs: &'_ Expr<'_>, index: &'_ Expr<'_>) -> Option<Constant> {
444         let lhs = self.expr(lhs);
445         let index = self.expr(index);
446
447         match (lhs, index) {
448             (Some(Constant::Vec(vec)), Some(Constant::Int(index))) => match vec.get(index as usize) {
449                 Some(Constant::F32(x)) => Some(Constant::F32(*x)),
450                 Some(Constant::F64(x)) => Some(Constant::F64(*x)),
451                 _ => None,
452             },
453             (Some(Constant::Vec(vec)), _) => {
454                 if !vec.is_empty() && vec.iter().all(|x| *x == vec[0]) {
455                     match vec.get(0) {
456                         Some(Constant::F32(x)) => Some(Constant::F32(*x)),
457                         Some(Constant::F64(x)) => Some(Constant::F64(*x)),
458                         _ => None,
459                     }
460                 } else {
461                     None
462                 }
463             },
464             _ => None,
465         }
466     }
467
468     /// A block can only yield a constant if it only has one constant expression.
469     fn block(&mut self, block: &Block<'_>) -> Option<Constant> {
470         if block.stmts.is_empty() {
471             block.expr.as_ref().and_then(|b| self.expr(b))
472         } else {
473             None
474         }
475     }
476
477     fn ifthenelse(&mut self, cond: &Expr<'_>, then: &Expr<'_>, otherwise: Option<&Expr<'_>>) -> Option<Constant> {
478         if let Some(Constant::Bool(b)) = self.expr(cond) {
479             if b {
480                 self.expr(then)
481             } else {
482                 otherwise.as_ref().and_then(|expr| self.expr(expr))
483             }
484         } else {
485             None
486         }
487     }
488
489     fn binop(&mut self, op: BinOp, left: &Expr<'_>, right: &Expr<'_>) -> Option<Constant> {
490         let l = self.expr(left)?;
491         let r = self.expr(right);
492         match (l, r) {
493             (Constant::Int(l), Some(Constant::Int(r))) => match *self.typeck_results.expr_ty_opt(left)?.kind() {
494                 ty::Int(ity) => {
495                     let l = sext(self.lcx.tcx, l, ity);
496                     let r = sext(self.lcx.tcx, r, ity);
497                     let zext = |n: i128| Constant::Int(unsext(self.lcx.tcx, n, ity));
498                     match op.node {
499                         BinOpKind::Add => l.checked_add(r).map(zext),
500                         BinOpKind::Sub => l.checked_sub(r).map(zext),
501                         BinOpKind::Mul => l.checked_mul(r).map(zext),
502                         BinOpKind::Div if r != 0 => l.checked_div(r).map(zext),
503                         BinOpKind::Rem if r != 0 => l.checked_rem(r).map(zext),
504                         BinOpKind::Shr => l.checked_shr(r.try_into().expect("invalid shift")).map(zext),
505                         BinOpKind::Shl => l.checked_shl(r.try_into().expect("invalid shift")).map(zext),
506                         BinOpKind::BitXor => Some(zext(l ^ r)),
507                         BinOpKind::BitOr => Some(zext(l | r)),
508                         BinOpKind::BitAnd => Some(zext(l & r)),
509                         BinOpKind::Eq => Some(Constant::Bool(l == r)),
510                         BinOpKind::Ne => Some(Constant::Bool(l != r)),
511                         BinOpKind::Lt => Some(Constant::Bool(l < r)),
512                         BinOpKind::Le => Some(Constant::Bool(l <= r)),
513                         BinOpKind::Ge => Some(Constant::Bool(l >= r)),
514                         BinOpKind::Gt => Some(Constant::Bool(l > r)),
515                         _ => None,
516                     }
517                 },
518                 ty::Uint(_) => match op.node {
519                     BinOpKind::Add => l.checked_add(r).map(Constant::Int),
520                     BinOpKind::Sub => l.checked_sub(r).map(Constant::Int),
521                     BinOpKind::Mul => l.checked_mul(r).map(Constant::Int),
522                     BinOpKind::Div => l.checked_div(r).map(Constant::Int),
523                     BinOpKind::Rem => l.checked_rem(r).map(Constant::Int),
524                     BinOpKind::Shr => l.checked_shr(r.try_into().expect("shift too large")).map(Constant::Int),
525                     BinOpKind::Shl => l.checked_shl(r.try_into().expect("shift too large")).map(Constant::Int),
526                     BinOpKind::BitXor => Some(Constant::Int(l ^ r)),
527                     BinOpKind::BitOr => Some(Constant::Int(l | r)),
528                     BinOpKind::BitAnd => Some(Constant::Int(l & r)),
529                     BinOpKind::Eq => Some(Constant::Bool(l == r)),
530                     BinOpKind::Ne => Some(Constant::Bool(l != r)),
531                     BinOpKind::Lt => Some(Constant::Bool(l < r)),
532                     BinOpKind::Le => Some(Constant::Bool(l <= r)),
533                     BinOpKind::Ge => Some(Constant::Bool(l >= r)),
534                     BinOpKind::Gt => Some(Constant::Bool(l > r)),
535                     _ => None,
536                 },
537                 _ => None,
538             },
539             (Constant::F32(l), Some(Constant::F32(r))) => match op.node {
540                 BinOpKind::Add => Some(Constant::F32(l + r)),
541                 BinOpKind::Sub => Some(Constant::F32(l - r)),
542                 BinOpKind::Mul => Some(Constant::F32(l * r)),
543                 BinOpKind::Div => Some(Constant::F32(l / r)),
544                 BinOpKind::Rem => Some(Constant::F32(l % r)),
545                 BinOpKind::Eq => Some(Constant::Bool(l == r)),
546                 BinOpKind::Ne => Some(Constant::Bool(l != r)),
547                 BinOpKind::Lt => Some(Constant::Bool(l < r)),
548                 BinOpKind::Le => Some(Constant::Bool(l <= r)),
549                 BinOpKind::Ge => Some(Constant::Bool(l >= r)),
550                 BinOpKind::Gt => Some(Constant::Bool(l > r)),
551                 _ => None,
552             },
553             (Constant::F64(l), Some(Constant::F64(r))) => match op.node {
554                 BinOpKind::Add => Some(Constant::F64(l + r)),
555                 BinOpKind::Sub => Some(Constant::F64(l - r)),
556                 BinOpKind::Mul => Some(Constant::F64(l * r)),
557                 BinOpKind::Div => Some(Constant::F64(l / r)),
558                 BinOpKind::Rem => Some(Constant::F64(l % r)),
559                 BinOpKind::Eq => Some(Constant::Bool(l == r)),
560                 BinOpKind::Ne => Some(Constant::Bool(l != r)),
561                 BinOpKind::Lt => Some(Constant::Bool(l < r)),
562                 BinOpKind::Le => Some(Constant::Bool(l <= r)),
563                 BinOpKind::Ge => Some(Constant::Bool(l >= r)),
564                 BinOpKind::Gt => Some(Constant::Bool(l > r)),
565                 _ => None,
566             },
567             (l, r) => match (op.node, l, r) {
568                 (BinOpKind::And, Constant::Bool(false), _) => Some(Constant::Bool(false)),
569                 (BinOpKind::Or, Constant::Bool(true), _) => Some(Constant::Bool(true)),
570                 (BinOpKind::And, Constant::Bool(true), Some(r)) | (BinOpKind::Or, Constant::Bool(false), Some(r)) => {
571                     Some(r)
572                 },
573                 (BinOpKind::BitXor, Constant::Bool(l), Some(Constant::Bool(r))) => Some(Constant::Bool(l ^ r)),
574                 (BinOpKind::BitAnd, Constant::Bool(l), Some(Constant::Bool(r))) => Some(Constant::Bool(l & r)),
575                 (BinOpKind::BitOr, Constant::Bool(l), Some(Constant::Bool(r))) => Some(Constant::Bool(l | r)),
576                 _ => None,
577             },
578         }
579     }
580 }
581
582 pub fn miri_to_const<'tcx>(tcx: TyCtxt<'tcx>, result: ty::Const<'tcx>) -> Option<Constant> {
583     match result.kind() {
584         ty::ConstKind::Value(valtree) => {
585             match (valtree, result.ty().kind()) {
586                 (ty::ValTree::Leaf(int), ty::Bool) => Some(Constant::Bool(int == ScalarInt::TRUE)),
587                 (ty::ValTree::Leaf(int), ty::Uint(_) | ty::Int(_)) => Some(Constant::Int(int.assert_bits(int.size()))),
588                 (ty::ValTree::Leaf(int), ty::Float(FloatTy::F32)) => Some(Constant::F32(f32::from_bits(
589                     int.try_into().expect("invalid f32 bit representation"),
590                 ))),
591                 (ty::ValTree::Leaf(int), ty::Float(FloatTy::F64)) => Some(Constant::F64(f64::from_bits(
592                     int.try_into().expect("invalid f64 bit representation"),
593                 ))),
594                 (ty::ValTree::Leaf(int), ty::RawPtr(type_and_mut)) => {
595                     if let ty::Uint(_) = type_and_mut.ty.kind() {
596                         return Some(Constant::RawPtr(int.assert_bits(int.size())));
597                     }
598                     None
599                 },
600                 (ty::ValTree::Branch(_), ty::Ref(_, inner_ty, _)) if *inner_ty == tcx.types.str_ => valtree
601                     .try_to_raw_bytes(tcx, result.ty())
602                     .and_then(|bytes| String::from_utf8(bytes.to_owned()).ok().map(Constant::Str)),
603                 (ty::ValTree::Branch(_), ty::Array(arr_ty, len)) => match arr_ty.kind() {
604                     ty::Float(float_ty) => {
605                         let chunk_size = match float_ty {
606                             FloatTy::F32 => 4,
607                             FloatTy::F64 => 8,
608                         };
609
610                         match miri_to_const(tcx, *len) {
611                             Some(Constant::Int(_)) => valtree.try_to_raw_bytes(tcx, result.ty()).and_then(|bytes| {
612                                 bytes
613                                     .to_owned()
614                                     .chunks(chunk_size)
615                                     .map(|chunk| match float_ty {
616                                         FloatTy::F32 => {
617                                             let float = f32::from_le_bytes(
618                                                 chunk
619                                                     .try_into()
620                                                     .expect(&format!("expected to construct f32 from {:?}", chunk)),
621                                             );
622                                             Some(Constant::F32(float))
623                                         },
624                                         FloatTy::F64 => {
625                                             let float = f64::from_le_bytes(
626                                                 chunk
627                                                     .try_into()
628                                                     .expect(&format!("expected to construct f64 from {:?}", chunk)),
629                                             );
630                                             Some(Constant::F64(float))
631                                         },
632                                     })
633                                     .collect::<Option<Vec<Constant>>>()
634                                     .map(Constant::Vec)
635                             }),
636                             _ => None,
637                         }
638                     },
639                     _ => None,
640                 },
641                 // FIXME: implement other conversions.
642                 _ => None,
643             }
644         },
645         _ => None,
646     }
647 }