Skip to content

Commit ae32137

Browse files
authored
Merge pull request #1467 from philipturnbull/option_map_nil_fn
Lint `Option.map(f)` where f returns unit
2 parents 9dc9487 + 26b9911 commit ae32137

File tree

10 files changed

+1076
-4
lines changed

10 files changed

+1076
-4
lines changed

CHANGELOG.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -710,6 +710,7 @@ All notable changes to this project will be documented in this file.
710710
[`nonsensical_open_options`]: https://rust-lang-nursery.github.io/rust-clippy/master/index.html#nonsensical_open_options
711711
[`not_unsafe_ptr_arg_deref`]: https://rust-lang-nursery.github.io/rust-clippy/master/index.html#not_unsafe_ptr_arg_deref
712712
[`ok_expect`]: https://rust-lang-nursery.github.io/rust-clippy/master/index.html#ok_expect
713+
[`map_unit_fn`]: https://rust-lang-nursery.github.io/rust-clippy/master/index.html#map_unit_fn
713714
[`op_ref`]: https://rust-lang-nursery.github.io/rust-clippy/master/index.html#op_ref
714715
[`option_map_or_none`]: https://rust-lang-nursery.github.io/rust-clippy/master/index.html#option_map_or_none
715716
[`option_map_unwrap_or`]: https://rust-lang-nursery.github.io/rust-clippy/master/index.html#option_map_unwrap_or

clippy_lints/src/lib.rs

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -145,6 +145,7 @@ pub mod lifetimes;
145145
pub mod literal_representation;
146146
pub mod loops;
147147
pub mod map_clone;
148+
pub mod map_unit_fn;
148149
pub mod matches;
149150
pub mod mem_forget;
150151
pub mod methods;
@@ -405,6 +406,7 @@ pub fn register_plugins(reg: &mut rustc_plugin::Registry) {
405406
reg.register_late_lint_pass(box question_mark::QuestionMarkPass);
406407
reg.register_late_lint_pass(box suspicious_trait_impl::SuspiciousImpl);
407408
reg.register_late_lint_pass(box redundant_field_names::RedundantFieldNames);
409+
reg.register_late_lint_pass(box map_unit_fn::Pass);
408410

409411

410412
reg.register_lint_group("clippy_restriction", vec![
@@ -441,6 +443,8 @@ pub fn register_plugins(reg: &mut rustc_plugin::Registry) {
441443
if_not_else::IF_NOT_ELSE,
442444
infinite_iter::MAYBE_INFINITE_ITER,
443445
items_after_statements::ITEMS_AFTER_STATEMENTS,
446+
map_unit_fn::OPTION_MAP_UNIT_FN,
447+
map_unit_fn::RESULT_MAP_UNIT_FN,
444448
matches::SINGLE_MATCH_ELSE,
445449
methods::FILTER_MAP,
446450
methods::OPTION_MAP_UNWRAP_OR,

clippy_lints/src/map_unit_fn.rs

Lines changed: 251 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,251 @@
1+
use rustc::hir;
2+
use rustc::lint::*;
3+
use rustc::ty;
4+
use syntax::codemap::Span;
5+
use utils::{in_macro, iter_input_pats, match_type, method_chain_args, snippet, span_lint_and_then};
6+
use utils::paths;
7+
8+
#[derive(Clone)]
9+
pub struct Pass;
10+
11+
/// **What it does:** Checks for usage of `option.map(f)` where f is a function
12+
/// or closure that returns the unit type.
13+
///
14+
/// **Why is this bad?** Readability, this can be written more clearly with
15+
/// an if let statement
16+
///
17+
/// **Known problems:** None.
18+
///
19+
/// **Example:**
20+
///
21+
/// ```rust
22+
/// let x: Option<&str> = do_stuff();
23+
/// x.map(log_err_msg);
24+
/// x.map(|msg| log_err_msg(format_msg(msg)))
25+
/// ```
26+
///
27+
/// The correct use would be:
28+
///
29+
/// ```rust
30+
/// let x: Option<&str> = do_stuff();
31+
/// if let Some(msg) = x {
32+
/// log_err_msg(msg)
33+
/// }
34+
/// if let Some(msg) = x {
35+
/// log_err_msg(format_msg(msg))
36+
/// }
37+
/// ```
38+
declare_clippy_lint! {
39+
pub OPTION_MAP_UNIT_FN,
40+
complexity,
41+
"using `option.map(f)`, where f is a function or closure that returns ()"
42+
}
43+
44+
/// **What it does:** Checks for usage of `result.map(f)` where f is a function
45+
/// or closure that returns the unit type.
46+
///
47+
/// **Why is this bad?** Readability, this can be written more clearly with
48+
/// an if let statement
49+
///
50+
/// **Known problems:** None.
51+
///
52+
/// **Example:**
53+
///
54+
/// ```rust
55+
/// let x: Result<&str, &str> = do_stuff();
56+
/// x.map(log_err_msg);
57+
/// x.map(|msg| log_err_msg(format_msg(msg)))
58+
/// ```
59+
///
60+
/// The correct use would be:
61+
///
62+
/// ```rust
63+
/// let x: Result<&str, &str> = do_stuff();
64+
/// if let Ok(msg) = x {
65+
/// log_err_msg(msg)
66+
/// }
67+
/// if let Ok(msg) = x {
68+
/// log_err_msg(format_msg(msg))
69+
/// }
70+
/// ```
71+
declare_clippy_lint! {
72+
pub RESULT_MAP_UNIT_FN,
73+
complexity,
74+
"using `result.map(f)`, where f is a function or closure that returns ()"
75+
}
76+
77+
78+
impl LintPass for Pass {
79+
fn get_lints(&self) -> LintArray {
80+
lint_array!(OPTION_MAP_UNIT_FN, RESULT_MAP_UNIT_FN)
81+
}
82+
}
83+
84+
fn is_unit_type(ty: ty::Ty) -> bool {
85+
match ty.sty {
86+
ty::TyTuple(slice) => slice.is_empty(),
87+
ty::TyNever => true,
88+
_ => false,
89+
}
90+
}
91+
92+
fn is_unit_function(cx: &LateContext, expr: &hir::Expr) -> bool {
93+
let ty = cx.tables.expr_ty(expr);
94+
95+
if let ty::TyFnDef(id, _) = ty.sty {
96+
if let Some(fn_type) = cx.tcx.fn_sig(id).no_late_bound_regions() {
97+
return is_unit_type(fn_type.output());
98+
}
99+
}
100+
false
101+
}
102+
103+
fn is_unit_expression(cx: &LateContext, expr: &hir::Expr) -> bool {
104+
is_unit_type(cx.tables.expr_ty(expr))
105+
}
106+
107+
/// The expression inside a closure may or may not have surrounding braces and
108+
/// semicolons, which causes problems when generating a suggestion. Given an
109+
/// expression that evaluates to '()' or '!', recursively remove useless braces
110+
/// and semi-colons until is suitable for including in the suggestion template
111+
fn reduce_unit_expression<'a>(cx: &LateContext, expr: &'a hir::Expr) -> Option<Span> {
112+
if !is_unit_expression(cx, expr) {
113+
return None;
114+
}
115+
116+
match expr.node {
117+
hir::ExprCall(_, _) |
118+
hir::ExprMethodCall(_, _, _) => {
119+
// Calls can't be reduced any more
120+
Some(expr.span)
121+
},
122+
hir::ExprBlock(ref block) => {
123+
match (&block.stmts[..], block.expr.as_ref()) {
124+
(&[], Some(inner_expr)) => {
125+
// If block only contains an expression,
126+
// reduce `{ X }` to `X`
127+
reduce_unit_expression(cx, inner_expr)
128+
},
129+
(&[ref inner_stmt], None) => {
130+
// If block only contains statements,
131+
// reduce `{ X; }` to `X` or `X;`
132+
match inner_stmt.node {
133+
hir::StmtDecl(ref d, _) => Some(d.span),
134+
hir::StmtExpr(ref e, _) => Some(e.span),
135+
hir::StmtSemi(_, _) => Some(inner_stmt.span),
136+
}
137+
},
138+
_ => {
139+
// For closures that contain multiple statements
140+
// it's difficult to get a correct suggestion span
141+
// for all cases (multi-line closures specifically)
142+
//
143+
// We do not attempt to build a suggestion for those right now.
144+
None
145+
}
146+
}
147+
},
148+
_ => None,
149+
}
150+
}
151+
152+
fn unit_closure<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, expr: &'a hir::Expr) -> Option<(&'tcx hir::Arg, &'a hir::Expr)> {
153+
if let hir::ExprClosure(_, ref decl, inner_expr_id, _, _) = expr.node {
154+
let body = cx.tcx.hir.body(inner_expr_id);
155+
let body_expr = &body.value;
156+
157+
if_chain! {
158+
if decl.inputs.len() == 1;
159+
if is_unit_expression(cx, body_expr);
160+
if let Some(binding) = iter_input_pats(&decl, body).next();
161+
then {
162+
return Some((binding, body_expr));
163+
}
164+
}
165+
}
166+
None
167+
}
168+
169+
/// Builds a name for the let binding variable (var_arg)
170+
///
171+
/// `x.field` => `x_field`
172+
/// `y` => `_y`
173+
///
174+
/// Anything else will return `_`.
175+
fn let_binding_name(cx: &LateContext, var_arg: &hir::Expr) -> String {
176+
match &var_arg.node {
177+
hir::ExprField(_, _) => snippet(cx, var_arg.span, "_").replace(".", "_"),
178+
hir::ExprPath(_) => format!("_{}", snippet(cx, var_arg.span, "")),
179+
_ => "_".to_string()
180+
}
181+
}
182+
183+
fn suggestion_msg(function_type: &str, map_type: &str) -> String {
184+
format!(
185+
"called `map(f)` on an {0} value where `f` is a unit {1}",
186+
map_type,
187+
function_type
188+
)
189+
}
190+
191+
fn lint_map_unit_fn(cx: &LateContext, stmt: &hir::Stmt, expr: &hir::Expr, map_args: &[hir::Expr]) {
192+
let var_arg = &map_args[0];
193+
let fn_arg = &map_args[1];
194+
195+
let (map_type, variant, lint) =
196+
if match_type(cx, cx.tables.expr_ty(var_arg), &paths::OPTION) {
197+
("Option", "Some", OPTION_MAP_UNIT_FN)
198+
} else if match_type(cx, cx.tables.expr_ty(var_arg), &paths::RESULT) {
199+
("Result", "Ok", RESULT_MAP_UNIT_FN)
200+
} else {
201+
return
202+
};
203+
204+
if is_unit_function(cx, fn_arg) {
205+
let msg = suggestion_msg("function", map_type);
206+
let suggestion = format!("if let {0}({1}) = {2} {{ {3}(...) }}",
207+
variant,
208+
let_binding_name(cx, var_arg),
209+
snippet(cx, var_arg.span, "_"),
210+
snippet(cx, fn_arg.span, "_"));
211+
212+
span_lint_and_then(cx, lint, expr.span, &msg, |db| {
213+
db.span_approximate_suggestion(stmt.span, "try this", suggestion);
214+
});
215+
} else if let Some((binding, closure_expr)) = unit_closure(cx, fn_arg) {
216+
let msg = suggestion_msg("closure", map_type);
217+
218+
span_lint_and_then(cx, lint, expr.span, &msg, |db| {
219+
if let Some(reduced_expr_span) = reduce_unit_expression(cx, closure_expr) {
220+
let suggestion = format!("if let {0}({1}) = {2} {{ {3} }}",
221+
variant,
222+
snippet(cx, binding.pat.span, "_"),
223+
snippet(cx, var_arg.span, "_"),
224+
snippet(cx, reduced_expr_span, "_"));
225+
db.span_suggestion(stmt.span, "try this", suggestion);
226+
} else {
227+
let suggestion = format!("if let {0}({1}) = {2} {{ ... }}",
228+
variant,
229+
snippet(cx, binding.pat.span, "_"),
230+
snippet(cx, var_arg.span, "_"));
231+
db.span_approximate_suggestion(stmt.span, "try this", suggestion);
232+
}
233+
});
234+
}
235+
}
236+
237+
impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Pass {
238+
fn check_stmt(&mut self, cx: &LateContext, stmt: &hir::Stmt) {
239+
if in_macro(stmt.span) {
240+
return;
241+
}
242+
243+
if let hir::StmtSemi(ref expr, _) = stmt.node {
244+
if let hir::ExprMethodCall(_, _, _) = expr.node {
245+
if let Some(arglists) = method_chain_args(expr, &["map"]) {
246+
lint_map_unit_fn(cx, stmt, expr, arglists[0]);
247+
}
248+
}
249+
}
250+
}
251+
}

clippy_lints/src/misc.rs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -432,16 +432,16 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Pass {
432432

433433
fn check_nan(cx: &LateContext, path: &Path, expr: &Expr) {
434434
if !in_constant(cx, expr.id) {
435-
path.segments.last().map(|seg| {
435+
if let Some(seg) = path.segments.last() {
436436
if seg.name == "NAN" {
437437
span_lint(
438438
cx,
439439
CMP_NAN,
440440
expr.span,
441441
"doomed comparison with NAN, use `std::{f32,f64}::is_nan()` instead",
442-
);
442+
);
443443
}
444-
});
444+
}
445445
}
446446
}
447447

tests/ui/eta.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11

22

3-
#![allow(unknown_lints, unused, no_effect, redundant_closure_call, many_single_char_names, needless_pass_by_value)]
3+
#![allow(unknown_lints, unused, no_effect, redundant_closure_call, many_single_char_names, needless_pass_by_value, option_map_unit_fn)]
44
#![warn(redundant_closure, needless_borrow)]
55

66
fn main() {

0 commit comments

Comments
 (0)