Skip to content
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

On irrefutable let pattern lint point only at pattern #81366

Closed
wants to merge 4 commits into from
Closed
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
23 changes: 17 additions & 6 deletions compiler/rustc_ast_lowering/src/expr.rs
Original file line number Diff line number Diff line change
Expand Up @@ -88,9 +88,14 @@ impl<'hir> LoweringContext<'_, 'hir> {
self.lower_expr_let(e.span, pat, scrutinee)
}
ExprKind::If(ref cond, ref then, ref else_opt) => match cond.kind {
ExprKind::Let(ref pat, ref scrutinee) => {
self.lower_expr_if_let(e.span, pat, scrutinee, then, else_opt.as_deref())
}
ExprKind::Let(ref pat, ref scrutinee) => self.lower_expr_if_let(
e.span,
pat,
scrutinee,
then,
else_opt.as_deref(),
cond.span,
),
_ => self.lower_expr_if(cond, then, else_opt.as_deref()),
},
ExprKind::While(ref cond, ref body, opt_label) => self
Expand Down Expand Up @@ -366,6 +371,7 @@ impl<'hir> LoweringContext<'_, 'hir> {
scrutinee: &Expr,
then: &Block,
else_opt: Option<&Expr>,
let_span: Span,
) -> hir::ExprKind<'hir> {
// FIXME(#53667): handle lowering of && and parens.

Expand All @@ -384,7 +390,7 @@ impl<'hir> LoweringContext<'_, 'hir> {
let then_expr = self.lower_block_expr(then);
let then_arm = self.arm(then_pat, self.arena.alloc(then_expr));

let desugar = hir::MatchSource::IfLetDesugar { contains_else_clause };
let desugar = hir::MatchSource::IfLetDesugar { contains_else_clause, let_span };
hir::ExprKind::Match(scrutinee, arena_vec![self; then_arm, else_arm], desugar)
}

Expand Down Expand Up @@ -420,7 +426,12 @@ impl<'hir> LoweringContext<'_, 'hir> {
// }
let scrutinee = self.with_loop_condition_scope(|t| t.lower_expr(scrutinee));
let pat = self.lower_pat(pat);
(pat, scrutinee, hir::MatchSource::WhileLetDesugar, hir::LoopSource::WhileLet)
(
pat,
scrutinee,
hir::MatchSource::WhileLetDesugar { let_span: cond.span },
hir::LoopSource::WhileLet,
)
}
_ => {
// We desugar: `'label: while $cond $body` into:
Expand Down Expand Up @@ -521,7 +532,7 @@ impl<'hir> LoweringContext<'_, 'hir> {
let pat = self.lower_pat(&arm.pat);
let guard = arm.guard.as_ref().map(|cond| {
if let ExprKind::Let(ref pat, ref scrutinee) = cond.kind {
hir::Guard::IfLet(self.lower_pat(pat), self.lower_expr(scrutinee))
hir::Guard::IfLet(self.lower_pat(pat), self.lower_expr(scrutinee), cond.span)
} else {
hir::Guard::If(self.lower_expr(cond))
}
Expand Down
32 changes: 26 additions & 6 deletions compiler/rustc_hir/src/hir.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1210,7 +1210,7 @@ pub struct Arm<'hir> {
#[derive(Debug, HashStable_Generic)]
pub enum Guard<'hir> {
If(&'hir Expr<'hir>),
IfLet(&'hir Pat<'hir>, &'hir Expr<'hir>),
IfLet(&'hir Pat<'hir>, &'hir Expr<'hir>, Span),
}

#[derive(Debug, HashStable_Generic)]
Expand Down Expand Up @@ -1879,14 +1879,14 @@ pub enum MatchSource {
/// A `match _ { .. }`.
Normal,
/// An `if let _ = _ { .. }` (optionally with `else { .. }`).
IfLetDesugar { contains_else_clause: bool },
IfLetDesugar { contains_else_clause: bool, let_span: Span },
/// An `if let _ = _ => { .. }` match guard.
IfLetGuardDesugar,
IfLetGuardDesugar { let_span: Span },
/// A `while _ { .. }` (which was desugared to a `loop { match _ { .. } }`).
WhileDesugar,
/// A `while let _ = _ { .. }` (which was desugared to a
/// `loop { match _ { .. } }`).
WhileLetDesugar,
WhileLetDesugar { let_span: Span },
/// A desugared `for _ in _ { .. }` loop.
ForLoopDesugar,
/// A desugared `?` operator.
Expand All @@ -1895,13 +1895,33 @@ pub enum MatchSource {
AwaitDesugar,
}

impl MatchSource {
pub fn equivalent(&self, other: &Self) -> bool {
use MatchSource::*;
match (self, other) {
(Normal, Normal)
| (IfLetGuardDesugar { .. }, IfLetGuardDesugar { .. })
| (WhileDesugar, WhileDesugar)
| (WhileLetDesugar { .. }, WhileLetDesugar { .. })
| (ForLoopDesugar, ForLoopDesugar)
| (TryDesugar, TryDesugar)
| (AwaitDesugar, AwaitDesugar) => true,
(
IfLetDesugar { contains_else_clause: l, .. },
IfLetDesugar { contains_else_clause: r, .. },
) => l == r,
_ => false,
}
}
}

impl MatchSource {
pub fn name(self) -> &'static str {
use MatchSource::*;
match self {
Normal => "match",
IfLetDesugar { .. } | IfLetGuardDesugar => "if",
WhileDesugar | WhileLetDesugar => "while",
IfLetDesugar { .. } | IfLetGuardDesugar { .. } => "if",
WhileDesugar | WhileLetDesugar { .. } => "while",
ForLoopDesugar => "for",
TryDesugar => "?",
AwaitDesugar => ".await",
Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_hir/src/intravisit.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1239,7 +1239,7 @@ pub fn walk_arm<'v, V: Visitor<'v>>(visitor: &mut V, arm: &'v Arm<'v>) {
if let Some(ref g) = arm.guard {
match g {
Guard::If(ref e) => visitor.visit_expr(e),
Guard::IfLet(ref pat, ref e) => {
Guard::IfLet(ref pat, ref e, _) => {
visitor.visit_pat(pat);
visitor.visit_expr(e);
}
Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_hir_pretty/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2043,7 +2043,7 @@ impl<'a> State<'a> {
self.print_expr(&e);
self.s.space();
}
hir::Guard::IfLet(pat, e) => {
hir::Guard::IfLet(pat, e, _) => {
self.word_nbsp("if");
self.word_nbsp("let");
self.print_pat(&pat);
Expand Down
4 changes: 3 additions & 1 deletion compiler/rustc_mir_build/src/thir/cx/expr.rs
Original file line number Diff line number Diff line change
Expand Up @@ -781,7 +781,9 @@ fn convert_arm<'tcx>(cx: &mut Cx<'_, 'tcx>, arm: &'tcx hir::Arm<'tcx>) -> Arm<'t
pattern: cx.pattern_from_hir(&arm.pat),
guard: arm.guard.as_ref().map(|g| match g {
hir::Guard::If(ref e) => Guard::If(e.to_ref()),
hir::Guard::IfLet(ref pat, ref e) => Guard::IfLet(cx.pattern_from_hir(pat), e.to_ref()),
hir::Guard::IfLet(ref pat, ref e, _) => {
Guard::IfLet(cx.pattern_from_hir(pat), e.to_ref())
}
}),
body: arm.body.to_ref(),
lint_level: LintLevel::Explicit(arm.hir_id),
Expand Down
86 changes: 50 additions & 36 deletions compiler/rustc_mir_build/src/thir/pattern/check_match.rs
Original file line number Diff line number Diff line change
Expand Up @@ -164,17 +164,17 @@ impl<'tcx> MatchVisitor<'_, 'tcx> {
for arm in arms {
// Check the arm for some things unrelated to exhaustiveness.
self.check_patterns(&arm.pat);
if let Some(hir::Guard::IfLet(ref pat, _)) = arm.guard {
if let Some(hir::Guard::IfLet(ref pat, _, _)) = arm.guard {
self.check_patterns(pat);
}
}

let mut cx = self.new_cx(scrut.hir_id);

for arm in arms {
if let Some(hir::Guard::IfLet(ref pat, _)) = arm.guard {
if let Some(hir::Guard::IfLet(ref pat, _, span)) = arm.guard {
let tpat = self.lower_pattern(&mut cx, pat, &mut false).0;
check_if_let_guard(&mut cx, &tpat, pat.hir_id);
check_if_let_guard(&mut cx, &tpat, pat.hir_id, span);
}
}

Expand Down Expand Up @@ -366,46 +366,59 @@ fn unreachable_pattern(tcx: TyCtxt<'_>, span: Span, id: HirId, catchall: Option<
}

fn irrefutable_let_pattern(tcx: TyCtxt<'_>, span: Span, id: HirId, source: hir::MatchSource) {
tcx.struct_span_lint_hir(IRREFUTABLE_LET_PATTERNS, id, span, |lint| match source {
hir::MatchSource::IfLetDesugar { .. } => {
let mut diag = lint.build("irrefutable `if let` pattern");
diag.note("this pattern will always match, so the `if let` is useless");
diag.help("consider replacing the `if let` with a `let`");
diag.emit()
}
hir::MatchSource::WhileLetDesugar => {
let mut diag = lint.build("irrefutable `while let` pattern");
diag.note("this pattern will always match, so the loop will never exit");
diag.help("consider instead using a `loop { ... }` with a `let` inside it");
diag.emit()
}
hir::MatchSource::IfLetGuardDesugar => {
let mut diag = lint.build("irrefutable `if let` guard pattern");
diag.note("this pattern will always match, so the guard is useless");
diag.help("consider removing the guard and adding a `let` inside the match arm");
diag.emit()
}
_ => {
bug!(
"expected `if let`, `while let`, or `if let` guard HIR match source, found {:?}",
source,
)
}
tcx.struct_span_lint_hir(IRREFUTABLE_LET_PATTERNS, id, span, |lint| {
let mut diag = match source {
hir::MatchSource::IfLetDesugar { .. } => {
let mut diag = lint.build("irrefutable `if let` pattern");
diag.span_label(span, "this pattern will always match, so the `if let` is useless");
diag.help("consider replacing the `if let` with a `let`");
diag
}
hir::MatchSource::WhileLetDesugar { .. } => {
let mut diag = lint.build("irrefutable `while let` pattern");
diag.span_label(span, "this pattern will always match, so the loop will never exit");
diag.help("consider instead using a `loop { ... }` with a `let` inside it");
diag
}
hir::MatchSource::IfLetGuardDesugar { .. }=> {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
hir::MatchSource::IfLetGuardDesugar { .. }=> {
hir::MatchSource::IfLetGuardDesugar { .. } => {

not sure why rustfmt didn't catch this

let mut diag = lint.build("irrefutable `if let` guard pattern");
diag.span_label(span, "this pattern will always match, so the guard is useless");
diag.help("consider removing the guard and adding a `let` inside the match arm");
diag
}
_ => {
bug!(
"expected `if let`, `while let`, or `if let` guard HIR match source, found {:?}",
source,
)
}
};
diag.help(
"for more information, visit \
<https://doc.rust-lang.org/book/ch18-02-refutability.html>",
);
diag.emit();
});
}

fn check_if_let_guard<'p, 'tcx>(
cx: &mut MatchCheckCtxt<'p, 'tcx>,
pat: &'p super::Pat<'tcx>,
pat_id: HirId,
let_span: Span,
) {
let arms = [MatchArm { pat, hir_id: pat_id, has_guard: false }];
let report = compute_match_usefulness(&cx, &arms, pat_id, pat.ty);
report_arm_reachability(&cx, &report, hir::MatchSource::IfLetGuardDesugar);
report_arm_reachability(&cx, &report, hir::MatchSource::IfLetGuardDesugar { let_span });

if report.non_exhaustiveness_witnesses.is_empty() {
// The match is exhaustive, i.e. the `if let` pattern is irrefutable.
irrefutable_let_pattern(cx.tcx, pat.span, pat_id, hir::MatchSource::IfLetGuardDesugar)
// The match is exhaustive, i.e. the if let pattern is irrefutable.
irrefutable_let_pattern(
cx.tcx,
let_span,
pat_id,
hir::MatchSource::IfLetGuardDesugar { let_span },
)
}
}

Expand All @@ -423,20 +436,21 @@ fn report_arm_reachability<'p, 'tcx>(
match source {
hir::MatchSource::WhileDesugar => bug!(),

hir::MatchSource::IfLetDesugar { .. } | hir::MatchSource::WhileLetDesugar => {
hir::MatchSource::IfLetDesugar { let_span, .. }
| hir::MatchSource::WhileLetDesugar { let_span } => {
// Check which arm we're on.
match arm_index {
// The arm with the user-specified pattern.
0 => unreachable_pattern(cx.tcx, arm.pat.span, arm.hir_id, None),
0 => unreachable_pattern(cx.tcx, let_span, arm.hir_id, None),
// The arm with the wildcard pattern.
1 => irrefutable_let_pattern(cx.tcx, arm.pat.span, arm.hir_id, source),
1 => irrefutable_let_pattern(cx.tcx, let_span, arm.hir_id, source),
_ => bug!(),
}
}

hir::MatchSource::IfLetGuardDesugar => {
hir::MatchSource::IfLetGuardDesugar { let_span } => {
assert_eq!(arm_index, 0);
unreachable_pattern(cx.tcx, arm.pat.span, arm.hir_id, None);
unreachable_pattern(cx.tcx, let_span, arm.hir_id, None);
}

hir::MatchSource::ForLoopDesugar | hir::MatchSource::Normal => {
Expand Down
10 changes: 7 additions & 3 deletions compiler/rustc_passes/src/check_const.rs
Original file line number Diff line number Diff line change
Expand Up @@ -45,11 +45,15 @@ impl NonConstExpr {
return None;
}

Self::Match(IfLetGuardDesugar) => bug!("`if let` guard outside a `match` expression"),
Self::Match(IfLetGuardDesugar { .. }) => {
bug!("if-let guard outside a `match` expression")
}

// All other expressions are allowed.
Self::Loop(Loop | While | WhileLet)
| Self::Match(WhileDesugar | WhileLetDesugar | Normal | IfLetDesugar { .. }) => &[],
| Self::Match(WhileDesugar | WhileLetDesugar { .. } | Normal | IfLetDesugar { .. }) => {
&[]
}
};

Some(gates)
Expand Down Expand Up @@ -207,7 +211,7 @@ impl<'tcx> Visitor<'tcx> for CheckConstVisitor<'tcx> {
let non_const_expr = match source {
// These are handled by `ExprKind::Loop` above.
hir::MatchSource::WhileDesugar
| hir::MatchSource::WhileLetDesugar
| hir::MatchSource::WhileLetDesugar { .. }
| hir::MatchSource::ForLoopDesugar => None,

_ => Some(NonConstExpr::Match(*source)),
Expand Down
4 changes: 2 additions & 2 deletions compiler/rustc_passes/src/liveness.rs
Original file line number Diff line number Diff line change
Expand Up @@ -360,7 +360,7 @@ impl<'tcx> Visitor<'tcx> for IrMaps<'tcx> {

fn visit_arm(&mut self, arm: &'tcx hir::Arm<'tcx>) {
self.add_from_pat(&arm.pat);
if let Some(hir::Guard::IfLet(ref pat, _)) = arm.guard {
if let Some(hir::Guard::IfLet(ref pat, _, _)) = arm.guard {
self.add_from_pat(pat);
}
intravisit::walk_arm(self, arm);
Expand Down Expand Up @@ -891,7 +891,7 @@ impl<'a, 'tcx> Liveness<'a, 'tcx> {

let guard_succ = arm.guard.as_ref().map_or(body_succ, |g| match g {
hir::Guard::If(e) => self.propagate_through_expr(e, body_succ),
hir::Guard::IfLet(pat, e) => {
hir::Guard::IfLet(pat, e, _) => {
let let_bind = self.define_bindings_in_pat(pat, body_succ);
self.propagate_through_expr(e, let_bind)
}
Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_typeck/src/check/_match.rs
Original file line number Diff line number Diff line change
Expand Up @@ -134,7 +134,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
hir::Guard::If(e) => {
self.check_expr_has_type_or_error(e, tcx.types.bool, |_| {});
}
hir::Guard::IfLet(pat, e) => {
hir::Guard::IfLet(pat, e, _) => {
let scrutinee_ty = self.demand_scrutinee_type(
e,
pat.contains_explicit_ref_binding(),
Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_typeck/src/check/generator_interior.rs
Original file line number Diff line number Diff line change
Expand Up @@ -248,7 +248,7 @@ impl<'a, 'tcx> Visitor<'tcx> for InteriorVisitor<'a, 'tcx> {
Guard::If(ref e) => {
self.visit_expr(e);
}
Guard::IfLet(ref pat, ref e) => {
Guard::IfLet(ref pat, ref e, _) => {
self.visit_pat(pat);
self.visit_expr(e);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,17 +8,14 @@ LL | #![feature(capture_disjoint_fields)]
= note: see issue #53488 <https://github.com/rust-lang/rust/issues/53488> for more information

warning: irrefutable `if let` pattern
--> $DIR/closure-origin-single-variant-diagnostics.rs:18:9
--> $DIR/closure-origin-single-variant-diagnostics.rs:18:12
|
LL | / if let SingleVariant::Point(ref mut x, _) = point {
LL | |
LL | | *x += 1;
LL | | }
| |_________^
LL | if let SingleVariant::Point(ref mut x, _) = point {
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ this pattern will always match, so the `if let` is useless
|
= note: `#[warn(irrefutable_let_patterns)]` on by default
= note: this pattern will always match, so the `if let` is useless
= help: consider replacing the `if let` with a `let`
= help: for more information, visit <https://doc.rust-lang.org/book/ch18-02-refutability.html>

error[E0382]: use of moved value: `c`
--> $DIR/closure-origin-single-variant-diagnostics.rs:25:13
Expand Down
Loading