Skip to content

cast_possible_truncation: Support size_of, align_of, and size_of_val #15488

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

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
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
7 changes: 5 additions & 2 deletions clippy_lints/src/casts/cast_possible_truncation.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,9 @@ fn get_constant_bits(cx: &LateContext<'_>, expr: &Expr<'_>) -> Option<u64> {
}

fn apply_reductions(cx: &LateContext<'_>, nbits: u64, expr: &Expr<'_>, signed: bool) -> u64 {
match expr_or_init(cx, expr).kind {
let expr = expr_or_init(cx, expr);

match expr.kind {
ExprKind::Cast(inner, _) => apply_reductions(cx, nbits, inner, signed),
ExprKind::Block(block, _) => block.expr.map_or(nbits, |e| apply_reductions(cx, nbits, e, signed)),
ExprKind::Binary(op, left, right) => match op.node {
Expand Down Expand Up @@ -79,6 +81,7 @@ fn apply_reductions(cx: &LateContext<'_>, nbits: u64, expr: &Expr<'_>, signed: b
nbits
}
},
ExprKind::Call(..) => get_constant_bits(cx, expr).unwrap_or(nbits),
_ => nbits,
}
}
Expand All @@ -103,7 +106,7 @@ pub(super) fn check(
let (should_lint, suffix) = match (is_isize_or_usize(cast_from), is_isize_or_usize(cast_to)) {
(true, true) | (false, false) => (to_nbits < from_nbits, ""),
(true, false) => (
to_nbits <= 32,
to_nbits <= 32 && from_nbits >= to_nbits,
if to_nbits == 32 {
" on targets with 64-bit wide pointers"
} else {
Expand Down
62 changes: 45 additions & 17 deletions clippy_utils/src/consts.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ use rustc_middle::ty::{self, FloatTy, IntTy, ScalarInt, Ty, TyCtxt, TypeckResult
use rustc_middle::{bug, mir, span_bug};
use rustc_span::def_id::DefId;
use rustc_span::symbol::Ident;
use rustc_span::{SyntaxContext, sym};
use rustc_span::{Symbol, SyntaxContext, sym};
use std::cell::Cell;
use std::cmp::Ordering;
use std::hash::{Hash, Hasher};
Expand Down Expand Up @@ -505,22 +505,21 @@ impl<'tcx> ConstEvalCtxt<'tcx> {
}),
ExprKind::If(cond, then, ref otherwise) => self.ifthenelse(cond, then, *otherwise),
ExprKind::Binary(op, left, right) => self.binop(op.node, left, right),
ExprKind::Call(callee, []) => {
// We only handle a few const functions for now.
if let ExprKind::Path(qpath) = &callee.kind
&& let Some(did) = self.typeck.qpath_res(qpath, callee.hir_id).opt_def_id()
{
match self.tcx.get_diagnostic_name(did) {
Some(sym::i8_legacy_fn_max_value) => Some(Constant::Int(i8::MAX as u128)),
Some(sym::i16_legacy_fn_max_value) => Some(Constant::Int(i16::MAX as u128)),
Some(sym::i32_legacy_fn_max_value) => Some(Constant::Int(i32::MAX as u128)),
Some(sym::i64_legacy_fn_max_value) => Some(Constant::Int(i64::MAX as u128)),
Some(sym::i128_legacy_fn_max_value) => Some(Constant::Int(i128::MAX as u128)),
_ => None,
}
} else {
None
}
ExprKind::Call(callee, []) => match self.get_fn_diagnostic_name(callee) {
Some(sym::i8_legacy_fn_max_value) => Some(Constant::Int(i8::MAX as u128)),
Some(sym::i16_legacy_fn_max_value) => Some(Constant::Int(i16::MAX as u128)),
Some(sym::i32_legacy_fn_max_value) => Some(Constant::Int(i32::MAX as u128)),
Some(sym::i64_legacy_fn_max_value) => Some(Constant::Int(i64::MAX as u128)),
Some(sym::i128_legacy_fn_max_value) => Some(Constant::Int(i128::MAX as u128)),
Some(sym::mem_align_of) => self.align_of_call(callee),
Some(sym::mem_size_of) => self.size_of_call(callee),
_ => None,
},
ExprKind::Call(callee, [_]) => match self.get_fn_diagnostic_name(callee) {
// `align_of_val` doesn't have a diagnostic name, unfortunately.
// Some(sym::mem_align_of_val) => self.align_of_call(callee),
Some(sym::mem_size_of_val) => self.size_of_call(callee),
_ => None,
},
ExprKind::Index(arr, index, _) => self.index(arr, index),
ExprKind::AddrOf(_, _, inner) => self.expr(inner).map(|r| Constant::Ref(Box::new(r))),
Expand Down Expand Up @@ -854,6 +853,35 @@ impl<'tcx> ConstEvalCtxt<'tcx> {
},
}
}

fn get_fn_diagnostic_name(&self, callee: &Expr<'_>) -> Option<Symbol> {
if let ExprKind::Path(qpath) = &callee.kind
&& let Some(def_id) = self.typeck.qpath_res(qpath, callee.hir_id).opt_def_id()
{
self.tcx.get_diagnostic_name(def_id)
} else {
None
}
}

fn align_of_call(&self, callee: &Expr<'_>) -> Option<Constant<'tcx>> {
let ty = self.typeck.node_args(callee.hir_id).types().next()?;
if let Ok(layout) = self.tcx.layout_of(self.typing_env.as_query_input(ty)) {
Some(Constant::Int(u128::from(layout.align.bytes())))
} else {
None
}
}
fn size_of_call(&self, callee: &Expr<'_>) -> Option<Constant<'tcx>> {
let ty = self.typeck.node_args(callee.hir_id).types().next()?;
if let Ok(layout) = self.tcx.layout_of(self.typing_env.as_query_input(ty))
&& layout.is_sized()
{
Some(Constant::Int(u128::from(layout.size.bytes())))
} else {
None
}
}
}

pub fn mir_to_const<'tcx>(tcx: TyCtxt<'tcx>, result: mir::Const<'tcx>) -> Option<Constant<'tcx>> {
Expand Down
7 changes: 6 additions & 1 deletion tests/ui-toml/min_rust_version/min_rust_version.fixed
Original file line number Diff line number Diff line change
@@ -1,4 +1,9 @@
#![allow(clippy::redundant_clone, clippy::unnecessary_operation, clippy::incompatible_msrv)]
#![allow(
clippy::redundant_clone,
clippy::unnecessary_operation,
clippy::incompatible_msrv,
clippy::identity_op
)]
#![warn(clippy::manual_non_exhaustive, clippy::borrow_as_ptr, clippy::manual_bits)]

use std::mem::{size_of, size_of_val};
Expand Down
7 changes: 6 additions & 1 deletion tests/ui-toml/min_rust_version/min_rust_version.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,9 @@
#![allow(clippy::redundant_clone, clippy::unnecessary_operation, clippy::incompatible_msrv)]
#![allow(
clippy::redundant_clone,
clippy::unnecessary_operation,
clippy::incompatible_msrv,
clippy::identity_op
)]
#![warn(clippy::manual_non_exhaustive, clippy::borrow_as_ptr, clippy::manual_bits)]

use std::mem::{size_of, size_of_val};
Expand Down
2 changes: 1 addition & 1 deletion tests/ui-toml/min_rust_version/min_rust_version.stderr
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
error: you are using an explicit closure for cloning elements
--> tests/ui-toml/min_rust_version/min_rust_version.rs:74:26
--> tests/ui-toml/min_rust_version/min_rust_version.rs:79:26
|
LL | let _: Option<u64> = Some(&16).map(|b| *b);
| ^^^^^^^^^^^^^^^^^^^^^ help: consider calling the dedicated `cloned` method: `Some(&16).cloned()`
Expand Down
21 changes: 21 additions & 0 deletions tests/ui/cast.rs
Original file line number Diff line number Diff line change
Expand Up @@ -251,6 +251,27 @@ fn main() {
999999u64.clamp(0, 256) as u8;
//~^ cast_possible_truncation

std::mem::size_of::<u64>() as u8;
std::mem::size_of_val(&1_u64) as u8;
std::mem::align_of::<u64>() as u8;
// currently not supported by const eval
std::mem::align_of_val(&1_u64) as u8;
//~^ cast_possible_truncation

std::mem::size_of::<[u8; 256]>() as u8;
//~^ cast_possible_truncation
std::mem::size_of_val(&[0_u8; 256]) as u8;
//~^ cast_possible_truncation
std::mem::size_of_val("foo") as u8;
//~^ cast_possible_truncation

#[repr(C, align(256))]
struct HighAlign([u8; 256]);
std::mem::size_of::<HighAlign>() as u8;
//~^ cast_possible_truncation
std::mem::align_of::<HighAlign>() as u8;
//~^ cast_possible_truncation

#[derive(Clone, Copy)]
enum E1 {
A,
Expand Down
Loading