Skip to content

Commit 8e56c2c

Browse files
committed
Suggest ..= when someone tries to create an overflowing range
1 parent cf073ec commit 8e56c2c

File tree

3 files changed

+35
-7
lines changed

3 files changed

+35
-7
lines changed

compiler/rustc_lint/src/types.rs

Lines changed: 20 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -136,6 +136,13 @@ fn lint_overflowing_range_endpoint<'tcx>(
136136
expr: &'tcx hir::Expr<'tcx>,
137137
ty: &str,
138138
) -> bool {
139+
let (expr, cast_ty) = if let Node::Expr(par_expr) = cx.tcx.hir().get(cx.tcx.hir().parent_id(expr.hir_id))
140+
&& let ExprKind::Cast(_, ty) = par_expr.kind {
141+
(par_expr, Some(ty))
142+
} else {
143+
(expr, None)
144+
};
145+
139146
// We only want to handle exclusive (`..`) ranges,
140147
// which are represented as `ExprKind::Struct`.
141148
let par_id = cx.tcx.hir().parent_id(expr.hir_id);
@@ -157,13 +164,19 @@ fn lint_overflowing_range_endpoint<'tcx>(
157164
};
158165
let Ok(start) = cx.sess().source_map().span_to_snippet(eps[0].span) else { return false };
159166

160-
use rustc_ast::{LitIntType, LitKind};
161-
let suffix = match lit.node {
162-
LitKind::Int(_, LitIntType::Signed(s)) => s.name_str(),
163-
LitKind::Int(_, LitIntType::Unsigned(s)) => s.name_str(),
164-
LitKind::Int(_, LitIntType::Unsuffixed) => "",
165-
_ => bug!(),
167+
let suffix = if let Some(cast_ty) = cast_ty {
168+
let Ok(ty) = cx.sess().source_map().span_to_snippet(cast_ty.span) else { return false };
169+
format!(" as {}", ty)
170+
} else {
171+
use rustc_ast::{LitIntType, LitKind};
172+
match lit.node {
173+
LitKind::Int(_, LitIntType::Signed(s)) => s.name_str().to_owned(),
174+
LitKind::Int(_, LitIntType::Unsigned(s)) => s.name_str().to_owned(),
175+
LitKind::Int(_, LitIntType::Unsuffixed) => "".to_owned(),
176+
_ => bug!(),
177+
}
166178
};
179+
167180
cx.emit_spanned_lint(
168181
OVERFLOWING_LITERALS,
169182
struct_expr.span,
@@ -172,7 +185,7 @@ fn lint_overflowing_range_endpoint<'tcx>(
172185
suggestion: struct_expr.span,
173186
start,
174187
literal: lit_val - 1,
175-
suffix,
188+
suffix: &suffix,
176189
},
177190
);
178191

tests/ui/lint/issue-109529.rs

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
fn main() {
2+
for i in 0..256 as u8 { //~ ERROR range endpoint is out of range
3+
println!("{}", i);
4+
}
5+
}

tests/ui/lint/issue-109529.stderr

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
error: range endpoint is out of range for `u8`
2+
--> $DIR/issue-109529.rs:2:14
3+
|
4+
LL | for i in 0..256 as u8 {
5+
| ^^^^^^^^^^^^ help: use an inclusive range instead: `0..=255 as u8`
6+
|
7+
= note: `#[deny(overflowing_literals)]` on by default
8+
9+
error: aborting due to previous error
10+

0 commit comments

Comments
 (0)