Skip to content

Commit e998bb8

Browse files
committed
limit eval const items to the current local crate
1 parent d05e9d7 commit e998bb8

File tree

3 files changed

+29
-2
lines changed

3 files changed

+29
-2
lines changed

clippy_lints/src/casts/cast_possible_truncation.rs

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -80,7 +80,20 @@ fn apply_reductions(cx: &LateContext<'_>, nbits: u64, expr: &Expr<'_>, signed: b
8080
nbits
8181
}
8282
},
83-
ExprKind::Path(ref _qpath) => get_constant_bits(cx, expr).unwrap_or(nbits),
83+
ExprKind::Path(QPath::Resolved(
84+
None,
85+
rustc_hir::Path {
86+
res: Res::Def(DefKind::Const | DefKind::AssocConst, def_id),
87+
..
88+
},
89+
))
90+
// NOTE(@Jarcho): A constant from another crate might not have the same value
91+
// for all versions of the crate. This isn't a problem for constants in the
92+
// current crate since a crate can't compile against multiple versions of itself.
93+
if def_id.is_local() => {
94+
// `constant()` already checks if a const item is based on `cfg!`.
95+
get_constant_bits(cx, expr).unwrap_or(nbits)
96+
},
8497
// mem::size_of::<T>();
8598
ExprKind::Call(func, []) => {
8699
if let ExprKind::Path(ref func_qpath) = func.kind

tests/ui/cast.rs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -509,5 +509,7 @@ pub fn issue_7486() -> u8 {
509509
pub fn issue_9613() {
510510
const CHUNK: usize = 64;
511511
CHUNK as u32;
512+
u64::MIN as u32;
513+
//~^ ERROR: casting `u64` to `u32` may truncate the value
512514
core::mem::size_of::<String>() as u32;
513515
}

tests/ui/cast.stderr

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -731,5 +731,17 @@ help: ... or use `try_from` and handle the error accordingly
731731
LL | u8::try_from(255 % 999999u64);
732732
| ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
733733

734-
error: aborting due to 92 previous errors
734+
error: casting `u64` to `u32` may truncate the value
735+
--> tests/ui/cast.rs:510:5
736+
|
737+
LL | u64::MIN as u32;
738+
| ^^^^^^^^^^^^^^^
739+
|
740+
= help: if this is intentional allow the lint with `#[allow(clippy::cast_possible_truncation)]` ...
741+
help: ... or use `try_from` and handle the error accordingly
742+
|
743+
LL | u32::try_from(u64::MIN);
744+
| ~~~~~~~~~~~~~~~~~~~~~~~
745+
746+
error: aborting due to 93 previous errors
735747

0 commit comments

Comments
 (0)