Skip to content

Commit 8b12eee

Browse files
authored
Merge pull request #3233 from rust-lang-nursery/unused-unit
new lint: unused_unit
2 parents 78860a7 + e8687a6 commit 8b12eee

File tree

8 files changed

+215
-7
lines changed

8 files changed

+215
-7
lines changed

CHANGELOG.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -878,6 +878,7 @@ All notable changes to this project will be documented in this file.
878878
[`unused_collect`]: https://rust-lang-nursery.github.io/rust-clippy/master/index.html#unused_collect
879879
[`unused_io_amount`]: https://rust-lang-nursery.github.io/rust-clippy/master/index.html#unused_io_amount
880880
[`unused_label`]: https://rust-lang-nursery.github.io/rust-clippy/master/index.html#unused_label
881+
[`unused_unit`]: https://rust-lang-nursery.github.io/rust-clippy/master/index.html#unused_unit
881882
[`use_debug`]: https://rust-lang-nursery.github.io/rust-clippy/master/index.html#use_debug
882883
[`use_self`]: https://rust-lang-nursery.github.io/rust-clippy/master/index.html#use_self
883884
[`used_underscore_binding`]: https://rust-lang-nursery.github.io/rust-clippy/master/index.html#used_underscore_binding

README.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@ We are currently in the process of discussing Clippy 1.0 via the RFC process in
99

1010
A collection of lints to catch common mistakes and improve your [Rust](https://github.com/rust-lang/rust) code.
1111

12-
[There are 279 lints included in this crate!](https://rust-lang-nursery.github.io/rust-clippy/master/index.html)
12+
[There are 280 lints included in this crate!](https://rust-lang-nursery.github.io/rust-clippy/master/index.html)
1313

1414
We have a bunch of lint categories to allow you to choose how much Clippy is supposed to ~~annoy~~ help you:
1515

clippy_lints/src/lib.rs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -687,6 +687,7 @@ pub fn register_plugins(reg: &mut rustc_plugin::Registry<'_>, conf: &Conf) {
687687
regex::TRIVIAL_REGEX,
688688
returns::LET_AND_RETURN,
689689
returns::NEEDLESS_RETURN,
690+
returns::UNUSED_UNIT,
690691
serde_api::SERDE_API_MISUSE,
691692
strings::STRING_LIT_AS_BYTES,
692693
suspicious_trait_impl::SUSPICIOUS_ARITHMETIC_IMPL,
@@ -803,6 +804,7 @@ pub fn register_plugins(reg: &mut rustc_plugin::Registry<'_>, conf: &Conf) {
803804
regex::TRIVIAL_REGEX,
804805
returns::LET_AND_RETURN,
805806
returns::NEEDLESS_RETURN,
807+
returns::UNUSED_UNIT,
806808
strings::STRING_LIT_AS_BYTES,
807809
types::FN_TO_NUMERIC_CAST,
808810
types::FN_TO_NUMERIC_CAST_WITH_TRUNCATION,

clippy_lints/src/returns.rs

Lines changed: 97 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -14,8 +14,8 @@ use if_chain::if_chain;
1414
use crate::syntax::ast;
1515
use crate::syntax::source_map::Span;
1616
use crate::syntax::visit::FnKind;
17+
use crate::syntax_pos::BytePos;
1718
use crate::rustc_errors::Applicability;
18-
1919
use crate::utils::{in_macro, match_path_ast, snippet_opt, span_lint_and_then, span_note_and_lint};
2020

2121
/// **What it does:** Checks for return statements at the end of a block.
@@ -68,6 +68,25 @@ declare_clippy_lint! {
6868
the end of a block"
6969
}
7070

71+
/// **What it does:** Checks for unit (`()`) expressions that can be removed.
72+
///
73+
/// **Why is this bad?** Such expressions add no value, but can make the code
74+
/// less readable. Depending on formatting they can make a `break` or `return`
75+
/// statement look like a function call.
76+
///
77+
/// **Known problems:** The lint currently misses unit return types in types,
78+
/// e.g. the `F` in `fn generic_unit<F: Fn() -> ()>(f: F) { .. }`.
79+
///
80+
/// **Example:**
81+
/// ```rust
82+
/// fn return_unit() -> () { () }
83+
/// ```
84+
declare_clippy_lint! {
85+
pub UNUSED_UNIT,
86+
style,
87+
"needless unit expression"
88+
}
89+
7190
#[derive(Copy, Clone)]
7291
pub struct ReturnPass;
7392

@@ -162,23 +181,98 @@ impl ReturnPass {
162181

163182
impl LintPass for ReturnPass {
164183
fn get_lints(&self) -> LintArray {
165-
lint_array!(NEEDLESS_RETURN, LET_AND_RETURN)
184+
lint_array!(NEEDLESS_RETURN, LET_AND_RETURN, UNUSED_UNIT)
166185
}
167186
}
168187

169188
impl EarlyLintPass for ReturnPass {
170-
fn check_fn(&mut self, cx: &EarlyContext<'_>, kind: FnKind<'_>, _: &ast::FnDecl, _: Span, _: ast::NodeId) {
189+
fn check_fn(&mut self, cx: &EarlyContext<'_>, kind: FnKind<'_>, decl: &ast::FnDecl, span: Span, _: ast::NodeId) {
171190
match kind {
172191
FnKind::ItemFn(.., block) | FnKind::Method(.., block) => self.check_block_return(cx, block),
173192
FnKind::Closure(body) => self.check_final_expr(cx, body, Some(body.span)),
174193
}
194+
if_chain! {
195+
if let ast::FunctionRetTy::Ty(ref ty) = decl.output;
196+
if let ast::TyKind::Tup(ref vals) = ty.node;
197+
if vals.is_empty() && !in_macro(ty.span) && get_def(span) == get_def(ty.span);
198+
then {
199+
let (rspan, appl) = if let Ok(fn_source) =
200+
cx.sess().source_map()
201+
.span_to_snippet(span.with_hi(ty.span.hi())) {
202+
if let Some(rpos) = fn_source.rfind("->") {
203+
(ty.span.with_lo(BytePos(span.lo().0 + rpos as u32)),
204+
Applicability::MachineApplicable)
205+
} else {
206+
(ty.span, Applicability::MaybeIncorrect)
207+
}
208+
} else {
209+
(ty.span, Applicability::MaybeIncorrect)
210+
};
211+
span_lint_and_then(cx, UNUSED_UNIT, rspan, "unneeded unit return type", |db| {
212+
db.span_suggestion_with_applicability(
213+
rspan,
214+
"remove the `-> ()`",
215+
String::new(),
216+
appl,
217+
);
218+
});
219+
}
220+
}
175221
}
176222

177223
fn check_block(&mut self, cx: &EarlyContext<'_>, block: &ast::Block) {
178224
self.check_let_return(cx, block);
225+
if_chain! {
226+
if let Some(ref stmt) = block.stmts.last();
227+
if let ast::StmtKind::Expr(ref expr) = stmt.node;
228+
if is_unit_expr(expr) && !in_macro(expr.span);
229+
then {
230+
let sp = expr.span;
231+
span_lint_and_then(cx, UNUSED_UNIT, sp, "unneeded unit expression", |db| {
232+
db.span_suggestion_with_applicability(
233+
sp,
234+
"remove the final `()`",
235+
String::new(),
236+
Applicability::MachineApplicable,
237+
);
238+
});
239+
}
240+
}
241+
}
242+
243+
fn check_expr(&mut self, cx: &EarlyContext<'_>, e: &ast::Expr) {
244+
match e.node {
245+
ast::ExprKind::Ret(Some(ref expr)) | ast::ExprKind::Break(_, Some(ref expr)) => {
246+
if is_unit_expr(expr) && !in_macro(expr.span) {
247+
span_lint_and_then(cx, UNUSED_UNIT, expr.span, "unneeded `()`", |db| {
248+
db.span_suggestion_with_applicability(
249+
expr.span,
250+
"remove the `()`",
251+
String::new(),
252+
Applicability::MachineApplicable,
253+
);
254+
});
255+
}
256+
}
257+
_ => ()
258+
}
179259
}
180260
}
181261

182262
fn attr_is_cfg(attr: &ast::Attribute) -> bool {
183263
attr.meta_item_list().is_some() && attr.name() == "cfg"
184264
}
265+
266+
// get the def site
267+
fn get_def(span: Span) -> Option<Span> {
268+
span.ctxt().outer().expn_info().and_then(|info| info.def_site)
269+
}
270+
271+
// is this expr a `()` unit?
272+
fn is_unit_expr(expr: &ast::Expr) -> bool {
273+
if let ast::ExprKind::Tup(ref vals) = expr.node {
274+
vals.is_empty()
275+
} else {
276+
false
277+
}
278+
}

tests/ui/copies.rs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -7,12 +7,11 @@
77
// option. This file may not be copied, modified, or distributed
88
// except according to those terms.
99

10+
#![allow(clippy::blacklisted_name, clippy::collapsible_if, clippy::cyclomatic_complexity, clippy::eq_op, clippy::needless_continue,
11+
clippy::needless_return, clippy::never_loop, clippy::no_effect, clippy::zero_divided_by_zero, clippy::unused_unit)]
1012

1113

1214

13-
#![allow(clippy::blacklisted_name, clippy::collapsible_if, clippy::cyclomatic_complexity, clippy::eq_op, clippy::needless_continue,
14-
clippy::needless_return, clippy::never_loop, clippy::no_effect, clippy::zero_divided_by_zero)]
15-
1615
fn bar<T>(_: T) {}
1716
fn foo() -> bool { unimplemented!() }
1817

@@ -28,6 +27,7 @@ pub enum Abc {
2827

2928
#[warn(clippy::if_same_then_else)]
3029
#[warn(clippy::match_same_arms)]
30+
#[allow(clippy::unused_unit)]
3131
fn if_same_then_else() -> Result<&'static str, ()> {
3232
if true {
3333
Foo { bar: 42 };

tests/ui/my_lint.rs

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
#[clippy::author]
2+
#[cfg(any(target_arch = "x86"))]
3+
pub struct Foo {
4+
x: u32,
5+
}
6+
7+
fn main() {}

tests/ui/unused_unit.rs

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
// Copyright 2017 The Rust Project Developers. See the COPYRIGHT
2+
// file at the top-level directory of this distribution and at
3+
// http://rust-lang.org/COPYRIGHT.
4+
//
5+
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6+
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7+
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8+
// option. This file may not be copied, modified, or distributed
9+
// except according to those terms.
10+
11+
// run-rustfix
12+
// compile-pass
13+
14+
// The output for humans should just highlight the whole span without showing
15+
// the suggested replacement, but we also want to test that suggested
16+
// replacement only removes one set of parentheses, rather than naïvely
17+
// stripping away any starting or ending parenthesis characters—hence this
18+
// test of the JSON error format.
19+
20+
21+
#![deny(clippy::unused_unit)]
22+
#![allow(clippy::needless_return)]
23+
24+
struct Unitter;
25+
26+
impl Unitter {
27+
// try to disorient the lint with multiple unit returns and newlines
28+
pub fn get_unit<F: Fn() -> (), G>(&self, f: F, _g: G) ->
29+
()
30+
where G: Fn() -> () {
31+
let _y: &Fn() -> () = &f;
32+
(); // this should not lint, as it's not in return type position
33+
}
34+
}
35+
36+
impl Into<()> for Unitter {
37+
fn into(self) -> () {
38+
()
39+
}
40+
}
41+
42+
fn return_unit() -> () { () }
43+
44+
fn main() {
45+
let u = Unitter;
46+
assert_eq!(u.get_unit(|| {}, return_unit), u.into());
47+
return_unit();
48+
loop {
49+
break();
50+
}
51+
return();
52+
}

tests/ui/unused_unit.stderr

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
error: unneeded unit return type
2+
--> $DIR/unused_unit.rs:28:59
3+
|
4+
28 | pub fn get_unit<F: Fn() -> (), G>(&self, f: F, _g: G) ->
5+
| ___________________________________________________________^
6+
29 | | ()
7+
| |__________^ help: remove the `-> ()`
8+
|
9+
note: lint level defined here
10+
--> $DIR/unused_unit.rs:21:9
11+
|
12+
21 | #![deny(clippy::unused_unit)]
13+
| ^^^^^^^^^^^^^^^^^^^
14+
15+
error: unneeded unit return type
16+
--> $DIR/unused_unit.rs:37:19
17+
|
18+
37 | fn into(self) -> () {
19+
| ^^^^^ help: remove the `-> ()`
20+
21+
error: unneeded unit expression
22+
--> $DIR/unused_unit.rs:38:9
23+
|
24+
38 | ()
25+
| ^^ help: remove the final `()`
26+
27+
error: unneeded unit return type
28+
--> $DIR/unused_unit.rs:42:18
29+
|
30+
42 | fn return_unit() -> () { () }
31+
| ^^^^^ help: remove the `-> ()`
32+
33+
error: unneeded unit expression
34+
--> $DIR/unused_unit.rs:42:26
35+
|
36+
42 | fn return_unit() -> () { () }
37+
| ^^ help: remove the final `()`
38+
39+
error: unneeded `()`
40+
--> $DIR/unused_unit.rs:49:14
41+
|
42+
49 | break();
43+
| ^^ help: remove the `()`
44+
45+
error: unneeded `()`
46+
--> $DIR/unused_unit.rs:51:11
47+
|
48+
51 | return();
49+
| ^^ help: remove the `()`
50+
51+
error: aborting due to 7 previous errors
52+

0 commit comments

Comments
 (0)