]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/returns.rs
Auto merge of #6915 - smoelius:docs-link, r=llogiq
[rust.git] / clippy_lints / src / returns.rs
1 use clippy_utils::diagnostics::{span_lint_and_sugg, span_lint_and_then};
2 use clippy_utils::source::snippet_opt;
3 use if_chain::if_chain;
4 use rustc_ast::ast::Attribute;
5 use rustc_errors::Applicability;
6 use rustc_hir::intravisit::{walk_expr, FnKind, NestedVisitorMap, Visitor};
7 use rustc_hir::{Block, Body, Expr, ExprKind, FnDecl, HirId, MatchSource, PatKind, StmtKind};
8 use rustc_lint::{LateContext, LateLintPass, LintContext};
9 use rustc_middle::hir::map::Map;
10 use rustc_middle::lint::in_external_macro;
11 use rustc_middle::ty::subst::GenericArgKind;
12 use rustc_session::{declare_lint_pass, declare_tool_lint};
13 use rustc_span::source_map::Span;
14 use rustc_span::sym;
15
16 use crate::utils::{fn_def_id, in_macro, match_qpath};
17
18 declare_clippy_lint! {
19     /// **What it does:** Checks for `let`-bindings, which are subsequently
20     /// returned.
21     ///
22     /// **Why is this bad?** It is just extraneous code. Remove it to make your code
23     /// more rusty.
24     ///
25     /// **Known problems:** None.
26     ///
27     /// **Example:**
28     /// ```rust
29     /// fn foo() -> String {
30     ///     let x = String::new();
31     ///     x
32     /// }
33     /// ```
34     /// instead, use
35     /// ```
36     /// fn foo() -> String {
37     ///     String::new()
38     /// }
39     /// ```
40     pub LET_AND_RETURN,
41     style,
42     "creating a let-binding and then immediately returning it like `let x = expr; x` at the end of a block"
43 }
44
45 declare_clippy_lint! {
46     /// **What it does:** Checks for return statements at the end of a block.
47     ///
48     /// **Why is this bad?** Removing the `return` and semicolon will make the code
49     /// more rusty.
50     ///
51     /// **Known problems:** None.
52     ///
53     /// **Example:**
54     /// ```rust
55     /// fn foo(x: usize) -> usize {
56     ///     return x;
57     /// }
58     /// ```
59     /// simplify to
60     /// ```rust
61     /// fn foo(x: usize) -> usize {
62     ///     x
63     /// }
64     /// ```
65     pub NEEDLESS_RETURN,
66     style,
67     "using a return statement like `return expr;` where an expression would suffice"
68 }
69
70 #[derive(PartialEq, Eq, Copy, Clone)]
71 enum RetReplacement {
72     Empty,
73     Block,
74 }
75
76 declare_lint_pass!(Return => [LET_AND_RETURN, NEEDLESS_RETURN]);
77
78 impl<'tcx> LateLintPass<'tcx> for Return {
79     fn check_block(&mut self, cx: &LateContext<'tcx>, block: &'tcx Block<'_>) {
80         // we need both a let-binding stmt and an expr
81         if_chain! {
82             if let Some(retexpr) = block.expr;
83             if let Some(stmt) = block.stmts.iter().last();
84             if let StmtKind::Local(local) = &stmt.kind;
85             if local.ty.is_none();
86             if cx.tcx.hir().attrs(local.hir_id).is_empty();
87             if let Some(initexpr) = &local.init;
88             if let PatKind::Binding(.., ident, _) = local.pat.kind;
89             if let ExprKind::Path(qpath) = &retexpr.kind;
90             if match_qpath(qpath, &[&*ident.name.as_str()]);
91             if !last_statement_borrows(cx, initexpr);
92             if !in_external_macro(cx.sess(), initexpr.span);
93             if !in_external_macro(cx.sess(), retexpr.span);
94             if !in_external_macro(cx.sess(), local.span);
95             if !in_macro(local.span);
96             then {
97                 span_lint_and_then(
98                     cx,
99                     LET_AND_RETURN,
100                     retexpr.span,
101                     "returning the result of a `let` binding from a block",
102                     |err| {
103                         err.span_label(local.span, "unnecessary `let` binding");
104
105                         if let Some(mut snippet) = snippet_opt(cx, initexpr.span) {
106                             if !cx.typeck_results().expr_adjustments(&retexpr).is_empty() {
107                                 snippet.push_str(" as _");
108                             }
109                             err.multipart_suggestion(
110                                 "return the expression directly",
111                                 vec![
112                                     (local.span, String::new()),
113                                     (retexpr.span, snippet),
114                                 ],
115                                 Applicability::MachineApplicable,
116                             );
117                         } else {
118                             err.span_help(initexpr.span, "this expression can be directly returned");
119                         }
120                     },
121                 );
122             }
123         }
124     }
125
126     fn check_fn(
127         &mut self,
128         cx: &LateContext<'tcx>,
129         kind: FnKind<'tcx>,
130         _: &'tcx FnDecl<'tcx>,
131         body: &'tcx Body<'tcx>,
132         _: Span,
133         _: HirId,
134     ) {
135         match kind {
136             FnKind::Closure => {
137                 // when returning without value in closure, replace this `return`
138                 // with an empty block to prevent invalid suggestion (see #6501)
139                 let replacement = if let ExprKind::Ret(None) = &body.value.kind {
140                     RetReplacement::Block
141                 } else {
142                     RetReplacement::Empty
143                 };
144                 check_final_expr(cx, &body.value, Some(body.value.span), replacement)
145             },
146             FnKind::ItemFn(..) | FnKind::Method(..) => {
147                 if let ExprKind::Block(ref block, _) = body.value.kind {
148                     check_block_return(cx, block);
149                 }
150             },
151         }
152     }
153 }
154
155 fn attr_is_cfg(attr: &Attribute) -> bool {
156     attr.meta_item_list().is_some() && attr.has_name(sym::cfg)
157 }
158
159 fn check_block_return<'tcx>(cx: &LateContext<'tcx>, block: &Block<'tcx>) {
160     if let Some(expr) = block.expr {
161         check_final_expr(cx, expr, Some(expr.span), RetReplacement::Empty);
162     } else if let Some(stmt) = block.stmts.iter().last() {
163         match stmt.kind {
164             StmtKind::Expr(ref expr) | StmtKind::Semi(ref expr) => {
165                 check_final_expr(cx, expr, Some(stmt.span), RetReplacement::Empty);
166             },
167             _ => (),
168         }
169     }
170 }
171
172 fn check_final_expr<'tcx>(
173     cx: &LateContext<'tcx>,
174     expr: &'tcx Expr<'tcx>,
175     span: Option<Span>,
176     replacement: RetReplacement,
177 ) {
178     match expr.kind {
179         // simple return is always "bad"
180         ExprKind::Ret(ref inner) => {
181             // allow `#[cfg(a)] return a; #[cfg(b)] return b;`
182             let attrs = cx.tcx.hir().attrs(expr.hir_id);
183             if !attrs.iter().any(attr_is_cfg) {
184                 let borrows = inner.map_or(false, |inner| last_statement_borrows(cx, inner));
185                 if !borrows {
186                     emit_return_lint(
187                         cx,
188                         span.expect("`else return` is not possible"),
189                         inner.as_ref().map(|i| i.span),
190                         replacement,
191                     );
192                 }
193             }
194         },
195         // a whole block? check it!
196         ExprKind::Block(ref block, _) => {
197             check_block_return(cx, block);
198         },
199         ExprKind::If(_, then, else_clause_opt) => {
200             if let ExprKind::Block(ref ifblock, _) = then.kind {
201                 check_block_return(cx, ifblock);
202             }
203             if let Some(else_clause) = else_clause_opt {
204                 check_final_expr(cx, else_clause, None, RetReplacement::Empty);
205             }
206         },
207         // a match expr, check all arms
208         // an if/if let expr, check both exprs
209         // note, if without else is going to be a type checking error anyways
210         // (except for unit type functions) so we don't match it
211         ExprKind::Match(_, ref arms, source) => match source {
212             MatchSource::Normal => {
213                 for arm in arms.iter() {
214                     check_final_expr(cx, &arm.body, Some(arm.body.span), RetReplacement::Block);
215                 }
216             },
217             MatchSource::IfLetDesugar {
218                 contains_else_clause: true,
219             } => {
220                 if let ExprKind::Block(ref ifblock, _) = arms[0].body.kind {
221                     check_block_return(cx, ifblock);
222                 }
223                 check_final_expr(cx, arms[1].body, None, RetReplacement::Empty);
224             },
225             _ => (),
226         },
227         _ => (),
228     }
229 }
230
231 fn emit_return_lint(cx: &LateContext<'_>, ret_span: Span, inner_span: Option<Span>, replacement: RetReplacement) {
232     if ret_span.from_expansion() {
233         return;
234     }
235     match inner_span {
236         Some(inner_span) => {
237             if in_external_macro(cx.tcx.sess, inner_span) || inner_span.from_expansion() {
238                 return;
239             }
240
241             span_lint_and_then(cx, NEEDLESS_RETURN, ret_span, "unneeded `return` statement", |diag| {
242                 if let Some(snippet) = snippet_opt(cx, inner_span) {
243                     diag.span_suggestion(ret_span, "remove `return`", snippet, Applicability::MachineApplicable);
244                 }
245             })
246         },
247         None => match replacement {
248             RetReplacement::Empty => {
249                 span_lint_and_sugg(
250                     cx,
251                     NEEDLESS_RETURN,
252                     ret_span,
253                     "unneeded `return` statement",
254                     "remove `return`",
255                     String::new(),
256                     Applicability::MachineApplicable,
257                 );
258             },
259             RetReplacement::Block => {
260                 span_lint_and_sugg(
261                     cx,
262                     NEEDLESS_RETURN,
263                     ret_span,
264                     "unneeded `return` statement",
265                     "replace `return` with an empty block",
266                     "{}".to_string(),
267                     Applicability::MachineApplicable,
268                 );
269             },
270         },
271     }
272 }
273
274 fn last_statement_borrows<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'tcx>) -> bool {
275     let mut visitor = BorrowVisitor { cx, borrows: false };
276     walk_expr(&mut visitor, expr);
277     visitor.borrows
278 }
279
280 struct BorrowVisitor<'a, 'tcx> {
281     cx: &'a LateContext<'tcx>,
282     borrows: bool,
283 }
284
285 impl<'tcx> Visitor<'tcx> for BorrowVisitor<'_, 'tcx> {
286     type Map = Map<'tcx>;
287
288     fn visit_expr(&mut self, expr: &'tcx Expr<'_>) {
289         if self.borrows {
290             return;
291         }
292
293         if let Some(def_id) = fn_def_id(self.cx, expr) {
294             self.borrows = self
295                 .cx
296                 .tcx
297                 .fn_sig(def_id)
298                 .output()
299                 .skip_binder()
300                 .walk()
301                 .any(|arg| matches!(arg.unpack(), GenericArgKind::Lifetime(_)));
302         }
303
304         walk_expr(self, expr);
305     }
306
307     fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
308         NestedVisitorMap::None
309     }
310 }