mirror of
https://github.com/rust-lang/rust-clippy
synced 2024-11-18 02:38:28 +00:00
Merge pull request #196 from birkenfeld/const_struct
[rfc] consts: convert to using a struct with state
This commit is contained in:
commit
8a9e03dd9f
4 changed files with 289 additions and 330 deletions
587
src/consts.rs
587
src/consts.rs
|
@ -8,7 +8,7 @@ use std::cmp::PartialOrd;
|
|||
use std::cmp::Ordering::{self, Greater, Less, Equal};
|
||||
use std::rc::Rc;
|
||||
use std::ops::Deref;
|
||||
use self::ConstantVariant::*;
|
||||
use self::Constant::*;
|
||||
use self::FloatWidth::*;
|
||||
|
||||
#[derive(PartialEq, Eq, Debug, Copy, Clone)]
|
||||
|
@ -27,42 +27,9 @@ impl From<FloatTy> for FloatWidth {
|
|||
}
|
||||
}
|
||||
|
||||
#[derive(PartialEq, Eq, Debug, Clone)]
|
||||
pub struct Constant {
|
||||
pub constant: ConstantVariant,
|
||||
pub needed_resolution: bool
|
||||
}
|
||||
|
||||
impl Constant {
|
||||
pub fn new(variant: ConstantVariant) -> Constant {
|
||||
Constant { constant: variant, needed_resolution: false }
|
||||
}
|
||||
|
||||
pub fn new_resolved(variant: ConstantVariant) -> Constant {
|
||||
Constant { constant: variant, needed_resolution: true }
|
||||
}
|
||||
|
||||
// convert this constant to a f64, if possible
|
||||
pub fn as_float(&self) -> Option<f64> {
|
||||
match &self.constant {
|
||||
&ConstantByte(b) => Some(b as f64),
|
||||
&ConstantFloat(ref s, _) => s.parse().ok(),
|
||||
&ConstantInt(i, ty) => Some(if is_negative(ty) {
|
||||
-(i as f64) } else { i as f64 }),
|
||||
_ => None
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl PartialOrd for Constant {
|
||||
fn partial_cmp(&self, other: &Constant) -> Option<Ordering> {
|
||||
self.constant.partial_cmp(&other.constant)
|
||||
}
|
||||
}
|
||||
|
||||
/// a Lit_-like enum to fold constant `Expr`s into
|
||||
#[derive(Eq, Debug, Clone)]
|
||||
pub enum ConstantVariant {
|
||||
pub enum Constant {
|
||||
/// a String "abc"
|
||||
ConstantStr(String, StrStyle),
|
||||
/// a Binary String b"abc"
|
||||
|
@ -80,12 +47,12 @@ pub enum ConstantVariant {
|
|||
/// an array of constants
|
||||
ConstantVec(Vec<Constant>),
|
||||
/// also an array, but with only one constant, repeated N times
|
||||
ConstantRepeat(Box<ConstantVariant>, usize),
|
||||
ConstantRepeat(Box<Constant>, usize),
|
||||
/// a tuple of constants
|
||||
ConstantTuple(Vec<Constant>),
|
||||
}
|
||||
|
||||
impl ConstantVariant {
|
||||
impl Constant {
|
||||
/// convert to u64 if possible
|
||||
///
|
||||
/// # panics
|
||||
|
@ -98,10 +65,21 @@ impl ConstantVariant {
|
|||
panic!("Could not convert a {:?} to u64");
|
||||
}
|
||||
}
|
||||
|
||||
/// convert this constant to a f64, if possible
|
||||
pub fn as_float(&self) -> Option<f64> {
|
||||
match *self {
|
||||
ConstantByte(b) => Some(b as f64),
|
||||
ConstantFloat(ref s, _) => s.parse().ok(),
|
||||
ConstantInt(i, ty) => Some(if is_negative(ty) {
|
||||
-(i as f64) } else { i as f64 }),
|
||||
_ => None
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl PartialEq for ConstantVariant {
|
||||
fn eq(&self, other: &ConstantVariant) -> bool {
|
||||
impl PartialEq for Constant {
|
||||
fn eq(&self, other: &Constant) -> bool {
|
||||
match (self, other) {
|
||||
(&ConstantStr(ref ls, ref lsty), &ConstantStr(ref rs, ref rsty)) =>
|
||||
ls == rs && lsty == rsty,
|
||||
|
@ -130,8 +108,8 @@ impl PartialEq for ConstantVariant {
|
|||
}
|
||||
}
|
||||
|
||||
impl PartialOrd for ConstantVariant {
|
||||
fn partial_cmp(&self, other: &ConstantVariant) -> Option<Ordering> {
|
||||
impl PartialOrd for Constant {
|
||||
fn partial_cmp(&self, other: &Constant) -> Option<Ordering> {
|
||||
match (self, other) {
|
||||
(&ConstantStr(ref ls, ref lsty), &ConstantStr(ref rs, ref rsty)) =>
|
||||
if lsty != rsty { None } else { Some(ls.cmp(rs)) },
|
||||
|
@ -168,173 +146,67 @@ impl PartialOrd for ConstantVariant {
|
|||
}
|
||||
}
|
||||
|
||||
/// simple constant folding: Insert an expression, get a constant or none.
|
||||
pub fn constant(cx: &Context, e: &Expr) -> Option<Constant> {
|
||||
match &e.node {
|
||||
&ExprParen(ref inner) => constant(cx, inner),
|
||||
&ExprPath(_, _) => fetch_path(cx, e),
|
||||
&ExprBlock(ref block) => constant_block(cx, block),
|
||||
&ExprIf(ref cond, ref then, ref otherwise) =>
|
||||
constant_if(cx, &*cond, &*then, &*otherwise),
|
||||
&ExprLit(ref lit) => Some(lit_to_constant(&lit.node)),
|
||||
&ExprVec(ref vec) => constant_vec(cx, &vec[..]),
|
||||
&ExprTup(ref tup) => constant_tup(cx, &tup[..]),
|
||||
&ExprRepeat(ref value, ref number) =>
|
||||
constant_binop_apply(cx, value, number,|v, n|
|
||||
Some(ConstantRepeat(Box::new(v), n.as_u64() as usize))),
|
||||
&ExprUnary(op, ref operand) => constant(cx, operand).and_then(
|
||||
|o| match op {
|
||||
UnNot => constant_not(o),
|
||||
UnNeg => constant_negate(o),
|
||||
UnUniq | UnDeref => Some(o),
|
||||
}),
|
||||
&ExprBinary(op, ref left, ref right) =>
|
||||
constant_binop(cx, op, left, right),
|
||||
//TODO: add other expressions
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
fn lit_to_constant(lit: &Lit_) -> Constant {
|
||||
match lit {
|
||||
&LitStr(ref is, style) =>
|
||||
Constant::new(ConstantStr(is.to_string(), style)),
|
||||
&LitBinary(ref blob) => Constant::new(ConstantBinary(blob.clone())),
|
||||
&LitByte(b) => Constant::new(ConstantByte(b)),
|
||||
&LitChar(c) => Constant::new(ConstantChar(c)),
|
||||
&LitInt(value, ty) => Constant::new(ConstantInt(value, ty)),
|
||||
&LitFloat(ref is, ty) => {
|
||||
Constant::new(ConstantFloat(is.to_string(), ty.into()))
|
||||
},
|
||||
&LitFloatUnsuffixed(ref is) => {
|
||||
Constant::new(ConstantFloat(is.to_string(), FwAny))
|
||||
},
|
||||
&LitBool(b) => Constant::new(ConstantBool(b)),
|
||||
&LitStr(ref is, style) => ConstantStr(is.to_string(), style),
|
||||
&LitBinary(ref blob) => ConstantBinary(blob.clone()),
|
||||
&LitByte(b) => ConstantByte(b),
|
||||
&LitChar(c) => ConstantChar(c),
|
||||
&LitInt(value, ty) => ConstantInt(value, ty),
|
||||
&LitFloat(ref is, ty) => ConstantFloat(is.to_string(), ty.into()),
|
||||
&LitFloatUnsuffixed(ref is) => ConstantFloat(is.to_string(), FwAny),
|
||||
&LitBool(b) => ConstantBool(b),
|
||||
}
|
||||
}
|
||||
|
||||
/// create `Some(ConstantVec(..))` of all constants, unless there is any
|
||||
/// non-constant part
|
||||
fn constant_vec<E: Deref<Target=Expr> + Sized>(cx: &Context, vec: &[E]) -> Option<Constant> {
|
||||
let mut parts = Vec::new();
|
||||
let mut resolved = false;
|
||||
for opt_part in vec {
|
||||
match constant(cx, opt_part) {
|
||||
Some(p) => {
|
||||
resolved |= p.needed_resolution;
|
||||
parts.push(p)
|
||||
},
|
||||
None => { return None; },
|
||||
}
|
||||
}
|
||||
Some(Constant {
|
||||
constant: ConstantVec(parts),
|
||||
needed_resolution: resolved
|
||||
})
|
||||
}
|
||||
|
||||
fn constant_tup<E: Deref<Target=Expr> + Sized>(cx: &Context, tup: &[E]) -> Option<Constant> {
|
||||
let mut parts = Vec::new();
|
||||
let mut resolved = false;
|
||||
for opt_part in tup {
|
||||
match constant(cx, opt_part) {
|
||||
Some(p) => {
|
||||
resolved |= p.needed_resolution;
|
||||
parts.push(p)
|
||||
},
|
||||
None => { return None; },
|
||||
}
|
||||
}
|
||||
Some(Constant {
|
||||
constant: ConstantTuple(parts),
|
||||
needed_resolution: resolved
|
||||
})
|
||||
}
|
||||
|
||||
/// lookup a possibly constant expression from a ExprPath
|
||||
fn fetch_path(cx: &Context, e: &Expr) -> Option<Constant> {
|
||||
if let Some(&PathResolution { base_def: DefConst(id), ..}) =
|
||||
cx.tcx.def_map.borrow().get(&e.id) {
|
||||
lookup_const_by_id(cx.tcx, id, None).and_then(
|
||||
|l| constant(cx, l).map(|c| Constant::new_resolved(c.constant)))
|
||||
} else { None }
|
||||
}
|
||||
|
||||
/// A block can only yield a constant if it only has one constant expression
|
||||
fn constant_block(cx: &Context, block: &Block) -> Option<Constant> {
|
||||
if block.stmts.is_empty() {
|
||||
block.expr.as_ref().and_then(|b| constant(cx, &*b))
|
||||
} else { None }
|
||||
}
|
||||
|
||||
fn constant_if(cx: &Context, cond: &Expr, then: &Block, otherwise:
|
||||
&Option<P<Expr>>) -> Option<Constant> {
|
||||
if let Some(Constant{ constant: ConstantBool(b), needed_resolution: res }) =
|
||||
constant(cx, cond) {
|
||||
if b {
|
||||
constant_block(cx, then)
|
||||
} else {
|
||||
otherwise.as_ref().and_then(|expr| constant(cx, &*expr))
|
||||
}.map(|part|
|
||||
Constant {
|
||||
constant: part.constant,
|
||||
needed_resolution: res || part.needed_resolution,
|
||||
})
|
||||
} else { None }
|
||||
}
|
||||
|
||||
fn constant_not(o: Constant) -> Option<Constant> {
|
||||
Some(Constant {
|
||||
needed_resolution: o.needed_resolution,
|
||||
constant: match o.constant {
|
||||
ConstantBool(b) => ConstantBool(!b),
|
||||
ConstantInt(value, ty) => {
|
||||
let (nvalue, nty) = match ty {
|
||||
SignedIntLit(ity, Plus) => {
|
||||
if value == ::std::u64::MAX { return None; }
|
||||
(value + 1, SignedIntLit(ity, Minus))
|
||||
},
|
||||
SignedIntLit(ity, Minus) => {
|
||||
if value == 0 {
|
||||
(1, SignedIntLit(ity, Minus))
|
||||
} else {
|
||||
(value - 1, SignedIntLit(ity, Plus))
|
||||
}
|
||||
Some(match o {
|
||||
ConstantBool(b) => ConstantBool(!b),
|
||||
ConstantInt(value, ty) => {
|
||||
let (nvalue, nty) = match ty {
|
||||
SignedIntLit(ity, Plus) => {
|
||||
if value == ::std::u64::MAX { return None; }
|
||||
(value + 1, SignedIntLit(ity, Minus))
|
||||
},
|
||||
SignedIntLit(ity, Minus) => {
|
||||
if value == 0 {
|
||||
(1, SignedIntLit(ity, Minus))
|
||||
} else {
|
||||
(value - 1, SignedIntLit(ity, Plus))
|
||||
}
|
||||
UnsignedIntLit(ity) => {
|
||||
let mask = match ity {
|
||||
UintTy::TyU8 => ::std::u8::MAX as u64,
|
||||
UintTy::TyU16 => ::std::u16::MAX as u64,
|
||||
UintTy::TyU32 => ::std::u32::MAX as u64,
|
||||
UintTy::TyU64 => ::std::u64::MAX,
|
||||
UintTy::TyUs => { return None; } // refuse to guess
|
||||
};
|
||||
(!value & mask, UnsignedIntLit(ity))
|
||||
}
|
||||
UnsuffixedIntLit(_) => { return None; } // refuse to guess
|
||||
};
|
||||
ConstantInt(nvalue, nty)
|
||||
},
|
||||
_ => { return None; }
|
||||
}
|
||||
}
|
||||
UnsignedIntLit(ity) => {
|
||||
let mask = match ity {
|
||||
UintTy::TyU8 => ::std::u8::MAX as u64,
|
||||
UintTy::TyU16 => ::std::u16::MAX as u64,
|
||||
UintTy::TyU32 => ::std::u32::MAX as u64,
|
||||
UintTy::TyU64 => ::std::u64::MAX,
|
||||
UintTy::TyUs => { return None; } // refuse to guess
|
||||
};
|
||||
(!value & mask, UnsignedIntLit(ity))
|
||||
}
|
||||
UnsuffixedIntLit(_) => { return None; } // refuse to guess
|
||||
};
|
||||
ConstantInt(nvalue, nty)
|
||||
},
|
||||
_ => { return None; }
|
||||
})
|
||||
}
|
||||
|
||||
fn constant_negate(o: Constant) -> Option<Constant> {
|
||||
Some(Constant{
|
||||
needed_resolution: o.needed_resolution,
|
||||
constant: match o.constant {
|
||||
ConstantInt(value, ty) =>
|
||||
ConstantInt(value, match ty {
|
||||
SignedIntLit(ity, sign) =>
|
||||
SignedIntLit(ity, neg_sign(sign)),
|
||||
UnsuffixedIntLit(sign) => UnsuffixedIntLit(neg_sign(sign)),
|
||||
_ => { return None; },
|
||||
}),
|
||||
ConstantFloat(is, ty) =>
|
||||
ConstantFloat(neg_float_str(is), ty),
|
||||
_ => { return None; },
|
||||
}
|
||||
Some(match o {
|
||||
ConstantInt(value, ty) =>
|
||||
ConstantInt(value, match ty {
|
||||
SignedIntLit(ity, sign) =>
|
||||
SignedIntLit(ity, neg_sign(sign)),
|
||||
UnsuffixedIntLit(sign) => UnsuffixedIntLit(neg_sign(sign)),
|
||||
_ => { return None; },
|
||||
}),
|
||||
ConstantFloat(is, ty) =>
|
||||
ConstantFloat(neg_float_str(is), ty),
|
||||
_ => { return None; },
|
||||
})
|
||||
}
|
||||
|
||||
|
@ -386,92 +258,8 @@ fn unify_int_type(l: LitIntType, r: LitIntType, s: Sign) -> Option<LitIntType> {
|
|||
}
|
||||
}
|
||||
|
||||
fn constant_binop(cx: &Context, op: BinOp, left: &Expr, right: &Expr)
|
||||
-> Option<Constant> {
|
||||
match op.node {
|
||||
BiAdd => constant_binop_apply(cx, left, right, |l, r|
|
||||
match (l, r) {
|
||||
(ConstantByte(l8), ConstantByte(r8)) =>
|
||||
l8.checked_add(r8).map(ConstantByte),
|
||||
(ConstantInt(l64, lty), ConstantInt(r64, rty)) => {
|
||||
let (ln, rn) = (is_negative(lty), is_negative(rty));
|
||||
if ln == rn {
|
||||
unify_int_type(lty, rty, if ln { Minus } else { Plus })
|
||||
.and_then(|ty| l64.checked_add(r64).map(
|
||||
|v| ConstantInt(v, ty)))
|
||||
} else {
|
||||
if ln {
|
||||
add_neg_int(r64, rty, l64, lty)
|
||||
} else {
|
||||
add_neg_int(l64, lty, r64, rty)
|
||||
}
|
||||
}
|
||||
},
|
||||
// TODO: float (would need bignum library?)
|
||||
_ => None
|
||||
}),
|
||||
BiSub => constant_binop_apply(cx, left, right, |l, r|
|
||||
match (l, r) {
|
||||
(ConstantByte(l8), ConstantByte(r8)) => if r8 > l8 {
|
||||
None } else { Some(ConstantByte(l8 - r8)) },
|
||||
(ConstantInt(l64, lty), ConstantInt(r64, rty)) => {
|
||||
let (ln, rn) = (is_negative(lty), is_negative(rty));
|
||||
match (ln, rn) {
|
||||
(false, false) => sub_int(l64, lty, r64, rty, r64 > l64),
|
||||
(true, true) => sub_int(l64, lty, r64, rty, l64 > r64),
|
||||
(true, false) => unify_int_type(lty, rty, Minus)
|
||||
.and_then(|ty| l64.checked_add(r64).map(
|
||||
|v| ConstantInt(v, ty))),
|
||||
(false, true) => unify_int_type(lty, rty, Plus)
|
||||
.and_then(|ty| l64.checked_add(r64).map(
|
||||
|v| ConstantInt(v, ty))),
|
||||
}
|
||||
},
|
||||
_ => None,
|
||||
}),
|
||||
//BiMul,
|
||||
//BiDiv,
|
||||
//BiRem,
|
||||
BiAnd => constant_short_circuit(cx, left, right, false),
|
||||
BiOr => constant_short_circuit(cx, left, right, true),
|
||||
BiBitXor => constant_bitop(cx, left, right, |x, y| x ^ y),
|
||||
BiBitAnd => constant_bitop(cx, left, right, |x, y| x & y),
|
||||
BiBitOr => constant_bitop(cx, left, right, |x, y| (x | y)),
|
||||
BiShl => constant_bitop(cx, left, right, |x, y| x << y),
|
||||
BiShr => constant_bitop(cx, left, right, |x, y| x >> y),
|
||||
BiEq => constant_binop_apply(cx, left, right,
|
||||
|l, r| Some(ConstantBool(l == r))),
|
||||
BiNe => constant_binop_apply(cx, left, right,
|
||||
|l, r| Some(ConstantBool(l != r))),
|
||||
BiLt => constant_cmp(cx, left, right, Less, true),
|
||||
BiLe => constant_cmp(cx, left, right, Greater, false),
|
||||
BiGe => constant_cmp(cx, left, right, Less, false),
|
||||
BiGt => constant_cmp(cx, left, right, Greater, true),
|
||||
_ => None
|
||||
}
|
||||
}
|
||||
|
||||
fn constant_bitop<F>(cx: &Context, left: &Expr, right: &Expr, f: F)
|
||||
-> Option<Constant> where F: Fn(u64, u64) -> u64 {
|
||||
constant_binop_apply(cx, left, right, |l, r| match (l, r) {
|
||||
(ConstantBool(l), ConstantBool(r)) =>
|
||||
Some(ConstantBool(f(l as u64, r as u64) != 0)),
|
||||
(ConstantByte(l8), ConstantByte(r8)) =>
|
||||
Some(ConstantByte(f(l8 as u64, r8 as u64) as u8)),
|
||||
(ConstantInt(l, lty), ConstantInt(r, rty)) =>
|
||||
unify_int_type(lty, rty, Plus).map(|ty| ConstantInt(f(l, r), ty)),
|
||||
_ => None
|
||||
})
|
||||
}
|
||||
|
||||
fn constant_cmp(cx: &Context, left: &Expr, right: &Expr, ordering: Ordering,
|
||||
b: bool) -> Option<Constant> {
|
||||
constant_binop_apply(cx, left, right, |l, r| l.partial_cmp(&r).map(|o|
|
||||
ConstantBool(b == (o == ordering))))
|
||||
}
|
||||
|
||||
fn add_neg_int(pos: u64, pty: LitIntType, neg: u64, nty: LitIntType) ->
|
||||
Option<ConstantVariant> {
|
||||
Option<Constant> {
|
||||
if neg > pos {
|
||||
unify_int_type(nty, pty, Minus).map(|ty| ConstantInt(neg - pos, ty))
|
||||
} else {
|
||||
|
@ -480,42 +268,221 @@ fn add_neg_int(pos: u64, pty: LitIntType, neg: u64, nty: LitIntType) ->
|
|||
}
|
||||
|
||||
fn sub_int(l: u64, lty: LitIntType, r: u64, rty: LitIntType, neg: bool) ->
|
||||
Option<ConstantVariant> {
|
||||
Option<Constant> {
|
||||
unify_int_type(lty, rty, if neg { Minus } else { Plus }).and_then(
|
||||
|ty| l.checked_sub(r).map(|v| ConstantInt(v, ty)))
|
||||
}
|
||||
|
||||
fn constant_binop_apply<F>(cx: &Context, left: &Expr, right: &Expr, op: F)
|
||||
-> Option<Constant>
|
||||
where F: Fn(ConstantVariant, ConstantVariant) -> Option<ConstantVariant> {
|
||||
if let (Some(Constant { constant: lc, needed_resolution: ln }),
|
||||
Some(Constant { constant: rc, needed_resolution: rn })) =
|
||||
(constant(cx, left), constant(cx, right)) {
|
||||
op(lc, rc).map(|c|
|
||||
Constant {
|
||||
needed_resolution: ln || rn,
|
||||
constant: c,
|
||||
})
|
||||
} else { None }
|
||||
|
||||
pub fn constant(lcx: &Context, e: &Expr) -> Option<(Constant, bool)> {
|
||||
let mut cx = ConstEvalContext { lcx: Some(lcx), needed_resolution: false };
|
||||
cx.expr(e).map(|cst| (cst, cx.needed_resolution))
|
||||
}
|
||||
|
||||
fn constant_short_circuit(cx: &Context, left: &Expr, right: &Expr, b: bool) ->
|
||||
Option<Constant> {
|
||||
constant(cx, left).and_then(|left|
|
||||
if let &ConstantBool(lbool) = &left.constant {
|
||||
if lbool == b {
|
||||
Some(left)
|
||||
pub fn constant_simple(e: &Expr) -> Option<Constant> {
|
||||
let mut cx = ConstEvalContext { lcx: None, needed_resolution: false };
|
||||
cx.expr(e)
|
||||
}
|
||||
|
||||
struct ConstEvalContext<'c, 'cc: 'c> {
|
||||
lcx: Option<&'c Context<'c, 'cc>>,
|
||||
needed_resolution: bool
|
||||
}
|
||||
|
||||
impl<'c, 'cc> ConstEvalContext<'c, 'cc> {
|
||||
|
||||
/// simple constant folding: Insert an expression, get a constant or none.
|
||||
fn expr(&mut self, e: &Expr) -> Option<Constant> {
|
||||
match &e.node {
|
||||
&ExprParen(ref inner) => self.expr(inner),
|
||||
&ExprPath(_, _) => self.fetch_path(e),
|
||||
&ExprBlock(ref block) => self.block(block),
|
||||
&ExprIf(ref cond, ref then, ref otherwise) =>
|
||||
self.ifthenelse(&*cond, &*then, &*otherwise),
|
||||
&ExprLit(ref lit) => Some(lit_to_constant(&lit.node)),
|
||||
&ExprVec(ref vec) => self.vec(&vec[..]),
|
||||
&ExprTup(ref tup) => self.tup(&tup[..]),
|
||||
&ExprRepeat(ref value, ref number) =>
|
||||
self.binop_apply(value, number,|v, n|
|
||||
Some(ConstantRepeat(Box::new(v), n.as_u64() as usize))),
|
||||
&ExprUnary(op, ref operand) => self.expr(operand).and_then(
|
||||
|o| match op {
|
||||
UnNot => constant_not(o),
|
||||
UnNeg => constant_negate(o),
|
||||
UnUniq | UnDeref => Some(o),
|
||||
}),
|
||||
&ExprBinary(op, ref left, ref right) =>
|
||||
self.binop(op, left, right),
|
||||
//TODO: add other expressions
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// create `Some(ConstantVec(..))` of all constants, unless there is any
|
||||
/// non-constant part
|
||||
fn vec<E: Deref<Target=Expr> + Sized>(&mut self, vec: &[E]) -> Option<Constant> {
|
||||
let mut parts = Vec::new();
|
||||
for opt_part in vec {
|
||||
match self.expr(opt_part) {
|
||||
Some(p) => {
|
||||
parts.push(p)
|
||||
},
|
||||
None => { return None; },
|
||||
}
|
||||
}
|
||||
Some(ConstantVec(parts))
|
||||
}
|
||||
|
||||
fn tup<E: Deref<Target=Expr> + Sized>(&mut self, tup: &[E]) -> Option<Constant> {
|
||||
let mut parts = Vec::new();
|
||||
for opt_part in tup {
|
||||
match self.expr(opt_part) {
|
||||
Some(p) => {
|
||||
parts.push(p)
|
||||
},
|
||||
None => { return None; },
|
||||
}
|
||||
}
|
||||
Some(ConstantTuple(parts),)
|
||||
}
|
||||
|
||||
/// lookup a possibly constant expression from a ExprPath
|
||||
fn fetch_path(&mut self, e: &Expr) -> Option<Constant> {
|
||||
if let Some(lcx) = self.lcx {
|
||||
if let Some(&PathResolution { base_def: DefConst(id), ..}) =
|
||||
lcx.tcx.def_map.borrow().get(&e.id) {
|
||||
if let Some(const_expr) = lookup_const_by_id(lcx.tcx, id, None) {
|
||||
let ret = self.expr(const_expr);
|
||||
if ret.is_some() {
|
||||
self.needed_resolution = true;
|
||||
}
|
||||
return ret;
|
||||
}
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// A block can only yield a constant if it only has one constant expression
|
||||
fn block(&mut self, block: &Block) -> Option<Constant> {
|
||||
if block.stmts.is_empty() {
|
||||
block.expr.as_ref().and_then(|b| self.expr(&*b))
|
||||
} else { None }
|
||||
}
|
||||
|
||||
fn ifthenelse(&mut self, cond: &Expr, then: &Block, otherwise: &Option<P<Expr>>)
|
||||
-> Option<Constant> {
|
||||
if let Some(ConstantBool(b)) = self.expr(cond) {
|
||||
if b {
|
||||
self.block(then)
|
||||
} else {
|
||||
constant(cx, right).and_then(|right|
|
||||
if let ConstantBool(_) = right.constant {
|
||||
Some(Constant {
|
||||
constant: right.constant,
|
||||
needed_resolution: left.needed_resolution ||
|
||||
right.needed_resolution,
|
||||
})
|
||||
} else { None }
|
||||
)
|
||||
otherwise.as_ref().and_then(|expr| self.expr(&*expr))
|
||||
}
|
||||
} else { None }
|
||||
)
|
||||
}
|
||||
|
||||
fn binop(&mut self, op: BinOp, left: &Expr, right: &Expr) -> Option<Constant> {
|
||||
match op.node {
|
||||
BiAdd => self.binop_apply(left, right, |l, r|
|
||||
match (l, r) {
|
||||
(ConstantByte(l8), ConstantByte(r8)) =>
|
||||
l8.checked_add(r8).map(ConstantByte),
|
||||
(ConstantInt(l64, lty), ConstantInt(r64, rty)) => {
|
||||
let (ln, rn) = (is_negative(lty), is_negative(rty));
|
||||
if ln == rn {
|
||||
unify_int_type(lty, rty, if ln { Minus } else { Plus })
|
||||
.and_then(|ty| l64.checked_add(r64).map(
|
||||
|v| ConstantInt(v, ty)))
|
||||
} else {
|
||||
if ln {
|
||||
add_neg_int(r64, rty, l64, lty)
|
||||
} else {
|
||||
add_neg_int(l64, lty, r64, rty)
|
||||
}
|
||||
}
|
||||
},
|
||||
// TODO: float (would need bignum library?)
|
||||
_ => None
|
||||
}),
|
||||
BiSub => self.binop_apply(left, right, |l, r|
|
||||
match (l, r) {
|
||||
(ConstantByte(l8), ConstantByte(r8)) => if r8 > l8 {
|
||||
None } else { Some(ConstantByte(l8 - r8)) },
|
||||
(ConstantInt(l64, lty), ConstantInt(r64, rty)) => {
|
||||
let (ln, rn) = (is_negative(lty), is_negative(rty));
|
||||
match (ln, rn) {
|
||||
(false, false) => sub_int(l64, lty, r64, rty, r64 > l64),
|
||||
(true, true) => sub_int(l64, lty, r64, rty, l64 > r64),
|
||||
(true, false) => unify_int_type(lty, rty, Minus)
|
||||
.and_then(|ty| l64.checked_add(r64).map(
|
||||
|v| ConstantInt(v, ty))),
|
||||
(false, true) => unify_int_type(lty, rty, Plus)
|
||||
.and_then(|ty| l64.checked_add(r64).map(
|
||||
|v| ConstantInt(v, ty))),
|
||||
}
|
||||
},
|
||||
_ => None,
|
||||
}),
|
||||
//BiMul,
|
||||
//BiDiv,
|
||||
//BiRem,
|
||||
BiAnd => self.short_circuit(left, right, false),
|
||||
BiOr => self.short_circuit(left, right, true),
|
||||
BiBitXor => self.bitop(left, right, |x, y| x ^ y),
|
||||
BiBitAnd => self.bitop(left, right, |x, y| x & y),
|
||||
BiBitOr => self.bitop(left, right, |x, y| (x | y)),
|
||||
BiShl => self.bitop(left, right, |x, y| x << y),
|
||||
BiShr => self.bitop(left, right, |x, y| x >> y),
|
||||
BiEq => self.binop_apply(left, right,
|
||||
|l, r| Some(ConstantBool(l == r))),
|
||||
BiNe => self.binop_apply(left, right,
|
||||
|l, r| Some(ConstantBool(l != r))),
|
||||
BiLt => self.cmp(left, right, Less, true),
|
||||
BiLe => self.cmp(left, right, Greater, false),
|
||||
BiGe => self.cmp(left, right, Less, false),
|
||||
BiGt => self.cmp(left, right, Greater, true),
|
||||
_ => None
|
||||
}
|
||||
}
|
||||
|
||||
fn bitop<F>(&mut self, left: &Expr, right: &Expr, f: F)
|
||||
-> Option<Constant> where F: Fn(u64, u64) -> u64 {
|
||||
self.binop_apply(left, right, |l, r| match (l, r) {
|
||||
(ConstantBool(l), ConstantBool(r)) =>
|
||||
Some(ConstantBool(f(l as u64, r as u64) != 0)),
|
||||
(ConstantByte(l8), ConstantByte(r8)) =>
|
||||
Some(ConstantByte(f(l8 as u64, r8 as u64) as u8)),
|
||||
(ConstantInt(l, lty), ConstantInt(r, rty)) =>
|
||||
unify_int_type(lty, rty, Plus).map(|ty| ConstantInt(f(l, r), ty)),
|
||||
_ => None
|
||||
})
|
||||
}
|
||||
|
||||
fn cmp(&mut self, left: &Expr, right: &Expr, ordering: Ordering, b: bool) -> Option<Constant> {
|
||||
self.binop_apply(left, right, |l, r| l.partial_cmp(&r).map(|o|
|
||||
ConstantBool(b == (o == ordering))))
|
||||
}
|
||||
|
||||
fn binop_apply<F>(&mut self, left: &Expr, right: &Expr, op: F) -> Option<Constant>
|
||||
where F: Fn(Constant, Constant) -> Option<Constant> {
|
||||
if let (Some(lc), Some(rc)) = (self.expr(left), self.expr(right)) {
|
||||
op(lc, rc)
|
||||
} else { None }
|
||||
}
|
||||
|
||||
fn short_circuit(&mut self, left: &Expr, right: &Expr, b: bool) -> Option<Constant> {
|
||||
self.expr(left).and_then(|left|
|
||||
if let &ConstantBool(lbool) = &left {
|
||||
if lbool == b {
|
||||
Some(left)
|
||||
} else {
|
||||
self.expr(right).and_then(|right|
|
||||
if let ConstantBool(_) = right {
|
||||
Some(right)
|
||||
} else { None }
|
||||
)
|
||||
}
|
||||
} else { None }
|
||||
)
|
||||
}
|
||||
}
|
||||
|
|
|
@ -3,7 +3,7 @@ use syntax::ast::*;
|
|||
use syntax::codemap::Span;
|
||||
|
||||
use consts::{constant, is_negative};
|
||||
use consts::ConstantVariant::ConstantInt;
|
||||
use consts::Constant::ConstantInt;
|
||||
use utils::{span_lint, snippet};
|
||||
|
||||
declare_lint! { pub IDENTITY_OP, Warn,
|
||||
|
@ -44,9 +44,9 @@ impl LintPass for IdentityOp {
|
|||
|
||||
|
||||
fn check(cx: &Context, e: &Expr, m: i8, span: Span, arg: Span) {
|
||||
if let Some(c) = constant(cx, e) {
|
||||
if c.needed_resolution { return; } // skip linting w/ lookup for now
|
||||
if let ConstantInt(v, ty) = c.constant {
|
||||
if let Some((c, needed_resolution)) = constant(cx, e) {
|
||||
if needed_resolution { return; } // skip linting w/ lookup for now
|
||||
if let ConstantInt(v, ty) = c {
|
||||
if match m {
|
||||
0 => v == 0,
|
||||
-1 => is_negative(ty) && v == 1,
|
||||
|
|
|
@ -149,7 +149,7 @@ impl LintPass for FloatCmp {
|
|||
let op = cmp.node;
|
||||
if (op == BiEq || op == BiNe) && (is_float(cx, left) || is_float(cx, right)) {
|
||||
if constant(cx, left).or_else(|| constant(cx, right)).map_or(
|
||||
false, |c| c.as_float().map_or(false, |f| f == 0.0)) {
|
||||
false, |c| c.0.as_float().map_or(false, |f| f == 0.0)) {
|
||||
return;
|
||||
}
|
||||
span_lint(cx, FLOAT_CMP, expr.span, &format!(
|
||||
|
|
22
tests/consts.rs
Normal file → Executable file
22
tests/consts.rs
Normal file → Executable file
|
@ -5,21 +5,13 @@ extern crate clippy;
|
|||
extern crate syntax;
|
||||
extern crate rustc;
|
||||
|
||||
use clippy::consts::{constant, ConstantVariant};
|
||||
use clippy::consts::ConstantVariant::*;
|
||||
use syntax::ast::*;
|
||||
use syntax::parse::token::InternedString;
|
||||
use syntax::ptr::P;
|
||||
use syntax::codemap::{Spanned, COMMAND_LINE_SP};
|
||||
use std::mem;
|
||||
use rustc::lint::Context;
|
||||
|
||||
fn ctx() -> &'static Context<'static, 'static> {
|
||||
unsafe {
|
||||
let x : *const Context<'static, 'static> = std::ptr::null();
|
||||
mem::transmute(x)
|
||||
}
|
||||
}
|
||||
use clippy::consts::{constant_simple, Constant};
|
||||
use clippy::consts::Constant::*;
|
||||
|
||||
fn spanned<T>(t: T) -> Spanned<T> {
|
||||
Spanned{ node: t, span: COMMAND_LINE_SP }
|
||||
|
@ -41,13 +33,13 @@ fn binop(op: BinOp_, l: Expr, r: Expr) -> Expr {
|
|||
expr(ExprBinary(spanned(op), P(l), P(r)))
|
||||
}
|
||||
|
||||
fn check(expect: ConstantVariant, expr: &Expr) {
|
||||
assert_eq!(Some(expect), constant(ctx(), expr).map(|x| x.constant))
|
||||
fn check(expect: Constant, expr: &Expr) {
|
||||
assert_eq!(Some(expect), constant_simple(expr))
|
||||
}
|
||||
|
||||
const TRUE : ConstantVariant = ConstantBool(true);
|
||||
const FALSE : ConstantVariant = ConstantBool(false);
|
||||
const ZERO : ConstantVariant = ConstantInt(0, UnsuffixedIntLit(Plus));
|
||||
const TRUE : Constant = ConstantBool(true);
|
||||
const FALSE : Constant = ConstantBool(false);
|
||||
const ZERO : Constant = ConstantInt(0, UnsuffixedIntLit(Plus));
|
||||
|
||||
#[test]
|
||||
fn test_lit() {
|
||||
|
|
Loading…
Reference in a new issue