A loop body always ends in break, return or throw, so it runs at most once

tx0/java:single-pass-looprecommendedwarningbug

What it finds

A loop whose body always ends in break, return or throw, with no continue, runs its body at most once: it is an if written as a loop. Either the jump was meant to be conditional, which is a bug, or the loop only takes the first element, which an if or iterator().next() says more plainly.

From the rule's source, single_pass_loop.rs.

Example from the rule's tests
import java.util.List; class Finder {  String first(List<String> names) {    for (String name : names) {      return name;tx0 reports: this loop runs at most once    }    while (names.isEmpty()) {      names.add("x");      break;tx0 reports: this loop runs at most once    }    for (String name : names) {      if (name.isEmpty()) {        continue;      }      return name;    }    for (String name : names) {      if (name.isEmpty()) {        return name;      }    }    return null;  }}
Highlighted lines are the ones tx0 reports, with its message under each; the other lines are left alone.

Turn it on, off or suppress it

The rule runs from the recommended tier up. To turn it on in a lower tier, give it a level in tx0.toml:

tx0.toml
[rules]
"tx0/java:single-pass-loop" = "warning"

To keep one finding, suppress it with a reason. tx0 suppress ID --reason "..." writes the comment on the line before the code:

// tx0: ignore[tx0/java:single-pass-loop] reason="..."

tx0 explain tx0/java:single-pass-loop shows the same in the terminal. Found a false positive? Report it.