]> git.lizzy.rs Git - rust.git/blob - src/consts.rs
lint ! and != in if expressions with else branches
[rust.git] / src / consts.rs
1 #![allow(cast_possible_truncation)]
2
3 use rustc::lint::LateContext;
4 use rustc::middle::const_eval::lookup_const_by_id;
5 use rustc::middle::def::{Def, PathResolution};
6 use rustc_front::hir::*;
7 use std::cmp::Ordering::{self, Greater, Less, Equal};
8 use std::cmp::PartialOrd;
9 use std::hash::{Hash, Hasher};
10 use std::mem;
11 use std::ops::Deref;
12 use std::rc::Rc;
13 use syntax::ast::{FloatTy, LitIntType, LitKind, StrStyle, UintTy};
14 use syntax::ptr::P;
15
16 #[derive(Debug, Copy, Clone)]
17 pub enum FloatWidth {
18     F32,
19     F64,
20     Any,
21 }
22
23 impl From<FloatTy> for FloatWidth {
24     fn from(ty: FloatTy) -> FloatWidth {
25         match ty {
26             FloatTy::F32 => FloatWidth::F32,
27             FloatTy::F64 => FloatWidth::F64,
28         }
29     }
30 }
31
32 #[derive(Copy, Eq, Debug, Clone, PartialEq, Hash)]
33 pub enum Sign {
34     Plus,
35     Minus,
36 }
37
38 /// a Lit_-like enum to fold constant `Expr`s into
39 #[derive(Debug, Clone)]
40 pub enum Constant {
41     /// a String "abc"
42     Str(String, StrStyle),
43     /// a Binary String b"abc"
44     Binary(Rc<Vec<u8>>),
45     /// a single byte b'a'
46     Byte(u8),
47     /// a single char 'a'
48     Char(char),
49     /// an integer, third argument is whether the value is negated
50     Int(u64, LitIntType, Sign),
51     /// a float with given type
52     Float(String, FloatWidth),
53     /// true or false
54     Bool(bool),
55     /// an array of constants
56     Vec(Vec<Constant>),
57     /// also an array, but with only one constant, repeated N times
58     Repeat(Box<Constant>, usize),
59     /// a tuple of constants
60     Tuple(Vec<Constant>),
61 }
62
63 impl Constant {
64     /// convert to u64 if possible
65     ///
66     /// # panics
67     ///
68     /// if the constant could not be converted to u64 losslessly
69     fn as_u64(&self) -> u64 {
70         if let Constant::Int(val, _, _) = *self {
71             val // TODO we may want to check the sign if any
72         } else {
73             panic!("Could not convert a {:?} to u64", self);
74         }
75     }
76
77     /// convert this constant to a f64, if possible
78     #[allow(cast_precision_loss)]
79     pub fn as_float(&self) -> Option<f64> {
80         match *self {
81             Constant::Byte(b) => Some(b as f64),
82             Constant::Float(ref s, _) => s.parse().ok(),
83             Constant::Int(i, _, Sign::Minus) => Some(-(i as f64)),
84             Constant::Int(i, _, Sign::Plus) => Some(i as f64),
85             _ => None,
86         }
87     }
88 }
89
90 impl PartialEq for Constant {
91     fn eq(&self, other: &Constant) -> bool {
92         match (self, other) {
93             (&Constant::Str(ref ls, ref lsty), &Constant::Str(ref rs, ref rsty)) => ls == rs && lsty == rsty,
94             (&Constant::Binary(ref l), &Constant::Binary(ref r)) => l == r,
95             (&Constant::Byte(l), &Constant::Byte(r)) => l == r,
96             (&Constant::Char(l), &Constant::Char(r)) => l == r,
97             (&Constant::Int(0, _, _), &Constant::Int(0, _, _)) => true,
98             (&Constant::Int(lv, _, lneg), &Constant::Int(rv, _, rneg)) => lv == rv && lneg == rneg,
99             (&Constant::Float(ref ls, _), &Constant::Float(ref rs, _)) => {
100                 // we want `Fw32 == FwAny` and `FwAny == Fw64`, by transitivity we must have
101                 // `Fw32 == Fw64` so don’t compare them
102                 match (ls.parse::<f64>(), rs.parse::<f64>()) {
103                     (Ok(l), Ok(r)) => l.eq(&r),
104                     _ => false,
105                 }
106             }
107             (&Constant::Bool(l), &Constant::Bool(r)) => l == r,
108             (&Constant::Vec(ref l), &Constant::Vec(ref r)) => l == r,
109             (&Constant::Repeat(ref lv, ref ls), &Constant::Repeat(ref rv, ref rs)) => ls == rs && lv == rv,
110             (&Constant::Tuple(ref l), &Constant::Tuple(ref r)) => l == r,
111             _ => false, //TODO: Are there inter-type equalities?
112         }
113     }
114 }
115
116 impl Hash for Constant {
117     fn hash<H>(&self, state: &mut H)
118         where H: Hasher
119     {
120         match *self {
121             Constant::Str(ref s, ref k) => {
122                 s.hash(state);
123                 k.hash(state);
124             }
125             Constant::Binary(ref b) => {
126                 b.hash(state);
127             }
128             Constant::Byte(u) => {
129                 u.hash(state);
130             }
131             Constant::Char(c) => {
132                 c.hash(state);
133             }
134             Constant::Int(u, _, t) => {
135                 u.hash(state);
136                 t.hash(state);
137             }
138             Constant::Float(ref f, _) => {
139                 // don’t use the width here because of PartialEq implementation
140                 if let Ok(f) = f.parse::<f64>() {
141                     unsafe { mem::transmute::<f64, u64>(f) }.hash(state);
142                 }
143             }
144             Constant::Bool(b) => {
145                 b.hash(state);
146             }
147             Constant::Vec(ref v) | Constant::Tuple(ref v) => {
148                 v.hash(state);
149             }
150             Constant::Repeat(ref c, l) => {
151                 c.hash(state);
152                 l.hash(state);
153             }
154         }
155     }
156 }
157
158 impl PartialOrd for Constant {
159     fn partial_cmp(&self, other: &Constant) -> Option<Ordering> {
160         match (self, other) {
161             (&Constant::Str(ref ls, ref lsty), &Constant::Str(ref rs, ref rsty)) => {
162                 if lsty == rsty {
163                     Some(ls.cmp(rs))
164                 } else {
165                     None
166                 }
167             }
168             (&Constant::Byte(ref l), &Constant::Byte(ref r)) => Some(l.cmp(r)),
169             (&Constant::Char(ref l), &Constant::Char(ref r)) => Some(l.cmp(r)),
170             (&Constant::Int(0, _, _), &Constant::Int(0, _, _)) => Some(Equal),
171             (&Constant::Int(ref lv, _, Sign::Plus), &Constant::Int(ref rv, _, Sign::Plus)) => Some(lv.cmp(rv)),
172             (&Constant::Int(ref lv, _, Sign::Minus), &Constant::Int(ref rv, _, Sign::Minus)) => Some(rv.cmp(lv)),
173             (&Constant::Int(_, _, Sign::Minus), &Constant::Int(_, _, Sign::Plus)) => Some(Less),
174             (&Constant::Int(_, _, Sign::Plus), &Constant::Int(_, _, Sign::Minus)) => Some(Greater),
175             (&Constant::Float(ref ls, _), &Constant::Float(ref rs, _)) => {
176                 match (ls.parse::<f64>(), rs.parse::<f64>()) {
177                     (Ok(ref l), Ok(ref r)) => l.partial_cmp(r),
178                     _ => None,
179                 }
180             }
181             (&Constant::Bool(ref l), &Constant::Bool(ref r)) => Some(l.cmp(r)),
182             (&Constant::Vec(ref l), &Constant::Vec(ref r)) => l.partial_cmp(&r),
183             (&Constant::Repeat(ref lv, ref ls), &Constant::Repeat(ref rv, ref rs)) => {
184                 match lv.partial_cmp(rv) {
185                     Some(Equal) => Some(ls.cmp(rs)),
186                     x => x,
187                 }
188             }
189             (&Constant::Tuple(ref l), &Constant::Tuple(ref r)) => l.partial_cmp(r),
190             _ => None, //TODO: Are there any useful inter-type orderings?
191         }
192     }
193 }
194
195 fn lit_to_constant(lit: &LitKind) -> Constant {
196     match *lit {
197         LitKind::Str(ref is, style) => Constant::Str(is.to_string(), style),
198         LitKind::Byte(b) => Constant::Byte(b),
199         LitKind::ByteStr(ref s) => Constant::Binary(s.clone()),
200         LitKind::Char(c) => Constant::Char(c),
201         LitKind::Int(value, ty) => Constant::Int(value, ty, Sign::Plus),
202         LitKind::Float(ref is, ty) => Constant::Float(is.to_string(), ty.into()),
203         LitKind::FloatUnsuffixed(ref is) => Constant::Float(is.to_string(), FloatWidth::Any),
204         LitKind::Bool(b) => Constant::Bool(b),
205     }
206 }
207
208 fn constant_not(o: Constant) -> Option<Constant> {
209     use self::Constant::*;
210     match o {
211         Bool(b) => Some(Bool(!b)),
212         Int(value, LitIntType::Signed(ity), Sign::Plus) if value != ::std::u64::MAX => {
213             Some(Int(value + 1, LitIntType::Signed(ity), Sign::Minus))
214         }
215         Int(0, LitIntType::Signed(ity), Sign::Minus) => Some(Int(1, LitIntType::Signed(ity), Sign::Minus)),
216         Int(value, LitIntType::Signed(ity), Sign::Minus) => Some(Int(value - 1, LitIntType::Signed(ity), Sign::Plus)),
217         Int(value, LitIntType::Unsigned(ity), Sign::Plus) => {
218             let mask = match ity {
219                 UintTy::U8 => ::std::u8::MAX as u64,
220                 UintTy::U16 => ::std::u16::MAX as u64,
221                 UintTy::U32 => ::std::u32::MAX as u64,
222                 UintTy::U64 => ::std::u64::MAX,
223                 UintTy::Us => {
224                     return None;
225                 }  // refuse to guess
226             };
227             Some(Int(!value & mask, LitIntType::Unsigned(ity), Sign::Plus))
228         }
229         _ => None,
230     }
231 }
232
233 fn constant_negate(o: Constant) -> Option<Constant> {
234     use self::Constant::*;
235     match o {
236         Int(value, LitIntType::Signed(ity), sign) => Some(Int(value, LitIntType::Signed(ity), neg_sign(sign))),
237         Int(value, LitIntType::Unsuffixed, sign) => Some(Int(value, LitIntType::Unsuffixed, neg_sign(sign))),
238         Float(is, ty) => Some(Float(neg_float_str(is), ty)),
239         _ => None,
240     }
241 }
242
243 fn neg_sign(s: Sign) -> Sign {
244     match s {
245         Sign::Plus => Sign::Minus,
246         Sign::Minus => Sign::Plus,
247     }
248 }
249
250 fn neg_float_str(s: String) -> String {
251     if s.starts_with('-') {
252         s[1..].to_owned()
253     } else {
254         format!("-{}", s)
255     }
256 }
257
258 fn unify_int_type(l: LitIntType, r: LitIntType) -> Option<LitIntType> {
259     use syntax::ast::LitIntType::*;
260     match (l, r) {
261         (Signed(lty), Signed(rty)) => {
262             if lty == rty {
263                 Some(LitIntType::Signed(lty))
264             } else {
265                 None
266             }
267         }
268         (Unsigned(lty), Unsigned(rty)) => {
269             if lty == rty {
270                 Some(LitIntType::Unsigned(lty))
271             } else {
272                 None
273             }
274         }
275         (Unsuffixed, Unsuffixed) => Some(Unsuffixed),
276         (Signed(lty), Unsuffixed) => Some(Signed(lty)),
277         (Unsigned(lty), Unsuffixed) => Some(Unsigned(lty)),
278         (Unsuffixed, Signed(rty)) => Some(Signed(rty)),
279         (Unsuffixed, Unsigned(rty)) => Some(Unsigned(rty)),
280         _ => None,
281     }
282 }
283
284 pub fn constant(lcx: &LateContext, e: &Expr) -> Option<(Constant, bool)> {
285     let mut cx = ConstEvalLateContext {
286         lcx: Some(lcx),
287         needed_resolution: false,
288     };
289     cx.expr(e).map(|cst| (cst, cx.needed_resolution))
290 }
291
292 pub fn constant_simple(e: &Expr) -> Option<Constant> {
293     let mut cx = ConstEvalLateContext {
294         lcx: None,
295         needed_resolution: false,
296     };
297     cx.expr(e)
298 }
299
300 struct ConstEvalLateContext<'c, 'cc: 'c> {
301     lcx: Option<&'c LateContext<'c, 'cc>>,
302     needed_resolution: bool,
303 }
304
305 impl<'c, 'cc> ConstEvalLateContext<'c, 'cc> {
306     /// simple constant folding: Insert an expression, get a constant or none.
307     fn expr(&mut self, e: &Expr) -> Option<Constant> {
308         match e.node {
309             ExprPath(_, _) => self.fetch_path(e),
310             ExprBlock(ref block) => self.block(block),
311             ExprIf(ref cond, ref then, ref otherwise) => self.ifthenelse(cond, then, otherwise),
312             ExprLit(ref lit) => Some(lit_to_constant(&lit.node)),
313             ExprVec(ref vec) => self.multi(vec).map(Constant::Vec),
314             ExprTup(ref tup) => self.multi(tup).map(Constant::Tuple),
315             ExprRepeat(ref value, ref number) => {
316                 self.binop_apply(value, number, |v, n| Some(Constant::Repeat(Box::new(v), n.as_u64() as usize)))
317             }
318             ExprUnary(op, ref operand) => {
319                 self.expr(operand).and_then(|o| {
320                     match op {
321                         UnNot => constant_not(o),
322                         UnNeg => constant_negate(o),
323                         UnDeref => Some(o),
324                     }
325                 })
326             }
327             ExprBinary(op, ref left, ref right) => self.binop(op, left, right),
328             // TODO: add other expressions
329             _ => None,
330         }
331     }
332
333     /// create `Some(Vec![..])` of all constants, unless there is any
334     /// non-constant part
335     fn multi<E: Deref<Target = Expr> + Sized>(&mut self, vec: &[E]) -> Option<Vec<Constant>> {
336         vec.iter()
337            .map(|elem| self.expr(elem))
338            .collect::<Option<_>>()
339     }
340
341     /// lookup a possibly constant expression from a ExprPath
342     fn fetch_path(&mut self, e: &Expr) -> Option<Constant> {
343         if let Some(lcx) = self.lcx {
344             let mut maybe_id = None;
345             if let Some(&PathResolution { base_def: Def::Const(id), ..}) = lcx.tcx.def_map.borrow().get(&e.id) {
346                 maybe_id = Some(id);
347             }
348             // separate if lets to avoid double borrowing the def_map
349             if let Some(id) = maybe_id {
350                 if let Some(const_expr) = lookup_const_by_id(lcx.tcx, id, None, None) {
351                     let ret = self.expr(const_expr);
352                     if ret.is_some() {
353                         self.needed_resolution = true;
354                     }
355                     return ret;
356                 }
357             }
358         }
359         None
360     }
361
362     /// A block can only yield a constant if it only has one constant expression
363     fn block(&mut self, block: &Block) -> Option<Constant> {
364         if block.stmts.is_empty() {
365             block.expr.as_ref().and_then(|ref b| self.expr(b))
366         } else {
367             None
368         }
369     }
370
371     fn ifthenelse(&mut self, cond: &Expr, then: &Block, otherwise: &Option<P<Expr>>) -> Option<Constant> {
372         if let Some(Constant::Bool(b)) = self.expr(cond) {
373             if b {
374                 self.block(then)
375             } else {
376                 otherwise.as_ref().and_then(|expr| self.expr(expr))
377             }
378         } else {
379             None
380         }
381     }
382
383     fn binop(&mut self, op: BinOp, left: &Expr, right: &Expr) -> Option<Constant> {
384         match op.node {
385             BiAdd => {
386                 self.binop_apply(left, right, |l, r| {
387                     match (l, r) {
388                         (Constant::Byte(l8), Constant::Byte(r8)) => l8.checked_add(r8).map(Constant::Byte),
389                         (Constant::Int(l64, lty, lsign), Constant::Int(r64, rty, rsign)) => {
390                             add_ints(l64, r64, lty, rty, lsign, rsign)
391                         }
392                         // TODO: float (would need bignum library?)
393                         _ => None,
394                     }
395                 })
396             }
397             BiSub => {
398                 self.binop_apply(left, right, |l, r| {
399                     match (l, r) {
400                         (Constant::Byte(l8), Constant::Byte(r8)) => {
401                             if r8 > l8 {
402                                 None
403                             } else {
404                                 Some(Constant::Byte(l8 - r8))
405                             }
406                         }
407                         (Constant::Int(l64, lty, lsign), Constant::Int(r64, rty, rsign)) => {
408                             add_ints(l64, r64, lty, rty, lsign, neg_sign(rsign))
409                         }
410                         _ => None,
411                     }
412                 })
413             }
414             BiMul => self.divmul(left, right, u64::checked_mul),
415             BiDiv => self.divmul(left, right, u64::checked_div),
416             // BiRem,
417             BiAnd => self.short_circuit(left, right, false),
418             BiOr => self.short_circuit(left, right, true),
419             BiBitXor => self.bitop(left, right, |x, y| x ^ y),
420             BiBitAnd => self.bitop(left, right, |x, y| x & y),
421             BiBitOr => self.bitop(left, right, |x, y| (x | y)),
422             BiShl => self.bitop(left, right, |x, y| x << y),
423             BiShr => self.bitop(left, right, |x, y| x >> y),
424             BiEq => self.binop_apply(left, right, |l, r| Some(Constant::Bool(l == r))),
425             BiNe => self.binop_apply(left, right, |l, r| Some(Constant::Bool(l != r))),
426             BiLt => self.cmp(left, right, Less, true),
427             BiLe => self.cmp(left, right, Greater, false),
428             BiGe => self.cmp(left, right, Less, false),
429             BiGt => self.cmp(left, right, Greater, true),
430             _ => None,
431         }
432     }
433
434     fn divmul<F>(&mut self, left: &Expr, right: &Expr, f: F) -> Option<Constant>
435         where F: Fn(u64, u64) -> Option<u64>
436     {
437         self.binop_apply(left, right, |l, r| {
438             match (l, r) {
439                 (Constant::Int(l64, lty, lsign), Constant::Int(r64, rty, rsign)) => {
440                     f(l64, r64).and_then(|value| {
441                         let sign = if lsign == rsign {
442                             Sign::Plus
443                         } else {
444                             Sign::Minus
445                         };
446                         unify_int_type(lty, rty).map(|ty| Constant::Int(value, ty, sign))
447                     })
448                 }
449                 _ => None,
450             }
451         })
452     }
453
454     fn bitop<F>(&mut self, left: &Expr, right: &Expr, f: F) -> Option<Constant>
455         where F: Fn(u64, u64) -> u64
456     {
457         self.binop_apply(left, right, |l, r| {
458             match (l, r) {
459                 (Constant::Bool(l), Constant::Bool(r)) => Some(Constant::Bool(f(l as u64, r as u64) != 0)),
460                 (Constant::Byte(l8), Constant::Byte(r8)) => Some(Constant::Byte(f(l8 as u64, r8 as u64) as u8)),
461                 (Constant::Int(l, lty, lsign), Constant::Int(r, rty, rsign)) => {
462                     if lsign == Sign::Plus && rsign == Sign::Plus {
463                         unify_int_type(lty, rty).map(|ty| Constant::Int(f(l, r), ty, Sign::Plus))
464                     } else {
465                         None
466                     }
467                 }
468                 _ => None,
469             }
470         })
471     }
472
473     fn cmp(&mut self, left: &Expr, right: &Expr, ordering: Ordering, b: bool) -> Option<Constant> {
474         self.binop_apply(left,
475                          right,
476                          |l, r| l.partial_cmp(&r).map(|o| Constant::Bool(b == (o == ordering))))
477     }
478
479     fn binop_apply<F>(&mut self, left: &Expr, right: &Expr, op: F) -> Option<Constant>
480         where F: Fn(Constant, Constant) -> Option<Constant>
481     {
482         if let (Some(lc), Some(rc)) = (self.expr(left), self.expr(right)) {
483             op(lc, rc)
484         } else {
485             None
486         }
487     }
488
489     fn short_circuit(&mut self, left: &Expr, right: &Expr, b: bool) -> Option<Constant> {
490         self.expr(left).and_then(|left| {
491             if let Constant::Bool(lbool) = left {
492                 if lbool == b {
493                     Some(left)
494                 } else {
495                     self.expr(right).and_then(|right| {
496                         if let Constant::Bool(_) = right {
497                             Some(right)
498                         } else {
499                             None
500                         }
501                     })
502                 }
503             } else {
504                 None
505             }
506         })
507     }
508 }
509
510 fn add_ints(l64: u64, r64: u64, lty: LitIntType, rty: LitIntType, lsign: Sign, rsign: Sign) -> Option<Constant> {
511     let ty = if let Some(ty) = unify_int_type(lty, rty) {
512         ty
513     } else {
514         return None;
515     };
516
517     match (lsign, rsign) {
518         (Sign::Plus, Sign::Plus) => l64.checked_add(r64).map(|v| Constant::Int(v, ty, Sign::Plus)),
519         (Sign::Plus, Sign::Minus) => {
520             if r64 > l64 {
521                 Some(Constant::Int(r64 - l64, ty, Sign::Minus))
522             } else {
523                 Some(Constant::Int(l64 - r64, ty, Sign::Plus))
524             }
525         }
526         (Sign::Minus, Sign::Minus) => l64.checked_add(r64).map(|v| Constant::Int(v, ty, Sign::Minus)),
527         (Sign::Minus, Sign::Plus) => {
528             if l64 > r64 {
529                 Some(Constant::Int(l64 - r64, ty, Sign::Minus))
530             } else {
531                 Some(Constant::Int(r64 - l64, ty, Sign::Plus))
532             }
533         }
534     }
535 }