]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/implicit_return.rs
Auto merge of #3569 - phansch:update_contributing, r=flip1995
[rust.git] / clippy_lints / src / implicit_return.rs
1 // Copyright 2014-2018 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution.
3 //
4 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
5 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
7 // option. This file may not be copied, modified, or distributed
8 // except according to those terms.
9
10 use crate::rustc::hir::{intravisit::FnKind, Body, ExprKind, FnDecl};
11 use crate::rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
12 use crate::rustc::{declare_tool_lint, lint_array};
13 use crate::rustc_errors::Applicability;
14 use crate::syntax::{ast::NodeId, source_map::Span};
15 use crate::utils::{snippet_opt, span_lint_and_then};
16
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) {
30 ///     x
31 /// }
32 /// ```
33 /// add return
34 /// ```rust
35 /// fn foo(x: usize) {
36 ///     return x;
37 /// }
38 /// ```
39 declare_clippy_lint! {
40     pub IMPLICIT_RETURN,
41     restriction,
42     "use a return statement like `return expr` instead of an expression"
43 }
44
45 pub struct Pass;
46
47 impl Pass {
48     fn lint(cx: &LateContext<'_, '_>, outer_span: syntax_pos::Span, inner_span: syntax_pos::Span, msg: &str) {
49         span_lint_and_then(cx, IMPLICIT_RETURN, outer_span, "missing return statement", |db| {
50             if let Some(snippet) = snippet_opt(cx, inner_span) {
51                 db.span_suggestion_with_applicability(
52                     outer_span,
53                     msg,
54                     format!("return {}", snippet),
55                     Applicability::MachineApplicable,
56                 );
57             }
58         });
59     }
60
61     fn expr_match(cx: &LateContext<'_, '_>, expr: &rustc::hir::Expr) {
62         match &expr.node {
63             // loops could be using `break` instead of `return`
64             ExprKind::Block(block, ..) | ExprKind::Loop(block, ..) => {
65                 if let Some(expr) = &block.expr {
66                     Self::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 let rustc::hir::StmtKind::Semi(expr, ..) = &stmt.node {
71                         // make sure it's a break, otherwise we want to skip
72                         if let ExprKind::Break(.., break_expr) = &expr.node {
73                             if let Some(break_expr) = break_expr {
74                                 Self::lint(cx, expr.span, break_expr.span, "change `break` to `return` as shown");
75                             }
76                         }
77                     }
78                 }
79             },
80             // use `return` instead of `break`
81             ExprKind::Break(.., break_expr) => {
82                 if let Some(break_expr) = break_expr {
83                     Self::lint(cx, expr.span, break_expr.span, "change `break` to `return` as shown");
84                 }
85             },
86             ExprKind::If(.., if_expr, else_expr) => {
87                 Self::expr_match(cx, if_expr);
88
89                 if let Some(else_expr) = else_expr {
90                     Self::expr_match(cx, else_expr);
91                 }
92             },
93             ExprKind::Match(_, arms, ..) => {
94                 for arm in arms {
95                     Self::expr_match(cx, &arm.body);
96                 }
97             },
98             // skip if it already has a return statement
99             ExprKind::Ret(..) => (),
100             // everything else is missing `return`
101             _ => Self::lint(cx, expr.span, expr.span, "add `return` as shown"),
102         }
103     }
104 }
105
106 impl LintPass for Pass {
107     fn get_lints(&self) -> LintArray {
108         lint_array!(IMPLICIT_RETURN)
109     }
110 }
111
112 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Pass {
113     fn check_fn(
114         &mut self,
115         cx: &LateContext<'a, 'tcx>,
116         _: FnKind<'tcx>,
117         _: &'tcx FnDecl,
118         body: &'tcx Body,
119         _: Span,
120         _: NodeId,
121     ) {
122         let def_id = cx.tcx.hir().body_owner_def_id(body.id());
123         let mir = cx.tcx.optimized_mir(def_id);
124
125         // checking return type through MIR, HIR is not able to determine inferred closure return types
126         if !mir.return_ty().is_unit() {
127             Self::expr_match(cx, &body.value);
128         }
129     }
130 }