Design decisions

33. Fresh domains and existential returns (2026-11-21)

33.1. Existential return syntax -> (domain P, [P]Int) and let (domain P, part) = f(..) uses TypeKind::DomainBinder(Name) in parenthesized tuple types and PatternKind::Domain(Name) in patterns, alongside existing record-based (new domain C, ...) syntax. Reason: matches the 0.3 spec while keeping existing stdlib signatures (components, scc) working without breaking ports. Reverse: unify record and tuple syntax under one AST form once all stdlib signatures migrate.

33.2. One hidden runtime slot per fresh declaration site, saved and restored on function re-entry. Each domain D = <expr> declaration owns one (lo, len) slot in both cpl-interp and cpl-codegen (generic functions specialize per domain and read the slot directly with no hidden witness parameter). Shared Program::fn_guarded_domains collects local domains defined in a function body that do not escape through its return type; cpl-interp saves/restores them on function entry/exit and cpl-codegen emits an RAII cpl::DomGuard at the top of the function body. Reason: zero overhead for generic code, correct recursion, escaping value-owned domains (Compressed<D, T>, Rooted<V, P>) survive return, and identical semantics across interpreter and C++. Reverse: pass explicit (lo, len) witness structs to generic functions if re-entrant closures ever need independent live instances of the same declaration site.

33.3. Fresh-domain escape checking (E0313) allows explicitly existential returns and domain-carrying structs. Returning a fresh domain value, assigning it to an outer variable, storing it into an outer container (.push/.insert/.set/.add), or capturing it in a returned closure is rejected with E0313, naming the domain and pointing to -> (domain P, ...) syntax. User-defined structs parameterized by a fresh domain (e.g. Compressed<D, T>, Rooted<V, P>) pack the domain existentially as a value-owned domain (xs.D, t.Pre). Reason: prevents dangling index-space escapes while keeping value-owned stdlib domains (compress, Rooted) ergonomic. Reverse: require explicit domain D field annotations on domain-carrying structs instead of inferring from struct type arguments.

33.4. Runtime-bounded fields in read() records (w: 0..=m) keep Int arithmetic and validate against the runtime bound. let edges: [0..m](u: V, v: V, w: 0..=m) = read() validates 0 <= w <= m in both interpreter (R0001) and C++ (cpl::read_in(0, m)), preserving Int arithmetic on e.w without duplicating the maximum constant. Reason: resolves research/frictions/cf2222f.md. Reverse: none needed; this is general range-type lowering.