1 use crate::utils::paths;
2 use crate::utils::{iter_input_pats, match_type, method_chain_args, snippet, span_lint_and_then};
3 use if_chain::if_chain;
5 use rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
6 use rustc::ty::{self, Ty};
7 use rustc::{declare_lint_pass, declare_tool_lint};
8 use rustc_errors::Applicability;
9 use syntax::source_map::Span;
11 declare_clippy_lint! {
12 /// **What it does:** Checks for usage of `option.map(f)` where f is a function
13 /// or closure that returns the unit type.
15 /// **Why is this bad?** Readability, this can be written more clearly with
16 /// an if let statement
18 /// **Known problems:** None.
23 /// # fn do_stuff() -> Option<String> { Some(String::new()) }
24 /// # fn log_err_msg(foo: String) -> Option<String> { Some(foo) }
25 /// # fn format_msg(foo: String) -> String { String::new() }
26 /// let x: Option<String> = do_stuff();
27 /// x.map(log_err_msg);
28 /// # let x: Option<String> = do_stuff();
29 /// x.map(|msg| log_err_msg(format_msg(msg)));
32 /// The correct use would be:
35 /// # fn do_stuff() -> Option<String> { Some(String::new()) }
36 /// # fn log_err_msg(foo: String) -> Option<String> { Some(foo) }
37 /// # fn format_msg(foo: String) -> String { String::new() }
38 /// let x: Option<String> = do_stuff();
39 /// if let Some(msg) = x {
43 /// # let x: Option<String> = do_stuff();
44 /// if let Some(msg) = x {
45 /// log_err_msg(format_msg(msg));
48 pub OPTION_MAP_UNIT_FN,
50 "using `option.map(f)`, where f is a function or closure that returns ()"
53 declare_clippy_lint! {
54 /// **What it does:** Checks for usage of `result.map(f)` where f is a function
55 /// or closure that returns the unit type.
57 /// **Why is this bad?** Readability, this can be written more clearly with
58 /// an if let statement
60 /// **Known problems:** None.
65 /// # fn do_stuff() -> Result<String, String> { Ok(String::new()) }
66 /// # fn log_err_msg(foo: String) -> Result<String, String> { Ok(foo) }
67 /// # fn format_msg(foo: String) -> String { String::new() }
68 /// let x: Result<String, String> = do_stuff();
69 /// x.map(log_err_msg);
70 /// # let x: Result<String, String> = do_stuff();
71 /// x.map(|msg| log_err_msg(format_msg(msg)));
74 /// The correct use would be:
77 /// # fn do_stuff() -> Result<String, String> { Ok(String::new()) }
78 /// # fn log_err_msg(foo: String) -> Result<String, String> { Ok(foo) }
79 /// # fn format_msg(foo: String) -> String { String::new() }
80 /// let x: Result<String, String> = do_stuff();
81 /// if let Ok(msg) = x {
84 /// # let x: Result<String, String> = do_stuff();
85 /// if let Ok(msg) = x {
86 /// log_err_msg(format_msg(msg));
89 pub RESULT_MAP_UNIT_FN,
91 "using `result.map(f)`, where f is a function or closure that returns ()"
94 declare_lint_pass!(MapUnit => [OPTION_MAP_UNIT_FN, RESULT_MAP_UNIT_FN]);
96 fn is_unit_type(ty: Ty<'_>) -> bool {
98 ty::Tuple(slice) => slice.is_empty(),
104 fn is_unit_function(cx: &LateContext<'_, '_>, expr: &hir::Expr) -> bool {
105 let ty = cx.tables.expr_ty(expr);
107 if let ty::FnDef(id, _) = ty.kind {
108 if let Some(fn_type) = cx.tcx.fn_sig(id).no_bound_vars() {
109 return is_unit_type(fn_type.output());
115 fn is_unit_expression(cx: &LateContext<'_, '_>, expr: &hir::Expr) -> bool {
116 is_unit_type(cx.tables.expr_ty(expr))
119 /// The expression inside a closure may or may not have surrounding braces and
120 /// semicolons, which causes problems when generating a suggestion. Given an
121 /// expression that evaluates to '()' or '!', recursively remove useless braces
122 /// and semi-colons until is suitable for including in the suggestion template
123 fn reduce_unit_expression<'a>(cx: &LateContext<'_, '_>, expr: &'a hir::Expr) -> Option<Span> {
124 if !is_unit_expression(cx, expr) {
129 hir::ExprKind::Call(_, _) | hir::ExprKind::MethodCall(_, _, _) => {
130 // Calls can't be reduced any more
133 hir::ExprKind::Block(ref block, _) => {
134 match (&block.stmts[..], block.expr.as_ref()) {
135 (&[], Some(inner_expr)) => {
136 // If block only contains an expression,
137 // reduce `{ X }` to `X`
138 reduce_unit_expression(cx, inner_expr)
140 (&[ref inner_stmt], None) => {
141 // If block only contains statements,
142 // reduce `{ X; }` to `X` or `X;`
143 match inner_stmt.kind {
144 hir::StmtKind::Local(ref local) => Some(local.span),
145 hir::StmtKind::Expr(ref e) => Some(e.span),
146 hir::StmtKind::Semi(..) => Some(inner_stmt.span),
147 hir::StmtKind::Item(..) => None,
151 // For closures that contain multiple statements
152 // it's difficult to get a correct suggestion span
153 // for all cases (multi-line closures specifically)
155 // We do not attempt to build a suggestion for those right now.
164 fn unit_closure<'a, 'tcx>(
165 cx: &LateContext<'a, 'tcx>,
167 ) -> Option<(&'tcx hir::Param, &'a hir::Expr)> {
168 if let hir::ExprKind::Closure(_, ref decl, inner_expr_id, _, _) = expr.kind {
169 let body = cx.tcx.hir().body(inner_expr_id);
170 let body_expr = &body.value;
173 if decl.inputs.len() == 1;
174 if is_unit_expression(cx, body_expr);
175 if let Some(binding) = iter_input_pats(&decl, body).next();
177 return Some((binding, body_expr));
184 /// Builds a name for the let binding variable (`var_arg`)
186 /// `x.field` => `x_field`
189 /// Anything else will return `_`.
190 fn let_binding_name(cx: &LateContext<'_, '_>, var_arg: &hir::Expr) -> String {
191 match &var_arg.kind {
192 hir::ExprKind::Field(_, _) => snippet(cx, var_arg.span, "_").replace(".", "_"),
193 hir::ExprKind::Path(_) => format!("_{}", snippet(cx, var_arg.span, "")),
194 _ => "_".to_string(),
199 fn suggestion_msg(function_type: &str, map_type: &str) -> String {
201 "called `map(f)` on an {0} value where `f` is a unit {1}",
202 map_type, function_type
206 fn lint_map_unit_fn(cx: &LateContext<'_, '_>, stmt: &hir::Stmt, expr: &hir::Expr, map_args: &[hir::Expr]) {
207 let var_arg = &map_args[0];
209 let (map_type, variant, lint) = if match_type(cx, cx.tables.expr_ty(var_arg), &paths::OPTION) {
210 ("Option", "Some", OPTION_MAP_UNIT_FN)
211 } else if match_type(cx, cx.tables.expr_ty(var_arg), &paths::RESULT) {
212 ("Result", "Ok", RESULT_MAP_UNIT_FN)
216 let fn_arg = &map_args[1];
218 if is_unit_function(cx, fn_arg) {
219 let msg = suggestion_msg("function", map_type);
220 let suggestion = format!(
221 "if let {0}({binding}) = {1} {{ {2}({binding}) }}",
223 snippet(cx, var_arg.span, "_"),
224 snippet(cx, fn_arg.span, "_"),
225 binding = let_binding_name(cx, var_arg)
228 span_lint_and_then(cx, lint, expr.span, &msg, |db| {
229 db.span_suggestion(stmt.span, "try this", suggestion, Applicability::MachineApplicable);
231 } else if let Some((binding, closure_expr)) = unit_closure(cx, fn_arg) {
232 let msg = suggestion_msg("closure", map_type);
234 span_lint_and_then(cx, lint, expr.span, &msg, |db| {
235 if let Some(reduced_expr_span) = reduce_unit_expression(cx, closure_expr) {
236 let suggestion = format!(
237 "if let {0}({1}) = {2} {{ {3} }}",
239 snippet(cx, binding.pat.span, "_"),
240 snippet(cx, var_arg.span, "_"),
241 snippet(cx, reduced_expr_span, "_")
247 Applicability::MachineApplicable, // snippet
250 let suggestion = format!(
251 "if let {0}({1}) = {2} {{ ... }}",
253 snippet(cx, binding.pat.span, "_"),
254 snippet(cx, var_arg.span, "_"),
256 db.span_suggestion(stmt.span, "try this", suggestion, Applicability::HasPlaceholders);
262 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for MapUnit {
263 fn check_stmt(&mut self, cx: &LateContext<'_, '_>, stmt: &hir::Stmt) {
264 if stmt.span.from_expansion() {
268 if let hir::StmtKind::Semi(ref expr) = stmt.kind {
269 if let Some(arglists) = method_chain_args(expr, &["map"]) {
270 lint_map_unit_fn(cx, stmt, expr, arglists[0]);