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 &
F64semantics 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 proposedrequire/hidden/export/extern/interactor/checker/genstay 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, andF64(8-byte IEEE double, nolong double).I32,I64,U8,U32are deleted (1.7). OnF64(1.5, Batch 21 E1–E5):1e18staysIntand only literals with.areF64; integer literals unify withF64in typed positions whileIntvariables require explicitF64(x);Int(x)on anF64is a compile error requiringfloor(x),ceil(x),round(x), ortrunc(x); NaN and infinity trap at creation in checked runs so quiet NaN is the 8-byte?F64niche and<is a total order; bareprint(x)of anF64is a compile error suggesting"{x:.6f}"(round half away from zero, never-0.00, never scientific notation);==/!=lint toward explicitclose(a, b, eps)andsign(x, eps)(exempting literal== 0.0); andsqrt,sin,cos,tan,atan2,exp,ln,hypot,floor,ceil,round,trunc,PIare listed intrinsics. - 7 + 2 language traits (the count as revised in 3.5): 7 auto-derived core traits (
Index,Seq,Eq,Ordonly when all fields areOrd,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, andBagWindoware 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(nothen, no postfixif),elif(noelse if), barePattern => exprmatcharms (nocase),x => exprlambdas (no.field),^XOR /**power,v.l/v.rboundaries (nov.before/v.after),v + k/v - k/v.cyc(k)stepping (nov.offset/v.next/v.prev),.step(k)(noby),a.items(noenumerate),xs.adjacent(nopairs),Bitset<D>, explicit<D>on genericfndefinitions, no;or{ ... }or<=>ordo:orstatic let.
- 40 keywords total: 32 contestant keywords including the 3 literals
(
- 16.2
Strrevised to0..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 nominals.Idxas defaultStrfights real string algorithms (4331904,noip20p2,noi16p1,sac22cc3p5) because Z/KMP/SA/hashing constantly add lengths (i + x.len,2 * w) and land on boundarys.len. DefaultStris now a flat0..len-indexed ASCII byte sequence (Char= 1 byte, zero UTF-8) supportings[i],s[l..r],s.push(ch)(whenvar),s + t,s * k,sep.join,s.starts_with(x, at: i),s.split,s.split_once,s.trim_start,s.parse_int(), andStr(chars). Nominal[domain S]Char = read()remains a 1-line explicit opt-in for multi-string DP (LCS, edit distance) using the unchanged[domain]Tkernel mechanism (2.14). Open slicess[..k]/s[k..]work onStr(Batch 22 X2), andvar t = sstrictly obeys value semantics (last-use move or explicits.copy(), never silent mutable aliasing oflet s, Batch 22 X4).Charaddsis_alpha,is_alnum,digit(base = 10) -> ?Int,Char.digit(d);Scanneris 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 callbacksliding(D, add:, drop:, ok:)are all deleted: Fork 1 caught a real bug in callbackMonoDeque(noi05p1) and showed imperativeMonoDequeuses fewer keystrokes and 11 fewer symbols. CP Lang v2 ships imperativeDeque<T>, imperativeMonoDeque<T>(min | max)(push(at, val),drop_before(min_at),clear(),best -> ?T), fixedD.windows(k)+sliding_min/sliding_max, explicitwhileloops for stateful two-pointers, and statelessslide_until(r, ok). To keep oneRange<I>type (confirming Cut 7 and deletingRange1<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)Copyshapes) & noPool<T>(2.7, 2.16, 5.6, Stage 3 Cuts 5 & 6, Batch 15 N1, Batch 18 Collision 1).Bool, unit and payloadenum(on demand),?T(T: Index), bounded rangeslo..hi/lo..=hi(structural equality for identical written bounds in scope —[0..n]Tis a plainInt-indexed array that unifies across function boundaries, whiledomain D = 1..=nopts into nominal index safety, Blind Critic 3), and tuples/records(A, B)deriveIndexautomatically (alongsideSubset<D>). Payload enums derivingIndexsolve typed multi-roleFlowGraph<Node>with zero newdomainsum syntax.[D]E: Indexis deleted (violates O(1)Copyinvariant; useSubset<D>or@memo(hash)), andPool<T>/Pool<Node<_>>/PoolMap/Handleare deleted (usetype Id = 0..=MAXwith 4-byte storage + 4-byte niche?Id,List<Node>,.push_id(x),??=, and.freeze()). Whole-array reset usesa.fill(x)(includinga.fill(none)), andcompress(xs)returns aCompressed<T>object with fresh domainc.D, value lookupc[v] -> T, and value-to-indexc.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 dedicatedGrid<T>type. Product-domaintype Cell = (Row, Col)composes with[Cell]T,bfs,Dsu<Cell>, and@memo, while userlandstd.gridprovidesDir4/Dir8(.cw,.ccw,.back,.from("UDLR", ch)),p.step(d),p.ray(d), explicitp.adj4andp.adj8(deleting silent-4p.around()), and zero-copyg.transposed/g.flippedviews.
- 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, andstd.graph/std.treeplace those arguments first (bfs(from: [s], next: ...),dijkstra(g, from: s),Rooted(root: r, adj: ...)) while accepting plainV -> Iter<V>unweighted adjacency without[(to: v) ...]wrappers. This removes ~90% of turbofish calls while keepingf::<T>()unambiguous for return-polymorphic calls likeparse::<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_whereare 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, andbsearch_first_some(r, f) -> ?(I, W)(debug-checked monotone;bsearch_first/bsearch_lastalso takeF64ranges withsteps: 80). Sorted lookup uses.first_ge(x)/.last_le(x)uniformly acrossList,[D]T,Set,Map, andSortedBag. Linear search usesfirst(it),a.find(x), andmin_by/max_by.r.midstays onRange<I>.
- 16.8 Bare ops, unified
Mod<P>,LazySegTree.max_right,Rooted.fold_path/apply_path+Reversible, and signedBitset.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, orAction(LazySegTreestock tagsAddSum/AddMin/AddMax/AssignSum/AssignMin/AssignMax). Heaps and sorts useMinHeap<T>/MaxHeap<T>,by:, anddesc(x). BothSegTreeandLazySegTreeexpose.max_right/.min_left.Mod<P>unifies compile-timeconstand runtime-frozenletmoduli (ModRretired).Bitset<D>.shifted(k)andSubset<D>.shifted(k)accept signedk(positive up, negative down).Rooted<V>is the single tree abstraction (DFS spanning tree/forest, flat CSRkids, lazy LCA sparse table & jump table, zero-allocchains), adding generictree.fold_path(a, b, ds)andtree.apply_path(a, b, mut ds, tag)over anytree.Pre-indexed DS (usingstd.algebra.Reversiblefor 1×-memory non-commutative folds — retiring dual-treeHldandLazyHld), plusancestor(v, k),postorder,lift_while(v, pred), andvirtual_tree(keys). Corestd.graph/std.flow/std.dsu/std.geometryaddtwo_edge_components,biconnected_components,articulation_points,two_color,topo_prefix,MinCostFlow,max_weight_matching,Dsu.mark()/undo_to(snap), and genericPt<T = Int>(exactturnstaysInt-only;turn_epsandunitforF64). Niche structures (Rope,RangeKth,LiChao,PotentialDsu,Cover,Line/Hom,TwoStackFold,mo,Poly,XorBasis,Frac,Fixed,Tri,Counter, etc.) live inexamples/local-lib/.
- 16.9 Scope cleanup (
defer), nestedfnmutation, parallel tuple assignment, coherent?Tordering, 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),undoblocks, andmut fnare deleted:deferis the one cleanup primitive,lendskeeps its unbroken single-lendlaw (with post-lendwrite-back), and plain nestedfnmutates outervars directly.if letandmatchare expressions, destructuringlet (a, b) = xs[i]always owns/copies values,var (a, b) = ...declares mutablevars, 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 implementsOrd(superseding 15.11, Blind Critic 3):6f113c3made emitted C++ orderOpt<T>withnonefirst while keepinga < ban error, which silently makesMinHeap<(?Int, V)>pop unreachable (none) entries first! MeanwhileList<(Int, Z, Int)>failed ing++because tuples unconditionally emittedoperator<even onMod<P>. In v2, neither?TnorMod<P>implementsOrd, and structs/records/tuples deriveOrd(and emit C++operator<) only when every field implementsOrd. To sort or heap-order optional keys, state wherenonebelongs explicitly viaby:or??(e.g.sort(mut xs, by: x => (x.d == none, x.d ?? 0))).min/max/min=/max=continue to skipnoneon either side (soans min= dist[i]works whenans: Intanddist[i]: ?Int, Blind Critic 3). - Uniform optionality & diagnostics (Stage 5, Batch 20 W11):
i + k,xs.last, andmin(gen)/max(gen)ALWAYS return?T(removing the inconsistent constant-rangeminexception that forced guessing!). Open-range DS calls (st.fold(..h[i])),if letexpressions, andwhile let ... andeliminate 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)).
- Parallel tuple assignment
- 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 toassert(always checked local + judge; lints onmut) andassume(local/debug/stress only; statically rejectsmut/I/O side effects so nothing is ever silently erased on the judge). Thestress ... by ...DSL and standaloneprotocolDSL are deleted. Non-typeable stress constraints use dependent bounds (incl. record fields) +Perm<V>/Tree<V>+ typedread(gen:)(withwitnessand coupled tuple reads) + whole-input@gen+ automatic choice-stream shrinking. Verification uses@checker(inheriting inputs, reading solution stdout viaread_output()andassert),@interactor(paired with expression-formask(..., limit: K)), and@grader(bodyless extern fn, exported entry fn, or stateful grader struct). I/O adds symmetricnone:sentinels onread/print/read_output,read_line()(after a tokenread(), skips trailing whitespace to the next line; empty line is""; strips\r, Batch 22 X1),read_until(sentinel), char-range@tags('.', '*', '1'..='9'), andread()in assignments/expressions. Every fenced code block indocs/one-page-cheat-sheet.mdis compiled in CI as a P0 gate so docs and implementation never diverge again (Blind Critic 3).cpl stressis unified into one honest command: defaults to in-file@brute/@checker/@interactor(never emitting parameterless@bruteintomain), escalates sizes (1..=20default), compares line-by-line unless@checker(with--close <eps>for float tolerance), always builds with-DLOCAL, shrinks every failure and replaysdebug(...)side-by-side, reports max size / rejection rate (>50% warning) / diff mode / output diversity, warns if a@brute-tested fn mutates top-levelvar, 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-bit1 << kUB), packs?Int(LLONG_MIN) and?F64(quiet NaN) in 8 bytes, packsMod<P>in 4-byteuint32_tforP <= 2^31 - 1, never usesstd::vector<bool>, lowers@memoto flat arrays for every algebraicIndextuple up to2^26slots, backsHashMap/HashSetwith a per-process salted open-addressed flat hash table, buildsRootedLCA/jump tables lazily with flat CSRkids, backsStepswith a lazy-sortedvector, and tree-shakes all unused runtime/stdlib code (plus strippingCP_GEN/assume/debug/@brute) so typical judge submissions are 4–10 KB with the.cpsource in a top comment header.