1 use crate::utils::{is_adjusted, is_trait_method, match_path, match_var, paths, remove_blocks};
2 use clippy_utils::diagnostics::span_lint_and_sugg;
3 use clippy_utils::ty::is_type_diagnostic_item;
4 use if_chain::if_chain;
5 use rustc_errors::Applicability;
6 use rustc_hir::{Body, Expr, ExprKind, Pat, PatKind, QPath, StmtKind};
7 use rustc_lint::{LateContext, LateLintPass};
8 use rustc_session::{declare_lint_pass, declare_tool_lint};
11 declare_clippy_lint! {
12 /// **What it does:** Checks for instances of `map(f)` where `f` is the identity function.
14 /// **Why is this bad?** It can be written more concisely without the call to `map`.
16 /// **Known problems:** None.
21 /// let x = [1, 2, 3];
22 /// let y: Vec<_> = x.iter().map(|x| x).map(|x| 2*x).collect();
26 /// let x = [1, 2, 3];
27 /// let y: Vec<_> = x.iter().map(|x| 2*x).collect();
31 "using iterator.map(|x| x)"
34 declare_lint_pass!(MapIdentity => [MAP_IDENTITY]);
36 impl<'tcx> LateLintPass<'tcx> for MapIdentity {
37 fn check_expr(&mut self, cx: &LateContext<'_>, expr: &Expr<'_>) {
38 if expr.span.from_expansion() {
43 if let Some([caller, func]) = get_map_argument(cx, expr);
44 if is_expr_identity_function(cx, func);
49 expr.span.trim_start(caller.span).unwrap(),
50 "unnecessary map of the identity function",
51 "remove the call to `map`",
53 Applicability::MachineApplicable
60 /// Returns the arguments passed into map() if the expression is a method call to
61 /// map(). Otherwise, returns None.
62 fn get_map_argument<'a>(cx: &LateContext<'_>, expr: &'a Expr<'a>) -> Option<&'a [Expr<'a>]> {
64 if let ExprKind::MethodCall(ref method, _, ref args, _) = expr.kind;
65 if args.len() == 2 && method.ident.name == sym::map;
66 let caller_ty = cx.typeck_results().expr_ty(&args[0]);
67 if is_trait_method(cx, expr, sym::Iterator)
68 || is_type_diagnostic_item(cx, caller_ty, sym::result_type)
69 || is_type_diagnostic_item(cx, caller_ty, sym::option_type);
78 /// Checks if an expression represents the identity function
79 /// Only examines closures and `std::convert::identity`
80 fn is_expr_identity_function(cx: &LateContext<'_>, expr: &Expr<'_>) -> bool {
82 ExprKind::Closure(_, _, body_id, _, _) => is_body_identity_function(cx, cx.tcx.hir().body(body_id)),
83 ExprKind::Path(QPath::Resolved(_, ref path)) => match_path(path, &paths::STD_CONVERT_IDENTITY),
88 /// Checks if a function's body represents the identity function
89 /// Looks for bodies of the form `|x| x`, `|x| return x`, `|x| { return x }` or `|x| {
91 fn is_body_identity_function(cx: &LateContext<'_>, func: &Body<'_>) -> bool {
92 let params = func.params;
93 let body = remove_blocks(&func.value);
95 // if there's less/more than one parameter, then it is not the identity function
96 if params.len() != 1 {
101 ExprKind::Path(QPath::Resolved(None, _)) => match_expr_param(cx, body, params[0].pat),
102 ExprKind::Ret(Some(ref ret_val)) => match_expr_param(cx, ret_val, params[0].pat),
103 ExprKind::Block(ref block, _) => {
105 if block.stmts.len() == 1;
106 if let StmtKind::Semi(ref expr) | StmtKind::Expr(ref expr) = block.stmts[0].kind;
107 if let ExprKind::Ret(Some(ref ret_val)) = expr.kind;
109 match_expr_param(cx, ret_val, params[0].pat)
119 /// Returns true iff an expression returns the same thing as a parameter's pattern
120 fn match_expr_param(cx: &LateContext<'_>, expr: &Expr<'_>, pat: &Pat<'_>) -> bool {
121 if let PatKind::Binding(_, _, ident, _) = pat.kind {
122 match_var(expr, ident.name) && !(cx.typeck_results().hir_owner == expr.hir_id.owner && is_adjusted(cx, expr))