Skip to content

Commit 5289bbe

Browse files
committed
Expand validator to be more precise on checked binary ops
1 parent e209e85 commit 5289bbe

File tree

1 file changed

+41
-3
lines changed

1 file changed

+41
-3
lines changed

compiler/rustc_const_eval/src/transform/validate.rs

Lines changed: 41 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -291,7 +291,7 @@ impl<'a, 'tcx> Visitor<'tcx> for TypeChecker<'a, 'tcx> {
291291
ty::Array(..) | ty::Slice(..)
292292
);
293293
}
294-
Rvalue::BinaryOp(op, vals) | Rvalue::CheckedBinaryOp(op, vals) => {
294+
Rvalue::BinaryOp(op, vals) => {
295295
use BinOp::*;
296296
let a = vals.0.ty(&self.body.local_decls, self.tcx);
297297
let b = vals.1.ty(&self.body.local_decls, self.tcx);
@@ -355,17 +355,55 @@ impl<'a, 'tcx> Visitor<'tcx> for TypeChecker<'a, 'tcx> {
355355
for x in [a, b] {
356356
check_kinds!(
357357
x,
358-
"Cannot perform op on type {:?}",
358+
"Cannot perform arithmetic on type {:?}",
359359
ty::Uint(..) | ty::Int(..) | ty::Float(..)
360360
)
361361
}
362362
if a != b {
363363
self.fail(
364364
location,
365-
format!("Cannot perform op on unequal types {:?} and {:?}", a, b),
365+
format!(
366+
"Cannot perform arithmetic on unequal types {:?} and {:?}",
367+
a, b
368+
),
369+
);
370+
}
371+
}
372+
}
373+
}
374+
Rvalue::CheckedBinaryOp(op, vals) => {
375+
use BinOp::*;
376+
let a = vals.0.ty(&self.body.local_decls, self.tcx);
377+
let b = vals.1.ty(&self.body.local_decls, self.tcx);
378+
match op {
379+
Add | Sub | Mul => {
380+
for x in [a, b] {
381+
check_kinds!(
382+
x,
383+
"Cannot perform checked arithmetic on type {:?}",
384+
ty::Uint(..) | ty::Int(..)
385+
)
386+
}
387+
if a != b {
388+
self.fail(
389+
location,
390+
format!(
391+
"Cannot perform checked arithmetic on unequal types {:?} and {:?}",
392+
a, b
393+
),
366394
);
367395
}
368396
}
397+
Shl | Shr => {
398+
for x in [a, b] {
399+
check_kinds!(
400+
x,
401+
"Cannot perform checked shift on non-integer type {:?}",
402+
ty::Uint(..) | ty::Int(..)
403+
)
404+
}
405+
}
406+
_ => self.fail(location, format!("There is no checked version of {:?}", op)),
369407
}
370408
}
371409
Rvalue::UnaryOp(op, operand) => {

0 commit comments

Comments
 (0)