Skip to content

Commit

Permalink
Do not expose fallible to_int operation on Scalar.
Browse files Browse the repository at this point in the history
Any use of it has been shown to be a bug in the past.
  • Loading branch information
oli-obk committed Mar 15, 2021
1 parent 0dd5a1b commit 9f407ae
Show file tree
Hide file tree
Showing 3 changed files with 17 additions and 19 deletions.
32 changes: 15 additions & 17 deletions compiler/rustc_middle/src/mir/interpret/value.rs
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,7 @@ impl<'tcx> ConstValue<'tcx> {
}

pub fn try_to_scalar_int(&self) -> Option<ScalarInt> {
self.try_to_scalar()?.to_int().ok()
Some(self.try_to_scalar()?.assert_int())
}

pub fn try_to_bits(&self, size: Size) -> Option<u128> {
Expand Down Expand Up @@ -367,13 +367,16 @@ impl<'tcx, Tag> Scalar<Tag> {
#[inline]
fn to_bits(self, target_size: Size) -> InterpResult<'tcx, u128> {
assert_ne!(target_size.bytes(), 0, "you should never look at the bits of a ZST");
self.to_int()?.to_bits(target_size).map_err(|size| {
err_ub!(ScalarSizeMismatch {
target_size: target_size.bytes(),
data_size: size.bytes(),
})
.into()
})
match self {
Scalar::Int(int) => int.to_bits(target_size).map_err(|size| {
err_ub!(ScalarSizeMismatch {
target_size: target_size.bytes(),
data_size: size.bytes(),
})
.into()
}),
Scalar::Ptr(_) => throw_unsup!(ReadPointerAsBytes),
}
}

#[inline(always)]
Expand All @@ -383,7 +386,10 @@ impl<'tcx, Tag> Scalar<Tag> {

#[inline]
pub fn assert_int(self) -> ScalarInt {
self.to_int().expect("expected an int but got an abstract pointer")
match self {
Scalar::Ptr(_) => bug!("expected an int but got an abstract pointer"),
Scalar::Int(int) => int,
}
}

#[inline]
Expand Down Expand Up @@ -518,14 +524,6 @@ impl<Tag> From<Pointer<Tag>> for Scalar<Tag> {
}
}

impl TryFrom<Scalar> for ScalarInt {
type Error = super::InterpErrorInfo<'static>;
#[inline]
fn try_from(scalar: Scalar) -> InterpResult<'static, Self> {
scalar.to_int()
}
}

impl<Tag> From<ScalarInt> for Scalar<Tag> {
#[inline(always)]
fn from(ptr: ScalarInt) -> Self {
Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_middle/src/mir/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2473,7 +2473,7 @@ impl ConstantKind<'tcx> {

#[inline]
pub fn try_to_scalar_int(self) -> Option<ScalarInt> {
self.try_to_value()?.try_to_scalar()?.to_int().ok()
Some(self.try_to_value()?.try_to_scalar()?.assert_int())
}

#[inline]
Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_middle/src/ty/consts/kind.rs
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ impl<'tcx> ConstKind<'tcx> {

#[inline]
pub fn try_to_scalar_int(self) -> Option<ScalarInt> {
self.try_to_value()?.try_to_scalar()?.to_int().ok()
Some(self.try_to_value()?.try_to_scalar()?.assert_int())
}

#[inline]
Expand Down

0 comments on commit 9f407ae

Please sign in to comment.