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