Skip to content

Commit ef95ca1

Browse files
committed
Add new lint to detect unnecessarily wrapped value
1 parent 01dd31f commit ef95ca1

File tree

7 files changed

+318
-0
lines changed

7 files changed

+318
-0
lines changed

CHANGELOG.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1994,6 +1994,7 @@ Released 2018-09-13
19941994
[`unnecessary_operation`]: https://rust-lang.github.io/rust-clippy/master/index.html#unnecessary_operation
19951995
[`unnecessary_sort_by`]: https://rust-lang.github.io/rust-clippy/master/index.html#unnecessary_sort_by
19961996
[`unnecessary_unwrap`]: https://rust-lang.github.io/rust-clippy/master/index.html#unnecessary_unwrap
1997+
[`unnecessary_wrap`]: https://rust-lang.github.io/rust-clippy/master/index.html#unnecessary_wrap
19971998
[`unneeded_field_pattern`]: https://rust-lang.github.io/rust-clippy/master/index.html#unneeded_field_pattern
19981999
[`unneeded_wildcard_pattern`]: https://rust-lang.github.io/rust-clippy/master/index.html#unneeded_wildcard_pattern
19992000
[`unnested_or_patterns`]: https://rust-lang.github.io/rust-clippy/master/index.html#unnested_or_patterns

clippy_lints/src/lib.rs

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -318,6 +318,7 @@ mod unicode;
318318
mod unit_return_expecting_ord;
319319
mod unnamed_address;
320320
mod unnecessary_sort_by;
321+
mod unnecessary_wrap;
321322
mod unnested_or_patterns;
322323
mod unsafe_removed_from_name;
323324
mod unused_io_amount;
@@ -869,6 +870,7 @@ pub fn register_plugins(store: &mut rustc_lint::LintStore, sess: &Session, conf:
869870
&unnamed_address::FN_ADDRESS_COMPARISONS,
870871
&unnamed_address::VTABLE_ADDRESS_COMPARISONS,
871872
&unnecessary_sort_by::UNNECESSARY_SORT_BY,
873+
&unnecessary_wrap::UNNECESSARY_WRAP,
872874
&unnested_or_patterns::UNNESTED_OR_PATTERNS,
873875
&unsafe_removed_from_name::UNSAFE_REMOVED_FROM_NAME,
874876
&unused_io_amount::UNUSED_IO_AMOUNT,
@@ -1038,6 +1040,7 @@ pub fn register_plugins(store: &mut rustc_lint::LintStore, sess: &Session, conf:
10381040
store.register_late_pass(|| box redundant_clone::RedundantClone);
10391041
store.register_late_pass(|| box slow_vector_initialization::SlowVectorInit);
10401042
store.register_late_pass(|| box unnecessary_sort_by::UnnecessarySortBy);
1043+
store.register_late_pass(|| box unnecessary_wrap::UnnecessaryWrap);
10411044
store.register_late_pass(|| box types::RefToMut);
10421045
store.register_late_pass(|| box assertions_on_constants::AssertionsOnConstants);
10431046
store.register_late_pass(|| box missing_const_for_fn::MissingConstForFn);
@@ -1526,6 +1529,7 @@ pub fn register_plugins(store: &mut rustc_lint::LintStore, sess: &Session, conf:
15261529
LintId::of(&unnamed_address::FN_ADDRESS_COMPARISONS),
15271530
LintId::of(&unnamed_address::VTABLE_ADDRESS_COMPARISONS),
15281531
LintId::of(&unnecessary_sort_by::UNNECESSARY_SORT_BY),
1532+
LintId::of(&unnecessary_wrap::UNNECESSARY_WRAP),
15291533
LintId::of(&unsafe_removed_from_name::UNSAFE_REMOVED_FROM_NAME),
15301534
LintId::of(&unused_io_amount::UNUSED_IO_AMOUNT),
15311535
LintId::of(&unused_unit::UNUSED_UNIT),
@@ -1721,6 +1725,7 @@ pub fn register_plugins(store: &mut rustc_lint::LintStore, sess: &Session, conf:
17211725
LintId::of(&types::UNNECESSARY_CAST),
17221726
LintId::of(&types::VEC_BOX),
17231727
LintId::of(&unnecessary_sort_by::UNNECESSARY_SORT_BY),
1728+
LintId::of(&unnecessary_wrap::UNNECESSARY_WRAP),
17241729
LintId::of(&unwrap::UNNECESSARY_UNWRAP),
17251730
LintId::of(&useless_conversion::USELESS_CONVERSION),
17261731
LintId::of(&zero_div_zero::ZERO_DIVIDED_BY_ZERO),

clippy_lints/src/unnecessary_wrap.rs

Lines changed: 177 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,177 @@
1+
use crate::utils::{
2+
is_type_diagnostic_item, match_qpath, multispan_sugg_with_applicability, paths, return_ty, snippet,
3+
span_lint_and_then,
4+
};
5+
use if_chain::if_chain;
6+
use rustc_errors::Applicability;
7+
use rustc_hir::intravisit::{FnKind, NestedVisitorMap, Visitor};
8+
use rustc_hir::*;
9+
use rustc_lint::{LateContext, LateLintPass};
10+
use rustc_middle::hir::map::Map;
11+
use rustc_session::{declare_lint_pass, declare_tool_lint};
12+
use rustc_span::Span;
13+
14+
declare_clippy_lint! {
15+
/// **What it does:** Checks for private functions that only return `Ok` or `Some`.
16+
///
17+
/// **Why is this bad?** It is not meaningful to wrap values when no `None` or `Err` is returned.
18+
///
19+
/// **Known problems:** Since this lint changes function type signature, you may need to
20+
/// adjust some codes at callee side.
21+
///
22+
/// **Example:**
23+
///
24+
/// ```rust
25+
/// pub fn get_cool_number(a: bool, b: bool) -> Option<i32> {
26+
/// if a && b {
27+
/// return Some(50);
28+
/// }
29+
/// if a {
30+
/// Some(0)
31+
/// } else {
32+
/// Some(10)
33+
/// }
34+
/// }
35+
/// ```
36+
/// Use instead:
37+
/// ```rust
38+
/// pub fn get_cool_number(a: bool, b: bool) -> i32 {
39+
/// if a && b {
40+
/// return 50;
41+
/// }
42+
/// if a {
43+
/// 0
44+
/// } else {
45+
/// 10
46+
/// }
47+
/// }
48+
/// ```
49+
pub UNNECESSARY_WRAP,
50+
complexity,
51+
"functions that only return `Ok` or `Some`"
52+
}
53+
54+
declare_lint_pass!(UnnecessaryWrap => [UNNECESSARY_WRAP]);
55+
56+
impl<'tcx> LateLintPass<'tcx> for UnnecessaryWrap {
57+
fn check_fn(
58+
&mut self,
59+
cx: &LateContext<'tcx>,
60+
fn_kind: FnKind<'tcx>,
61+
fn_decl: &FnDecl<'tcx>,
62+
body: &Body<'tcx>,
63+
span: Span,
64+
hir_id: HirId,
65+
) {
66+
if_chain! {
67+
if let FnKind::ItemFn(.., visibility, _) = fn_kind;
68+
if visibility.node.is_pub();
69+
then {
70+
return;
71+
}
72+
}
73+
74+
if let ExprKind::Block(ref block, ..) = body.value.kind {
75+
let path = if is_type_diagnostic_item(cx, return_ty(cx, hir_id), sym!(option_type)) {
76+
&paths::OPTION_SOME
77+
} else if is_type_diagnostic_item(cx, return_ty(cx, hir_id), sym!(result_type)) {
78+
&paths::RESULT_OK
79+
} else {
80+
return;
81+
};
82+
83+
let mut visitor = UnnecessaryWrapVisitor { result: Vec::new() };
84+
visitor.visit_block(block);
85+
let result = visitor.result;
86+
87+
if result.iter().any(|expr| {
88+
if_chain! {
89+
if let ExprKind::Call(ref func, ref args) = expr.kind;
90+
if let ExprKind::Path(ref qpath) = func.kind;
91+
if match_qpath(qpath, path);
92+
if args.len() == 1;
93+
then {
94+
false
95+
} else {
96+
true
97+
}
98+
}
99+
}) {
100+
return;
101+
}
102+
103+
let suggs = result.iter().filter_map(|expr| {
104+
let snippet = if let ExprKind::Call(_, ref args) = expr.kind {
105+
Some(snippet(cx, args[0].span, "..").to_string())
106+
} else {
107+
None
108+
};
109+
snippet.map(|snip| (expr.span, snip))
110+
});
111+
112+
span_lint_and_then(
113+
cx,
114+
UNNECESSARY_WRAP,
115+
span,
116+
"this function returns unnecessarily wrapping data",
117+
move |diag| {
118+
multispan_sugg_with_applicability(
119+
diag,
120+
"factor this out to",
121+
Applicability::MachineApplicable,
122+
suggs,
123+
);
124+
},
125+
);
126+
}
127+
}
128+
}
129+
130+
struct UnnecessaryWrapVisitor<'tcx> {
131+
result: Vec<&'tcx Expr<'tcx>>,
132+
}
133+
134+
impl<'tcx> Visitor<'tcx> for UnnecessaryWrapVisitor<'tcx> {
135+
type Map = Map<'tcx>;
136+
137+
fn visit_block(&mut self, block: &'tcx Block<'tcx>) {
138+
for stmt in block.stmts {
139+
self.visit_stmt(stmt);
140+
}
141+
if let Some(expr) = block.expr {
142+
self.visit_expr(expr)
143+
}
144+
}
145+
146+
fn visit_stmt(&mut self, stmt: &'tcx Stmt<'tcx>) {
147+
match stmt.kind {
148+
StmtKind::Semi(ref expr) => {
149+
if let ExprKind::Ret(Some(value)) = expr.kind {
150+
self.result.push(value);
151+
}
152+
},
153+
StmtKind::Expr(ref expr) => self.visit_expr(expr),
154+
_ => (),
155+
}
156+
}
157+
158+
fn visit_expr(&mut self, expr: &'tcx Expr<'tcx>) {
159+
match expr.kind {
160+
ExprKind::Ret(Some(value)) => self.result.push(value),
161+
ExprKind::Call(..) | ExprKind::Path(..) => self.result.push(expr),
162+
ExprKind::Block(ref block, _) | ExprKind::Loop(ref block, ..) => {
163+
self.visit_block(block);
164+
},
165+
ExprKind::Match(_, arms, _) => {
166+
for arm in arms {
167+
self.visit_expr(arm.body);
168+
}
169+
},
170+
_ => intravisit::walk_expr(self, expr),
171+
}
172+
}
173+
174+
fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
175+
NestedVisitorMap::None
176+
}
177+
}

src/lintlist/mod.rs

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2517,6 +2517,13 @@ vec![
25172517
deprecation: None,
25182518
module: "unwrap",
25192519
},
2520+
Lint {
2521+
name: "unnecessary_wrap",
2522+
group: "complexity",
2523+
desc: "functions that only return `Ok` or `Some`",
2524+
deprecation: None,
2525+
module: "unnecessary_wrap",
2526+
},
25202527
Lint {
25212528
name: "unneeded_field_pattern",
25222529
group: "restriction",

tests/ui/unnecessary_wrap.fixed

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
// run-rustfix
2+
#![warn(clippy::unnecessary_wrap)]
3+
#![allow(clippy::no_effect)]
4+
#![allow(clippy::needless_return)]
5+
#![allow(clippy::if_same_then_else)]
6+
7+
// should be linted
8+
fn func1(a: bool, b: bool) -> Option<i32> {
9+
if a && b {
10+
return Some(42);
11+
}
12+
if a {
13+
Some(-1);
14+
Some(2)
15+
} else {
16+
return Some(1337);
17+
}
18+
}
19+
20+
// public fns should not be linted
21+
pub fn func2(a: bool) -> Option<i32> {
22+
if a {
23+
Some(1)
24+
} else {
25+
Some(1)
26+
}
27+
}
28+
29+
// should not be linted
30+
fn func3(a: bool) -> Option<i32> {
31+
if a {
32+
Some(1)
33+
} else {
34+
None
35+
}
36+
}
37+
38+
// should be linted
39+
fn func4() -> Option<i32> {
40+
1
41+
}
42+
43+
fn main() {
44+
// method calls are not linted
45+
func1(true, true);
46+
func2(true);
47+
}

tests/ui/unnecessary_wrap.rs

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
// run-rustfix
2+
#![warn(clippy::unnecessary_wrap)]
3+
#![allow(clippy::no_effect)]
4+
#![allow(clippy::needless_return)]
5+
#![allow(clippy::if_same_then_else)]
6+
7+
// should be linted
8+
fn func1(a: bool, b: bool) -> Option<i32> {
9+
if a && b {
10+
return Some(42);
11+
}
12+
if a {
13+
Some(-1);
14+
Some(2)
15+
} else {
16+
return Some(1337);
17+
}
18+
}
19+
20+
// public fns should not be linted
21+
pub fn func2(a: bool) -> Option<i32> {
22+
if a {
23+
Some(1)
24+
} else {
25+
Some(1)
26+
}
27+
}
28+
29+
// should not be linted
30+
fn func3(a: bool) -> Option<i32> {
31+
if a {
32+
Some(1)
33+
} else {
34+
None
35+
}
36+
}
37+
38+
// should be linted
39+
fn func4() -> Option<i32> {
40+
Some(1)
41+
}
42+
43+
fn main() {
44+
// method calls are not linted
45+
func1(true, true);
46+
func2(true);
47+
}

tests/ui/unnecessary_wrap.stderr

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
error: this function unnecessarily wrapping data
2+
--> $DIR/unnecessary_wrap.rs:8:1
3+
|
4+
LL | / fn func1(a: bool, b: bool) -> Option<i32> {
5+
LL | | if a && b {
6+
LL | | return Some(42);
7+
LL | | }
8+
... |
9+
LL | | }
10+
LL | | }
11+
| |_^
12+
|
13+
= note: `-D clippy::unnecessary-wrap` implied by `-D warnings`
14+
help: factor this out to
15+
|
16+
LL | return 42;
17+
LL | }
18+
LL | if a {
19+
LL | Some(-1);
20+
LL | 2
21+
LL | } else {
22+
...
23+
24+
error: this function unnecessarily wrapping data
25+
--> $DIR/unnecessary_wrap.rs:39:1
26+
|
27+
LL | / fn func4() -> Option<i32> {
28+
LL | | Some(1)
29+
| | ------- help: factor this out to: `1`
30+
LL | | }
31+
| |_^
32+
33+
error: aborting due to 2 previous errors
34+

0 commit comments

Comments
 (0)