← All lints

depth_by_hand

L0567Idiomswarn

Tree depths stepped from the parent by hand

depth[v] = depth[par[v]] + 1: Rooted.from_parents(par).depth(v)

Flagged
let n: 2..=200000 = read()
let par: [0..n - 1]1..=n = read()
var depth: List<Int> = [0, 0]
for v in 2..=n:
    depth.push(depth[par[v - 2]] + 1)
print(depth.max()!)
Write instead
let n: 2..=200000 = read()
domain V = 1..=n
let par: [0..n - 1]V = read()
let t = Rooted.from_parents([V] v => if v == 1: None else: Some(par[v.ord - 1]))
print([t.depth(v) for v in V].max()!)

Why

Filling depth[v] from the parent's depth plus one, in a loop over the parent list or inside a DFS, is the first step of almost every tree algorithm written by hand, and the next steps (the parent table, a climb to the LCA) follow it. Rooted.from_parents(par) builds the rooted tree from parents keyed by vertex (None at the root), and Rooted.new(adj, root) from an adjacency list; either knows t.depth(v), t.parent(v) and t.lca(u, v), so none of these tables is written. There is no automatic fix, since the tree has to be typed over a vertex domain first. The rule reads tables whose name says depth (depth, dep, level, lvl); a breadth-first dist on a general graph is not a tree depth and is not reported.

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 n: 2..=200000 = read()
let par: [0..n - 1]1..=n = read()
var size: List<Int> = [0 for _ in 0..=n]
for v in 2..=n:
    size[par[v - 2]] = size[par[v - 2]] + 1
print(size[1])

Turn it off

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

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