rust-lang / rust-lang/rust-clippy

Confusing`try_fold` suggestion from Clippy

Open
#11,554 2 comments 2 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

C-bug I-false-positive
Dominant language
Rust
Stars
13.5k
Forks
2.2k
Avg merge
2d 10h
Merged PRs (30d)
32

Description

Description

In our code, we used fold to collect a vector of custom errors and covert them into a Report, but clippy suggested us to use try_fold instead: https://rust-lang.github.io/rust-clippy/master/index.html#/manual_try_fold. We followed it but it created a new issue because of the way we used fold (i.e., we used it to collect error).

    |
217 |               .fold(Err(eyre!("Error parsing specs")), |report, e| {
    |  ______________^
218 | |                 report.error(e)
219 | |             });
    | |______________^
    |
    = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#manual_try_fold
help: use `try_fold` instead
    |
217 ~             .try_fold({
218 +         let error = $crate::private::format_err($crate::private::format_args!($msg));
219 +         error
220 ~     }, |report, e| ...);

Note: our function returns this Result<(), Report>

The main confusing point is that try_fold itself will short-circuits on failure, but our initial value to fold originally is an Err. When Clippy suggested us to use try_fold, it could not detect this special use case.

Version
  • Rust 1.72.0
  • clippy 0.1.72 (5680fa18 2023-08-23)
Additional Labels

No response

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start with the manual_try_fold lint implementation and its existing tests, then reproduce the reported fold over an initial Err value using the example in the issue. The issue is resolved when Clippy no longer suggests an inappropriate try_fold transformation for this error-collecting pattern and the behavior is covered by a regression test.

Written by the indexing model from the issue text.

Assessment

Tech stack
rust
Domain
tooling
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.