Skip to content

Commit 5e49c4b

Browse files
committed
Auto merge of #6951 - Jarcho:implicit_return_fp, r=flip1995
`implicit_return` improvements fixes: #6940 changelog: Fix `implicit_return` suggestion for async functions changelog: Improve `implicit_return` suggestions when returning the result of a macro changelog: Check for `break` expressions inside a loop which are then implicitly returned changelog: Allow all diverging functions in `implicit_return`, not just panic functions
2 parents 14f1551 + 3d793f3 commit 5e49c4b

File tree

7 files changed

+450
-140
lines changed

7 files changed

+450
-140
lines changed

clippy_lints/src/implicit_return.rs

+169-82
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,16 @@
1-
use clippy_utils::diagnostics::span_lint_and_then;
2-
use clippy_utils::match_panic_def_id;
3-
use clippy_utils::source::snippet_opt;
4-
use if_chain::if_chain;
1+
use clippy_utils::{
2+
diagnostics::span_lint_and_sugg,
3+
get_async_fn_body, is_async_fn,
4+
source::{snippet_with_applicability, snippet_with_context, walk_span_to_context},
5+
visitors::visit_break_exprs,
6+
};
57
use rustc_errors::Applicability;
68
use rustc_hir::intravisit::FnKind;
7-
use rustc_hir::{Body, Expr, ExprKind, FnDecl, HirId, MatchSource, StmtKind};
8-
use rustc_lint::{LateContext, LateLintPass};
9+
use rustc_hir::{Block, Body, Expr, ExprKind, FnDecl, FnRetTy, HirId};
10+
use rustc_lint::{LateContext, LateLintPass, LintContext};
11+
use rustc_middle::lint::in_external_macro;
912
use rustc_session::{declare_lint_pass, declare_tool_lint};
10-
use rustc_span::source_map::Span;
13+
use rustc_span::{Span, SyntaxContext};
1114

1215
declare_clippy_lint! {
1316
/// **What it does:** Checks for missing return statements at the end of a block.
@@ -39,109 +42,193 @@ declare_clippy_lint! {
3942

4043
declare_lint_pass!(ImplicitReturn => [IMPLICIT_RETURN]);
4144

42-
static LINT_BREAK: &str = "change `break` to `return` as shown";
43-
static LINT_RETURN: &str = "add `return` as shown";
44-
45-
fn lint(cx: &LateContext<'_>, outer_span: Span, inner_span: Span, msg: &str) {
46-
let outer_span = outer_span.source_callsite();
47-
let inner_span = inner_span.source_callsite();
48-
49-
span_lint_and_then(cx, IMPLICIT_RETURN, outer_span, "missing `return` statement", |diag| {
50-
if let Some(snippet) = snippet_opt(cx, inner_span) {
51-
diag.span_suggestion(
52-
outer_span,
53-
msg,
54-
format!("return {}", snippet),
55-
Applicability::MachineApplicable,
56-
);
57-
}
58-
});
45+
fn lint_return(cx: &LateContext<'_>, span: Span) {
46+
let mut app = Applicability::MachineApplicable;
47+
let snip = snippet_with_applicability(cx, span, "..", &mut app);
48+
span_lint_and_sugg(
49+
cx,
50+
IMPLICIT_RETURN,
51+
span,
52+
"missing `return` statement",
53+
"add `return` as shown",
54+
format!("return {}", snip),
55+
app,
56+
);
57+
}
58+
59+
fn lint_break(cx: &LateContext<'_>, break_span: Span, expr_span: Span) {
60+
let mut app = Applicability::MachineApplicable;
61+
let snip = snippet_with_context(cx, expr_span, break_span.ctxt(), "..", &mut app).0;
62+
span_lint_and_sugg(
63+
cx,
64+
IMPLICIT_RETURN,
65+
break_span,
66+
"missing `return` statement",
67+
"change `break` to `return` as shown",
68+
format!("return {}", snip),
69+
app,
70+
)
71+
}
72+
73+
#[derive(Clone, Copy, PartialEq, Eq)]
74+
enum LintLocation {
75+
/// The lint was applied to a parent expression.
76+
Parent,
77+
/// The lint was applied to this expression, a child, or not applied.
78+
Inner,
79+
}
80+
impl LintLocation {
81+
fn still_parent(self, b: bool) -> Self {
82+
if b { self } else { Self::Inner }
83+
}
84+
85+
fn is_parent(self) -> bool {
86+
self == Self::Parent
87+
}
88+
}
89+
90+
// Gets the call site if the span is in a child context. Otherwise returns `None`.
91+
fn get_call_site(span: Span, ctxt: SyntaxContext) -> Option<Span> {
92+
(span.ctxt() != ctxt).then(|| walk_span_to_context(span, ctxt).unwrap_or(span))
5993
}
6094

61-
fn expr_match(cx: &LateContext<'_>, expr: &Expr<'_>) {
95+
fn lint_implicit_returns(
96+
cx: &LateContext<'tcx>,
97+
expr: &'tcx Expr<'_>,
98+
// The context of the function body.
99+
ctxt: SyntaxContext,
100+
// Whether the expression is from a macro expansion.
101+
call_site_span: Option<Span>,
102+
) -> LintLocation {
62103
match expr.kind {
63-
// loops could be using `break` instead of `return`
64-
ExprKind::Block(block, ..) | ExprKind::Loop(block, ..) => {
65-
if let Some(expr) = &block.expr {
66-
expr_match(cx, expr);
67-
}
68-
// only needed in the case of `break` with `;` at the end
69-
else if let Some(stmt) = block.stmts.last() {
70-
if_chain! {
71-
if let StmtKind::Semi(expr, ..) = &stmt.kind;
72-
// make sure it's a break, otherwise we want to skip
73-
if let ExprKind::Break(.., Some(break_expr)) = &expr.kind;
74-
then {
75-
lint(cx, expr.span, break_expr.span, LINT_BREAK);
76-
}
77-
}
78-
}
79-
},
80-
// use `return` instead of `break`
81-
ExprKind::Break(.., break_expr) => {
82-
if let Some(break_expr) = break_expr {
83-
lint(cx, expr.span, break_expr.span, LINT_BREAK);
104+
ExprKind::Block(
105+
Block {
106+
expr: Some(block_expr), ..
107+
},
108+
_,
109+
) => lint_implicit_returns(
110+
cx,
111+
block_expr,
112+
ctxt,
113+
call_site_span.or_else(|| get_call_site(block_expr.span, ctxt)),
114+
)
115+
.still_parent(call_site_span.is_some()),
116+
117+
ExprKind::If(_, then_expr, Some(else_expr)) => {
118+
// Both `then_expr` or `else_expr` are required to be blocks in the same context as the `if`. Don't
119+
// bother checking.
120+
let res = lint_implicit_returns(cx, then_expr, ctxt, call_site_span).still_parent(call_site_span.is_some());
121+
if res.is_parent() {
122+
// The return was added as a parent of this if expression.
123+
return res;
84124
}
125+
lint_implicit_returns(cx, else_expr, ctxt, call_site_span).still_parent(call_site_span.is_some())
85126
},
86-
ExprKind::If(.., if_expr, else_expr) => {
87-
expr_match(cx, if_expr);
88127

89-
if let Some(else_expr) = else_expr {
90-
expr_match(cx, else_expr);
128+
ExprKind::Match(_, arms, _) => {
129+
for arm in arms {
130+
let res = lint_implicit_returns(
131+
cx,
132+
arm.body,
133+
ctxt,
134+
call_site_span.or_else(|| get_call_site(arm.body.span, ctxt)),
135+
)
136+
.still_parent(call_site_span.is_some());
137+
if res.is_parent() {
138+
// The return was added as a parent of this match expression.
139+
return res;
140+
}
91141
}
142+
LintLocation::Inner
92143
},
93-
ExprKind::Match(.., arms, source) => {
94-
let check_all_arms = match source {
95-
MatchSource::IfLetDesugar {
96-
contains_else_clause: has_else,
97-
} => has_else,
98-
_ => true,
99-
};
100-
101-
if check_all_arms {
102-
for arm in arms {
103-
expr_match(cx, arm.body);
144+
145+
ExprKind::Loop(block, ..) => {
146+
let mut add_return = false;
147+
visit_break_exprs(block, |break_expr, dest, sub_expr| {
148+
if dest.target_id.ok() == Some(expr.hir_id) {
149+
if call_site_span.is_none() && break_expr.span.ctxt() == ctxt {
150+
lint_break(cx, break_expr.span, sub_expr.unwrap().span);
151+
} else {
152+
// the break expression is from a macro call, add a return to the loop
153+
add_return = true;
154+
}
155+
}
156+
});
157+
if add_return {
158+
#[allow(clippy::option_if_let_else)]
159+
if let Some(span) = call_site_span {
160+
lint_return(cx, span);
161+
LintLocation::Parent
162+
} else {
163+
lint_return(cx, expr.span);
164+
LintLocation::Inner
104165
}
105166
} else {
106-
expr_match(cx, arms.first().expect("`if let` doesn't have a single arm").body);
167+
LintLocation::Inner
107168
}
108169
},
109-
// skip if it already has a return statement
110-
ExprKind::Ret(..) => (),
111-
// make sure it's not a call that panics
112-
ExprKind::Call(expr, ..) => {
113-
if_chain! {
114-
if let ExprKind::Path(qpath) = &expr.kind;
115-
if let Some(path_def_id) = cx.qpath_res(qpath, expr.hir_id).opt_def_id();
116-
if match_panic_def_id(cx, path_def_id);
117-
then { }
118-
else {
119-
lint(cx, expr.span, expr.span, LINT_RETURN)
120-
}
170+
171+
// If expressions without an else clause, and blocks without a final expression can only be the final expression
172+
// if they are divergent, or return the unit type.
173+
ExprKind::If(_, _, None) | ExprKind::Block(Block { expr: None, .. }, _) | ExprKind::Ret(_) => {
174+
LintLocation::Inner
175+
},
176+
177+
// Any divergent expression doesn't need a return statement.
178+
ExprKind::MethodCall(..)
179+
| ExprKind::Call(..)
180+
| ExprKind::Binary(..)
181+
| ExprKind::Unary(..)
182+
| ExprKind::Index(..)
183+
if cx.typeck_results().expr_ty(expr).is_never() =>
184+
{
185+
LintLocation::Inner
186+
},
187+
188+
_ =>
189+
{
190+
#[allow(clippy::option_if_let_else)]
191+
if let Some(span) = call_site_span {
192+
lint_return(cx, span);
193+
LintLocation::Parent
194+
} else {
195+
lint_return(cx, expr.span);
196+
LintLocation::Inner
121197
}
122198
},
123-
// everything else is missing `return`
124-
_ => lint(cx, expr.span, expr.span, LINT_RETURN),
125199
}
126200
}
127201

128202
impl<'tcx> LateLintPass<'tcx> for ImplicitReturn {
129203
fn check_fn(
130204
&mut self,
131205
cx: &LateContext<'tcx>,
132-
_: FnKind<'tcx>,
133-
_: &'tcx FnDecl<'_>,
206+
kind: FnKind<'tcx>,
207+
decl: &'tcx FnDecl<'_>,
134208
body: &'tcx Body<'_>,
135209
span: Span,
136210
_: HirId,
137211
) {
138-
if span.from_expansion() {
212+
if (!matches!(kind, FnKind::Closure) && matches!(decl.output, FnRetTy::DefaultReturn(_)))
213+
|| span.ctxt() != body.value.span.ctxt()
214+
|| in_external_macro(cx.sess(), span)
215+
{
139216
return;
140217
}
141-
let body = cx.tcx.hir().body(body.id());
142-
if cx.typeck_results().expr_ty(&body.value).is_unit() {
218+
219+
let res_ty = cx.typeck_results().expr_ty(&body.value);
220+
if res_ty.is_unit() || res_ty.is_never() {
143221
return;
144222
}
145-
expr_match(cx, &body.value);
223+
224+
let expr = if is_async_fn(kind) {
225+
match get_async_fn_body(cx.tcx, body) {
226+
Some(e) => e,
227+
None => return,
228+
}
229+
} else {
230+
&body.value
231+
};
232+
lint_implicit_returns(cx, expr, expr.span.ctxt(), None);
146233
}
147234
}

clippy_utils/src/lib.rs

+37-3
Original file line numberDiff line numberDiff line change
@@ -61,12 +61,12 @@ use rustc_data_structures::fx::FxHashMap;
6161
use rustc_hir as hir;
6262
use rustc_hir::def::{DefKind, Res};
6363
use rustc_hir::def_id::{DefId, LOCAL_CRATE};
64-
use rustc_hir::intravisit::{self, walk_expr, ErasedMap, NestedVisitorMap, Visitor};
64+
use rustc_hir::intravisit::{self, walk_expr, ErasedMap, FnKind, NestedVisitorMap, Visitor};
6565
use rustc_hir::LangItem::{ResultErr, ResultOk};
6666
use rustc_hir::{
6767
def, Arm, BindingAnnotation, Block, Body, Constness, Destination, Expr, ExprKind, FnDecl, GenericArgs, HirId, Impl,
68-
ImplItem, ImplItemKind, Item, ItemKind, LangItem, Local, MatchSource, Node, Param, Pat, PatKind, Path, PathSegment,
69-
QPath, Stmt, StmtKind, TraitItem, TraitItemKind, TraitRef, TyKind,
68+
ImplItem, ImplItemKind, IsAsync, Item, ItemKind, LangItem, Local, MatchSource, Node, Param, Pat, PatKind, Path,
69+
PathSegment, QPath, Stmt, StmtKind, TraitItem, TraitItemKind, TraitRef, TyKind,
7070
};
7171
use rustc_lint::{LateContext, Level, Lint, LintContext};
7272
use rustc_middle::hir::exports::Export;
@@ -1301,6 +1301,40 @@ pub fn if_sequence<'tcx>(mut expr: &'tcx Expr<'tcx>) -> (Vec<&'tcx Expr<'tcx>>,
13011301
(conds, blocks)
13021302
}
13031303

1304+
/// Checks if the given function kind is an async function.
1305+
pub fn is_async_fn(kind: FnKind) -> bool {
1306+
matches!(kind, FnKind::ItemFn(_, _, header, _) if header.asyncness == IsAsync::Async)
1307+
}
1308+
1309+
/// Peels away all the compiler generated code surrounding the body of an async function,
1310+
pub fn get_async_fn_body(tcx: TyCtxt<'tcx>, body: &Body<'_>) -> Option<&'tcx Expr<'tcx>> {
1311+
if let ExprKind::Call(
1312+
_,
1313+
&[Expr {
1314+
kind: ExprKind::Closure(_, _, body, _, _),
1315+
..
1316+
}],
1317+
) = body.value.kind
1318+
{
1319+
if let ExprKind::Block(
1320+
Block {
1321+
stmts: [],
1322+
expr:
1323+
Some(Expr {
1324+
kind: ExprKind::DropTemps(expr),
1325+
..
1326+
}),
1327+
..
1328+
},
1329+
_,
1330+
) = tcx.hir().body(body).value.kind
1331+
{
1332+
return Some(expr);
1333+
}
1334+
};
1335+
None
1336+
}
1337+
13041338
// Finds the `#[must_use]` attribute, if any
13051339
pub fn must_use_attr(attrs: &[Attribute]) -> Option<&Attribute> {
13061340
attrs.iter().find(|a| a.has_name(sym::must_use))

0 commit comments

Comments
 (0)