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, in_macro, 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 {
42 "creating a let-binding and then immediately returning it like `let x = expr; x` at the end of a block"
45 declare_clippy_lint! {
47 /// Checks for return statements at the end of a block.
49 /// ### Why is this bad?
50 /// Removing the `return` and semicolon will make the code
55 /// fn foo(x: usize) -> usize {
61 /// fn foo(x: usize) -> usize {
67 "using a return statement like `return expr;` where an expression would suffice"
70 #[derive(PartialEq, Eq, Copy, Clone)]
76 declare_lint_pass!(Return => [LET_AND_RETURN, NEEDLESS_RETURN]);
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
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(_, local_id, _, _) = local.pat.kind;
89 if path_to_local_id(retexpr, local_id);
90 if !last_statement_borrows(cx, initexpr);
91 if !in_external_macro(cx.sess(), initexpr.span);
92 if !in_external_macro(cx.sess(), retexpr.span);
93 if !in_external_macro(cx.sess(), local.span);
94 if !in_macro(local.span);
100 "returning the result of a `let` binding from a block",
102 err.span_label(local.span, "unnecessary `let` binding");
104 if let Some(mut snippet) = snippet_opt(cx, initexpr.span) {
105 if !cx.typeck_results().expr_adjustments(retexpr).is_empty() {
106 snippet.push_str(" as _");
108 err.multipart_suggestion(
109 "return the expression directly",
111 (local.span, String::new()),
112 (retexpr.span, snippet),
114 Applicability::MachineApplicable,
117 err.span_help(initexpr.span, "this expression can be directly returned");
127 cx: &LateContext<'tcx>,
129 _: &'tcx FnDecl<'tcx>,
130 body: &'tcx Body<'tcx>,
136 // when returning without value in closure, replace this `return`
137 // with an empty block to prevent invalid suggestion (see #6501)
138 let replacement = if let ExprKind::Ret(None) = &body.value.kind {
139 RetReplacement::Block
141 RetReplacement::Empty
143 check_final_expr(cx, &body.value, Some(body.value.span), replacement);
145 FnKind::ItemFn(..) | FnKind::Method(..) => {
146 if let ExprKind::Block(block, _) = body.value.kind {
147 check_block_return(cx, block);
154 fn attr_is_cfg(attr: &Attribute) -> bool {
155 attr.meta_item_list().is_some() && attr.has_name(sym::cfg)
158 fn check_block_return<'tcx>(cx: &LateContext<'tcx>, block: &Block<'tcx>) {
159 if let Some(expr) = block.expr {
160 check_final_expr(cx, expr, Some(expr.span), RetReplacement::Empty);
161 } else if let Some(stmt) = block.stmts.iter().last() {
163 StmtKind::Expr(expr) | StmtKind::Semi(expr) => {
164 check_final_expr(cx, expr, Some(stmt.span), RetReplacement::Empty);
171 fn check_final_expr<'tcx>(
172 cx: &LateContext<'tcx>,
173 expr: &'tcx Expr<'tcx>,
175 replacement: RetReplacement,
178 // simple return is always "bad"
179 ExprKind::Ret(ref inner) => {
180 // allow `#[cfg(a)] return a; #[cfg(b)] return b;`
181 let attrs = cx.tcx.hir().attrs(expr.hir_id);
182 if !attrs.iter().any(attr_is_cfg) {
183 let borrows = inner.map_or(false, |inner| last_statement_borrows(cx, inner));
187 span.expect("`else return` is not possible"),
188 inner.as_ref().map(|i| i.span),
194 // a whole block? check it!
195 ExprKind::Block(block, _) => {
196 check_block_return(cx, block);
198 ExprKind::If(_, then, else_clause_opt) => {
199 if let ExprKind::Block(ifblock, _) = then.kind {
200 check_block_return(cx, ifblock);
202 if let Some(else_clause) = else_clause_opt {
203 if expr.span.desugaring_kind() != Some(DesugaringKind::LetElse) {
204 check_final_expr(cx, else_clause, None, RetReplacement::Empty);
208 // a match expr, check all arms
209 // an if/if let expr, check both exprs
210 // note, if without else is going to be a type checking error anyways
211 // (except for unit type functions) so we don't match it
212 ExprKind::Match(_, arms, MatchSource::Normal) => {
213 for arm in arms.iter() {
214 check_final_expr(cx, arm.body, Some(arm.body.span), RetReplacement::Block);
217 ExprKind::DropTemps(expr) => check_final_expr(cx, expr, None, RetReplacement::Empty),
222 fn emit_return_lint(cx: &LateContext<'_>, ret_span: Span, inner_span: Option<Span>, replacement: RetReplacement) {
223 if ret_span.from_expansion() {
227 Some(inner_span) => {
228 if in_external_macro(cx.tcx.sess, inner_span) || inner_span.from_expansion() {
232 span_lint_and_then(cx, NEEDLESS_RETURN, ret_span, "unneeded `return` statement", |diag| {
233 if let Some(snippet) = snippet_opt(cx, inner_span) {
234 diag.span_suggestion(ret_span, "remove `return`", snippet, Applicability::MachineApplicable);
238 None => match replacement {
239 RetReplacement::Empty => {
244 "unneeded `return` statement",
247 Applicability::MachineApplicable,
250 RetReplacement::Block => {
255 "unneeded `return` statement",
256 "replace `return` with an empty block",
258 Applicability::MachineApplicable,
265 fn last_statement_borrows<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'tcx>) -> bool {
266 let mut visitor = BorrowVisitor { cx, borrows: false };
267 walk_expr(&mut visitor, expr);
271 struct BorrowVisitor<'a, 'tcx> {
272 cx: &'a LateContext<'tcx>,
276 impl<'tcx> Visitor<'tcx> for BorrowVisitor<'_, 'tcx> {
277 type Map = Map<'tcx>;
279 fn visit_expr(&mut self, expr: &'tcx Expr<'_>) {
284 if let Some(def_id) = fn_def_id(self.cx, expr) {
292 .any(|arg| matches!(arg.unpack(), GenericArgKind::Lifetime(_)));
295 walk_expr(self, expr);
298 fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
299 NestedVisitorMap::None