rustc::middle::const_eval : add overflow-checking for {+, -, *}.

The overflow-checking attempts to accommodate early evaluation where
we do not have type information yet.

Also, add fixme note about something that has been bothering me.
This commit is contained in:
Felix S. Klock II 2015-03-25 11:10:09 +01:00
parent 2e93e386fd
commit b02f7d2fac

View file

@ -13,6 +13,8 @@
pub use self::const_val::*;
use self::ErrKind::*;
use metadata::csearch;
use middle::{astencode, def};
use middle::pat_util::def_to_path;
@ -27,6 +29,7 @@
use std::borrow::{Cow, IntoCow};
use std::num::wrapping::OverflowingOps;
use std::num::ToPrimitive;
use std::cmp::Ordering;
use std::collections::hash_map::Entry::Vacant;
use std::{i8, i16, i32, i64};
@ -234,6 +237,7 @@ pub enum ErrKind {
NotOnStruct,
NotOnTuple,
NegateWithOverflow(i64),
AddiWithOverflow(i64, i64),
SubiWithOverflow(i64, i64),
MuliWithOverflow(i64, i64),
@ -244,6 +248,8 @@ pub enum ErrKind {
DivideWithOverflow,
ModuloByZero,
ModuloWithOverflow,
ShiftLeftWithOverflow,
ShiftRightWithOverflow,
MissingStructField,
NonConstPath,
ExpectedConstTuple,
@ -257,6 +263,7 @@ pub enum ErrKind {
impl ConstEvalErr {
pub fn description(&self) -> Cow<str> {
use self::ErrKind::*;
match self.kind {
CannotCast => "can't cast this type".into_cow(),
CannotCastTo(s) => format!("can't cast this type to {}", s).into_cow(),
@ -275,6 +282,7 @@ pub fn description(&self) -> Cow<str> {
NotOnStruct => "not on struct".into_cow(),
NotOnTuple => "not on tuple".into_cow(),
NegateWithOverflow(..) => "attempted to negate with overflow".into_cow(),
AddiWithOverflow(..) => "attempted to add with overflow".into_cow(),
SubiWithOverflow(..) => "attempted to sub with overflow".into_cow(),
MuliWithOverflow(..) => "attempted to mul with overflow".into_cow(),
@ -285,6 +293,8 @@ pub fn description(&self) -> Cow<str> {
DivideWithOverflow => "attempted to divide with overflow".into_cow(),
ModuloByZero => "attempted remainder with a divisor of zero".into_cow(),
ModuloWithOverflow => "attempted remainder with overflow".into_cow(),
ShiftLeftWithOverflow => "attempted left shift with overflow".into_cow(),
ShiftRightWithOverflow => "attempted right shift with overflow".into_cow(),
MissingStructField => "nonexistent struct field".into_cow(),
NonConstPath => "non-constant path in constant expr".into_cow(),
ExpectedConstTuple => "expected constant tuple".into_cow(),
@ -297,57 +307,294 @@ pub fn description(&self) -> Cow<str> {
}
}
macro_rules! signal {
($e:expr, $ctor:ident) => {
return Err(ConstEvalErr { span: $e.span, kind: ErrKind::$ctor })
};
pub type EvalResult = Result<const_val, ConstEvalErr>;
pub type CastResult = Result<const_val, ErrKind>;
($e:expr, $ctor:ident($($arg:expr),*)) => {
return Err(ConstEvalErr { span: $e.span, kind: ErrKind::$ctor($($arg),*) })
#[derive(Copy, Clone, PartialEq, Debug)]
pub enum IntTy { I8, I16, I32, I64 }
#[derive(Copy, Clone, PartialEq, Debug)]
pub enum UintTy { U8, U16, U32, U64 }
impl IntTy {
pub fn from(tcx: &ty::ctxt, t: ast::IntTy) -> IntTy {
let t = if let ast::TyIs = t {
tcx.sess.target.int_type
} else {
t
};
match t {
ast::TyIs => unreachable!(),
ast::TyI8 => IntTy::I8,
ast::TyI16 => IntTy::I16,
ast::TyI32 => IntTy::I32,
ast::TyI64 => IntTy::I64,
}
}
}
fn checked_add_int(e: &Expr, a: i64, b: i64) -> Result<const_val, ConstEvalErr> {
let (ret, oflo) = a.overflowing_add(b);
if !oflo { Ok(const_int(ret)) } else { signal!(e, AddiWithOverflow(a, b)) }
}
fn checked_sub_int(e: &Expr, a: i64, b: i64) -> Result<const_val, ConstEvalErr> {
let (ret, oflo) = a.overflowing_sub(b);
if !oflo { Ok(const_int(ret)) } else { signal!(e, SubiWithOverflow(a, b)) }
}
fn checked_mul_int(e: &Expr, a: i64, b: i64) -> Result<const_val, ConstEvalErr> {
let (ret, oflo) = a.overflowing_mul(b);
if !oflo { Ok(const_int(ret)) } else { signal!(e, MuliWithOverflow(a, b)) }
impl UintTy {
pub fn from(tcx: &ty::ctxt, t: ast::UintTy) -> UintTy {
let t = if let ast::TyUs = t {
tcx.sess.target.uint_type
} else {
t
};
match t {
ast::TyUs => unreachable!(),
ast::TyU8 => UintTy::U8,
ast::TyU16 => UintTy::U16,
ast::TyU32 => UintTy::U32,
ast::TyU64 => UintTy::U64,
}
}
}
fn checked_add_uint(e: &Expr, a: u64, b: u64) -> Result<const_val, ConstEvalErr> {
let (ret, oflo) = a.overflowing_add(b);
if !oflo { Ok(const_uint(ret)) } else { signal!(e, AdduWithOverflow(a, b)) }
}
fn checked_sub_uint(e: &Expr, a: u64, b: u64) -> Result<const_val, ConstEvalErr> {
let (ret, oflo) = a.overflowing_sub(b);
if !oflo { Ok(const_uint(ret)) } else { signal!(e, SubuWithOverflow(a, b)) }
}
fn checked_mul_uint(e: &Expr, a: u64, b: u64) -> Result<const_val, ConstEvalErr> {
let (ret, oflo) = a.overflowing_mul(b);
if !oflo { Ok(const_uint(ret)) } else { signal!(e, MuluWithOverflow(a, b)) }
macro_rules! signal {
($e:expr, $exn:expr) => {
return Err(ConstEvalErr { span: $e.span, kind: $exn })
}
}
// The const_{int,uint}_checked_{neg,add,sub,mul,div,shl,shr} family
// of functions catch and signal overflow errors during constant
// evaluation.
//
// They all take the operator's arguments (`a` and `b` if binary), the
// overall expression (`e`) and, if available, whole expression's
// concrete type (`opt_ety`).
//
// If the whole expression's concrete type is None, then this is a
// constant evaluation happening before type check (e.g. in the check
// to confirm that a pattern range's left-side is not greater than its
// right-side). We do not do arithmetic modulo the type's bitwidth in
// such a case; we just do 64-bit arithmetic and assume that later
// passes will do it again with the type information, and thus do the
// overflow checks then.
pub fn const_int_checked_neg<'a>(
a: i64, e: &'a Expr, opt_ety: Option<IntTy>) -> EvalResult {
let (min,max) = match opt_ety {
// (-i8::MIN is itself not an i8, etc, but this is an easy way
// to allow literals to pass the check. Of course that does
// not work for i64::MIN.)
Some(IntTy::I8) => (-(i8::MAX as i64), -(i8::MIN as i64)),
Some(IntTy::I16) => (-(i16::MAX as i64), -(i16::MIN as i64)),
Some(IntTy::I32) => (-(i32::MAX as i64), -(i32::MIN as i64)),
None | Some(IntTy::I64) => (-i64::MAX, -(i64::MIN+1)),
};
let oflo = a < min || a > max;
if oflo {
signal!(e, NegateWithOverflow(a));
} else {
Ok(const_int(-a))
}
}
pub fn const_uint_checked_neg<'a>(
a: u64, _e: &'a Expr, _opt_ety: Option<UintTy>) -> EvalResult {
// This always succeeds, and by definition, returns `(!a)+1`.
Ok(const_uint(-a))
}
macro_rules! overflow_checking_body {
($a:ident, $b:ident, $ety:ident, $overflowing_op:ident,
lhs: $to_8_lhs:ident $to_16_lhs:ident $to_32_lhs:ident,
rhs: $to_8_rhs:ident $to_16_rhs:ident $to_32_rhs:ident $to_64_rhs:ident,
$EnumTy:ident $T8: ident $T16: ident $T32: ident $T64: ident,
$result_type: ident) => { {
let (a,b,opt_ety) = ($a,$b,$ety);
match opt_ety {
Some($EnumTy::$T8) => match (a.$to_8_lhs(), b.$to_8_rhs()) {
(Some(a), Some(b)) => {
let (a, oflo) = a.$overflowing_op(b);
(a as $result_type, oflo)
}
(None, _) | (_, None) => (0, true)
},
Some($EnumTy::$T16) => match (a.$to_16_lhs(), b.$to_16_rhs()) {
(Some(a), Some(b)) => {
let (a, oflo) = a.$overflowing_op(b);
(a as $result_type, oflo)
}
(None, _) | (_, None) => (0, true)
},
Some($EnumTy::$T32) => match (a.$to_32_lhs(), b.$to_32_rhs()) {
(Some(a), Some(b)) => {
let (a, oflo) = a.$overflowing_op(b);
(a as $result_type, oflo)
}
(None, _) | (_, None) => (0, true)
},
None | Some($EnumTy::$T64) => match b.$to_64_rhs() {
Some(b) => a.$overflowing_op(b),
None => (0, true),
}
}
} }
}
macro_rules! int_arith_body {
($a:ident, $b:ident, $ety:ident, $overflowing_op:ident) => {
overflow_checking_body!(
$a, $b, $ety, $overflowing_op,
lhs: to_i8 to_i16 to_i32,
rhs: to_i8 to_i16 to_i32 to_i64, IntTy I8 I16 I32 I64, i64)
}
}
macro_rules! uint_arith_body {
($a:ident, $b:ident, $ety:ident, $overflowing_op:ident) => {
overflow_checking_body!(
$a, $b, $ety, $overflowing_op,
lhs: to_u8 to_u16 to_u32,
rhs: to_u8 to_u16 to_u32 to_u64, UintTy U8 U16 U32 U64, u64)
}
}
macro_rules! int_shift_body {
($a:ident, $b:ident, $ety:ident, $overflowing_op:ident) => {
overflow_checking_body!(
$a, $b, $ety, $overflowing_op,
lhs: to_i8 to_i16 to_i32,
rhs: to_u32 to_u32 to_u32 to_u32, IntTy I8 I16 I32 I64, i64)
}
}
macro_rules! uint_shift_body {
($a:ident, $b:ident, $ety:ident, $overflowing_op:ident) => {
overflow_checking_body!(
$a, $b, $ety, $overflowing_op,
lhs: to_u8 to_u16 to_u32,
rhs: to_u32 to_u32 to_u32 to_u32, UintTy U8 U16 U32 U64, u64)
}
}
macro_rules! pub_fn_checked_op {
{$fn_name:ident ($a:ident : $a_ty:ty, $b:ident : $b_ty:ty,.. $WhichTy:ident) {
$ret_oflo_body:ident $overflowing_op:ident
$const_ty:ident $signal_exn:expr
}} => {
pub fn $fn_name<'a>($a: $a_ty,
$b: $b_ty,
e: &'a Expr,
opt_ety: Option<$WhichTy>) -> EvalResult {
let (ret, oflo) = $ret_oflo_body!($a, $b, opt_ety, $overflowing_op);
if !oflo { Ok($const_ty(ret)) } else { signal!(e, $signal_exn) }
}
}
}
pub_fn_checked_op!{ const_int_checked_add(a: i64, b: i64,.. IntTy) {
int_arith_body overflowing_add const_int AddiWithOverflow(a, b)
}}
pub_fn_checked_op!{ const_int_checked_sub(a: i64, b: i64,.. IntTy) {
int_arith_body overflowing_sub const_int SubiWithOverflow(a, b)
}}
pub_fn_checked_op!{ const_int_checked_mul(a: i64, b: i64,.. IntTy) {
int_arith_body overflowing_mul const_int MuliWithOverflow(a, b)
}}
pub fn const_int_checked_div<'a>(
a: i64, b: i64, e: &'a Expr, opt_ety: Option<IntTy>) -> EvalResult {
if b == 0 { signal!(e, DivideByZero); }
let (ret, oflo) = int_arith_body!(a, b, opt_ety, overflowing_div);
if !oflo { Ok(const_int(ret)) } else { signal!(e, DivideWithOverflow) }
}
pub fn const_int_checked_rem<'a>(
a: i64, b: i64, e: &'a Expr, opt_ety: Option<IntTy>) -> EvalResult {
if b == 0 { signal!(e, ModuloByZero); }
let (ret, oflo) = int_arith_body!(a, b, opt_ety, overflowing_rem);
if !oflo { Ok(const_int(ret)) } else { signal!(e, ModuloWithOverflow) }
}
pub_fn_checked_op!{ const_int_checked_shl(a: i64, b: i64,.. IntTy) {
int_shift_body overflowing_shl const_int ShiftLeftWithOverflow
}}
pub_fn_checked_op!{ const_int_checked_shl_via_uint(a: i64, b: u64,.. IntTy) {
int_shift_body overflowing_shl const_int ShiftLeftWithOverflow
}}
pub_fn_checked_op!{ const_int_checked_shr(a: i64, b: i64,.. IntTy) {
int_shift_body overflowing_shr const_int ShiftRightWithOverflow
}}
pub_fn_checked_op!{ const_int_checked_shr_via_uint(a: i64, b: u64,.. IntTy) {
int_shift_body overflowing_shr const_int ShiftRightWithOverflow
}}
pub_fn_checked_op!{ const_uint_checked_add(a: u64, b: u64,.. UintTy) {
uint_arith_body overflowing_add const_uint AdduWithOverflow(a, b)
}}
pub_fn_checked_op!{ const_uint_checked_sub(a: u64, b: u64,.. UintTy) {
uint_arith_body overflowing_sub const_uint SubuWithOverflow(a, b)
}}
pub_fn_checked_op!{ const_uint_checked_mul(a: u64, b: u64,.. UintTy) {
uint_arith_body overflowing_mul const_uint MuluWithOverflow(a, b)
}}
pub fn const_uint_checked_div<'a>(
a: u64, b: u64, e: &'a Expr, opt_ety: Option<UintTy>) -> EvalResult {
if b == 0 { signal!(e, DivideByZero); }
let (ret, oflo) = uint_arith_body!(a, b, opt_ety, overflowing_div);
if !oflo { Ok(const_uint(ret)) } else { signal!(e, DivideWithOverflow) }
}
pub fn const_uint_checked_rem<'a>(
a: u64, b: u64, e: &'a Expr, opt_ety: Option<UintTy>) -> EvalResult {
if b == 0 { signal!(e, ModuloByZero); }
let (ret, oflo) = uint_arith_body!(a, b, opt_ety, overflowing_rem);
if !oflo { Ok(const_uint(ret)) } else { signal!(e, ModuloWithOverflow) }
}
pub_fn_checked_op!{ const_uint_checked_shl(a: u64, b: u64,.. UintTy) {
uint_shift_body overflowing_shl const_uint ShiftLeftWithOverflow
}}
pub_fn_checked_op!{ const_uint_checked_shl_via_int(a: u64, b: i64,.. UintTy) {
uint_shift_body overflowing_shl const_uint ShiftLeftWithOverflow
}}
pub_fn_checked_op!{ const_uint_checked_shr(a: u64, b: u64,.. UintTy) {
uint_shift_body overflowing_shr const_uint ShiftRightWithOverflow
}}
pub_fn_checked_op!{ const_uint_checked_shr_via_int(a: u64, b: i64,.. UintTy) {
uint_shift_body overflowing_shr const_uint ShiftRightWithOverflow
}}
pub fn eval_const_expr_partial<'tcx>(tcx: &ty::ctxt<'tcx>,
e: &Expr,
ty_hint: Option<Ty<'tcx>>)
-> Result<const_val, ConstEvalErr> {
ty_hint: Option<Ty<'tcx>>) -> EvalResult {
fn fromb(b: bool) -> const_val { const_int(b as i64) }
let ety = ty_hint.or_else(|| ty::expr_ty_opt(tcx, e));
// If type of expression itself is int or uint, normalize in these
// bindings so that isize/usize is mapped to a type with an
// inherently known bitwidth.
let expr_int_type = ety.and_then(|ty| {
if let ty::ty_int(t) = ty.sty {
Some(IntTy::from(tcx, t)) } else { None }
});
let expr_uint_type = ety.and_then(|ty| {
if let ty::ty_uint(t) = ty.sty {
Some(UintTy::from(tcx, t)) } else { None }
});
let result = match e.node {
ast::ExprUnary(ast::UnNeg, ref inner) => {
match try!(eval_const_expr_partial(tcx, &**inner, ety)) {
const_float(f) => const_float(-f),
const_int(i) => const_int(-i),
const_uint(i) => const_uint(-i),
const_int(n) => try!(const_int_checked_neg(n, e, expr_int_type)),
const_uint(n) => try!(const_uint_checked_neg(n, e, expr_uint_type)),
const_str(_) => signal!(e, NegateOnString),
const_bool(_) => signal!(e, NegateOnBoolean),
const_binary(_) => signal!(e, NegateOnBinary),
@ -391,51 +638,17 @@ fn fromb(b: bool) -> const_val { const_int(b as i64) }
}
}
(const_int(a), const_int(b)) => {
let is_a_min_value = || {
let int_ty = match ty::expr_ty_opt(tcx, e).map(|ty| &ty.sty) {
Some(&ty::ty_int(int_ty)) => int_ty,
_ => return false
};
let int_ty = if let ast::TyIs = int_ty {
tcx.sess.target.int_type
} else {
int_ty
};
match int_ty {
ast::TyI8 => (a as i8) == i8::MIN,
ast::TyI16 => (a as i16) == i16::MIN,
ast::TyI32 => (a as i32) == i32::MIN,
ast::TyI64 => (a as i64) == i64::MIN,
ast::TyIs => unreachable!()
}
};
match op.node {
ast::BiAdd => try!(checked_add_int(e, a, b)),
ast::BiSub => try!(checked_sub_int(e, a, b)),
ast::BiMul => try!(checked_mul_int(e, a, b)),
ast::BiDiv => {
if b == 0 {
signal!(e, DivideByZero);
} else if b == -1 && is_a_min_value() {
signal!(e, DivideWithOverflow);
} else {
const_int(a / b)
}
}
ast::BiRem => {
if b == 0 {
signal!(e, ModuloByZero)
} else if b == -1 && is_a_min_value() {
signal!(e, ModuloWithOverflow)
} else {
const_int(a % b)
}
}
ast::BiAdd => try!(const_int_checked_add(a,b,e,expr_int_type)),
ast::BiSub => try!(const_int_checked_sub(a,b,e,expr_int_type)),
ast::BiMul => try!(const_int_checked_mul(a,b,e,expr_int_type)),
ast::BiDiv => try!(const_int_checked_div(a,b,e,expr_int_type)),
ast::BiRem => try!(const_int_checked_rem(a,b,e,expr_int_type)),
ast::BiAnd | ast::BiBitAnd => const_int(a & b),
ast::BiOr | ast::BiBitOr => const_int(a | b),
ast::BiBitXor => const_int(a ^ b),
ast::BiShl => const_int(a << b as usize),
ast::BiShr => const_int(a >> b as usize),
ast::BiShl => try!(const_int_checked_shl(a,b,e,expr_int_type)),
ast::BiShr => try!(const_int_checked_shr(a,b,e,expr_int_type)),
ast::BiEq => fromb(a == b),
ast::BiLt => fromb(a < b),
ast::BiLe => fromb(a <= b),
@ -446,18 +659,16 @@ fn fromb(b: bool) -> const_val { const_int(b as i64) }
}
(const_uint(a), const_uint(b)) => {
match op.node {
ast::BiAdd => try!(checked_add_uint(e, a, b)),
ast::BiSub => try!(checked_sub_uint(e, a, b)),
ast::BiMul => try!(checked_mul_uint(e, a, b)),
ast::BiDiv if b == 0 => signal!(e, DivideByZero),
ast::BiDiv => const_uint(a / b),
ast::BiRem if b == 0 => signal!(e, ModuloByZero),
ast::BiRem => const_uint(a % b),
ast::BiAdd => try!(const_uint_checked_add(a,b,e,expr_uint_type)),
ast::BiSub => try!(const_uint_checked_sub(a,b,e,expr_uint_type)),
ast::BiMul => try!(const_uint_checked_mul(a,b,e,expr_uint_type)),
ast::BiDiv => try!(const_uint_checked_div(a,b,e,expr_uint_type)),
ast::BiRem => try!(const_uint_checked_rem(a,b,e,expr_uint_type)),
ast::BiAnd | ast::BiBitAnd => const_uint(a & b),
ast::BiOr | ast::BiBitOr => const_uint(a | b),
ast::BiBitXor => const_uint(a ^ b),
ast::BiShl => const_uint(a << b as usize),
ast::BiShr => const_uint(a >> b as usize),
ast::BiShl => try!(const_uint_checked_shl(a,b,e,expr_uint_type)),
ast::BiShr => try!(const_uint_checked_shr(a,b,e,expr_uint_type)),
ast::BiEq => fromb(a == b),
ast::BiLt => fromb(a < b),
ast::BiLe => fromb(a <= b),
@ -469,15 +680,15 @@ fn fromb(b: bool) -> const_val { const_int(b as i64) }
// shifts can have any integral type as their rhs
(const_int(a), const_uint(b)) => {
match op.node {
ast::BiShl => const_int(a << b as usize),
ast::BiShr => const_int(a >> b as usize),
ast::BiShl => try!(const_int_checked_shl_via_uint(a,b,e,expr_int_type)),
ast::BiShr => try!(const_int_checked_shr_via_uint(a,b,e,expr_int_type)),
_ => signal!(e, InvalidOpForIntUint(op.node)),
}
}
(const_uint(a), const_int(b)) => {
match op.node {
ast::BiShl => const_uint(a << b as usize),
ast::BiShr => const_uint(a >> b as usize),
ast::BiShl => try!(const_uint_checked_shl_via_int(a,b,e,expr_uint_type)),
ast::BiShr => try!(const_uint_checked_shr_via_int(a,b,e,expr_uint_type)),
_ => signal!(e, InvalidOpForUintInt(op.node)),
}
}
@ -506,7 +717,12 @@ fn fromb(b: bool) -> const_val { const_int(b as i64) }
tcx.sess.span_fatal(target_ty.span,
"target type not found for const cast")
});
// Prefer known type to noop, but always have a type hint.
//
// FIXME (#23833): the type-hint can cause problems,
// e.g. `(i8::MAX + 1_i8) as u32` feeds in `u32` as result
// type to the sum, and thus no overflow is signaled.
let base_hint = ty::expr_ty_opt(tcx, &**base).unwrap_or(ety);
let val = try!(eval_const_expr_partial(tcx, &**base, Some(base_hint)));
match cast_const(tcx, val, ety) {
@ -607,7 +823,7 @@ fn fromb(b: bool) -> const_val { const_int(b as i64) }
Ok(result)
}
fn cast_const<'tcx>(tcx: &ty::ctxt<'tcx>, val: const_val, ty: Ty) -> Result<const_val, ErrKind> {
fn cast_const<'tcx>(tcx: &ty::ctxt<'tcx>, val: const_val, ty: Ty) -> CastResult {
macro_rules! convert_val {
($intermediate_ty:ty, $const_type:ident, $target_ty:ty) => {
match val {