]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/implicit_return.rs
Merge commit 'fdb84cbfd25908df5683f8f62388f663d9260e39' into clippyup
[rust.git] / clippy_lints / src / implicit_return.rs
1 use clippy_utils::{
2     diagnostics::span_lint_hir_and_then,
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<'_>, emission_place: HirId, span: Span) {
47     let mut app = Applicability::MachineApplicable;
48     let snip = snippet_with_applicability(cx, span, "..", &mut app);
49     span_lint_hir_and_then(
50         cx,
51         IMPLICIT_RETURN,
52         emission_place,
53         span,
54         "missing `return` statement",
55         |diag| {
56             diag.span_suggestion(span, "add `return` as shown", format!("return {}", snip), app);
57         },
58     );
59 }
60
61 fn lint_break(cx: &LateContext<'_>, emission_place: HirId, break_span: Span, expr_span: Span) {
62     let mut app = Applicability::MachineApplicable;
63     let snip = snippet_with_context(cx, expr_span, break_span.ctxt(), "..", &mut app).0;
64     span_lint_hir_and_then(
65         cx,
66         IMPLICIT_RETURN,
67         emission_place,
68         break_span,
69         "missing `return` statement",
70         |diag| {
71             diag.span_suggestion(
72                 break_span,
73                 "change `break` to `return` as shown",
74                 format!("return {}", snip),
75                 app,
76             );
77         },
78     );
79 }
80
81 #[derive(Clone, Copy, PartialEq, Eq)]
82 enum LintLocation {
83     /// The lint was applied to a parent expression.
84     Parent,
85     /// The lint was applied to this expression, a child, or not applied.
86     Inner,
87 }
88 impl LintLocation {
89     fn still_parent(self, b: bool) -> Self {
90         if b { self } else { Self::Inner }
91     }
92
93     fn is_parent(self) -> bool {
94         self == Self::Parent
95     }
96 }
97
98 // Gets the call site if the span is in a child context. Otherwise returns `None`.
99 fn get_call_site(span: Span, ctxt: SyntaxContext) -> Option<Span> {
100     (span.ctxt() != ctxt).then(|| walk_span_to_context(span, ctxt).unwrap_or(span))
101 }
102
103 fn lint_implicit_returns(
104     cx: &LateContext<'_>,
105     expr: &Expr<'_>,
106     // The context of the function body.
107     ctxt: SyntaxContext,
108     // Whether the expression is from a macro expansion.
109     call_site_span: Option<Span>,
110 ) -> LintLocation {
111     match expr.kind {
112         ExprKind::Block(
113             Block {
114                 expr: Some(block_expr), ..
115             },
116             _,
117         ) => lint_implicit_returns(
118             cx,
119             block_expr,
120             ctxt,
121             call_site_span.or_else(|| get_call_site(block_expr.span, ctxt)),
122         )
123         .still_parent(call_site_span.is_some()),
124
125         ExprKind::If(_, then_expr, Some(else_expr)) => {
126             // Both `then_expr` or `else_expr` are required to be blocks in the same context as the `if`. Don't
127             // bother checking.
128             let res = lint_implicit_returns(cx, then_expr, ctxt, call_site_span).still_parent(call_site_span.is_some());
129             if res.is_parent() {
130                 // The return was added as a parent of this if expression.
131                 return res;
132             }
133             lint_implicit_returns(cx, else_expr, ctxt, call_site_span).still_parent(call_site_span.is_some())
134         },
135
136         ExprKind::Match(_, arms, _) => {
137             for arm in arms {
138                 let res = lint_implicit_returns(
139                     cx,
140                     arm.body,
141                     ctxt,
142                     call_site_span.or_else(|| get_call_site(arm.body.span, ctxt)),
143                 )
144                 .still_parent(call_site_span.is_some());
145                 if res.is_parent() {
146                     // The return was added as a parent of this match expression.
147                     return res;
148                 }
149             }
150             LintLocation::Inner
151         },
152
153         ExprKind::Loop(block, ..) => {
154             let mut add_return = false;
155             expr_visitor_no_bodies(|e| {
156                 if let ExprKind::Break(dest, sub_expr) = e.kind {
157                     if dest.target_id.ok() == Some(expr.hir_id) {
158                         if call_site_span.is_none() && e.span.ctxt() == ctxt {
159                             // At this point sub_expr can be `None` in async functions which either diverge, or return
160                             // the unit type.
161                             if let Some(sub_expr) = sub_expr {
162                                 lint_break(cx, e.hir_id, e.span, sub_expr.span);
163                             }
164                         } else {
165                             // the break expression is from a macro call, add a return to the loop
166                             add_return = true;
167                         }
168                     }
169                 }
170                 true
171             })
172             .visit_block(block);
173             if add_return {
174                 #[expect(clippy::option_if_let_else)]
175                 if let Some(span) = call_site_span {
176                     lint_return(cx, expr.hir_id, span);
177                     LintLocation::Parent
178                 } else {
179                     lint_return(cx, expr.hir_id, expr.span);
180                     LintLocation::Inner
181                 }
182             } else {
183                 LintLocation::Inner
184             }
185         },
186
187         // If expressions without an else clause, and blocks without a final expression can only be the final expression
188         // if they are divergent, or return the unit type.
189         ExprKind::If(_, _, None) | ExprKind::Block(Block { expr: None, .. }, _) | ExprKind::Ret(_) => {
190             LintLocation::Inner
191         },
192
193         // Any divergent expression doesn't need a return statement.
194         ExprKind::MethodCall(..)
195         | ExprKind::Call(..)
196         | ExprKind::Binary(..)
197         | ExprKind::Unary(..)
198         | ExprKind::Index(..)
199             if cx.typeck_results().expr_ty(expr).is_never() =>
200         {
201             LintLocation::Inner
202         },
203
204         _ =>
205         {
206             #[expect(clippy::option_if_let_else)]
207             if let Some(span) = call_site_span {
208                 lint_return(cx, expr.hir_id, span);
209                 LintLocation::Parent
210             } else {
211                 lint_return(cx, expr.hir_id, expr.span);
212                 LintLocation::Inner
213             }
214         },
215     }
216 }
217
218 impl<'tcx> LateLintPass<'tcx> for ImplicitReturn {
219     fn check_fn(
220         &mut self,
221         cx: &LateContext<'tcx>,
222         kind: FnKind<'tcx>,
223         decl: &'tcx FnDecl<'_>,
224         body: &'tcx Body<'_>,
225         span: Span,
226         _: HirId,
227     ) {
228         if (!matches!(kind, FnKind::Closure) && matches!(decl.output, FnRetTy::DefaultReturn(_)))
229             || span.ctxt() != body.value.span.ctxt()
230             || in_external_macro(cx.sess(), span)
231         {
232             return;
233         }
234
235         let res_ty = cx.typeck_results().expr_ty(&body.value);
236         if res_ty.is_unit() || res_ty.is_never() {
237             return;
238         }
239
240         let expr = if is_async_fn(kind) {
241             match get_async_fn_body(cx.tcx, body) {
242                 Some(e) => e,
243                 None => return,
244             }
245         } else {
246             &body.value
247         };
248         lint_implicit_returns(cx, expr, expr.span.ctxt(), None);
249     }
250 }