Skip to content
Merged
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
13 changes: 11 additions & 2 deletions clippy_lints/src/invalid_upcast_comparisons.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
use rustc_errors::Applicability;
use rustc_hir::{Expr, ExprKind};
use rustc_lint::{LateContext, LateLintPass};
use rustc_middle::ty::layout::LayoutOf;
Expand All @@ -9,7 +10,7 @@ use clippy_utils::comparisons;
use clippy_utils::comparisons::Rel;
use clippy_utils::consts::{ConstEvalCtxt, FullInt};
use clippy_utils::diagnostics::span_lint;
use clippy_utils::source::snippet;
use clippy_utils::source::snippet_with_context;

declare_clippy_lint! {
/// ### What it does
Expand Down Expand Up @@ -69,13 +70,21 @@ fn numeric_cast_precast_bounds(cx: &LateContext<'_>, expr: &Expr<'_>) -> Option<

fn err_upcast_comparison(cx: &LateContext<'_>, span: Span, expr: &Expr<'_>, always: bool) {
if let ExprKind::Cast(cast_val, _) = expr.kind {
let mut applicability = Applicability::MachineApplicable;
let (cast_val_snip, _) = snippet_with_context(
cx,
cast_val.span,
expr.span.ctxt(),
"the expression",
&mut applicability,
);
span_lint(
cx,
INVALID_UPCAST_COMPARISONS,
span,
format!(
"because of the numeric bounds on `{}` prior to casting, this expression is always {}",
snippet(cx, cast_val.span, "the expression"),
cast_val_snip,
if always { "true" } else { "false" },
),
);
Expand Down
12 changes: 12 additions & 0 deletions tests/ui/invalid_upcast_comparisons.rs
Original file line number Diff line number Diff line change
Expand Up @@ -133,3 +133,15 @@ fn main() {

-5 == (u32 as i32);
}

fn issue15662() {
macro_rules! add_one {
($x:expr) => {
$x + 1
};
}

let x: u8 = 1;
(add_one!(x) as u32) > 300;
//~^ invalid_upcast_comparisons
}
8 changes: 7 additions & 1 deletion tests/ui/invalid_upcast_comparisons.stderr
Original file line number Diff line number Diff line change
Expand Up @@ -163,5 +163,11 @@ error: because of the numeric bounds on `u8` prior to casting, this expression i
LL | -5 >= (u8 as i32);
| ^^^^^^^^^^^^^^^^^

error: aborting due to 27 previous errors
error: because of the numeric bounds on `add_one!(x)` prior to casting, this expression is always false
--> tests/ui/invalid_upcast_comparisons.rs:145:5
|
LL | (add_one!(x) as u32) > 300;
| ^^^^^^^^^^^^^^^^^^^^^^^^^^

error: aborting due to 28 previous errors

Loading