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