← All lints

coalesce_test_then_unwrap

L0595Idiomswarn

Stand-in test, then unwrap

while (e ?? c) > y: then let w = e!: while let w = e, w > y:

Flagged
let prices = [7, 2, 4]
var cur: ?Int = Some(20)
var spent = 0
while (cur ?? 0) > 2:
    let c = cur!
    spent += c
    cur = if c > 3: Some(c / 2) else: None
print(spent)
let best = prices.find(x => x > 5)
if (best ?? 0) > 4:
    let b = best!
    print(b * 2)
Write instead
let prices = [7, 2, 4]
var cur: ?Int = Some(20)
var spent = 0
while let c = cur, c > 2:
    spent += c
    cur = if c > 3: Some(c / 2) else: None
print(spent)
let best = prices.find(x => x > 5)
if let b = best, b > 4:
    print(b * 2)

Why

A C++ habit is to give an empty container a stand-in value so one comparison covers both cases: while (!s.empty() && s.back() > cap). Written in CP Lang as while (s.last ?? 0) > cap: followed by let w = s.last!, the code says the same fact twice. The ?? 0 invents a value for "empty", and the ! then asserts it was not empty after all. The stand-in also has to fail the comparison: a cap below 0 would make 0 > cap true, and the ! would trap. while let w = s.last, w > cap: binds the value once and compares the real value. When s.last is None the loop simply stops, so there is no stand-in to choose and no ! to keep in step with the test. The same rewrite applies to if and elif: if let b = best, b > 4:. The lint fires when the condition is (e ?? c) op y, e is a name, field or index path with no call, and the branch's first statement is let w = e! on its own line. The fix rewrites the condition and deletes the let. It changes behaviour only where the original trapped: an empty e whose stand-in passed the test now skips the branch instead of failing the !.

The practice it serves

A hand-written pattern the language or the standard library already says in one step.

Not flagged

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

Near miss
let prices = [7, 2, 4]
let best = prices.find(x => x > 5)
let other = prices.find(x => x < 3)
// The unwrap names a different value: nothing is said twice.
if (best ?? 0) > 4:
    let b = other!
    print(b)
// The unwrap is not the first thing the branch does.
if (best ?? 0) > 4:
    print(0)
    let b = best!
    print(b)
// No unwrap: the stand-in is the answer for an empty list.
if (best ?? 0) > 4:
    print(1)
print(2)

Turn it off

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

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