]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/unused_unit.rs
Rollup merge of #7239 - flip1995:ci-windows-rustup, r=flip1995
[rust.git] / clippy_lints / src / unused_unit.rs
1 use clippy_utils::diagnostics::span_lint_and_sugg;
2 use clippy_utils::source::position_before_rarrow;
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, LintContext};
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:** 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:** None.
20     ///
21     /// **Example:**
22     /// ```rust
23     /// fn return_unit() -> () {
24     ///     ()
25     /// }
26     /// ```
27     pub UNUSED_UNIT,
28     style,
29     "needless unit expression"
30 }
31
32 declare_lint_pass!(UnusedUnit => [UNUSED_UNIT]);
33
34 impl EarlyLintPass for UnusedUnit {
35     fn check_fn(&mut self, cx: &EarlyContext<'_>, kind: FnKind<'_>, span: Span, _: ast::NodeId) {
36         if_chain! {
37             if let ast::FnRetTy::Ty(ref ty) = kind.decl().output;
38             if let ast::TyKind::Tup(ref vals) = ty.kind;
39             if vals.is_empty() && !ty.span.from_expansion() && get_def(span) == get_def(ty.span);
40             then {
41                 lint_unneeded_unit_return(cx, ty, span);
42             }
43         }
44     }
45
46     fn check_block(&mut self, cx: &EarlyContext<'_>, block: &ast::Block) {
47         if_chain! {
48             if let Some(stmt) = block.stmts.last();
49             if let ast::StmtKind::Expr(ref expr) = stmt.kind;
50             if is_unit_expr(expr);
51             let ctxt = block.span.ctxt();
52             if stmt.span.ctxt() == ctxt && expr.span.ctxt() == ctxt;
53             then {
54                 let sp = expr.span;
55                 span_lint_and_sugg(
56                     cx,
57                     UNUSED_UNIT,
58                     sp,
59                     "unneeded unit expression",
60                     "remove the final `()`",
61                     String::new(),
62                     Applicability::MachineApplicable,
63                 );
64             }
65         }
66     }
67
68     fn check_expr(&mut self, cx: &EarlyContext<'_>, e: &ast::Expr) {
69         match e.kind {
70             ast::ExprKind::Ret(Some(ref expr)) | ast::ExprKind::Break(_, Some(ref expr)) => {
71                 if is_unit_expr(expr) && !expr.span.from_expansion() {
72                     span_lint_and_sugg(
73                         cx,
74                         UNUSED_UNIT,
75                         expr.span,
76                         "unneeded `()`",
77                         "remove the `()`",
78                         String::new(),
79                         Applicability::MachineApplicable,
80                     );
81                 }
82             },
83             _ => (),
84         }
85     }
86
87     fn check_poly_trait_ref(&mut self, cx: &EarlyContext<'_>, poly: &ast::PolyTraitRef, _: &ast::TraitBoundModifier) {
88         let segments = &poly.trait_ref.path.segments;
89
90         if_chain! {
91             if segments.len() == 1;
92             if ["Fn", "FnMut", "FnOnce"].contains(&&*segments[0].ident.name.as_str());
93             if let Some(args) = &segments[0].args;
94             if let ast::GenericArgs::Parenthesized(generic_args) = &**args;
95             if let ast::FnRetTy::Ty(ty) = &generic_args.output;
96             if ty.kind.is_unit();
97             then {
98                 lint_unneeded_unit_return(cx, ty, generic_args.span);
99             }
100         }
101     }
102 }
103
104 // get the def site
105 #[must_use]
106 fn get_def(span: Span) -> Option<Span> {
107     if span.from_expansion() {
108         Some(span.ctxt().outer_expn_data().def_site)
109     } else {
110         None
111     }
112 }
113
114 // is this expr a `()` unit?
115 fn is_unit_expr(expr: &ast::Expr) -> bool {
116     if let ast::ExprKind::Tup(ref vals) = expr.kind {
117         vals.is_empty()
118     } else {
119         false
120     }
121 }
122
123 fn lint_unneeded_unit_return(cx: &EarlyContext<'_>, ty: &ast::Ty, span: Span) {
124     let (ret_span, appl) = if let Ok(fn_source) = cx.sess().source_map().span_to_snippet(span.with_hi(ty.span.hi())) {
125         position_before_rarrow(&fn_source).map_or((ty.span, Applicability::MaybeIncorrect), |rpos| {
126             (
127                 #[allow(clippy::cast_possible_truncation)]
128                 ty.span.with_lo(BytePos(span.lo().0 + rpos as u32)),
129                 Applicability::MachineApplicable,
130             )
131         })
132     } else {
133         (ty.span, Applicability::MaybeIncorrect)
134     };
135     span_lint_and_sugg(
136         cx,
137         UNUSED_UNIT,
138         ret_span,
139         "unneeded unit return type",
140         "remove the `-> ()`",
141         String::new(),
142         appl,
143     );
144 }