Design decisions

16. CP Lang v2 Spec Lock (2026-11-20 — Language Architect Wave 2)

Wave 2 synthesizes Wave 1 (research/archive/architecture/language-architecture-synthesis.md), Stage 3's 18 subtraction cuts (research/archive/audits/subtraction-audit-1.md), Stage 4's 7 syntax bakeoff verdicts on the 25-problem benchmark suite (research/archive/architecture/syntax-bakeoff-1.md), Stage 5's debug/pivot and cheat-sheet audits (research/archive/blind-evals/blind-critic-2-debug-pivot.md, research/archive/blind-evals/blind-critic-3-cheatsheet-test.md), Stage 6's max-N judge audit (research/perf/max-n-judge-audit-1.md), the bug-fix sprint (6f113c3, 7d1c976), and scout batches 15 and 17–22 into one contradiction-free CP Lang v2 spec. Full before/after snippets and the prototype implementation checklist live in research/archive/architecture/language-architecture-v2.md; docs/one-page-cheat-sheet.md is the canonical contestant reference. Every item below replaces earlier leans where they conflicted and is locked as the single source of truth for the prototype and Rust compiler sprints.

  • 16.1 Concept budget & F64 semantics locked (Stage 3 Cuts 1–13, Batch 21 E1–E5).
    • 40 keywords total: 32 contestant keywords including the 3 literals (let, var, const, fn, struct, enum, domain, type, use, pub, if, elif, else, for, while, in, match, return, break, continue, defer, and, or, not, assert, assume, mut, self, unchecked, true, false, none) plus 8 library-author keywords (trait, impl, where, lends, lend, law, inline, yield). Fifteen zombie/speculative keywords are permanently deleted (by, with, undo, requires, ensures, invariant, stress, protocol, limit, dyn, do, pool, decorator, static, yields), and Batch 19's proposed require/hidden/export/extern/interactor/ checker/gen stay ordinary functions or @ decorators rather than hard keywords.
    • 4 numeric types: Int (symmetric 64-bit, with range types packing to 1/2/4 bytes automatically), U64 (wrapping 64-bit), I128, and F64 (8-byte IEEE double, no long double). I32, I64, U8, U32 are deleted (1.7). On F64 (1.5, Batch 21 E1–E5): 1e18 stays Int and only literals with . are F64; integer literals unify with F64 in typed positions while Int variables require explicit F64(x); Int(x) on an F64 is a compile error requiring floor(x), ceil(x), round(x), or trunc(x); NaN and infinity trap at creation in checked runs so quiet NaN is the 8-byte ?F64 niche and < is a total order; bare print(x) of an F64 is a compile error suggesting "{x:.6f}" (round half away from zero, never -0.00, never scientific notation); ==/!= lint toward explicit close(a, b, eps) and sign(x, eps) (exempting literal == 0.0); and sqrt, sin, cos, tan, atan2, exp, ln, hypot, floor, ceil, round, trunc, PI are listed intrinsics.
    • 7 + 2 language traits (the count as revised in 3.5): 7 auto-derived core traits (Index, Seq, Eq, Ord only when all fields are Ord, Hash, Show, Read) plus 2 library-author traits (Indexed, Iterable). Small, Relocate, Zero, Bits, OrdKey, Bounded, Niche (internalized), Shrink (choice-stream shrinking), Modulus, Handle, FenwickIndex, Window, and BagWindow are deleted (3.5).
    • 7 + 2 @ decorators: @memo, @multitest, @brute, @tags, @gen, @checker/@interactor, @grader, plus library-author @get, @test (3.11).
    • One spelling per construct: if cond: a else: b (no then, no postfix if), elif (no else if), bare Pattern => expr match arms (no case), x => expr lambdas (no .field), ^ XOR / ** power, v.l/ v.r boundaries (no v.before/v.after), v + k/v - k/v.cyc(k) stepping (no v.offset/v.next/v.prev), .step(k) (no by), a.items (no enumerate), xs.adjacent (no pairs), Bitset<D>, explicit <D> on generic fn definitions, no ; or { ... } or <=> or do: or static let.
  • 16.2 Str revised to 0..len-indexed ASCII bytes + opt-in [domain S]Char (1.6, Stage 4 Fork 4, Batch 19 B19-9). Stage 4 proved that auto-opening nominal s.Idx as default Str fights real string algorithms (4331904, noip20p2, noi16p1, sac22cc3p5) because Z/KMP/SA/hashing constantly add lengths (i + x.len, 2 * w) and land on boundary s.len. Default Str is now a flat 0..len-indexed ASCII byte sequence (Char = 1 byte, zero UTF-8) supporting s[i], s[l..r], s.push(ch) (when var), s + t, s * k, sep.join, s.starts_with(x, at: i), s.split, s.split_once, s.trim_start, s.parse_int(), and Str(chars). Nominal [domain S]Char = read() remains a 1-line explicit opt-in for multi-string DP (LCS, edit distance) using the unchanged [domain]T kernel mechanism (2.14). Open slices s[..k]/s[k..] work on Str (Batch 22 X2), and var t = s strictly obeys value semantics (last-use move or explicit s.copy(), never silent mutable aliasing of let s, Batch 22 X4). Char adds is_alpha, is_alnum, digit(base = 10) -> ?Int, Char.digit(d); Scanner is dropped (Batch 22 X10, X13).
  • 16.3 Sliding windows & one Range<I> type (2.3, 4.3, Stage 3 Cuts 7 & 14, Stage 4 Fork 1, Batch 21 E7). Window<I>, BagWindow<I>, TwoStackFold, GroupWindow, and callback sliding(D, add:, drop:, ok:) are all deleted: Fork 1 caught a real bug in callback MonoDeque (noi05p1) and showed imperative MonoDeque uses fewer keystrokes and 11 fewer symbols. CP Lang v2 ships imperative Deque<T>, imperative MonoDeque<T>(min | max) (push(at, val), drop_before(min_at), clear(), best -> ?T), fixed D.windows(k) + sliding_min/sliding_max, explicit while loops for stateful two-pointers, and stateless slide_until(r, ok). To keep one Range<I> type (confirming Cut 7 and deleting Range1<I>) without ! panics, slide_until(r, ok) yields non-optional (lo: I, hi: I) endpoint pairs directly. Add (lo..=hi).clamp(D) on integer ranges to clip sweeps cleanly to a domain (Batch 21 E7).
  • 16.4 Algebraic Index (5 O(1) Copy shapes) & no Pool<T> (2.7, 2.16, 5.6, Stage 3 Cuts 5 & 6, Batch 15 N1, Batch 18 Collision 1). Bool, unit and payload enum (on demand), ?T (T: Index), bounded ranges lo..hi/lo..=hi (structural equality for identical written bounds in scope — [0..n]T is a plain Int-indexed array that unifies across function boundaries, while domain D = 1..=n opts into nominal index safety, Blind Critic 3), and tuples/records (A, B) derive Index automatically (alongside Subset<D>). Payload enums deriving Index solve typed multi-role FlowGraph<Node> with zero new domain sum syntax. [D]E: Index is deleted (violates O(1) Copy invariant; use Subset<D> or @memo(hash)), and Pool<T>/Pool<Node<_>>/PoolMap/Handle are deleted (use type Id = 0..=MAX with 4-byte storage + 4-byte niche ?Id, List<Node>, .push_id(x), ??=, and .freeze()). Whole-array reset uses a.fill(x) (including a.fill(none)), and compress(xs) returns a Compressed<T> object with fresh domain c.D, value lookup c[v] -> T, and value-to-index c.at(x) -> c.D / c.first_ge(x) (Blind Critic 3).
  • 16.5 Grids: type Cell = (Row, Col) + p.adj4 / p.adj8 (7.19, Stage 4 Fork 3, Batch 19 B19-10). No dedicated Grid<T> type. Product-domain type Cell = (Row, Col) composes with [Cell]T, bfs, Dsu<Cell>, and @memo, while userland std.grid provides Dir4/Dir8 (.cw, .ccw, .back, .from("UDLR", ch)), p.step(d), p.ray(d), explicit p.adj4 and p.adj8 (deleting silent-4 p.around()), and zero-copy g.transposed / g.flipped views.
  • 16.6 Bidirectional generic inference + f::<T>() + plain adjacency (2.13, Stage 4 Fork 2, Batch 15 N8). The type checker unifies concrete non-closure arguments (from:, root:, g) before checking closure parameters, and std.graph/std.tree place those arguments first (bfs(from: [s], next: ...), dijkstra(g, from: s), Rooted(root: r, adj: ...)) while accepting plain V -> Iter<V> unweighted adjacency without [(to: v) ...] wrappers. This removes ~90% of turbofish calls while keeping f::<T>() unambiguous for return-polymorphic calls like parse::<Int>(tok).
  • 16.7 Search: 8 canonical names, retiring first_where (4.3, Stage 3 Cut 16, Stage 4 Fork 5, Batch 18 SF5). first_where / last_where are retired after causing silent WAs on non-monotone predicates. Binary search uses free functions (also callable as methods on domains): bsearch_first(r, ok) -> ?I, bsearch_last(r, ok) -> ?I, and bsearch_first_some(r, f) -> ?(I, W) (debug-checked monotone; bsearch_first/ bsearch_last also take F64 ranges with steps: 80). Sorted lookup uses .first_ge(x) / .last_le(x) uniformly across List, [D]T, Set, Map, and SortedBag. Linear search uses first(it), a.find(x), and min_by/max_by. r.mid stays on Range<I>.
  • 16.8 Bare ops, unified Mod<P>, LazySegTree.max_right, Rooted.fold_path/apply_path + Reversible, and signed Bitset.shifted (3.1, 3.10, 7.19, Stage 3 Cuts 15 & 18, Stage 4 Fork 7, Batch 15 N2–N5, Batch 18 SF1–SF4, Batch 20 W10, Batch 21 E6). Contestant range structures accept bare operators (+, *, ^, &, |, min, max, gcd), (id, op) pairs, or Action (LazySegTree stock tags AddSum/AddMin/AddMax/AssignSum/AssignMin/AssignMax). Heaps and sorts use MinHeap<T>/MaxHeap<T>, by:, and desc(x). Both SegTree and LazySegTree expose .max_right/.min_left. Mod<P> unifies compile-time const and runtime-frozen let moduli (ModR retired). Bitset<D>.shifted(k) and Subset<D>.shifted(k) accept signed k (positive up, negative down). Rooted<V> is the single tree abstraction (DFS spanning tree/forest, flat CSR kids, lazy LCA sparse table & jump table, zero-alloc chains), adding generic tree.fold_path(a, b, ds) and tree.apply_path(a, b, mut ds, tag) over any tree.Pre-indexed DS (using std.algebra.Reversible for 1×-memory non-commutative folds — retiring dual-tree Hld and LazyHld), plus ancestor(v, k), postorder, lift_while(v, pred), and virtual_tree(keys). Core std.graph/std.flow/std.dsu/std.geometry add two_edge_components, biconnected_components, articulation_points, two_color, topo_prefix, MinCostFlow, max_weight_matching, Dsu.mark()/undo_to(snap), and generic Pt<T = Int> (exact turn stays Int-only; turn_eps and unit for F64). Niche structures (Rope, RangeKth, LiChao, PotentialDsu, Cover, Line/Hom, TwoStackFold, mo, Poly, XorBasis, Frac, Fixed, Tri, Counter, etc.) live in examples/local-lib/.
  • 16.9 Scope cleanup (defer), nested fn mutation, parallel tuple assignment, coherent ?T ordering, and uniform optionality (1.3, 4.9, 5.7, 5.8, 5.10, 5.12, Stage 3 Cuts 1 & 3, Stage 5, 6f113c3, 7d1c976, Batch 20 W6 & W11). with (both forms), undo blocks, and mut fn are deleted: defer is the one cleanup primitive, lends keeps its unbroken single-lend law (with post-lend write-back), and plain nested fn mutates outer vars directly. if let and match are expressions, destructuring let (a, b) = xs[i] always owns/copies values, var (a, b) = ... declares mutable vars, and ??= handles map-bucket init without silent auto-vivification ((m[k] ??= []).push(x)).
    • Parallel tuple assignment (a, b) = (x, y) IS locked in (resolving 15.12 & Batch 20 W6): A tuple of distinct mutable places on the LHS evaluates every RHS expression first into temporaries and then assigns each place — supporting swaps (a, b) = (b, a), extended Euclid (r0, r1) = (r1, r0 - q * r1), and rolling DP updates cleanly. Overlapping/duplicate LHS places without proven disjointness are a compile error.
    • Coherent ?T & Mod<P> ordering: neither implements Ord (superseding 15.11, Blind Critic 3): 6f113c3 made emitted C++ order Opt<T> with none first while keeping a < b an error, which silently makes MinHeap<(?Int, V)> pop unreachable (none) entries first! Meanwhile List<(Int, Z, Int)> failed in g++ because tuples unconditionally emitted operator< even on Mod<P>. In v2, neither ?T nor Mod<P> implements Ord, and structs/records/tuples derive Ord (and emit C++ operator<) only when every field implements Ord. To sort or heap-order optional keys, state where none belongs explicitly via by: or ?? (e.g. sort(mut xs, by: x => (x.d == none, x.d ?? 0))). min/max/min=/max= continue to skip none on either side (so ans min= dist[i] works when ans: Int and dist[i]: ?Int, Blind Critic 3).
    • Uniform optionality & diagnostics (Stage 5, Batch 20 W11): i + k, xs.last, and min(gen)/max(gen) ALWAYS return ?T (removing the inconsistent constant-range min exception that forced guessing !). Open-range DS calls (st.fold(..h[i])), if let expressions, and while let ... and eliminate most ! sites; flow facts elide proven-safe ! runtime checks; and optional-mismatch diagnostics print the column, name the optional sub-expression, and print the parenthesized fix (a + (max(...) ?? 0)).
  • 16.10 Predicates, stress hooks, checkers/interactors/graders, symmetric I/O, and honest cpl stress (6.6, 6.8, 7.1, 7.7–7.9, 7.18, Stage 3 Cuts 2 & 11, Stage 4 Fork 6, Stage 5, Batch 19, Batch 20 W7/W13/W15, Batch 21 E9). Predicates collapse to assert (always checked local + judge; lints on mut) and assume (local/debug/stress only; statically rejects mut/I/O side effects so nothing is ever silently erased on the judge). The stress ... by ... DSL and standalone protocol DSL are deleted. Non-typeable stress constraints use dependent bounds (incl. record fields) + Perm<V>/Tree<V> + typed read(gen:) (with witness and coupled tuple reads) + whole-input @gen + automatic choice-stream shrinking. Verification uses @checker (inheriting inputs, reading solution stdout via read_output() and assert), @interactor (paired with expression-form ask(..., limit: K)), and @grader (bodyless extern fn, exported entry fn, or stateful grader struct). I/O adds symmetric none: sentinels on read/print/read_output, read_line() (after a token read(), skips trailing whitespace to the next line; empty line is ""; strips \r, Batch 22 X1), read_until(sentinel), char-range @tags('.', '*', '1'..='9'), and read() in assignments/expressions. Every fenced code block in docs/one-page-cheat-sheet.md is compiled in CI as a P0 gate so docs and implementation never diverge again (Blind Critic 3). cpl stress is unified into one honest command: defaults to in-file @brute/@checker/@interactor (never emitting parameterless @brute into main), escalates sizes (1..=20 default), compares line-by-line unless @checker (with --close <eps> for float tolerance), always builds with -DLOCAL, shrinks every failure and replays debug(...) side-by-side, reports max size / rejection rate (>50% warning) / diff mode / output diversity, warns if a @brute-tested fn mutates top-level var, and suppresses complexity warnings inside @brute/ @gen/@checker/@interactor/assume.
  • 16.11 Max-N judge and compiler-trust guardrails (6.7, 7.4, Stage 6, Batch 18 §(e), Batch 19 B19-8, Batch 20 W5). Emitted C++17 never emits using namespace std;, always widens shift literals to 64-bit (1LL / cp_shl, fixing Batch 20 W5's 32-bit 1 << k UB), packs ?Int (LLONG_MIN) and ?F64 (quiet NaN) in 8 bytes, packs Mod<P> in 4-byte uint32_t for P <= 2^31 - 1, never uses std::vector<bool>, lowers @memo to flat arrays for every algebraic Index tuple up to 2^26 slots, backs HashMap/HashSet with a per-process salted open-addressed flat hash table, builds Rooted LCA/jump tables lazily with flat CSR kids, backs Steps with a lazy-sorted vector, and tree-shakes all unused runtime/stdlib code (plus stripping CP_GEN/assume/debug/@brute) so typical judge submissions are 4–10 KB with the .cp source in a top comment header.