]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/implicit_return.rs
Auto merge of #4372 - phansch:changelog_update, r=flip1995
[rust.git] / clippy_lints / src / implicit_return.rs
1 use crate::utils::{
2     match_def_path,
3     paths::{BEGIN_PANIC, BEGIN_PANIC_FMT},
4     resolve_node, snippet_opt, span_lint_and_then,
5 };
6 use if_chain::if_chain;
7 use rustc::{
8     declare_lint_pass, declare_tool_lint,
9     hir::{intravisit::FnKind, Body, Expr, ExprKind, FnDecl, HirId, MatchSource, StmtKind},
10     lint::{LateContext, LateLintPass, LintArray, LintPass},
11 };
12 use rustc_errors::Applicability;
13 use syntax::source_map::Span;
14
15 declare_clippy_lint! {
16     /// **What it does:** Checks for missing return statements at the end of a block.
17     ///
18     /// **Why is this bad?** Actually omitting the return keyword is idiomatic Rust code. Programmers
19     /// coming from other languages might prefer the expressiveness of `return`. It's possible to miss
20     /// the last returning statement because the only difference is a missing `;`. Especially in bigger
21     /// code with multiple return paths having a `return` keyword makes it easier to find the
22     /// corresponding statements.
23     ///
24     /// **Known problems:** None.
25     ///
26     /// **Example:**
27     /// ```rust
28     /// fn foo(x: usize) -> usize {
29     ///     x
30     /// }
31     /// ```
32     /// add return
33     /// ```rust
34     /// fn foo(x: usize) -> usize {
35     ///     return x;
36     /// }
37     /// ```
38     pub IMPLICIT_RETURN,
39     restriction,
40     "use a return statement like `return expr` instead of an expression"
41 }
42
43 declare_lint_pass!(ImplicitReturn => [IMPLICIT_RETURN]);
44
45 static LINT_BREAK: &str = "change `break` to `return` as shown";
46 static LINT_RETURN: &str = "add `return` as shown";
47
48 fn lint(cx: &LateContext<'_, '_>, outer_span: Span, inner_span: Span, msg: &str) {
49     let outer_span = outer_span.source_callsite();
50     let inner_span = inner_span.source_callsite();
51
52     span_lint_and_then(cx, IMPLICIT_RETURN, outer_span, "missing return statement", |db| {
53         if let Some(snippet) = snippet_opt(cx, inner_span) {
54             db.span_suggestion(
55                 outer_span,
56                 msg,
57                 format!("return {}", snippet),
58                 Applicability::MachineApplicable,
59             );
60         }
61     });
62 }
63
64 fn expr_match(cx: &LateContext<'_, '_>, expr: &Expr) {
65     match &expr.node {
66         // loops could be using `break` instead of `return`
67         ExprKind::Block(block, ..) | ExprKind::Loop(block, ..) => {
68             if let Some(expr) = &block.expr {
69                 expr_match(cx, expr);
70             }
71             // only needed in the case of `break` with `;` at the end
72             else if let Some(stmt) = block.stmts.last() {
73                 if_chain! {
74                     if let StmtKind::Semi(expr, ..) = &stmt.node;
75                     // make sure it's a break, otherwise we want to skip
76                     if let ExprKind::Break(.., break_expr) = &expr.node;
77                     if let Some(break_expr) = break_expr;
78                     then {
79                             lint(cx, expr.span, break_expr.span, LINT_BREAK);
80                     }
81                 }
82             }
83         },
84         // use `return` instead of `break`
85         ExprKind::Break(.., break_expr) => {
86             if let Some(break_expr) = break_expr {
87                 lint(cx, expr.span, break_expr.span, LINT_BREAK);
88             }
89         },
90         ExprKind::Match(.., arms, source) => {
91             let check_all_arms = match source {
92                 MatchSource::IfLetDesugar {
93                     contains_else_clause: has_else,
94                 } => *has_else,
95                 _ => true,
96             };
97
98             if check_all_arms {
99                 for arm in arms {
100                     expr_match(cx, &arm.body);
101                 }
102             } else {
103                 expr_match(cx, &arms.first().expect("if let doesn't have a single arm").body);
104             }
105         },
106         // skip if it already has a return statement
107         ExprKind::Ret(..) => (),
108         // make sure it's not a call that panics
109         ExprKind::Call(expr, ..) => {
110             if_chain! {
111                 if let ExprKind::Path(qpath) = &expr.node;
112                 if let Some(path_def_id) = resolve_node(cx, qpath, expr.hir_id).opt_def_id();
113                 if match_def_path(cx, path_def_id, &BEGIN_PANIC) ||
114                     match_def_path(cx, path_def_id, &BEGIN_PANIC_FMT);
115                 then { }
116                 else {
117                     lint(cx, expr.span, expr.span, LINT_RETURN)
118                 }
119             }
120         },
121         // everything else is missing `return`
122         _ => lint(cx, expr.span, expr.span, LINT_RETURN),
123     }
124 }
125
126 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for ImplicitReturn {
127     fn check_fn(
128         &mut self,
129         cx: &LateContext<'a, 'tcx>,
130         _: FnKind<'tcx>,
131         _: &'tcx FnDecl,
132         body: &'tcx Body,
133         span: Span,
134         _: HirId,
135     ) {
136         let def_id = cx.tcx.hir().body_owner_def_id(body.id());
137         let mir = cx.tcx.optimized_mir(def_id);
138
139         // checking return type through MIR, HIR is not able to determine inferred closure return types
140         // make sure it's not a macro
141         if !mir.return_ty().is_unit() && !span.from_expansion() {
142             expr_match(cx, &body.value);
143         }
144     }
145 }