2 match_trait_method, path_to_local_id, paths, remove_blocks, snippet_with_applicability, span_lint_and_sugg,
5 use if_chain::if_chain;
7 use rustc_errors::Applicability;
9 use rustc_hir::PatKind;
10 use rustc_lint::LateContext;
11 use rustc_span::source_map::Span;
13 use super::UNNECESSARY_FOLD;
15 pub(super) fn check(cx: &LateContext<'_>, expr: &hir::Expr<'_>, fold_args: &[hir::Expr<'_>], fold_span: Span) {
16 fn check_fold_with_op(
19 fold_args: &[hir::Expr<'_>],
22 replacement_method_name: &str,
23 replacement_has_args: bool,
26 // Extract the body of the closure passed to fold
27 if let hir::ExprKind::Closure(_, _, body_id, _, _) = fold_args[2].kind;
28 let closure_body = cx.tcx.hir().body(body_id);
29 let closure_expr = remove_blocks(&closure_body.value);
31 // Check if the closure body is of the form `acc <op> some_expr(x)`
32 if let hir::ExprKind::Binary(ref bin_op, ref left_expr, ref right_expr) = closure_expr.kind;
35 // Extract the names of the two arguments to the closure
36 if let [param_a, param_b] = closure_body.params;
37 if let PatKind::Binding(_, first_arg_id, ..) = strip_pat_refs(¶m_a.pat).kind;
38 if let PatKind::Binding(_, second_arg_id, second_arg_ident, _) = strip_pat_refs(¶m_b.pat).kind;
40 if path_to_local_id(left_expr, first_arg_id);
41 if replacement_has_args || path_to_local_id(right_expr, second_arg_id);
44 let mut applicability = Applicability::MachineApplicable;
45 let sugg = if replacement_has_args {
47 "{replacement}(|{s}| {r})",
48 replacement = replacement_method_name,
50 r = snippet_with_applicability(cx, right_expr.span, "EXPR", &mut applicability),
55 replacement = replacement_method_name,
62 fold_span.with_hi(expr.span.hi()),
63 // TODO #2371 don't suggest e.g., .any(|x| f(x)) if we can suggest .any(f)
64 "this `.fold` can be written more succinctly using another method",
73 // Check that this is a call to Iterator::fold rather than just some function called fold
74 if !match_trait_method(cx, expr, &paths::ITERATOR) {
80 "Expected fold_args to have three entries - the receiver, the initial value and the closure"
83 // Check if the first argument to .fold is a suitable literal
84 if let hir::ExprKind::Lit(ref lit) = fold_args[1].kind {
86 ast::LitKind::Bool(false) => {
87 check_fold_with_op(cx, expr, fold_args, fold_span, hir::BinOpKind::Or, "any", true)
89 ast::LitKind::Bool(true) => {
90 check_fold_with_op(cx, expr, fold_args, fold_span, hir::BinOpKind::And, "all", true)
92 ast::LitKind::Int(0, _) => {
93 check_fold_with_op(cx, expr, fold_args, fold_span, hir::BinOpKind::Add, "sum", false)
95 ast::LitKind::Int(1, _) => {
96 check_fold_with_op(cx, expr, fold_args, fold_span, hir::BinOpKind::Mul, "product", false)