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;
18 declare_clippy_lint! {
20 /// Checks for `let`-bindings, which are subsequently
23 /// ### Why is this bad?
24 /// It is just extraneous code. Remove it to make your code
29 /// fn foo() -> String {
30 /// let x = String::new();
36 /// fn foo() -> String {
40 #[clippy::version = "pre 1.29.0"]
43 "creating a let-binding and then immediately returning it like `let x = expr; x` at the end of a block"
46 declare_clippy_lint! {
48 /// Checks for return statements at the end of a block.
50 /// ### Why is this bad?
51 /// Removing the `return` and semicolon will make the code
56 /// fn foo(x: usize) -> usize {
62 /// fn foo(x: usize) -> usize {
66 #[clippy::version = "pre 1.29.0"]
69 "using a return statement like `return expr;` where an expression would suffice"
72 #[derive(PartialEq, Eq, Copy, Clone)]
79 declare_lint_pass!(Return => [LET_AND_RETURN, NEEDLESS_RETURN]);
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
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();
102 "returning the result of a `let` binding from a block",
104 err.span_label(local.span, "unnecessary `let` binding");
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 _");
110 err.multipart_suggestion(
111 "return the expression directly",
113 (local.span, String::new()),
114 (retexpr.span, snippet),
116 Applicability::MachineApplicable,
119 err.span_help(initexpr.span, "this expression can be directly returned");
129 cx: &LateContext<'tcx>,
131 _: &'tcx FnDecl<'tcx>,
132 body: &'tcx Body<'tcx>,
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
143 RetReplacement::Empty
145 check_final_expr(cx, &body.value, Some(body.value.span), replacement);
147 FnKind::ItemFn(..) | FnKind::Method(..) => {
148 if let ExprKind::Block(block, _) = body.value.kind {
149 check_block_return(cx, block);
156 fn attr_is_cfg(attr: &Attribute) -> bool {
157 attr.meta_item_list().is_some() && attr.has_name(sym::cfg)
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() {
165 StmtKind::Expr(expr) | StmtKind::Semi(expr) => {
166 check_final_expr(cx, expr, Some(stmt.span), RetReplacement::Empty);
173 fn check_final_expr<'tcx>(
174 cx: &LateContext<'tcx>,
175 expr: &'tcx Expr<'tcx>,
177 replacement: RetReplacement,
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));
189 span.expect("`else return` is not possible"),
190 inner.as_ref().map(|i| i.span),
196 // a whole block? check it!
197 ExprKind::Block(block, _) => {
198 check_block_return(cx, block);
200 ExprKind::If(_, then, else_clause_opt) => {
201 if let ExprKind::Block(ifblock, _) = then.kind {
202 check_block_return(cx, ifblock);
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);
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);
219 ExprKind::DropTemps(expr) => check_final_expr(cx, expr, None, RetReplacement::Empty),
224 fn emit_return_lint(cx: &LateContext<'_>, ret_span: Span, inner_span: Option<Span>, replacement: RetReplacement) {
225 if ret_span.from_expansion() {
229 Some(inner_span) => {
230 if in_external_macro(cx.tcx.sess, inner_span) || inner_span.from_expansion() {
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);
240 None => match replacement {
241 RetReplacement::Empty => {
246 "unneeded `return` statement",
249 Applicability::MachineApplicable,
252 RetReplacement::Block => {
257 "unneeded `return` statement",
258 "replace `return` with an empty block",
260 Applicability::MachineApplicable,
263 RetReplacement::Unit => {
268 "unneeded `return` statement",
269 "replace `return` with a unit value",
271 Applicability::MachineApplicable,
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);
284 struct BorrowVisitor<'a, 'tcx> {
285 cx: &'a LateContext<'tcx>,
289 impl<'tcx> Visitor<'tcx> for BorrowVisitor<'_, 'tcx> {
290 type Map = Map<'tcx>;
292 fn visit_expr(&mut self, expr: &'tcx Expr<'_>) {
297 if let Some(def_id) = fn_def_id(self.cx, expr) {
305 .any(|arg| matches!(arg.unpack(), GenericArgKind::Lifetime(_)));
308 walk_expr(self, expr);
311 fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
312 NestedVisitorMap::None