rust-clippy icon indicating copy to clipboard operation
rust-clippy copied to clipboard

unnecessary_fold: suggest bool bitwise ops

Open vilgotf opened this issue 2 months ago • 9 comments

Summary

The unnecessary_fold lint suggests using any over, e.g., fold(false, |acc, x| acc || x) because the former short-circuits. But whether or not short-circuiting is wanted depends, for example, iterators or fold closures may have side-effects. The previous example is therefore ambiguous because it uses the short-circuiting || op. It ought explicitly either short-circuit via any or use the non-short-circuiting | op.

Alternative solution to the #3351 issue

Reproducer

Code:

/// Broadcasts all previously recorded events to their respective listeners.
///
/// Returns `true` if an event was delivered to at least one listener.
fn broadcast(&self) -> bool {
    self.storage
        .iter()
        // Any signal of this kind arrived since we checked last?
        .filter(|event_info| event_info.pending.swap(false, Ordering::SeqCst))
        // Ignore errors if there are no listeners
        .map(|event_info| event_info.tx.send(()).is_ok())
        .fold(false, |acc, x| acc || x)
}

Current output:

warning: this `.fold` can be written more succinctly using another method
  --> tokio/src/signal/registry.rs:91:14
   |
91 |             .fold(false, |acc, x| acc || x)
   |              ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `any(|x| x)`
   |
   = note: the `any` method is short circuiting and may change the program semantics if the iterator has side effects
   = help: for further information visit https://rust-lang.github.io/rust-clippy/main/index.html#unnecessary_fold
   = note: `#[warn(clippy::unnecessary_fold)]` on by default

Desired output:

Suggest .fold(false, |acc, x| acc | x) as the explicit non-short-circuiting method.

Version

rustc 1.100.0-nightly (5ceaf6608 2026-09-25)
binary: rustc
commit-hash: 5ceaf6608eb354c2f5bbb3b8d974caa367dac81c
commit-date: 2026-09-25
host: aarch64-apple-darwin
release: 1.100.0-nightly
LLVM version: 23.1.1

Additional Labels

No response

vilgotf avatar Sep 26 '26 12:09 vilgotf

🤔 Why should bitwise be suggested here over logical or the current suggestion?

CommanderStorm avatar Sep 26 '26 16:09 CommanderStorm

Sorry, I was a bit unclear. The example posted above should not use early return. The any suggestion is therefore "wrong". My suggestion is to extend the lint to suggest either any (early return) or bitwise OR (not early return). The other "solution" is to annotate the code with #[allow(clip::unnecessary_fold)], but this is clearly worse!

vilgotf avatar Sep 26 '26 16:09 vilgotf

I still feel like the issue is missing an "Why?" 😉

In the example you gave both are interchangable to me and thus the suggestion seems good, or? It is not like the || can result in false after acc=true.. That does not have side-effects either.

bool_iterator
  .fold(false, |acc, x| acc || x)

can be simplified to this unless I am missing smething fundamental

bool_iterator
  .any(|x| x)

Bit wise ops could be argued that MAYBE you profiled and noticed that the branching of logical or is faster for your case, so not linting there seems good, or?

CommanderStorm avatar Sep 26 '26 17:09 CommanderStorm

The difference comes down to whether the iterator has side-effects (e.g. send()).

vilgotf avatar Sep 26 '26 21:09 vilgotf

What if both the iterator and the RHS have side effects? Or the iterator has side effects and the RHS is expensive? There can definitely be legitimate cases where neither of the suggestions are the desired behavior. In fact the only case where the bitwise fold is semantically preferable seems to be when you specifically want the side effects of the RHS, but there is no reason for the lint to assume this is the case. At best, I see the bitwise version to be a briefer-but-specific-to-this-lint version of #[allow(...)] when the RHS is trivial.

ronnodas avatar Sep 27 '26 02:09 ronnodas

Or the iterator has side effects and the RHS is expensive?

Both side-effects and resource-expensive iterators may want to short-circuit. I also expanded OP to answer your comment(s).

vilgotf avatar Sep 27 '26 06:09 vilgotf

Ah makes much more sense, so not side effects in the fold, but the iterator.

To be fair: I mean .any sounds like the thing this functions docs are promising as a contract (which is why I was so confused)...

/// Returns `true` if an event was delivered to at least one listener.
fn broadcast(&self) -> bool

How about this change in diagnostic:

  warning: this `.fold` can be written more succinctly using another method
    --> tokio/src/signal/registry.rs:91:14
     |
  91 |             .fold(false, |acc, x| acc || x)
     |              ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `any(|x| x)`
     |
    = note: the `any` method is short circuiting and may change the program semantics if the iterator has side effects
+   = help: if the side effect is wanted, use `.fold(false, |acc, x| acc | x)` instead
    = help: for further information visit https://rust-lang.github.io/rust-clippy/main/index.html#unnecessary_fold
    = note: `#[warn(clippy::unnecessary_fold)]` on by default

Maybe degrading from MachineApplicable to MaybeIncorrect too.

CommanderStorm avatar Sep 27 '26 07:09 CommanderStorm

That looks good 👍

vilgotf avatar Sep 27 '26 07:09 vilgotf

@rustbot claim

jny0444 avatar Oct 25 '26 17:10 jny0444