Skip to content

Fix false positive with if let and ranges #121075

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

Merged
merged 1 commit into from
Feb 14, 2024
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
16 changes: 12 additions & 4 deletions compiler/rustc_lint/src/unused.rs
Original file line number Diff line number Diff line change
Expand Up @@ -651,9 +651,11 @@ trait UnusedDelimLint {

fn is_expr_delims_necessary(
inner: &ast::Expr,
ctx: UnusedDelimsCtx,
followed_by_block: bool,
followed_by_else: bool,
) -> bool {
let followed_by_else = ctx == UnusedDelimsCtx::AssignedValueLetElse;

if followed_by_else {
match inner.kind {
ast::ExprKind::Binary(op, ..) if op.node.is_lazy() => return true,
Expand All @@ -662,6 +664,13 @@ trait UnusedDelimLint {
}
}

// Check it's range in LetScrutineeExpr
if let ast::ExprKind::Range(..) = inner.kind
&& matches!(ctx, UnusedDelimsCtx::LetScrutineeExpr)
{
return true;
}

// Check if LHS needs parens to prevent false-positives in cases like `fn x() -> u8 { ({ 0 } + 1) }`.
{
let mut innermost = inner;
Expand Down Expand Up @@ -1007,8 +1016,7 @@ impl UnusedDelimLint for UnusedParens {
) {
match value.kind {
ast::ExprKind::Paren(ref inner) => {
let followed_by_else = ctx == UnusedDelimsCtx::AssignedValueLetElse;
if !Self::is_expr_delims_necessary(inner, followed_by_block, followed_by_else)
if !Self::is_expr_delims_necessary(inner, ctx, followed_by_block)
&& value.attrs.is_empty()
&& !value.span.from_expansion()
&& (ctx != UnusedDelimsCtx::LetScrutineeExpr
Expand Down Expand Up @@ -1334,7 +1342,7 @@ impl UnusedDelimLint for UnusedBraces {
// FIXME(const_generics): handle paths when #67075 is fixed.
if let [stmt] = inner.stmts.as_slice() {
if let ast::StmtKind::Expr(ref expr) = stmt.kind {
if !Self::is_expr_delims_necessary(expr, followed_by_block, false)
if !Self::is_expr_delims_necessary(expr, ctx, followed_by_block)
&& (ctx != UnusedDelimsCtx::AnonConst
|| (matches!(expr.kind, ast::ExprKind::Lit(_))
&& !expr.span.from_expansion()))
Expand Down
16 changes: 16 additions & 0 deletions tests/ui/lint/issue-121070-let-range.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
// check-pass

#![feature(let_chains)]
#![allow(irrefutable_let_patterns)]
fn main() {
let _a = 0..1;

if let x = (0..1) {
eprintln!("x: {:?}", x);
}
if let x = (0..1) &&
let _y = (0..2)
{
eprintln!("x: {:?}", x);
}
}