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