]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/implicit_return.rs
Improve `implicit_return`
[rust.git] / clippy_lints / src / implicit_return.rs
1 use clippy_utils::{
2     diagnostics::span_lint_and_sugg,
3     source::{snippet_with_applicability, snippet_with_context, walk_span_to_context},
4     visitors::visit_break_exprs,
5 };
6 use rustc_errors::Applicability;
7 use rustc_hir::intravisit::FnKind;
8 use rustc_hir::{Block, Body, Expr, ExprKind, FnDecl, FnRetTy, HirId};
9 use rustc_lint::{LateContext, LateLintPass, LintContext};
10 use rustc_middle::lint::in_external_macro;
11 use rustc_session::{declare_lint_pass, declare_tool_lint};
12 use rustc_span::{Span, SyntaxContext};
13
14 declare_clippy_lint! {
15     /// **What it does:** Checks for missing return statements at the end of a block.
16     ///
17     /// **Why is this bad?** Actually omitting the return keyword is idiomatic Rust code. Programmers
18     /// coming from other languages might prefer the expressiveness of `return`. It's possible to miss
19     /// the last returning statement because the only difference is a missing `;`. Especially in bigger
20     /// code with multiple return paths having a `return` keyword makes it easier to find the
21     /// corresponding statements.
22     ///
23     /// **Known problems:** None.
24     ///
25     /// **Example:**
26     /// ```rust
27     /// fn foo(x: usize) -> usize {
28     ///     x
29     /// }
30     /// ```
31     /// add return
32     /// ```rust
33     /// fn foo(x: usize) -> usize {
34     ///     return x;
35     /// }
36     /// ```
37     pub IMPLICIT_RETURN,
38     restriction,
39     "use a return statement like `return expr` instead of an expression"
40 }
41
42 declare_lint_pass!(ImplicitReturn => [IMPLICIT_RETURN]);
43
44 fn lint_return(cx: &LateContext<'_>, span: Span) {
45     let mut app = Applicability::MachineApplicable;
46     let snip = snippet_with_applicability(cx, span, "..", &mut app);
47     span_lint_and_sugg(
48         cx,
49         IMPLICIT_RETURN,
50         span,
51         "missing `return` statement",
52         "add `return` as shown",
53         format!("return {}", snip),
54         app,
55     );
56 }
57
58 fn lint_break(cx: &LateContext<'_>, break_span: Span, expr_span: Span) {
59     let mut app = Applicability::MachineApplicable;
60     let snip = snippet_with_context(cx, expr_span, break_span.ctxt(), "..", &mut app).0;
61     span_lint_and_sugg(
62         cx,
63         IMPLICIT_RETURN,
64         break_span,
65         "missing `return` statement",
66         "change `break` to `return` as shown",
67         format!("return {}", snip),
68         app,
69     )
70 }
71
72 enum LintLocation {
73     /// The lint was applied to a parent expression.
74     Parent,
75     /// The lint was applied to this expression, a child, or not applied.
76     Inner,
77 }
78 impl LintLocation {
79     fn still_parent(self, b: bool) -> Self {
80         if b { self } else { Self::Inner }
81     }
82
83     fn is_parent(&self) -> bool {
84         matches!(*self, Self::Parent)
85     }
86 }
87
88 // Gets the call site if the span is in a child context. Otherwise returns `None`.
89 fn get_call_site(span: Span, ctxt: SyntaxContext) -> Option<Span> {
90     (span.ctxt() != ctxt).then(|| walk_span_to_context(span, ctxt).unwrap_or(span))
91 }
92
93 fn lint_implicit_returns(
94     cx: &LateContext<'tcx>,
95     expr: &'tcx Expr<'_>,
96     // The context of the function body.
97     ctxt: SyntaxContext,
98     // Whether the expression is from a macro expansion.
99     call_site_span: Option<Span>,
100 ) -> LintLocation {
101     match expr.kind {
102         ExprKind::Block(
103             Block {
104                 expr: Some(block_expr), ..
105             },
106             _,
107         ) => lint_implicit_returns(
108             cx,
109             block_expr,
110             ctxt,
111             call_site_span.or_else(|| get_call_site(block_expr.span, ctxt)),
112         )
113         .still_parent(call_site_span.is_some()),
114
115         ExprKind::If(_, then_expr, Some(else_expr)) => {
116             // Both `then_expr` or `else_expr` are required to be blocks in the same context as the `if`. Don't
117             // bother checking.
118             let res = lint_implicit_returns(cx, then_expr, ctxt, call_site_span).still_parent(call_site_span.is_some());
119             if res.is_parent() {
120                 // The return was added as a parent of this if expression.
121                 return res;
122             }
123             lint_implicit_returns(cx, else_expr, ctxt, call_site_span).still_parent(call_site_span.is_some())
124         },
125
126         ExprKind::Match(_, arms, _) => {
127             for arm in arms {
128                 let res = lint_implicit_returns(
129                     cx,
130                     arm.body,
131                     ctxt,
132                     call_site_span.or_else(|| get_call_site(arm.body.span, ctxt)),
133                 )
134                 .still_parent(call_site_span.is_some());
135                 if res.is_parent() {
136                     // The return was added as a parent of this match expression.
137                     return res;
138                 }
139             }
140             LintLocation::Inner
141         },
142
143         ExprKind::Loop(block, ..) => {
144             let mut add_return = false;
145             visit_break_exprs(block, |break_expr, dest, sub_expr| {
146                 if dest.target_id.ok() == Some(expr.hir_id) {
147                     if call_site_span.is_none() && break_expr.span.ctxt() == ctxt {
148                         lint_break(cx, break_expr.span, sub_expr.unwrap().span);
149                     } else {
150                         // the break expression is from a macro call, add a return to the loop
151                         add_return = true;
152                     }
153                 }
154             });
155             if add_return {
156                 #[allow(clippy::option_if_let_else)]
157                 if let Some(span) = call_site_span {
158                     lint_return(cx, span);
159                     LintLocation::Parent
160                 } else {
161                     lint_return(cx, expr.span);
162                     LintLocation::Inner
163                 }
164             } else {
165                 LintLocation::Inner
166             }
167         },
168
169         // If expressions without an else clause, and blocks without a final expression can only be the final expression
170         // if they are divergent, or return the unit type.
171         ExprKind::If(_, _, None) | ExprKind::Block(Block { expr: None, .. }, _) | ExprKind::Ret(_) => {
172             LintLocation::Inner
173         },
174
175         // Any divergent expression doesn't need a return statement.
176         ExprKind::MethodCall(..)
177         | ExprKind::Call(..)
178         | ExprKind::Binary(..)
179         | ExprKind::Unary(..)
180         | ExprKind::Index(..)
181             if cx.typeck_results().expr_ty(expr).is_never() =>
182         {
183             LintLocation::Inner
184         },
185
186         _ =>
187         {
188             #[allow(clippy::option_if_let_else)]
189             if let Some(span) = call_site_span {
190                 lint_return(cx, span);
191                 LintLocation::Parent
192             } else {
193                 lint_return(cx, expr.span);
194                 LintLocation::Inner
195             }
196         },
197     }
198 }
199
200 impl<'tcx> LateLintPass<'tcx> for ImplicitReturn {
201     fn check_fn(
202         &mut self,
203         cx: &LateContext<'tcx>,
204         kind: FnKind<'tcx>,
205         decl: &'tcx FnDecl<'_>,
206         body: &'tcx Body<'_>,
207         span: Span,
208         _: HirId,
209     ) {
210         if (!matches!(kind, FnKind::Closure) && matches!(decl.output, FnRetTy::DefaultReturn(_)))
211             || span.ctxt() != body.value.span.ctxt()
212             || in_external_macro(cx.sess(), span)
213         {
214             return;
215         }
216
217         let res_ty = cx.typeck_results().expr_ty(&body.value);
218         if res_ty.is_unit() || res_ty.is_never() {
219             return;
220         }
221
222         lint_implicit_returns(cx, &body.value, body.value.span.ctxt(), None);
223     }
224 }