← All lints

query_index_shift

L0577Idiomswarn

Positions read 1-based and shifted back by hand

let l: 1..=n = read() then a[l - 1]: declare the array over 1..=n

Flagged
let (n, q): (1..=200000, 1..=200000) = read()
let a: [0..n]Int = read()
for _ in 0..q:
    let i: 1..=n = read()
    print(a[i - 1])
Write instead
let (n, q): (1..=200000, 1..=200000) = read()
domain I = 1..=n
let a: [I]Int = read()
for _ in 0..q:
    let i: I = read()
    print(a[i])

Why

A statement numbers its positions from 1, so a query reads l and r as 1..=n, and code written for 0-based arrays then subtracts 1 at every use: a[l - 1], p[r] - p[l - 1]. Each use is a place to forget the shift, and the declared type 1..=n and the array's 0..n disagree about what a position is. Declaring the array over the positions as read, domain I = 1..=n and let a: [I]Int = read(), makes l: I index it directly, and a.scan(+).fold(l..=r) sums the query without a hand-built prefix. The rule fires when a name read as 1.. is used as [l - 1] later in the same block, unless it also bounds a range or a size (0..n, [n]), where a[n - 1] is the last element; there is no automatic fix, since every array over those positions changes together. A shift that is only written, as in d[l - 1] += x beside d[r] -= x, is a difference array over cuts; diff_by_hand reports that one.

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, q): (1..=200000, 1..=200000) = read()
let a: [0..n]Int = read()
var d: [0..=n]Int = 0
for _ in 0..q:
    let k: 1..=n = read()
    print(a[n - k])
    let (l, r, x): (1..=n, 1..=n, Int) = read()
    d[l - 1] += x
    d[r] -= x
print(d)

Turn it off

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

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