A loop steps its counter away from the bound of its condition
What it finds
for i := n; i >= 0; i++: a loop whose post statement moves the counter away from the bound of its condition runs until the counter overflows, or not at all. Usually the comparison or the step was copied from a loop that went the other way.
The condition must compare the counter itself with a bound that does not mention it, the step must be ++, -- or a positive literal, and the body must not change the counter. The init statement must declare the counter as an int: with an unsigned counter, running until it wraps around, as in for i := uint(1); i > 0; i++, can be meant, and so can counting down past zero in for i := n - 1; i < n; i--.
From the rule's source, wrong_loop_direction.rs.
package p func f(s []int, n int) { for i := len(s) - 1; i >= 0; i++ {tx0 reports: i++ counts up, but i >= 0 expects i to count down s[i] = 0 } for i := 0; i < n; i-- {tx0 reports: i-- counts down, but i < n expects i to count up } for i := 10; 0 < i; i += 2 {tx0 reports: i += 2 counts up, but 0 < i expects i to count down } for i := 0; n > i; i -= 1 {tx0 reports: i -= 1 counts down } for i := len(s) - 1; i >= 0; i-- { } for i := 0; i < n; i++ { } for i := uint(1); i > 0; i++ { } for i := n - 1; i < n; i-- { } for i := 0; i < n; i-- { i += 2 } for i := 0; i < len(s); i += n { } for i := 0; i < i+n; i-- { } for i := 0; i < n && s[i] > 0; i-- { } var k int for k = 0; k < n; k-- { }} Turn it on, off or suppress it
The rule runs in every tier. To turn it off for a project, set its level in tx0.toml:
[rules]
"tx0/go:wrong-loop-direction" = "off"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/go:wrong-loop-direction] reason="..."tx0 explain tx0/go:wrong-loop-direction shows the same in the terminal. Found a false positive? Report it.