Skip to content

Detect overflows of non u32 shifts #51839

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jun 29, 2018
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion src/librustc_mir/interpret/operator.rs
Original file line number Diff line number Diff line change
@@ -95,9 +95,10 @@ impl<'a, 'mir, 'tcx, M: Machine<'mir, 'tcx>> EvalContext<'a, 'mir, 'tcx, M> {
// These ops can have an RHS with a different numeric type.
if right_kind.is_int() && (bin_op == Shl || bin_op == Shr) {
let signed = left_layout.abi.is_signed();
let mut oflo = (r as u32 as u128) != r;
let mut r = r as u32;
let size = left_layout.size.bits() as u32;
let oflo = r >= size;
oflo |= r >= size;
if oflo {
r %= size;
}
19 changes: 19 additions & 0 deletions src/test/ui/const-eval/shift_overflow.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
// Copyright 2018 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

enum Foo {
// test that we detect overflows for non-u32 discriminants
X = 1 << ((u32::max_value() as u64) + 1), //~ ERROR E0080
Y = 42,
}


fn main() {
}
9 changes: 9 additions & 0 deletions src/test/ui/const-eval/shift_overflow.stderr
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
error[E0080]: could not evaluate enum discriminant
--> $DIR/shift_overflow.rs:13:9
|
LL | X = 1 << ((u32::max_value() as u64) + 1), //~ ERROR E0080
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ attempt to shift left with overflow

error: aborting due to previous error

For more information about this error, try `rustc --explain E0080`.