Lints
121 lints, each with the code it flags, the rewrite and the reason. cpl lint, the editor and the playground show them; none ever fails cpl build or cpl run. Set a lint's level in cp.toml under [lints], or silence one in code with with lint(name: allow).
By group
Correctness 9
Code that is wrong or almost certainly a bug. Denied by cpl lint.
- unknown_lint L0001Unknown lint name
with lintorcp.tomlnames a lint that does not exist - position_arithmetic L0101Position arithmetic via
.ordV(v.ord + 1)builds a position from a number - state_above_multitest L0211State above multitesta top-level
varabove@!multitestthat each test writes - float_equality L0301Exact float equality comparison
==or!=on floats - memo_key_space L0413
@memotable exceeds memory budgeta@memowhose table does not fit in memory at the input bounds - float_sqrt_for_int L0529Integer square root through F64
floor(sqrt(n))on anInt: the exact root isn.isqrt - same_place_read_write L0601Right side changes the place it writes
xs[0] = xs.pop()!: the right side changes the place being written - literal_slice_index L0605Literal index into a slice
w[0]on a slice that keeps its source's keys:w.first!orw.nth(0) - cache_field_written_outside L0609
@cachefield written outside its typean@cachefield written outside its type's methods
Performance 7
Code that does more work than it needs to.
- domain_keyed_map L0412Map or Set keyed by a domaina
MaporSetkeyed by a domain - loop_invariant_mod_div L0415Loop-invariant
Moddivisor inside loopaMod<P>division by a loop-invariant value computes an inverse every iteration - chain_walked_twice L0602Lazy chain walked twicea
.filter/.mapchain kept in aletand walked twice redoes the work - map_recomputed L0603
.mapview read by index many times.map(f)read by index in a loop callsfon every read - mut_generator_rewalked L0604Generator holding a
mutlend walked twicea generator called with amutargument and walked twice - wide_array L0606Wide
Intarray with narrow valuesa large[n]Intwhose every write fits a narrower range - padding L0607Padding in a large array's elementsover 20% of a large array's element is padding
Idioms 92
A hand-written pattern the language or the standard library already says in one step.
- search_loop L0501Flag-and-break search loopa loop that sets a flag or
?Tand breaks:first,anyorall - discarded_result L0502Discarded function return value
let _ =throws away what a fn of this file returns - symmetric_write L0503Duplicate symmetric writethe same fact written for
(u, v)and then(v, u) - loop_reduction L0504Manual accumulation loopa loop that only accumulates:
sum,count,maxormin - index_only_loop L0505Index loop that only reads
xs[i]for i in 0..xs.lenthat only readsxs[i] - repeated_literal L0506Repeated large literala big literal (a bound or modulus) written in several places
- push_loop L0507Loop that only pushesa list built by a loop that only pushes: a comprehension
- none_check_unwrap L0508Check for
None, then unwrapx != None and .. x!: the check and the unwrap say one thing twice - free_fold L0509Fold or sort of a sequence written as a free function
sum(xs),count(xs, p)orsort(mut xs): the method reads on the sequence - by_twin L0510
_bytwin instead of aby:optionmin_by,max_by,argmax_by,runs_by,group_by,first_ge_by: passby:to the base operation - tree_order L0511
preorderorpostorderof a rooted treet.preorder/t.postorder: iterate the preorder arrayt.at(t.at.revfor children first) - domain_spelling L0512Non-canonical domain/sequence method spelling
D.sorted(by:)->D.sort(by:);xs.first(where: p)->xs.first(p) - prefix_twin L0513Dimension-suffixed prefix or diff helper instead of
Prefix/Diffprefix1/prefix2/prefix_n,Prefix1/Prefix2/PrefixN,Diff1/Diff2: writePrefixorDiff - hand_rolled_range_tree L0514Hand-rolled Fenwick or segment treemanual BIT (
p += p & -p) or segment-tree (2 * p/2 * p + 1) loop: usestd.fenwick/std.segtree/std.lazy - sorted_range_method L0515Removed bound-query method on
SortedBagorSortedSetfirst_ge/first_gt/last_le/last_lt/count_rangeonSortedBag/SortedSet: use.range(r) - hand_rolled_string_algo L0516Hand-rolled string algorithmmanual prefix-function, Z-function, polynomial hash, or trie loop: use
std.strings - hand_rolled_dsu L0517Hand-rolled union-find (DSU)manual parent-pointer path compression: use
std.dsu - hand_rolled_sieve L0518Hand-rolled prime or SPF sievemanual Eratosthenes or linear sieve loop: use
std.math.Sieve - hand_rolled_binary_lifting L0519Hand-rolled binary lifting tablemanual
up[k][v] = up[k - 1][up[k - 1][v]]table: usestd.tree - hand_rolled_answer_search L0520Hand-rolled binary searchmanual
while lo < himidpoint loop over a predicate: user.first_true/r.last_true - hand_rolled_prefix_sum L0521Hand-rolled prefix summanual
p[i + 1] = p[i] + xorp[i.r] = p[i.l] + xloop: usePrefix(...) - copy_sort_writeback L0522Copy-mutate-writeback on a slicecopying
xs[l..r]to sort/reverse/rotate and writing it back: mutatexs[l..r]in place - chmin_chmax_if L0523Hand-written min= / max=
best = max(best, x): the update isbest max= x - bool_ternary_print L0524Answer words written out
if ok: "YES" else: "NO": the answer word isyes(ok) - peek_then_pop L0525Peek then pop
let x = s.last!thens.pop():let x = s.pop()!takes it - ceil_div_formula L0526Hand-written ceiling division
(a + b - 1) / b: the ceiling isceil_div(a, b) - neg_mod_fixup L0527C++ negative-remainder fixup
(a - b + m) % m:%never returns a negative, so(a - b) % mis enough - reverse_index L0528Hand-written reversed copy
[xs[xs.len - 1 - i] for i in 0..xs.len]: the copy isxs.reversed() - sentinel_table L0530Sentinel value meaning absent
var memo: [D]Int = -1tested with== -1:[D]?Intstarting atNone - manual_mod_reduce L0531Modular arithmetic by hand
a * b % 1000000007after each product:type Z = Mod<1000000007> - nested_list_grid L0532List of lists for a fixed grid
[[0 for _ in 0..m] for _ in 0..n]:[n, m]Int = 0 - grid_neighbour_step L0534Grid neighbour read behind a hand edge test
if r > 0: g[r - 1, c]:if let (pr, pc) = (r, c).step(Dir4.up()) - grid_bounds_check L0535Grid bounds tested by hand
0 <= x and x < h and 0 <= y and y < w:(r, c).adj4or.step(d) - sentinel_scalar L0536Scalar started at a sentinel
var found = -1/var best = -10**18:var found: ?Int = None - manual_adjacency_list L0537Adjacency list built edge by edge
adj[u].push(v)per read edge:Graph.undirected(es)/Graph.directed(es) - dx_dy_arrays L0539Grid directions as dx/dy lists
dx = [1, -1, 0, 0]:for d in Dir4.all()with(r, c).step(d) - manual_bit_test L0540C++ bit test
(x >> i) & 1 == 1:x.bit(i)reads one bit - sort_desc_by_negation L0541descending sort by a negated key
sorted(by: x => -x):sorted(desc: true)says it and never overflows - last_via_len L0542last element by
len - 1xs[xs.len - 1]:xs.last!is the last element - manual_pair_loop L0543C++ pair loop
for i ..: for j in i + 1..n:xs.pairs()walks each pair once - manual_digit_loop L0544C++ digit loop
while y > 0: .. y % 10 .. y /= 10:y.digits()lists the digits - hand_rolled_pow L0545hand-rolled fast powera square-and-halve loop:
pow_mod(b, e, m)orMod<P>with** - hand_rolled_gcd L0546hand-rolled gcd
f(b, a % b):gcd(a, b)is instd.math - loop_argmax L0547Hand-written argmax loop
for i ..: if a[i] > a[j]: j = i:D.max(by: i => a[i])names the index of the largest - manual_mex L0548Hand-written first-unmarked search
while seen[m]: m += 1:(lo..=hi).find(m => not seen[m])names the search - copy_comprehension L0549List copied by a comprehension
[x for x in a]:a.collect()copies a sequence into aList - queue_head_index L0550Queue run by a head index
var head = 0; while head < q.len: q[head]:bfsor aDeque - split_range_check L0551Range check written as two comparisons
x >= 0 and x < n: chain it as0 <= x < n - contains_then_add L0552Key tested before
+=on a mapif k in m: m[k] += v else: m[k] = v:m[k] += vstarts a missing key at 0 - stale_entry_skip L0553Stale heap entry skipped by hand
if d > dist[u]: continueafter a heap pop:dijkstra(g, from:) - memo_by_hand L0554Memo table kept by hand
if k in memo: return memo[k]:@memo(map)on the fn - lca_by_hand L0555Lowest common ancestor by hand
while depth[u] > depth[v]: u = parent[u]:Rooted.lca - cross_by_hand L0556Cross product of parallel coordinate lists
xs[i] * ys[j] - xs[j] * ys[i]: points asPt,p.cross(q),area2 - binom_by_hand L0557Binomial from factorial tables by hand
fact[a] * inv(fact[b]) * inv(fact[a - b]):Comb<Z>(n).choose(a, b) - runs_by_hand L0558Runs counted by hand
if c == x: run += 1 else: run = 0:s.runs()yields(val, len) - diff_by_hand L0559Difference array by hand
d[l] += x; d[r] -= x:Diff<D, T>()withadd(l..r, x)andfinish() - components_by_dfs L0560Components counted by DFS by hand
for u ..: if not seen[u]: count += 1; visit(u):components(adj) - trial_division L0561Trial division by hand
while d * d <= x: if x % d == 0:divisors(x)/factor(x)fromstd.math - count_until L0562Step counter searched by hand
while p < n: p *= 3; k += 1:(0..).find(k => 3 ** k >= n)!names the smallestk - map_as_multiset L0563Map used as a multiset
cnt[x] += 1/if cnt[x] > 0: cnt[x] -= 1:SortedBag<K>(std.bag) - read_loop L0564List read one item per loop step
for _ in 0..k: xs.push(read()):let xs: [0..k]T = read()reads them all - cycle_by_colors L0565Directed cycle found by colouring a DFS by hand
color[u] = 1; ... if color[v] == 1: cyc = true; ... color[u] = 2:find_cycle(g) - sliding_min_by_hand L0566Sliding-window minimum kept with a hand-written deque
while dq.len > head and a[dq[dq.len - 1]] >= a[i]: dq.pop():Window(min) - depth_by_hand L0567Tree depths stepped from the parent by hand
depth[v] = depth[par[v]] + 1:Rooted.from_parents(par).depth(v) - small_to_large_by_hand L0568Smaller set merged into the larger by hand
if a.len < b.len: (a, b) = (b, a)thenfor x in b: a.add(x):a.absorb(mut b) - inversions_by_fenwick L0569Inversions counted with a Fenwick tree by hand
inv += i - bit.prefix(x); bit.add(x, 1):inversions(xs) - interval_dp_by_length L0570Interval DP stepped by length by hand
for len in ..: for l in ..: let r = l + len - 1: a table over[I.ranges] - negated_heap L0571Negated values in a min-heap
h.push(-x)into aMinHeapto pop the largest:MaxHeap<T>(std.heap) - sort_for_extreme L0572Sorting to read the smallest or largest
xs.sorted()[0]/xs.sorted().last!sorts a copy for one element:xs.min()/xs.max() - fermat_inverse L0573Modular inverse by Fermat, by hand
pow_mod(a, P - 2, P):Mod<P>(std.mod) andZ(a).inv() - char_offset_index L0574Letter offset as an index
cnt[c - 'a']: index by adomain Letter = 'a'..='z'instead - push_pop_pair L0575Push then pop on a heap
h.push(x)thenh.pop()!:h.push_pop(x)(std.heap) - pop_min_loop L0576Read the smallest, then remove it
let x = s.first!thens.remove(x):s.pop_first()!(std.bag) - query_index_shift L0577Positions read 1-based and shifted back by hand
let l: 1..=n = read()thena[l - 1]: declare the array over1..=n - tuple_points L0578Points kept as parallel coordinate arrays
let xs: [D]Int = read()andlet ys: [D]Int = read()indexed together:[D] i => Pt(xs[i], ys[i]) - counter_by_map L0579Map used as a counter
cnt[x] = (cnt.get(x) ?? 0) + 1on aMap<K, Int>:Counter<K>(std.hashmap) - submask_loop L0580Submasks walked by hand
while s > 0: ..; s = (s - 1) & m:for s in submasks(m) - ternary_search_by_hand L0581Ternary search by handa
whileloop probinglo + (hi - lo) / 3andhi - (hi - lo) / 3:ternary_min(lo..hi, f)! - argsort_loop L0582Argsort through value-index pairs
(a[i], i)pairs sorted for their order:(0..n).sorted(by: i => a[i]) - palindrome_by_hand L0583Palindrome test by hand
s[i]againsts[n - 1 - i]over0..n / 2:is_palindrome(s) - monotone_stack_by_hand L0584Monotone stack by hand
while st.len > 0 and a[st.last!] < a[i]: .. st.pop():a.next_smaller(by: x => -x) - subset_masks_by_hand L0585Subsets as masks, elements picked bit by bit
for mask in 0..(1 << n)testing(mask >> i) & 1to picka[i]:for sub in a.subsequences() - adjacent_by_index L0586Neighbouring pairs by index
if i + 1 < n and a[i] .. a[i + 1](orv != V.last!) in a loop over positions:for (x, y) in a.adjacent - fact_tables_by_hand L0587Factorial table built by hand
fact[i] = fact[i - 1] * i % Pin a loop:Comb<Mod<P>>(n)withcomb.fact(i),comb.inv_fact(i),comb.choose(a, b) - manual_heap_drain L0588Heap popped a fixed number of times by hand
for _ in 0..k:usingh.pop()!:for x in h.drain().take(k) - group_into_map L0589Map of lists filled by key in a loop
for x in xs: (m[k] ??= []).push(v):let m = xs.group(by: x => k, of: x => v) - sliding_sum_by_hand L0590Window sum kept by hand
cur += a[i] - a[i - k]overk..n:Prefix(a)andp.fold(j - k..j) - while_not_empty_pop L0591Empty test, then unwrapped pop
while not q.is_empty:thenlet x = q.pop()!:while let x = q.pop(): - manual_starts_with L0592Slice compared with a pattern
s[0..p.len] == p:s.starts_with(p);s[s.len - p.len..] == p:s.ends_with(p) - test_count_loop L0593Test cases looped by hand
let t = read()thenfor _ in 0..t:around the program:@!multitest - map_contains_then_index L0594Key tested, then indexed again
if k in m:thenm[k]:if let v = m.get(k): - coalesce_test_then_unwrap L0595Stand-in test, then unwrap
while (e ?? c) > y:thenlet w = e!:while let w = e, w > y:
Style 12
Spelling that hides what the code means.
- var_never_reassigned L0201Mutable binding never reassigneda
varthat is never changed - unread_field L0202Struct field never reada struct field that is never read
- shadows_top_level L0203Local shadows top-level bindinga local name that hides a top-level
let - turbofish_type_args L0204Turbofish
::<...>on generic callf::<T>(...): canonical generic call spelling isf<T>(...) - pow_method L0205Power written with
.pow(e)a.pow(e): power is writtena ** e - getter_parens L0206Built-in getter called with
().len(),.is_empty(),.first(),.last(),.rev(),.items()are read without() - is_in_cond_header L0207Pattern test
x is pinif/elif/whileheaderif/elif/whileheaders bind withlet p = x, notx is p - redundant_prelude_import L0208
useof a name the prelude already providesuse std.tree.{Rooted}imports what the prelude gives every program - redundant_arg_name L0209Named argument or record field repeating its own name
f(moves: moves)or(val: val)can be punned asf(moves:)/(val:) - compound_self_ref L0210Assignment of a place in terms of itself
x = x + eorcnt[v] = cnt[v] % mis the compound assignmentx += e - missing_parens L0608Work without parentheses
xs.sum: a member that does work takes() - parens_on_o1 L0608Parentheses on an member
xs.len(): an member reads without()
Pedantic 1
Stricter checks, off by default.
By family
The families of the idioms catalog, spec/idioms/lints.md.
N. Naming and spelling
D. Domains, positions and cuts
W. Ownership, lending and moves
R. Redundancy and dead code
H. C++ habits
S. The standard library would say it shorter
- pow_method
- domain_keyed_map
- memo_key_space
- loop_invariant_mod_div
- search_loop
- loop_reduction
- index_only_loop
- push_loop
- free_fold
- by_twin
- tree_order
- prefix_twin
- hand_rolled_range_tree
- sorted_range_method
- hand_rolled_string_algo
- hand_rolled_dsu
- hand_rolled_sieve
- hand_rolled_binary_lifting
- hand_rolled_answer_search
- hand_rolled_prefix_sum
- copy_sort_writeback
- ceil_div_formula
- neg_mod_fixup
- float_sqrt_for_int
- manual_mod_reduce
- grid_neighbour_step
- grid_bounds_check
- manual_adjacency_list
- dx_dy_arrays
- queue_head_index
- stale_entry_skip
- map_as_multiset
- negated_heap
- sort_for_extreme
- fermat_inverse
- char_offset_index
- push_pop_pair
- pop_min_loop
- tuple_points
- counter_by_map
F. Functions, closures and generators
T. Multitest and state
K. Arithmetic, overflow, modulus and floats
O. Optionals and sentinels
I. Input and output
By practice
The practices of spec/idioms/principles.md each lint serves.