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