Skip to content

Commit

Permalink
fix: should use wrapping_ to handle exceeded shifts.
Browse files Browse the repository at this point in the history
  • Loading branch information
7086cmd authored and Boshen committed Oct 3, 2024
1 parent 115ccc9 commit 8086d27
Showing 1 changed file with 8 additions and 5 deletions.
13 changes: 8 additions & 5 deletions crates/oxc_minifier/src/ast_passes/peephole_fold_constants.rs
Original file line number Diff line number Diff line change
Expand Up @@ -837,17 +837,19 @@ impl<'a> PeepholeFoldConstants {
return None;
}

let right_val_int = right_val as i32;
let bits = NumericLiteral::ecmascript_to_int32(left_val);
#[allow(clippy::cast_sign_loss)]
let right_val_int = right_val as u32;
let bits = left_val.to_js_int_32();

let result_val: f64 = match op {
BinaryOperator::ShiftLeft => f64::from(bits << right_val_int),
BinaryOperator::ShiftRight => f64::from(bits >> right_val_int),
BinaryOperator::ShiftLeft => f64::from(bits.wrapping_shl(right_val_int)),
BinaryOperator::ShiftRight => f64::from(bits.wrapping_shr(right_val_int)),
BinaryOperator::ShiftRightZeroFill => {
// JavaScript always treats the result of >>> as unsigned.
// We must force Rust to do the same here.
#[allow(clippy::cast_sign_loss)]
let res = bits as u32 >> right_val_int as u32;
let bits = bits as u32;
let res = bits.wrapping_shr(right_val_int);
f64::from(res)
}
_ => unreachable!("Unknown binary operator {:?}", op),
Expand Down Expand Up @@ -1549,6 +1551,7 @@ mod test {
test("x = -1 >>> 0", "x=4294967295"); // 0xffffffff
test("x = -2 >>> 0", "x=4294967294"); // 0xfffffffe
test("x = 0x90000000 >>> 28", "x=9");
test("x = -2147483649 >>> 0", "x=2147483647");

test("x = 0xffffffff << 0", "x=-1");
test("x = 0xffffffff << 4", "x=-16");
Expand Down

0 comments on commit 8086d27

Please sign in to comment.