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