A loop steps its counter away from the bound of its condition
What it finds
for (let i = 0; i < n; i--): a loop whose update moves the counter away from the bound of its condition runs forever, 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 update must be ++, --, or += or -= with a positive number, and the initializer must declare or assign the counter. Nothing in the loop may assign the counter, which must be a variable the file declares.
From the rule's source, wrong_loop_direction.rs.
function f(items: number[], n: number) { for (let i = items.length - 1; i >= 0; i++) {tx0 reports: i++ counts up, but i >= 0 expects i to count down items[i] = 0; } for (let i = 0; i < n; i--) {tx0 reports: i-- counts down, but i < n expects i to count up } for (let i = 10; 0 < i; i += 2) {tx0 reports: i += 2 counts up, but 0 < i expects i to count down } for (let i = 0; n > i; --i) {tx0 reports: --i counts down } let k; for (k = 0; k < n; k -= 1) {tx0 reports: k -= 1 counts down } for (let i = items.length - 1; i >= 0; i--) { } for (let i = 0; i < n; i++) { } for (let i = 0; i < n; i--) { i += 2; } for (let i = 0; i < n; i--) { for (i = 0; i < 1; i++) { } } for (let i = 0; i < items.length; i += n) { } for (let i = 0; i < n; i -= -1) { } for (let i = 0; i < i + n; i--) { } for (let i = 0; i < n && items[i] > 0; i--) { } for (let j = 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/ts: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/ts:wrong-loop-direction] reason="..."tx0 explain tx0/ts:wrong-loop-direction shows the same in the terminal. Found a false positive? Report it.