← All lints

compound_self_ref

L0210Stylewarn

Assignment of a place in terms of itself

x = x + e or cnt[v] = cnt[v] % m is the compound assignment x += e

Flagged
var total = 0
var cnt = [0, 0, 0]
for v in 0..3:
    total = total + v
    cnt[v] = cnt[v] + 2
print(total, cnt[1])
Write instead
var total = 0
var cnt = [0, 0, 0]
for v in 0..3:
    total += v
    cnt[v] += 2
print(total, cnt[1])

Why

An assignment whose right side applies an operator to the place it writes, x = x + e or cnt[v] = cnt[v] % m, is the compound assignment x += e: the place is written once and cannot drift from the copy on the right. cpl fix rewrites it when neither side calls anything, so evaluating the place once instead of twice changes nothing.

The practice it serves

Spelling that hides what the code means.

Not flagged

A near miss: close to the pattern, but not it.

Near miss
var acc = 0
var best = 0
for d in [3, 1, 4]:
    acc = acc * 10 + d
    best = d - best
print(acc, best)
var low: ?Int = Some(2)
for d in [3, 1, 4]:
    low = low + d
print(low ?? 0)
var g = [[Some(1), Some(2)], [None, Some(4)]]
g[0][1] = g[0][1] + 5
print(g[0][1] ?? 0)

Turn it off

For one block, wrap it in with lint(compound_self_ref: allow):. For a project, add compound_self_ref = "allow" under [lints] in cp.toml.

Generated from spec/lints/compound_self_ref, the same record the linter is built from.