Skip to content

Commit 50bca8a

Browse files
committed
Auto merge of rust-lang#6330 - camsteffen:redundant-else, r=ebroto
Add Redundant else lint changelog: Add redundant_else lint It seemed appropriate for "pedantic". Closes rust-lang#112 \*blows off dust*
2 parents 856f4f3 + 70f6a2c commit 50bca8a

10 files changed

+387
-20
lines changed

CHANGELOG.md

+1
Original file line numberDiff line numberDiff line change
@@ -2024,6 +2024,7 @@ Released 2018-09-13
20242024
[`redundant_closure`]: https://rust-lang.github.io/rust-clippy/master/index.html#redundant_closure
20252025
[`redundant_closure_call`]: https://rust-lang.github.io/rust-clippy/master/index.html#redundant_closure_call
20262026
[`redundant_closure_for_method_calls`]: https://rust-lang.github.io/rust-clippy/master/index.html#redundant_closure_for_method_calls
2027+
[`redundant_else`]: https://rust-lang.github.io/rust-clippy/master/index.html#redundant_else
20272028
[`redundant_field_names`]: https://rust-lang.github.io/rust-clippy/master/index.html#redundant_field_names
20282029
[`redundant_pattern`]: https://rust-lang.github.io/rust-clippy/master/index.html#redundant_pattern
20292030
[`redundant_pattern_matching`]: https://rust-lang.github.io/rust-clippy/master/index.html#redundant_pattern_matching

clippy_lints/src/functions.rs

+5-8
Original file line numberDiff line numberDiff line change
@@ -405,13 +405,10 @@ impl<'tcx> Functions {
405405
break;
406406
}
407407
if in_comment {
408-
match line.find("*/") {
409-
Some(i) => {
410-
line = &line[i + 2..];
411-
in_comment = false;
412-
continue;
413-
},
414-
None => break,
408+
if let Some(i) = line.find("*/") {
409+
line = &line[i + 2..];
410+
in_comment = false;
411+
continue;
415412
}
416413
} else {
417414
let multi_idx = line.find("/*").unwrap_or_else(|| line.len());
@@ -423,8 +420,8 @@ impl<'tcx> Functions {
423420
in_comment = true;
424421
continue;
425422
}
426-
break;
427423
}
424+
break;
428425
}
429426
if code_in_line {
430427
line_count += 1;

clippy_lints/src/len_zero.rs

+1-2
Original file line numberDiff line numberDiff line change
@@ -222,9 +222,8 @@ fn check_impl_items(cx: &LateContext<'_>, item: &Item<'_>, impl_items: &[ImplIte
222222
let is_empty = if let Some(is_empty) = impl_items.iter().find(|i| is_named_self(cx, i, "is_empty")) {
223223
if cx.access_levels.is_exported(is_empty.id.hir_id) {
224224
return;
225-
} else {
226-
"a private"
227225
}
226+
"a private"
228227
} else {
229228
"no corresponding"
230229
};

clippy_lints/src/lib.rs

+4
Original file line numberDiff line numberDiff line change
@@ -294,6 +294,7 @@ mod question_mark;
294294
mod ranges;
295295
mod redundant_clone;
296296
mod redundant_closure_call;
297+
mod redundant_else;
297298
mod redundant_field_names;
298299
mod redundant_pub_crate;
299300
mod redundant_static_lifetimes;
@@ -831,6 +832,7 @@ pub fn register_plugins(store: &mut rustc_lint::LintStore, sess: &Session, conf:
831832
&ranges::REVERSED_EMPTY_RANGES,
832833
&redundant_clone::REDUNDANT_CLONE,
833834
&redundant_closure_call::REDUNDANT_CLOSURE_CALL,
835+
&redundant_else::REDUNDANT_ELSE,
834836
&redundant_field_names::REDUNDANT_FIELD_NAMES,
835837
&redundant_pub_crate::REDUNDANT_PUB_CRATE,
836838
&redundant_static_lifetimes::REDUNDANT_STATIC_LIFETIMES,
@@ -1132,6 +1134,7 @@ pub fn register_plugins(store: &mut rustc_lint::LintStore, sess: &Session, conf:
11321134
store.register_early_pass(|| box items_after_statements::ItemsAfterStatements);
11331135
store.register_early_pass(|| box precedence::Precedence);
11341136
store.register_early_pass(|| box needless_continue::NeedlessContinue);
1137+
store.register_early_pass(|| box redundant_else::RedundantElse);
11351138
store.register_late_pass(|| box create_dir::CreateDir);
11361139
store.register_early_pass(|| box needless_arbitrary_self_type::NeedlessArbitrarySelfType);
11371140
store.register_early_pass(|| box redundant_static_lifetimes::RedundantStaticLifetimes);
@@ -1308,6 +1311,7 @@ pub fn register_plugins(store: &mut rustc_lint::LintStore, sess: &Session, conf:
13081311
LintId::of(&pass_by_ref_or_value::TRIVIALLY_COPY_PASS_BY_REF),
13091312
LintId::of(&ranges::RANGE_MINUS_ONE),
13101313
LintId::of(&ranges::RANGE_PLUS_ONE),
1314+
LintId::of(&redundant_else::REDUNDANT_ELSE),
13111315
LintId::of(&ref_option_ref::REF_OPTION_REF),
13121316
LintId::of(&shadow::SHADOW_UNRELATED),
13131317
LintId::of(&strings::STRING_ADD_ASSIGN),

clippy_lints/src/matches.rs

+2-3
Original file line numberDiff line numberDiff line change
@@ -689,10 +689,9 @@ fn check_single_match(cx: &LateContext<'_>, ex: &Expr<'_>, arms: &[Arm<'_>], exp
689689
if stmts.len() == 1 && block_expr.is_none() || stmts.is_empty() && block_expr.is_some() {
690690
// single statement/expr "else" block, don't lint
691691
return;
692-
} else {
693-
// block with 2+ statements or 1 expr and 1+ statement
694-
Some(els)
695692
}
693+
// block with 2+ statements or 1 expr and 1+ statement
694+
Some(els)
696695
} else {
697696
// not a block, don't lint
698697
return;

clippy_lints/src/methods/unnecessary_filter_map.rs

+2-3
Original file line numberDiff line numberDiff line change
@@ -69,10 +69,9 @@ fn check_expression<'tcx>(cx: &LateContext<'tcx>, arg_id: hir::HirId, expr: &'tc
6969
}
7070
}
7171
return (true, false);
72-
} else {
73-
// We don't know. It might do anything.
74-
return (true, true);
7572
}
73+
// We don't know. It might do anything.
74+
return (true, true);
7675
}
7776
}
7877
(true, true)

clippy_lints/src/non_expressive_names.rs

+3-4
Original file line numberDiff line numberDiff line change
@@ -409,11 +409,10 @@ fn levenstein_not_1(a_name: &str, b_name: &str) -> bool {
409409
if let Some(b2) = b_chars.next() {
410410
// check if there's just one character inserted
411411
return a != b2 || a_chars.ne(b_chars);
412-
} else {
413-
// tuple
414-
// ntuple
415-
return true;
416412
}
413+
// tuple
414+
// ntuple
415+
return true;
417416
}
418417
// for item in items
419418
true

clippy_lints/src/redundant_else.rs

+135
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,135 @@
1+
use crate::utils::span_lint_and_help;
2+
use rustc_ast::ast::{Block, Expr, ExprKind, Stmt, StmtKind};
3+
use rustc_ast::visit::{walk_expr, Visitor};
4+
use rustc_lint::{EarlyContext, EarlyLintPass};
5+
use rustc_middle::lint::in_external_macro;
6+
use rustc_session::{declare_lint_pass, declare_tool_lint};
7+
8+
declare_clippy_lint! {
9+
/// **What it does:** Checks for `else` blocks that can be removed without changing semantics.
10+
///
11+
/// **Why is this bad?** The `else` block adds unnecessary indentation and verbosity.
12+
///
13+
/// **Known problems:** Some may prefer to keep the `else` block for clarity.
14+
///
15+
/// **Example:**
16+
///
17+
/// ```rust
18+
/// fn my_func(count: u32) {
19+
/// if count == 0 {
20+
/// print!("Nothing to do");
21+
/// return;
22+
/// } else {
23+
/// print!("Moving on...");
24+
/// }
25+
/// }
26+
/// ```
27+
/// Use instead:
28+
/// ```rust
29+
/// fn my_func(count: u32) {
30+
/// if count == 0 {
31+
/// print!("Nothing to do");
32+
/// return;
33+
/// }
34+
/// print!("Moving on...");
35+
/// }
36+
/// ```
37+
pub REDUNDANT_ELSE,
38+
pedantic,
39+
"`else` branch that can be removed without changing semantics"
40+
}
41+
42+
declare_lint_pass!(RedundantElse => [REDUNDANT_ELSE]);
43+
44+
impl EarlyLintPass for RedundantElse {
45+
fn check_stmt(&mut self, cx: &EarlyContext<'_>, stmt: &Stmt) {
46+
if in_external_macro(cx.sess, stmt.span) {
47+
return;
48+
}
49+
// Only look at expressions that are a whole statement
50+
let expr: &Expr = match &stmt.kind {
51+
StmtKind::Expr(expr) | StmtKind::Semi(expr) => expr,
52+
_ => return,
53+
};
54+
// if else
55+
let (mut then, mut els): (&Block, &Expr) = match &expr.kind {
56+
ExprKind::If(_, then, Some(els)) => (then, els),
57+
_ => return,
58+
};
59+
loop {
60+
if !BreakVisitor::default().check_block(then) {
61+
// then block does not always break
62+
return;
63+
}
64+
match &els.kind {
65+
// else if else
66+
ExprKind::If(_, next_then, Some(next_els)) => {
67+
then = next_then;
68+
els = next_els;
69+
continue;
70+
},
71+
// else if without else
72+
ExprKind::If(..) => return,
73+
// done
74+
_ => break,
75+
}
76+
}
77+
span_lint_and_help(
78+
cx,
79+
REDUNDANT_ELSE,
80+
els.span,
81+
"redundant else block",
82+
None,
83+
"remove the `else` block and move the contents out",
84+
);
85+
}
86+
}
87+
88+
/// Call `check` functions to check if an expression always breaks control flow
89+
#[derive(Default)]
90+
struct BreakVisitor {
91+
is_break: bool,
92+
}
93+
94+
impl<'ast> Visitor<'ast> for BreakVisitor {
95+
fn visit_block(&mut self, block: &'ast Block) {
96+
self.is_break = match block.stmts.as_slice() {
97+
[.., last] => self.check_stmt(last),
98+
_ => false,
99+
};
100+
}
101+
102+
fn visit_expr(&mut self, expr: &'ast Expr) {
103+
self.is_break = match expr.kind {
104+
ExprKind::Break(..) | ExprKind::Continue(..) | ExprKind::Ret(..) => true,
105+
ExprKind::Match(_, ref arms) => arms.iter().all(|arm| self.check_expr(&arm.body)),
106+
ExprKind::If(_, ref then, Some(ref els)) => self.check_block(then) && self.check_expr(els),
107+
ExprKind::If(_, _, None)
108+
// ignore loops for simplicity
109+
| ExprKind::While(..) | ExprKind::ForLoop(..) | ExprKind::Loop(..) => false,
110+
_ => {
111+
walk_expr(self, expr);
112+
return;
113+
},
114+
};
115+
}
116+
}
117+
118+
impl BreakVisitor {
119+
fn check<T>(&mut self, item: T, visit: fn(&mut Self, T)) -> bool {
120+
visit(self, item);
121+
std::mem::replace(&mut self.is_break, false)
122+
}
123+
124+
fn check_block(&mut self, block: &Block) -> bool {
125+
self.check(block, Self::visit_block)
126+
}
127+
128+
fn check_expr(&mut self, expr: &Expr) -> bool {
129+
self.check(expr, Self::visit_expr)
130+
}
131+
132+
fn check_stmt(&mut self, stmt: &Stmt) -> bool {
133+
self.check(stmt, Self::visit_stmt)
134+
}
135+
}

0 commit comments

Comments
 (0)