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