← All lints

cache_field_written_outside

L0609Correctnesswarn

@cache field written outside its type

an @cache field written outside its type's methods

Flagged
struct Best:
    @cache top: Int
    xs: List<Int>

    fn top_value(self) -> Int:
        if self.top < 0: self.top = self.xs.max()!
        self.top

var b = Best(top: -1, xs: [3, 9, 4])
b.top = 0
print(b.top_value())
Write instead
struct Best:
    @cache top: Int
    xs: List<Int>

    fn top_value(self) -> Int:
        if self.top < 0: self.top = self.xs.max()!
        self.top

let b = Best(top: -1, xs: [3, 9, 4])
print(b.top_value())

Why

An @cache field holds a value its type's methods derive from the other fields, like Dsu.find's compressed parent (spec/core/05-ownership.md §10a). Its methods may write it through a read self because they keep it in step; code outside can write any value, and the next read then returns a wrong answer. Write it only from a method of the type, or drop @cache if it is plain state.

The practice it serves

Code that is wrong or almost certainly a bug. Denied by cpl lint.

Not flagged

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

Near miss
struct Best:
    @cache top: Int
    xs: List<Int>

    fn top_value(self) -> Int:
        if self.top < 0: self.top = self.xs.max()!
        self.top

let b = Best(top: -1, xs: [3, 9, 4])
print(b.top_value(), b.top)

Turn it off

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

Generated from spec/checker-lints/cache_field_written_outside, the same record the linter is built from.