Design decisions

18. CP Lang v2.1 Unification & Concept-Budget Guard (2026-11-20 — Language Architect Wave 3)

Wave 3 synthesizes all 21 scout friction backlogs across Batches 21–41 (research/archive/frictions/friction-backlog-batch-21.md through batch-41-oly-icpc.md, covering 200+ hard ported problems) against locked v2 (§16), the max-N prototype pass (c8e381f), and the aligned stdlib/ + examples/local-lib/ (§17). Full before/after examples and the next-sprint checklist live in research/archive/architecture/language-architecture-v2.1.md; docs/one-page-cheat-sheet.md is synchronized to match. Zero keywords (40), zero numeric types (4), zero traits (7 + 2, as revised in 3.5), and zero @ decorators (7 + 2) are added.

  • 18.1 Tropical Optional Rule (?T), unparenthesized-?? guard, and ?T == T (1.3; Batches 27, 28, 32, 33, 34, 35, 36, 38, 39). Across nine batches, unlifted +/- on ?Int/?F64 forced repeated if let guards and hand-written plus/shift helpers that made ?Int longer than INF sentinels. CP Lang v2.1 locks one algebraic rule: none is the identity of min/max/min=/max= (including min(gen)/max(gen) over ?T and ans min= opt on plain T), and none is the absorber of +, -, +=, -=, unary -, and sum(gen) on numeric optionals ?Int and ?F64 (never *, /, %, bitwise, or ?V + k). To prevent the a[i] + max(...) ?? 0 precedence trap permanently, mixing ?? with binary arithmetic (+ - * / %) without parentheses is a compile error. Equality ==/!= auto-lifts T to ?T (if dq.last != x:), while </<=/>/>= remain compile errors (?T still does not implement Ord). Chained if let a = x and let b = y: and while let are surfaced on the cheat sheet; custom ?Struct merges use match (a, b):.
  • 18.2 Lexically scoped @memo, runtime flat-vs-hash dispatch, and uniform range narrowing (5.9; Batches 23, 28, 34, 35, 40). @memo is legal on any fn — top-level or nested inside a function or loop — capturing immutable outer let/loop variables (mutated captured var is a compile error). Its cache is scoped to the enclosing block and hoisted into one reusable buffer cleared/stamped on block entry (eliminating the 185 MB 5-arg hash cliff in coci21c1p3 and supporting scenario loops in ioi20p4). Default @memo over all-Index parameters chooses flat vs. salted open-addressed CpHashMap at runtime from prod(K_i) (<= 2^24 slots, or 2^26 for tri-state uint8_t ?Bool, fixing noip21p3), and reports the chosen mode in cpl check --verbose / LSP hover. Range-typed parameters on @memo follow the exact same entry-check and flow-narrowing rules as ordinary fns (cheerio1s5), and ../..= bind looser than arithmetic and tighter than comparisons/in (i + 1..=n is (i + 1)..=n).
  • 18.3 Complete algebraic Index surface & lossless scalar casts (2.16; Batches 22, 28, 30, 33, 35, 37, 38, 39, 41). Clarifies all five existing Index shapes: Bool (Bool.K == 2, for b in Bool, [V, Bool]T), structural Char ranges (['a'..='z']Int), guaranteed row-major .to_idx/.from_idx on tuple/record products (R, C), and Subset<D> (for s in Subset<D> in ascending integer order, .empty, .full, and O(1) s.first -> ?D via ctz for bitmask DP peeling). Lossless scalar casts Int(ch) (0..=127), Char(i), and Int(b) (0 | 1) are locked; Int(f) on F64 remains a compile error.
  • 18.4 Lexical borrow & evaluation rules: for mut, Copy release, RHS-before-LHS, .swap, .take(), .absorb() (5.3; Batches 24, 25, 26, 31, 34, 36, 38, 41). for mut x in xs: lends elements mutably for arrays/lists of self-adjusting structs (Block, Dsu, MonoDeque) while keeping generators pure. Reading a Copy element releases its borrow immediately before enclosing calls (merge_heap(hrc[u], v)). Indexed assignment a[i].f = rhs evaluates indices and rhs before borrowing a[i] (making recursive arena updates nodes[u].l = merge(nodes[u].l, b) both borrow-safe and reallocation-safe). a.swap(i, j) on [D]T/List<T> handles i == j as a no-op; free-fn swap(mut a, mut b) is guaranteed O(1) on every heap container; .take() moves a heap container out in O(1) leaving an empty one behind (for x in mem[u].take(): mem[v].push(x)); and .absorb(mut other) drains small-into-large so it cannot be inverted into O(n^2). [D]T = expr clones any T expression independently per slot ([D]List<T> = [] never aliases), and xs.last stays by-value (xs[xs.len - 1] mutates stack tops).
  • 18.5 Ranges, chunks, boundaries, SparseTable.fold -> ?T, and 2D grid flips (2.3, 7.19; Batches 24, 26, 32, 34, 37, 38, 41). Every Range<D> exposes .l and .r boundary cuts directly (even when empty, eliminating rw.first!.l noise in windows(k)). Add D.chunks(k) (clamped non-overlapping Range<D>), Compressed<T> range slicing ys[blk], domain prefix D[..k], range intersection r1 & r2, and p.mirror/r.mirror. Replace ambiguous 2D g.flipped with g.flipped_rows and g.flipped_cols (g.transposed yields [C, R]T). SparseTable.fold(r) returns ?T (none on empty ranges; no monoid identity needed).
  • 18.6 Block-scoped defer and bare top-level return (5.7; Batches 24, 31, 37, 38, 41). defer is explicitly locked as block-scoped LIFO (runs at the exit of the immediately enclosing loop iteration, branch, or fn, never Go function-scoped), covering Rollback Mo's and backtracking DFS cleanly. Bare top-level return exits the program cleanly (or ends the current case in whole-file @multitest).
  • 18.7 Unified Mod<P>, Int promotion, T.zero/T.one-seeded sum/prod, and cross-@multitest precomputation (3.10; Batches 23, 29, 34, 37, 41). Confirms ModR retirement (§17.5): let M = ...; type Z = Mod<M> unifies static and runtime moduli (including composite P >= 1, .try_inv() -> ?Z, I128 multiply past 2^31 - 1, compile-time inverses for constant divisors, and one-way Int ops). sum(it) seeds from the element type's zero, and prod(it) joins the sequence prelude seeded from the element type's one; binary-op diagnostics always print type names. Cross-@multitest precomputation needs no static or @once: Comb<P>() auto-grows lazily on demand, and top-level code above @multitest fn solve(): runs once.
  • 18.8 Value-owned t.Pre on Rooted<V>, vertexless graph turbofish, and Dsu.groups() (7.19; Batches 24, 26, 27, 34, 39, 41). Pre on Rooted<V> becomes a value-owned fresh domain t.Pre (like xs.D on compress), preventing cross-tree preorder mix-ups (ioi18p3, superseding the type-level Rooted<V>.Pre in §17.3). Add t.pos(v) -> t.Pre (inverse of t.preorder: [t.Pre]V), Rooted.from_parents(par), and iterative t.tour yielding (v, entering); pin t.lift_while(u, pred) -> ?V to highest ancestor where pred holds from u up (or none if pred(u) is false). Document topo::<V>(next) for vertexless closure graphs and add Dsu<V>.groups() -> List<List<V>>.
  • 18.9 Stamp table Marks<D>, generalized RollingHash, Map 4-lookup ?(K, V), min_by/max_by ties, and container polish (Batches 25, 29, 30, 31, 32, 33, 36, 38, 39, 40, 41). Add userland Marks<D>() (generation-stamped visited set with .add(v) -> Bool, v in m, and O(1) .clear()) alongside a.fill(x). Generalize RollingHash over Str and [D]T returning HashVal with independent per-instance salted bases. Give ordered Map<K, V> all four lookups (.first_ge, .first_gt, .last_le, .last_lt) returning ?(K, V) (Set/SortedBag return ?K); accept optional iterables in container constructors; support by: on sequence first_ge/last_le and .sorted()/.rev on slices; exempt mutating .pop*()/.add()/.unite() from unused-result warnings; add rotate_right. Pin min_by/max_by -> ?T with first-extremum tie breaking, guaranteed stable sort/sorted, bit_len(x) (retiring bit_width), hex/binary literals, and Sieve(n) / factor(x) / divisors(x) (retiring factorize).
  • 18.10 @grader constants & shared domains, sibling-sized array params, Int-indexed Str, and judge print (1.6, 6.8; Batches 23, 25–27, 30, 33, 36, 37, 40, 41). Allow @grader const N: T (extern judge constant), file-scope size-less domain V bound by grader parameters for shared callbacks, and sibling-sized array parameters left or right (fn Assist(needed: [0..r]Bool, n: Int, k: Int, r: Int)). Clarify Str is Int-indexed (0..s.len, zero .raw) with s + ch, s.items, and match s: on string literals, alongside [expr for x in it if c] and List.filled(n, v). Lock judge print: domain values print their declared label, lists/1D arrays print space-separated, and [R, C]Char grids print row-by-row (debug(...) prints structured brackets to stderr).
  • 18.11 Compiler-trust & stress guardrails (7.4, 7.18; Batches 21–30, 34, 36). Wrap all emitted C++17 user definitions in namespace cp_user { ... } with C++/POSIX macro mangling (eliminating tm, dup, arg, y0 collisions); pin LazySegTree.set root-to-leaf pushdown (ccc02s4hard); stream stdin incrementally for @interactor; add cpl stress --max-vals for overflow hunting (O2); and place constructive generators (perm, surjection, bounded_product, tree, connected, dag, functional, simple_graph, str_of, rand_points, rand_disjoint_rects, rand_convex) in std.gen.
  • 18.12 Concept-budget rejections (permanent; see research/archive/architecture/language-architecture-v2.1.md §3). Explicitly rejected to protect the 40-keyword / 4-numeric-type / 1-page budget: Pool<Node>/Node.Id/SegPool, I32/U32, undo/Journaled, static let/@once, ModR, domain A | B sum-domain syntax, min=/max= returning Bool, dependent @memo parameter bounds, rolling-row step ... into, variable-length @tags DSL, bitwise |/^ on Bool, loop: keyword, let inside generator comprehensions, keyed array literals [R: 1, G: 2], Rev<T> (use Desc<T>/desc(x)), Heap<T>(by:), user operators on structural type aliases, runtime-sized SegTree.from(list)/combine_into in core std, and single-problem core helpers (Pos.window, g.lattice, cyc_range, dag_dp, take_except). Niche structures (Centroids, reroot, kruskal_tree, linalg det/rank/solve, Interner, spanning, ranks, lis, count_in_rects, MinCount, RollbackArray, Functional (already landed in examples/local-lib/), arbitrary-prime Poly MTT + .interpolate, F64/record LiChao) live in examples/local-lib/.