]> git.lizzy.rs Git - rust.git/blob - src/tools/clippy/clippy_lints/src/implicit_return.rs
Auto merge of #71780 - jcotton42:string_remove_matches, r=joshtriplett
[rust.git] / src / tools / clippy / clippy_lints / src / implicit_return.rs
1 use crate::utils::{match_panic_def_id, snippet_opt, span_lint_and_then};
2 use if_chain::if_chain;
3 use rustc_errors::Applicability;
4 use rustc_hir::intravisit::FnKind;
5 use rustc_hir::{Body, Expr, ExprKind, FnDecl, HirId, MatchSource, StmtKind};
6 use rustc_lint::{LateContext, LateLintPass};
7 use rustc_session::{declare_lint_pass, declare_tool_lint};
8 use rustc_span::source_map::Span;
9
10 declare_clippy_lint! {
11     /// **What it does:** Checks for missing return statements at the end of a block.
12     ///
13     /// **Why is this bad?** Actually omitting the return keyword is idiomatic Rust code. Programmers
14     /// coming from other languages might prefer the expressiveness of `return`. It's possible to miss
15     /// the last returning statement because the only difference is a missing `;`. Especially in bigger
16     /// code with multiple return paths having a `return` keyword makes it easier to find the
17     /// corresponding statements.
18     ///
19     /// **Known problems:** None.
20     ///
21     /// **Example:**
22     /// ```rust
23     /// fn foo(x: usize) -> usize {
24     ///     x
25     /// }
26     /// ```
27     /// add return
28     /// ```rust
29     /// fn foo(x: usize) -> usize {
30     ///     return x;
31     /// }
32     /// ```
33     pub IMPLICIT_RETURN,
34     restriction,
35     "use a return statement like `return expr` instead of an expression"
36 }
37
38 declare_lint_pass!(ImplicitReturn => [IMPLICIT_RETURN]);
39
40 static LINT_BREAK: &str = "change `break` to `return` as shown";
41 static LINT_RETURN: &str = "add `return` as shown";
42
43 fn lint(cx: &LateContext<'_>, outer_span: Span, inner_span: Span, msg: &str) {
44     let outer_span = outer_span.source_callsite();
45     let inner_span = inner_span.source_callsite();
46
47     span_lint_and_then(cx, IMPLICIT_RETURN, outer_span, "missing `return` statement", |diag| {
48         if let Some(snippet) = snippet_opt(cx, inner_span) {
49             diag.span_suggestion(
50                 outer_span,
51                 msg,
52                 format!("return {}", snippet),
53                 Applicability::MachineApplicable,
54             );
55         }
56     });
57 }
58
59 fn expr_match(cx: &LateContext<'_>, expr: &Expr<'_>) {
60     match expr.kind {
61         // loops could be using `break` instead of `return`
62         ExprKind::Block(block, ..) | ExprKind::Loop(block, ..) => {
63             if let Some(expr) = &block.expr {
64                 expr_match(cx, expr);
65             }
66             // only needed in the case of `break` with `;` at the end
67             else if let Some(stmt) = block.stmts.last() {
68                 if_chain! {
69                     if let StmtKind::Semi(expr, ..) = &stmt.kind;
70                     // make sure it's a break, otherwise we want to skip
71                     if let ExprKind::Break(.., Some(break_expr)) = &expr.kind;
72                     then {
73                             lint(cx, expr.span, break_expr.span, LINT_BREAK);
74                     }
75                 }
76             }
77         },
78         // use `return` instead of `break`
79         ExprKind::Break(.., break_expr) => {
80             if let Some(break_expr) = break_expr {
81                 lint(cx, expr.span, break_expr.span, LINT_BREAK);
82             }
83         },
84         ExprKind::If(.., if_expr, else_expr) => {
85             expr_match(cx, if_expr);
86
87             if let Some(else_expr) = else_expr {
88                 expr_match(cx, else_expr);
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.qpath_res(qpath, expr.hir_id).opt_def_id();
114                 if match_panic_def_id(cx, path_def_id);
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<'tcx> LateLintPass<'tcx> for ImplicitReturn {
127     fn check_fn(
128         &mut self,
129         cx: &LateContext<'tcx>,
130         _: FnKind<'tcx>,
131         _: &'tcx FnDecl<'_>,
132         body: &'tcx Body<'_>,
133         span: Span,
134         _: HirId,
135     ) {
136         if span.from_expansion() {
137             return;
138         }
139         let body = cx.tcx.hir().body(body.id());
140         if cx.typeck_results().expr_ty(&body.value).is_unit() {
141             return;
142         }
143         expr_match(cx, &body.value);
144     }
145 }