]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/implicit_return.rs
Use 'tcx for references to AccessLevels wherever possible.
[rust.git] / clippy_lints / src / implicit_return.rs
1 use crate::utils::{
2     fn_has_unsatisfiable_preds, match_def_path,
3     paths::{BEGIN_PANIC, BEGIN_PANIC_FMT},
4     snippet_opt, span_lint_and_then,
5 };
6 use if_chain::if_chain;
7 use rustc_errors::Applicability;
8 use rustc_hir::intravisit::FnKind;
9 use rustc_hir::{Body, Expr, ExprKind, FnDecl, HirId, MatchSource, StmtKind};
10 use rustc_lint::{LateContext, LateLintPass};
11 use rustc_session::{declare_lint_pass, declare_tool_lint};
12 use rustc_span::source_map::Span;
13
14 declare_clippy_lint! {
15     /// **What it does:** Checks for missing return statements at the end of a block.
16     ///
17     /// **Why is this bad?** Actually omitting the return keyword is idiomatic Rust code. Programmers
18     /// coming from other languages might prefer the expressiveness of `return`. It's possible to miss
19     /// the last returning statement because the only difference is a missing `;`. Especially in bigger
20     /// code with multiple return paths having a `return` keyword makes it easier to find the
21     /// corresponding statements.
22     ///
23     /// **Known problems:** None.
24     ///
25     /// **Example:**
26     /// ```rust
27     /// fn foo(x: usize) -> usize {
28     ///     x
29     /// }
30     /// ```
31     /// add return
32     /// ```rust
33     /// fn foo(x: usize) -> usize {
34     ///     return x;
35     /// }
36     /// ```
37     pub IMPLICIT_RETURN,
38     restriction,
39     "use a return statement like `return expr` instead of an expression"
40 }
41
42 declare_lint_pass!(ImplicitReturn => [IMPLICIT_RETURN]);
43
44 static LINT_BREAK: &str = "change `break` to `return` as shown";
45 static LINT_RETURN: &str = "add `return` as shown";
46
47 fn lint(cx: &LateContext<'_>, outer_span: Span, inner_span: Span, msg: &str) {
48     let outer_span = outer_span.source_callsite();
49     let inner_span = inner_span.source_callsite();
50
51     span_lint_and_then(cx, IMPLICIT_RETURN, outer_span, "missing `return` statement", |diag| {
52         if let Some(snippet) = snippet_opt(cx, inner_span) {
53             diag.span_suggestion(
54                 outer_span,
55                 msg,
56                 format!("return {}", snippet),
57                 Applicability::MachineApplicable,
58             );
59         }
60     });
61 }
62
63 fn expr_match(cx: &LateContext<'_>, expr: &Expr<'_>) {
64     match expr.kind {
65         // loops could be using `break` instead of `return`
66         ExprKind::Block(block, ..) | ExprKind::Loop(block, ..) => {
67             if let Some(expr) = &block.expr {
68                 expr_match(cx, expr);
69             }
70             // only needed in the case of `break` with `;` at the end
71             else if let Some(stmt) = block.stmts.last() {
72                 if_chain! {
73                     if let StmtKind::Semi(expr, ..) = &stmt.kind;
74                     // make sure it's a break, otherwise we want to skip
75                     if let ExprKind::Break(.., break_expr) = &expr.kind;
76                     if let Some(break_expr) = break_expr;
77                     then {
78                             lint(cx, expr.span, break_expr.span, LINT_BREAK);
79                     }
80                 }
81             }
82         },
83         // use `return` instead of `break`
84         ExprKind::Break(.., break_expr) => {
85             if let Some(break_expr) = break_expr {
86                 lint(cx, expr.span, break_expr.span, LINT_BREAK);
87             }
88         },
89         ExprKind::Match(.., arms, source) => {
90             let check_all_arms = match source {
91                 MatchSource::IfLetDesugar {
92                     contains_else_clause: has_else,
93                 } => has_else,
94                 _ => true,
95             };
96
97             if check_all_arms {
98                 for arm in arms {
99                     expr_match(cx, &arm.body);
100                 }
101             } else {
102                 expr_match(cx, &arms.first().expect("`if let` doesn't have a single arm").body);
103             }
104         },
105         // skip if it already has a return statement
106         ExprKind::Ret(..) => (),
107         // make sure it's not a call that panics
108         ExprKind::Call(expr, ..) => {
109             if_chain! {
110                 if let ExprKind::Path(qpath) = &expr.kind;
111                 if let Some(path_def_id) = cx.qpath_res(qpath, expr.hir_id).opt_def_id();
112                 if match_def_path(cx, path_def_id, &BEGIN_PANIC) ||
113                     match_def_path(cx, path_def_id, &BEGIN_PANIC_FMT);
114                 then { }
115                 else {
116                     lint(cx, expr.span, expr.span, LINT_RETURN)
117                 }
118             }
119         },
120         // everything else is missing `return`
121         _ => lint(cx, expr.span, expr.span, LINT_RETURN),
122     }
123 }
124
125 impl<'tcx> LateLintPass<'tcx> for ImplicitReturn {
126     fn check_fn(
127         &mut self,
128         cx: &LateContext<'tcx>,
129         _: FnKind<'tcx>,
130         _: &'tcx FnDecl<'_>,
131         body: &'tcx Body<'_>,
132         span: Span,
133         _: HirId,
134     ) {
135         let def_id = cx.tcx.hir().body_owner_def_id(body.id());
136
137         // Building MIR for `fn`s with unsatisfiable preds results in ICE.
138         if fn_has_unsatisfiable_preds(cx, def_id.to_def_id()) {
139             return;
140         }
141
142         let mir = cx.tcx.optimized_mir(def_id.to_def_id());
143
144         // checking return type through MIR, HIR is not able to determine inferred closure return types
145         // make sure it's not a macro
146         if !mir.return_ty().is_unit() && !span.from_expansion() {
147             expr_match(cx, &body.value);
148         }
149     }
150 }