]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/implicit_return.rs
Auto merge of #9870 - koka831:unformat-unused-rounding, r=Jarcho
[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::for_each_expr,
6 };
7 use core::ops::ControlFlow;
8 use rustc_errors::Applicability;
9 use rustc_hir::intravisit::FnKind;
10 use rustc_hir::{Block, Body, Expr, ExprKind, FnDecl, FnRetTy, HirId};
11 use rustc_lint::{LateContext, LateLintPass, LintContext};
12 use rustc_middle::lint::in_external_macro;
13 use rustc_session::{declare_lint_pass, declare_tool_lint};
14 use rustc_span::{Span, SyntaxContext};
15
16 declare_clippy_lint! {
17     /// ### What it does
18     /// Checks for missing return statements at the end of a block.
19     ///
20     /// ### Why is this bad?
21     /// Actually omitting the return keyword is idiomatic Rust code. Programmers
22     /// coming from other languages might prefer the expressiveness of `return`. It's possible to miss
23     /// the last returning statement because the only difference is a missing `;`. Especially in bigger
24     /// code with multiple return paths having a `return` keyword makes it easier to find the
25     /// corresponding statements.
26     ///
27     /// ### Example
28     /// ```rust
29     /// fn foo(x: usize) -> usize {
30     ///     x
31     /// }
32     /// ```
33     /// add return
34     /// ```rust
35     /// fn foo(x: usize) -> usize {
36     ///     return x;
37     /// }
38     /// ```
39     #[clippy::version = "1.33.0"]
40     pub IMPLICIT_RETURN,
41     restriction,
42     "use a return statement like `return expr` instead of an expression"
43 }
44
45 declare_lint_pass!(ImplicitReturn => [IMPLICIT_RETURN]);
46
47 fn lint_return(cx: &LateContext<'_>, emission_place: HirId, span: Span) {
48     let mut app = Applicability::MachineApplicable;
49     let snip = snippet_with_applicability(cx, span, "..", &mut app);
50     span_lint_hir_and_then(
51         cx,
52         IMPLICIT_RETURN,
53         emission_place,
54         span,
55         "missing `return` statement",
56         |diag| {
57             diag.span_suggestion(span, "add `return` as shown", format!("return {snip}"), app);
58         },
59     );
60 }
61
62 fn lint_break(cx: &LateContext<'_>, emission_place: HirId, break_span: Span, expr_span: Span) {
63     let mut app = Applicability::MachineApplicable;
64     let snip = snippet_with_context(cx, expr_span, break_span.ctxt(), "..", &mut app).0;
65     span_lint_hir_and_then(
66         cx,
67         IMPLICIT_RETURN,
68         emission_place,
69         break_span,
70         "missing `return` statement",
71         |diag| {
72             diag.span_suggestion(
73                 break_span,
74                 "change `break` to `return` as shown",
75                 format!("return {snip}"),
76                 app,
77             );
78         },
79     );
80 }
81
82 #[derive(Clone, Copy, PartialEq, Eq)]
83 enum LintLocation {
84     /// The lint was applied to a parent expression.
85     Parent,
86     /// The lint was applied to this expression, a child, or not applied.
87     Inner,
88 }
89 impl LintLocation {
90     fn still_parent(self, b: bool) -> Self {
91         if b { self } else { Self::Inner }
92     }
93
94     fn is_parent(self) -> bool {
95         self == Self::Parent
96     }
97 }
98
99 // Gets the call site if the span is in a child context. Otherwise returns `None`.
100 fn get_call_site(span: Span, ctxt: SyntaxContext) -> Option<Span> {
101     (span.ctxt() != ctxt).then(|| walk_span_to_context(span, ctxt).unwrap_or(span))
102 }
103
104 fn lint_implicit_returns(
105     cx: &LateContext<'_>,
106     expr: &Expr<'_>,
107     // The context of the function body.
108     ctxt: SyntaxContext,
109     // Whether the expression is from a macro expansion.
110     call_site_span: Option<Span>,
111 ) -> LintLocation {
112     match expr.kind {
113         ExprKind::Block(
114             Block {
115                 expr: Some(block_expr), ..
116             },
117             _,
118         ) => lint_implicit_returns(
119             cx,
120             block_expr,
121             ctxt,
122             call_site_span.or_else(|| get_call_site(block_expr.span, ctxt)),
123         )
124         .still_parent(call_site_span.is_some()),
125
126         ExprKind::If(_, then_expr, Some(else_expr)) => {
127             // Both `then_expr` or `else_expr` are required to be blocks in the same context as the `if`. Don't
128             // bother checking.
129             let res = lint_implicit_returns(cx, then_expr, ctxt, call_site_span).still_parent(call_site_span.is_some());
130             if res.is_parent() {
131                 // The return was added as a parent of this if expression.
132                 return res;
133             }
134             lint_implicit_returns(cx, else_expr, ctxt, call_site_span).still_parent(call_site_span.is_some())
135         },
136
137         ExprKind::Match(_, arms, _) => {
138             for arm in arms {
139                 let res = lint_implicit_returns(
140                     cx,
141                     arm.body,
142                     ctxt,
143                     call_site_span.or_else(|| get_call_site(arm.body.span, ctxt)),
144                 )
145                 .still_parent(call_site_span.is_some());
146                 if res.is_parent() {
147                     // The return was added as a parent of this match expression.
148                     return res;
149                 }
150             }
151             LintLocation::Inner
152         },
153
154         ExprKind::Loop(block, ..) => {
155             let mut add_return = false;
156             let _: Option<!> = for_each_expr(block, |e| {
157                 if let ExprKind::Break(dest, sub_expr) = e.kind {
158                     if dest.target_id.ok() == Some(expr.hir_id) {
159                         if call_site_span.is_none() && e.span.ctxt() == ctxt {
160                             // At this point sub_expr can be `None` in async functions which either diverge, or return
161                             // the unit type.
162                             if let Some(sub_expr) = sub_expr {
163                                 lint_break(cx, e.hir_id, e.span, sub_expr.span);
164                             }
165                         } else {
166                             // the break expression is from a macro call, add a return to the loop
167                             add_return = true;
168                         }
169                     }
170                 }
171                 ControlFlow::Continue(())
172             });
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 }