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