cast_possible_truncation: don't lint when usize is masked to fit target type#16874
cast_possible_truncation: don't lint when usize is masked to fit target type#16874Souradip121 wants to merge 2 commits intorust-lang:masterfrom
cast_possible_truncation: don't lint when usize is masked to fit target type#16874Conversation
|
r? @dswij rustbot has assigned @dswij. Use Why was this reviewer chosen?The reviewer was selected based on:
|
a9aac26 to
1cb15c4
Compare
|
This PR was rebased onto a different master commit. Here's a range-diff highlighting what actually changed. Rebasing is a normal part of keeping PRs up to date, so no action is needed—this note is just to help reviewers. |
|
Lintcheck changes for 6a8bc47
This comment will be updated if you push new changes |
| help: ... or use `try_from` and handle the error accordingly | ||
| | | ||
| LL - let _ = y as u32; | ||
| LL + let _ = u32::try_from(y); |
There was a problem hiding this comment.
Could also suggest user to explicitly mask bits if that is what they intended to do.
let _ = y & 0xFFFF_FFFF as u32
There was a problem hiding this comment.
@simonsso good call, pushed 6a8bc47 which adds the mask alternative. The lint now offers a second help: alongside the existing try_from suggestion. Scoped narrowly to unsigned to unsigned integer casts where masking has clean semantics, so signed types, enum casts, and inferred _ targets fall back to try_from only.
Fixes the false positive in
cast_possible_truncationwhere masking ausizevalue to fit within au32(or smaller) before casting still triggered a warning.Closes #16854
What was wrong
Root cause (two bugs)
get_constant_bitscouldn't evaluateu32::MAX as usize—ConstEvalCtxthas noExprKind::Casthandler, so it returnedNonefor cast expressions even when the inner value is a known constant. Fixed by peeling through cast layers to reach the underlying constant.apply_reductionsresult was ignored forusize → fixed-size intcasts — the(true, false)match arm checkedto_nbits <= 32unconditionally, never consulting the reducedfrom_nbits. Fixed by adding&& from_nbits > to_nbits.changelog: [
cast_possible_truncation]: no longer lints when ausizevalue is masked to fit the target integer type before casting