1 use crate::utils::paths;
2 use crate::utils::{in_macro, 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};
7 use rustc::{declare_tool_lint, lint_array};
8 use rustc_errors::Applicability;
9 use syntax::source_map::Span;
14 /// **What it does:** Checks for usage of `option.map(f)` where f is a function
15 /// or closure that returns the unit type.
17 /// **Why is this bad?** Readability, this can be written more clearly with
18 /// an if let statement
20 /// **Known problems:** None.
25 /// let x: Option<&str> = do_stuff();
26 /// x.map(log_err_msg);
27 /// x.map(|msg| log_err_msg(format_msg(msg)))
30 /// The correct use would be:
33 /// let x: Option<&str> = do_stuff();
34 /// if let Some(msg) = x {
37 /// if let Some(msg) = x {
38 /// log_err_msg(format_msg(msg))
41 declare_clippy_lint! {
42 pub OPTION_MAP_UNIT_FN,
44 "using `option.map(f)`, where f is a function or closure that returns ()"
47 /// **What it does:** Checks for usage of `result.map(f)` where f is a function
48 /// or closure that returns the unit type.
50 /// **Why is this bad?** Readability, this can be written more clearly with
51 /// an if let statement
53 /// **Known problems:** None.
58 /// let x: Result<&str, &str> = do_stuff();
59 /// x.map(log_err_msg);
60 /// x.map(|msg| log_err_msg(format_msg(msg)))
63 /// The correct use would be:
66 /// let x: Result<&str, &str> = do_stuff();
67 /// if let Ok(msg) = x {
70 /// if let Ok(msg) = x {
71 /// log_err_msg(format_msg(msg))
74 declare_clippy_lint! {
75 pub RESULT_MAP_UNIT_FN,
77 "using `result.map(f)`, where f is a function or closure that returns ()"
80 impl LintPass for Pass {
81 fn get_lints(&self) -> LintArray {
82 lint_array!(OPTION_MAP_UNIT_FN, RESULT_MAP_UNIT_FN)
85 fn name(&self) -> &'static str {
90 fn is_unit_type(ty: ty::Ty<'_>) -> bool {
92 ty::Tuple(slice) => slice.is_empty(),
98 fn is_unit_function(cx: &LateContext<'_, '_>, expr: &hir::Expr) -> bool {
99 let ty = cx.tables.expr_ty(expr);
101 if let ty::FnDef(id, _) = ty.sty {
102 if let Some(fn_type) = cx.tcx.fn_sig(id).no_bound_vars() {
103 return is_unit_type(fn_type.output());
109 fn is_unit_expression(cx: &LateContext<'_, '_>, expr: &hir::Expr) -> bool {
110 is_unit_type(cx.tables.expr_ty(expr))
113 /// The expression inside a closure may or may not have surrounding braces and
114 /// semicolons, which causes problems when generating a suggestion. Given an
115 /// expression that evaluates to '()' or '!', recursively remove useless braces
116 /// and semi-colons until is suitable for including in the suggestion template
117 fn reduce_unit_expression<'a>(cx: &LateContext<'_, '_>, expr: &'a hir::Expr) -> Option<Span> {
118 if !is_unit_expression(cx, expr) {
123 hir::ExprKind::Call(_, _) | hir::ExprKind::MethodCall(_, _, _) => {
124 // Calls can't be reduced any more
127 hir::ExprKind::Block(ref block, _) => {
128 match (&block.stmts[..], block.expr.as_ref()) {
129 (&[], Some(inner_expr)) => {
130 // If block only contains an expression,
131 // reduce `{ X }` to `X`
132 reduce_unit_expression(cx, inner_expr)
134 (&[ref inner_stmt], None) => {
135 // If block only contains statements,
136 // reduce `{ X; }` to `X` or `X;`
137 match inner_stmt.node {
138 hir::StmtKind::Local(ref local) => Some(local.span),
139 hir::StmtKind::Expr(ref e) => Some(e.span),
140 hir::StmtKind::Semi(..) => Some(inner_stmt.span),
141 hir::StmtKind::Item(..) => None,
145 // For closures that contain multiple statements
146 // it's difficult to get a correct suggestion span
147 // for all cases (multi-line closures specifically)
149 // We do not attempt to build a suggestion for those right now.
158 fn unit_closure<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, expr: &'a hir::Expr) -> Option<(&'tcx hir::Arg, &'a hir::Expr)> {
159 if let hir::ExprKind::Closure(_, ref decl, inner_expr_id, _, _) = expr.node {
160 let body = cx.tcx.hir().body(inner_expr_id);
161 let body_expr = &body.value;
164 if decl.inputs.len() == 1;
165 if is_unit_expression(cx, body_expr);
166 if let Some(binding) = iter_input_pats(&decl, body).next();
168 return Some((binding, body_expr));
175 /// Builds a name for the let binding variable (`var_arg`)
177 /// `x.field` => `x_field`
180 /// Anything else will return `_`.
181 fn let_binding_name(cx: &LateContext<'_, '_>, var_arg: &hir::Expr) -> String {
182 match &var_arg.node {
183 hir::ExprKind::Field(_, _) => snippet(cx, var_arg.span, "_").replace(".", "_"),
184 hir::ExprKind::Path(_) => format!("_{}", snippet(cx, var_arg.span, "")),
185 _ => "_".to_string(),
189 fn suggestion_msg(function_type: &str, map_type: &str) -> String {
191 "called `map(f)` on an {0} value where `f` is a unit {1}",
192 map_type, function_type
196 fn lint_map_unit_fn(cx: &LateContext<'_, '_>, stmt: &hir::Stmt, expr: &hir::Expr, map_args: &[hir::Expr]) {
197 let var_arg = &map_args[0];
199 let (map_type, variant, lint) = if match_type(cx, cx.tables.expr_ty(var_arg), &paths::OPTION) {
200 ("Option", "Some", OPTION_MAP_UNIT_FN)
201 } else if match_type(cx, cx.tables.expr_ty(var_arg), &paths::RESULT) {
202 ("Result", "Ok", RESULT_MAP_UNIT_FN)
206 let fn_arg = &map_args[1];
208 if is_unit_function(cx, fn_arg) {
209 let msg = suggestion_msg("function", map_type);
210 let suggestion = format!(
211 "if let {0}({1}) = {2} {{ {3}(...) }}",
213 let_binding_name(cx, var_arg),
214 snippet(cx, var_arg.span, "_"),
215 snippet(cx, fn_arg.span, "_")
218 span_lint_and_then(cx, lint, expr.span, &msg, |db| {
219 db.span_suggestion(stmt.span, "try this", suggestion, Applicability::Unspecified);
221 } else if let Some((binding, closure_expr)) = unit_closure(cx, fn_arg) {
222 let msg = suggestion_msg("closure", map_type);
224 span_lint_and_then(cx, lint, expr.span, &msg, |db| {
225 if let Some(reduced_expr_span) = reduce_unit_expression(cx, closure_expr) {
226 let suggestion = format!(
227 "if let {0}({1}) = {2} {{ {3} }}",
229 snippet(cx, binding.pat.span, "_"),
230 snippet(cx, var_arg.span, "_"),
231 snippet(cx, reduced_expr_span, "_")
237 Applicability::MachineApplicable, // snippet
240 let suggestion = format!(
241 "if let {0}({1}) = {2} {{ ... }}",
243 snippet(cx, binding.pat.span, "_"),
244 snippet(cx, var_arg.span, "_")
246 db.span_suggestion(stmt.span, "try this", suggestion, Applicability::Unspecified);
252 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Pass {
253 fn check_stmt(&mut self, cx: &LateContext<'_, '_>, stmt: &hir::Stmt) {
254 if in_macro(stmt.span) {
258 if let hir::StmtKind::Semi(ref expr) = stmt.node {
259 if let Some(arglists) = method_chain_args(expr, &["map"]) {
260 lint_map_unit_fn(cx, stmt, expr, arglists[0]);