Skip to content

Commit 6d18fe7

Browse files
committed
Make needless_return a late lint pass
1 parent f0cc006 commit 6d18fe7

File tree

4 files changed

+175
-142
lines changed

4 files changed

+175
-142
lines changed

clippy_lints/src/lib.rs

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -256,6 +256,7 @@ mod needless_borrow;
256256
mod needless_borrowed_ref;
257257
mod needless_continue;
258258
mod needless_pass_by_value;
259+
mod needless_return;
259260
mod needless_update;
260261
mod neg_cmp_op_on_partial_ord;
261262
mod neg_multiply;
@@ -726,6 +727,7 @@ pub fn register_plugins(store: &mut rustc_lint::LintStore, sess: &Session, conf:
726727
&needless_borrowed_ref::NEEDLESS_BORROWED_REFERENCE,
727728
&needless_continue::NEEDLESS_CONTINUE,
728729
&needless_pass_by_value::NEEDLESS_PASS_BY_VALUE,
730+
&needless_return::NEEDLESS_RETURN,
729731
&needless_update::NEEDLESS_UPDATE,
730732
&neg_cmp_op_on_partial_ord::NEG_CMP_OP_ON_PARTIAL_ORD,
731733
&neg_multiply::NEG_MULTIPLY,
@@ -769,7 +771,6 @@ pub fn register_plugins(store: &mut rustc_lint::LintStore, sess: &Session, conf:
769771
&regex::INVALID_REGEX,
770772
&regex::TRIVIAL_REGEX,
771773
&repeat_once::REPEAT_ONCE,
772-
&returns::NEEDLESS_RETURN,
773774
&returns::UNUSED_UNIT,
774775
&serde_api::SERDE_API_MISUSE,
775776
&shadow::SHADOW_REUSE,
@@ -1027,6 +1028,7 @@ pub fn register_plugins(store: &mut rustc_lint::LintStore, sess: &Session, conf:
10271028
store.register_late_pass(|| box redundant_closure_call::RedundantClosureCall);
10281029
store.register_early_pass(|| box returns::Return);
10291030
store.register_late_pass(|| box let_and_return::LetReturn);
1031+
store.register_late_pass(|| box needless_return::NeedlessReturn);
10301032
store.register_early_pass(|| box collapsible_if::CollapsibleIf);
10311033
store.register_early_pass(|| box items_after_statements::ItemsAfterStatements);
10321034
store.register_early_pass(|| box precedence::Precedence);
@@ -1381,6 +1383,7 @@ pub fn register_plugins(store: &mut rustc_lint::LintStore, sess: &Session, conf:
13811383
LintId::of(&needless_bool::BOOL_COMPARISON),
13821384
LintId::of(&needless_bool::NEEDLESS_BOOL),
13831385
LintId::of(&needless_borrowed_ref::NEEDLESS_BORROWED_REFERENCE),
1386+
LintId::of(&needless_return::NEEDLESS_RETURN),
13841387
LintId::of(&needless_update::NEEDLESS_UPDATE),
13851388
LintId::of(&neg_cmp_op_on_partial_ord::NEG_CMP_OP_ON_PARTIAL_ORD),
13861389
LintId::of(&neg_multiply::NEG_MULTIPLY),
@@ -1413,7 +1416,6 @@ pub fn register_plugins(store: &mut rustc_lint::LintStore, sess: &Session, conf:
14131416
LintId::of(&regex::INVALID_REGEX),
14141417
LintId::of(&regex::TRIVIAL_REGEX),
14151418
LintId::of(&repeat_once::REPEAT_ONCE),
1416-
LintId::of(&returns::NEEDLESS_RETURN),
14171419
LintId::of(&returns::UNUSED_UNIT),
14181420
LintId::of(&serde_api::SERDE_API_MISUSE),
14191421
LintId::of(&single_component_path_imports::SINGLE_COMPONENT_PATH_IMPORTS),
@@ -1543,6 +1545,7 @@ pub fn register_plugins(store: &mut rustc_lint::LintStore, sess: &Session, conf:
15431545
LintId::of(&misc_early::MIXED_CASE_HEX_LITERALS),
15441546
LintId::of(&misc_early::REDUNDANT_PATTERN),
15451547
LintId::of(&mut_reference::UNNECESSARY_MUT_PASSED),
1548+
LintId::of(&needless_return::NEEDLESS_RETURN),
15461549
LintId::of(&neg_multiply::NEG_MULTIPLY),
15471550
LintId::of(&new_without_default::NEW_WITHOUT_DEFAULT),
15481551
LintId::of(&non_expressive_names::JUST_UNDERSCORES_AND_DIGITS),
@@ -1554,7 +1557,6 @@ pub fn register_plugins(store: &mut rustc_lint::LintStore, sess: &Session, conf:
15541557
LintId::of(&redundant_field_names::REDUNDANT_FIELD_NAMES),
15551558
LintId::of(&redundant_static_lifetimes::REDUNDANT_STATIC_LIFETIMES),
15561559
LintId::of(&regex::TRIVIAL_REGEX),
1557-
LintId::of(&returns::NEEDLESS_RETURN),
15581560
LintId::of(&returns::UNUSED_UNIT),
15591561
LintId::of(&single_component_path_imports::SINGLE_COMPONENT_PATH_IMPORTS),
15601562
LintId::of(&strings::STRING_LIT_AS_BYTES),

clippy_lints/src/needless_return.rs

Lines changed: 166 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,166 @@
1+
use rustc_lint::{LateLintPass, LateContext};
2+
use rustc_ast::ast::Attribute;
3+
use rustc_session::{declare_lint_pass, declare_tool_lint};
4+
use rustc_errors::Applicability;
5+
use rustc_hir::intravisit::FnKind;
6+
use rustc_span::source_map::Span;
7+
use rustc_middle::lint::in_external_macro;
8+
use rustc_hir::{Block, Body, Expr, ExprKind, FnDecl, HirId, MatchSource, StmtKind};
9+
10+
use crate::utils::{snippet_opt, span_lint_and_sugg, span_lint_and_then};
11+
12+
declare_clippy_lint! {
13+
/// **What it does:** Checks for return statements at the end of a block.
14+
///
15+
/// **Why is this bad?** Removing the `return` and semicolon will make the code
16+
/// more rusty.
17+
///
18+
/// **Known problems:** If the computation returning the value borrows a local
19+
/// variable, removing the `return` may run afoul of the borrow checker.
20+
///
21+
/// **Example:**
22+
/// ```rust
23+
/// fn foo(x: usize) -> usize {
24+
/// return x;
25+
/// }
26+
/// ```
27+
/// simplify to
28+
/// ```rust
29+
/// fn foo(x: usize) -> usize {
30+
/// x
31+
/// }
32+
/// ```
33+
pub NEEDLESS_RETURN,
34+
style,
35+
"using a return statement like `return expr;` where an expression would suffice"
36+
}
37+
38+
#[derive(PartialEq, Eq, Copy, Clone)]
39+
enum RetReplacement {
40+
Empty,
41+
Block,
42+
}
43+
44+
declare_lint_pass!(NeedlessReturn => [NEEDLESS_RETURN]);
45+
46+
impl<'tcx> LateLintPass<'tcx> for NeedlessReturn {
47+
fn check_fn(&mut self, cx: &LateContext<'tcx>, kind: FnKind<'tcx>, _: &'tcx FnDecl<'tcx>, body: &'tcx Body<'tcx>, _: Span, _: HirId) {
48+
match kind {
49+
FnKind::Closure(_) => {
50+
check_final_expr(cx, &body.value, Some(body.value.span), RetReplacement::Empty)
51+
}
52+
FnKind::ItemFn(..) | FnKind::Method(..) => {
53+
if let ExprKind::Block(ref block, _) = body.value.kind {
54+
check_block_return(cx, block)
55+
}
56+
}
57+
}
58+
}
59+
}
60+
61+
fn attr_is_cfg(attr: &Attribute) -> bool {
62+
attr.meta_item_list().is_some() && attr.has_name(sym!(cfg))
63+
}
64+
65+
fn check_block_return(cx: &LateContext<'_>, block: &Block<'_>) {
66+
if let Some(expr) = block.expr {
67+
check_final_expr(cx, expr, Some(expr.span), RetReplacement::Empty);
68+
} else if let Some(stmt) = block.stmts.iter().last() {
69+
match stmt.kind {
70+
StmtKind::Expr(ref expr) | StmtKind::Semi(ref expr) => {
71+
check_final_expr(cx, expr, Some(stmt.span), RetReplacement::Empty);
72+
}
73+
_ => (),
74+
}
75+
}
76+
}
77+
78+
79+
fn check_final_expr(
80+
cx: &LateContext<'_>,
81+
expr: &Expr<'_>,
82+
span: Option<Span>,
83+
replacement: RetReplacement,
84+
) {
85+
match expr.kind {
86+
// simple return is always "bad"
87+
ExprKind::Ret(ref inner) => {
88+
89+
// allow `#[cfg(a)] return a; #[cfg(b)] return b;`
90+
if !expr.attrs.iter().any(attr_is_cfg) {
91+
emit_return_lint(
92+
cx,
93+
span.expect("`else return` is not possible"),
94+
inner.as_ref().map(|i| i.span),
95+
replacement,
96+
);
97+
}
98+
}
99+
// a whole block? check it!
100+
ExprKind::Block(ref block, _) => {
101+
check_block_return(cx, block);
102+
}
103+
// a match expr, check all arms
104+
// an if/if let expr, check both exprs
105+
// note, if without else is going to be a type checking error anyways
106+
// (except for unit type functions) so we don't match it
107+
108+
ExprKind::Match(_, ref arms, source) => {
109+
match source {
110+
MatchSource::Normal => {
111+
for arm in arms.iter() {
112+
check_final_expr(cx, &arm.body, Some(arm.body.span), RetReplacement::Block);
113+
}
114+
}
115+
MatchSource::IfDesugar { contains_else_clause: true } | MatchSource::IfLetDesugar { contains_else_clause: true } => {
116+
if let ExprKind::Block(ref ifblock, _) = arms[0].body.kind {
117+
check_block_return(cx, ifblock);
118+
}
119+
check_final_expr(cx, arms[1].body, None, RetReplacement::Empty);
120+
}
121+
_ => ()
122+
}
123+
}
124+
_ => (),
125+
}
126+
}
127+
128+
fn emit_return_lint(cx: &LateContext<'_>, ret_span: Span, inner_span: Option<Span>, replacement: RetReplacement) {
129+
match inner_span {
130+
Some(inner_span) => {
131+
if in_external_macro(cx.tcx.sess, inner_span) || inner_span.from_expansion() {
132+
return;
133+
}
134+
135+
span_lint_and_then(cx, NEEDLESS_RETURN, ret_span, "unneeded `return` statement", |diag| {
136+
if let Some(snippet) = snippet_opt(cx, inner_span) {
137+
diag.span_suggestion(ret_span, "remove `return`", snippet, Applicability::MachineApplicable);
138+
}
139+
})
140+
}
141+
None => match replacement {
142+
RetReplacement::Empty => {
143+
span_lint_and_sugg(
144+
cx,
145+
NEEDLESS_RETURN,
146+
ret_span,
147+
"unneeded `return` statement",
148+
"remove `return`",
149+
String::new(),
150+
Applicability::MachineApplicable,
151+
);
152+
}
153+
RetReplacement::Block => {
154+
span_lint_and_sugg(
155+
cx,
156+
NEEDLESS_RETURN,
157+
ret_span,
158+
"unneeded `return` statement",
159+
"replace `return` with an empty block",
160+
"{}".to_string(),
161+
Applicability::MachineApplicable,
162+
);
163+
}
164+
},
165+
}
166+
}

0 commit comments

Comments
 (0)