Skip to content

Commit

Permalink
Auto merge of rust-lang#11879 - samueltardieu:issue-11876, r=Alexendoo
Browse files Browse the repository at this point in the history
`manual_try_fold`: check that `fold` is really `Iterator::fold`

Fix rust-lang#11876

changelog: [`manual_try_fold`]: suggest using `try_fold` only for `Iterator::fold` uses
  • Loading branch information
bors committed Nov 27, 2023
2 parents 5ba6480 + 0d09cb0 commit caa7394
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 2 deletions.
5 changes: 3 additions & 2 deletions clippy_lints/src/methods/manual_try_fold.rs
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
use clippy_config::msrvs::{self, Msrv};
use clippy_utils::diagnostics::span_lint_and_sugg;
use clippy_utils::is_from_proc_macro;
use clippy_utils::source::snippet_opt;
use clippy_utils::ty::implements_trait;
use clippy_utils::{is_from_proc_macro, is_trait_method};
use rustc_errors::Applicability;
use rustc_hir::def::{DefKind, Res};
use rustc_hir::{Expr, ExprKind};
use rustc_lint::{LateContext, LintContext};
use rustc_middle::lint::in_external_macro;
use rustc_span::Span;
use rustc_span::{sym, Span};

use super::MANUAL_TRY_FOLD;

Expand All @@ -22,6 +22,7 @@ pub(super) fn check<'tcx>(
) {
if !in_external_macro(cx.sess(), fold_span)
&& msrv.meets(msrvs::ITERATOR_TRY_FOLD)
&& is_trait_method(cx, expr, sym::Iterator)
&& let init_ty = cx.typeck_results().expr_ty(init)
&& let Some(try_trait) = cx.tcx.lang_items().try_trait()
&& implements_trait(cx, init_ty, try_trait, &[])
Expand Down
30 changes: 30 additions & 0 deletions tests/ui/manual_try_fold.rs
Original file line number Diff line number Diff line change
Expand Up @@ -96,3 +96,33 @@ fn msrv_juust_right() {
.fold(Some(0i32), |sum, i| sum?.checked_add(*i))
.unwrap();
}

mod issue11876 {
struct Foo;

impl Bar for Foo {
type Output = u32;
}

trait Bar: Sized {
type Output;
fn fold<A, F>(self, init: A, func: F) -> Fold<Self, A, F>
where
A: Clone,
F: Fn(A, Self::Output) -> A,
{
Fold { this: self, init, func }
}
}

#[allow(dead_code)]
struct Fold<S, A, F> {
this: S,
init: A,
func: F,
}

fn main() {
Foo.fold(Some(0), |acc, entry| Some(acc? + entry));
}
}

0 comments on commit caa7394

Please sign in to comment.