]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/unused_unit.rs
Modifications according to the code review
[rust.git] / clippy_lints / src / unused_unit.rs
1 use if_chain::if_chain;
2 use rustc_ast::ast;
3 use rustc_ast::visit::FnKind;
4 use rustc_errors::Applicability;
5 use rustc_lint::{EarlyContext, EarlyLintPass, LintContext};
6 use rustc_session::{declare_lint_pass, declare_tool_lint};
7 use rustc_span::source_map::Span;
8 use rustc_span::BytePos;
9
10 use crate::utils::span_lint_and_sugg;
11
12 declare_clippy_lint! {
13     /// **What it does:** Checks for unit (`()`) expressions that can be removed.
14     ///
15     /// **Why is this bad?** Such expressions add no value, but can make the code
16     /// less readable. Depending on formatting they can make a `break` or `return`
17     /// statement look like a function call.
18     ///
19     /// **Known problems:** The lint currently misses unit return types in types,
20     /// e.g., the `F` in `fn generic_unit<F: Fn() -> ()>(f: F) { .. }`.
21     ///
22     /// **Example:**
23     /// ```rust
24     /// fn return_unit() -> () {
25     ///     ()
26     /// }
27     /// ```
28     pub UNUSED_UNIT,
29     style,
30     "needless unit expression"
31 }
32
33 declare_lint_pass!(UnusedUnit => [UNUSED_UNIT]);
34
35 impl EarlyLintPass for UnusedUnit {
36     fn check_fn(&mut self, cx: &EarlyContext<'_>, kind: FnKind<'_>, span: Span, _: ast::NodeId) {
37         if_chain! {
38             if let ast::FnRetTy::Ty(ref ty) = kind.decl().output;
39             if let ast::TyKind::Tup(ref vals) = ty.kind;
40             if vals.is_empty() && !ty.span.from_expansion() && get_def(span) == get_def(ty.span);
41             then {
42                 lint_unneeded_unit_return(cx, ty, span);
43             }
44         }
45     }
46
47     fn check_block(&mut self, cx: &EarlyContext<'_>, block: &ast::Block) {
48         if_chain! {
49             if let Some(ref stmt) = block.stmts.last();
50             if let ast::StmtKind::Expr(ref expr) = stmt.kind;
51             if is_unit_expr(expr) && !stmt.span.from_expansion();
52             then {
53                 let sp = expr.span;
54                 span_lint_and_sugg(
55                     cx,
56                     UNUSED_UNIT,
57                     sp,
58                     "unneeded unit expression",
59                     "remove the final `()`",
60                     String::new(),
61                     Applicability::MachineApplicable,
62                 );
63             }
64         }
65     }
66
67     fn check_expr(&mut self, cx: &EarlyContext<'_>, e: &ast::Expr) {
68         match e.kind {
69             ast::ExprKind::Ret(Some(ref expr)) | ast::ExprKind::Break(_, Some(ref expr)) => {
70                 if is_unit_expr(expr) && !expr.span.from_expansion() {
71                     span_lint_and_sugg(
72                         cx,
73                         UNUSED_UNIT,
74                         expr.span,
75                         "unneeded `()`",
76                         "remove the `()`",
77                         String::new(),
78                         Applicability::MachineApplicable,
79                     );
80                 }
81             },
82             _ => (),
83         }
84     }
85
86     fn check_poly_trait_ref(&mut self, cx: &EarlyContext<'_>, poly: &ast::PolyTraitRef, _: &ast::TraitBoundModifier) {
87         let segments = &poly.trait_ref.path.segments;
88
89         if_chain! {
90             if segments.len() == 1;
91             if ["Fn", "FnMut", "FnOnce"].contains(&&*segments[0].ident.name.as_str());
92             if let Some(args) = &segments[0].args;
93             if let ast::GenericArgs::Parenthesized(generic_args) = &**args;
94             if let ast::FnRetTy::Ty(ty) = &generic_args.output;
95             if ty.kind.is_unit();
96             then {
97                 lint_unneeded_unit_return(cx, ty, generic_args.span);
98             }
99         }
100     }
101 }
102
103 // get the def site
104 #[must_use]
105 fn get_def(span: Span) -> Option<Span> {
106     if span.from_expansion() {
107         Some(span.ctxt().outer_expn_data().def_site)
108     } else {
109         None
110     }
111 }
112
113 // is this expr a `()` unit?
114 fn is_unit_expr(expr: &ast::Expr) -> bool {
115     if let ast::ExprKind::Tup(ref vals) = expr.kind {
116         vals.is_empty()
117     } else {
118         false
119     }
120 }
121
122 fn lint_unneeded_unit_return(cx: &EarlyContext<'_>, ty: &ast::Ty, span: Span) {
123     let (ret_span, appl) = if let Ok(fn_source) = cx.sess().source_map().span_to_snippet(span.with_hi(ty.span.hi())) {
124         fn_source
125             .rfind("->")
126             .map_or((ty.span, Applicability::MaybeIncorrect), |rpos| {
127                 (
128                     #[allow(clippy::cast_possible_truncation)]
129                     ty.span.with_lo(BytePos(span.lo().0 + rpos as u32)),
130                     Applicability::MachineApplicable,
131                 )
132             })
133     } else {
134         (ty.span, Applicability::MaybeIncorrect)
135     };
136     span_lint_and_sugg(
137         cx,
138         UNUSED_UNIT,
139         ret_span,
140         "unneeded unit return type",
141         "remove the `-> ()`",
142         String::new(),
143         appl,
144     );
145 }