Skip to content

Commit

Permalink
Fix implicit_return with async functions.
Browse files Browse the repository at this point in the history
Improve `implicit_return` suggestions when returning the result of a macro
Check for `break` expressions inside a loop which are then implicitly returned.
Allow all diverging functions in `implicit_return`, not just panic functions.
  • Loading branch information
Jarcho committed Mar 23, 2021
1 parent f3de78e commit 11916da
Show file tree
Hide file tree
Showing 7 changed files with 517 additions and 117 deletions.
236 changes: 155 additions & 81 deletions clippy_lints/src/implicit_return.rs
Original file line number Diff line number Diff line change
@@ -1,13 +1,17 @@
use clippy_utils::diagnostics::span_lint_and_then;
use clippy_utils::match_panic_def_id;
use clippy_utils::source::snippet_opt;
use if_chain::if_chain;
use clippy_utils::{
diagnostics::span_lint_and_sugg,
expr_sig, get_async_fn_body, is_async_fn,
source::{snippet_with_applicability, snippet_with_context, walk_span_to_context},
visitors::visit_break_exprs,
ExprFnSig,
};
use rustc_errors::Applicability;
use rustc_hir::intravisit::FnKind;
use rustc_hir::{Body, Expr, ExprKind, FnDecl, HirId, MatchSource, StmtKind};
use rustc_lint::{LateContext, LateLintPass};
use rustc_hir::{Block, Body, Expr, ExprKind, FnDecl, FnRetTy, HirId};
use rustc_lint::{LateContext, LateLintPass, LintContext};
use rustc_middle::lint::in_external_macro;
use rustc_session::{declare_lint_pass, declare_tool_lint};
use rustc_span::source_map::Span;
use rustc_span::{Span, SyntaxContext};

declare_clippy_lint! {
/// **What it does:** Checks for missing return statements at the end of a block.
Expand Down Expand Up @@ -39,109 +43,179 @@ declare_clippy_lint! {

declare_lint_pass!(ImplicitReturn => [IMPLICIT_RETURN]);

static LINT_BREAK: &str = "change `break` to `return` as shown";
static LINT_RETURN: &str = "add `return` as shown";

fn lint(cx: &LateContext<'_>, outer_span: Span, inner_span: Span, msg: &str) {
let outer_span = outer_span.source_callsite();
let inner_span = inner_span.source_callsite();

span_lint_and_then(cx, IMPLICIT_RETURN, outer_span, "missing `return` statement", |diag| {
if let Some(snippet) = snippet_opt(cx, inner_span) {
diag.span_suggestion(
outer_span,
msg,
format!("return {}", snippet),
Applicability::MachineApplicable,
);
}
});
fn lint_return(cx: &LateContext<'_>, span: Span) {
let mut app = Applicability::MachineApplicable;
let snip = snippet_with_applicability(cx, span, "..", &mut app);
span_lint_and_sugg(
cx,
IMPLICIT_RETURN,
span,
"missing `return` statement",
"add `return` as shown",
format!("return {}", snip),
app,
);
}

fn lint_break(cx: &LateContext<'_>, break_span: Span, expr_span: Span) {
let mut app = Applicability::MachineApplicable;
let snip = snippet_with_context(cx, expr_span, break_span.ctxt(), "..", &mut app).0;
span_lint_and_sugg(
cx,
IMPLICIT_RETURN,
break_span,
"missing `return` statement",
"change `break` to `return` as shown",
format!("return {}", snip),
app,
)
}

fn expr_match(cx: &LateContext<'_>, expr: &Expr<'_>) {
fn contains_implicit_return(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) -> bool {
match expr.kind {
// loops could be using `break` instead of `return`
ExprKind::Block(block, ..) | ExprKind::Loop(block, ..) => {
if let Some(expr) = &block.expr {
expr_match(cx, expr);
}
// only needed in the case of `break` with `;` at the end
else if let Some(stmt) = block.stmts.last() {
if_chain! {
if let StmtKind::Semi(expr, ..) = &stmt.kind;
// make sure it's a break, otherwise we want to skip
if let ExprKind::Break(.., Some(break_expr)) = &expr.kind;
then {
lint(cx, expr.span, break_expr.span, LINT_BREAK);
}
ExprKind::Block(
Block {
expr: Some(block_expr), ..
},
_,
) => contains_implicit_return(cx, block_expr),

ExprKind::If(_, then_expr, Some(else_expr)) => {
contains_implicit_return(cx, then_expr) || contains_implicit_return(cx, else_expr)
},
ExprKind::Match(_, arms, _) => arms.iter().any(|a| contains_implicit_return(cx, a.body)),
ExprKind::Loop(block, ..) => {
let mut break_found = false;
visit_break_exprs(block, |_, dest, _| {
if dest.target_id.ok() == Some(expr.hir_id) {
break_found = true;
}
}
});
break_found
},
// use `return` instead of `break`
ExprKind::Break(.., break_expr) => {
if let Some(break_expr) = break_expr {
lint(cx, expr.span, break_expr.span, LINT_BREAK);
}

// Diverging function and method calls are fine.
ExprKind::MethodCall(..)
if cx
.tcx
.fn_sig(cx.typeck_results().type_dependent_def_id(expr.hir_id).unwrap())
.skip_binder()
.output()
.is_never() =>
{
false
},
ExprKind::Call(func_expr, _)
if expr_sig(cx.tcx, cx.typeck_results(), func_expr)
.and_then(ExprFnSig::output)
.map_or(false, |ty| ty.skip_binder().is_never()) =>
{
false
},
ExprKind::If(.., if_expr, else_expr) => {
expr_match(cx, if_expr);

if let Some(else_expr) = else_expr {
expr_match(cx, else_expr);
// If expressions without an else clause, and blocks without a final expression can only be the final expression
// if they are divergent, or return the unit type.
ExprKind::If(_, _, None) | ExprKind::Block(Block { expr: None, .. }, _) | ExprKind::Ret(_) => false,

// everything else is missing `return`
_ => true,
}
}

fn lint_implicit_returns(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>, ctxt: SyntaxContext) {
match expr.kind {
ExprKind::Block(
Block {
expr: Some(block_expr), ..
},
_,
) => {
if ctxt == block_expr.span.ctxt() {
lint_implicit_returns(cx, block_expr, ctxt)
} else if contains_implicit_return(cx, block_expr) {
lint_return(
cx,
walk_span_to_context(block_expr.span, ctxt).unwrap_or(block_expr.span),
);
}
},
ExprKind::Match(.., arms, source) => {
let check_all_arms = match source {
MatchSource::IfLetDesugar {
contains_else_clause: has_else,
} => has_else,
_ => true,
};

if check_all_arms {
for arm in arms {
expr_match(cx, &arm.body);

ExprKind::If(_, then_expr, Some(else_expr)) => {
lint_implicit_returns(cx, then_expr, ctxt);
lint_implicit_returns(cx, else_expr, ctxt);
},

ExprKind::Match(_, arms, _) => {
for arm in arms {
if ctxt == arm.body.span.ctxt() {
lint_implicit_returns(cx, arm.body, ctxt);
} else if contains_implicit_return(cx, arm.body) {
lint_return(cx, walk_span_to_context(expr.span, ctxt).unwrap_or(expr.span));
}
} else {
expr_match(cx, &arms.first().expect("`if let` doesn't have a single arm").body);
}
},
// skip if it already has a return statement
ExprKind::Ret(..) => (),
// make sure it's not a call that panics
ExprKind::Call(expr, ..) => {
if_chain! {
if let ExprKind::Path(qpath) = &expr.kind;
if let Some(path_def_id) = cx.qpath_res(qpath, expr.hir_id).opt_def_id();
if match_panic_def_id(cx, path_def_id);
then { }
else {
lint(cx, expr.span, expr.span, LINT_RETURN)
ExprKind::Loop(block, ..) => {
let mut add_return = false;
visit_break_exprs(block, |break_expr, dest, sub_expr| {
if dest.target_id.ok() == Some(expr.hir_id) {
if break_expr.span.ctxt() == ctxt {
lint_break(cx, break_expr.span, sub_expr.unwrap().span);
} else {
add_return = true;
}
}
});
if add_return {
lint_return(cx, expr.span);
}
},

// Diverging function and method calls are fine.
ExprKind::MethodCall(..)
if cx
.tcx
.fn_sig(cx.typeck_results().type_dependent_def_id(expr.hir_id).unwrap())
.skip_binder()
.output()
.is_never() => {},
ExprKind::Call(func_expr, _)
if expr_sig(cx.tcx, cx.typeck_results(), func_expr)
.and_then(ExprFnSig::output)
.map_or(false, |ty| ty.skip_binder().is_never()) => {},

// If expressions without an else clause, and blocks without a final expression can only be the final expression
// if they are divergent, or return the unit type.
ExprKind::If(_, _, None) | ExprKind::Block(Block { expr: None, .. }, _) | ExprKind::Ret(_) => (),

// everything else is missing `return`
_ => lint(cx, expr.span, expr.span, LINT_RETURN),
_ => lint_return(cx, walk_span_to_context(expr.span, ctxt).unwrap_or(expr.span)),
}
}

impl<'tcx> LateLintPass<'tcx> for ImplicitReturn {
fn check_fn(
&mut self,
cx: &LateContext<'tcx>,
_: FnKind<'tcx>,
_: &'tcx FnDecl<'_>,
kind: FnKind<'tcx>,
decl: &'tcx FnDecl<'_>,
body: &'tcx Body<'_>,
span: Span,
_: HirId,
) {
if span.from_expansion() {
if (!matches!(kind, FnKind::Closure) && matches!(decl.output, FnRetTy::DefaultReturn(_)))
|| span.ctxt() != body.value.span.ctxt()
|| in_external_macro(cx.sess(), span)
|| cx.typeck_results().expr_ty(&body.value).is_unit()
{
return;
}
let body = cx.tcx.hir().body(body.id());
if cx.typeck_results().expr_ty(&body.value).is_unit() {
return;

if is_async_fn(kind) {
if let Some(expr) = get_async_fn_body(cx.tcx, body) {
lint_implicit_returns(cx, expr, expr.span.ctxt());
}
} else {
lint_implicit_returns(cx, &body.value, body.value.span.ctxt());
}
expr_match(cx, &body.value);
}
}
Loading

0 comments on commit 11916da

Please sign in to comment.