# RFC 0030: Open polymorphic variants | | | | --- | --- | | Status | Implemented (HM typechecker, evaluator, and VM); Effect 4 TypeScript/Schema lowering for structural `Variant` types remains planned | | Created | 2026-12-03 | | Scope | Structural open and closed sum types (`Variant`), ad-hoc variant injection (`variant`), row-polymorphic unification, exhaustive `match`, evaluator and VM parity | | Direction | Complete row polymorphism for sum types alongside open records (`{:name String & r}`), reusing the existing `Row` representation (`RExtend`, `RVar`, `REmpty`) | ## Summary Forma already has structural open records (`{:name String & r}`), where a function can require only the fields it reads and compose with any larger record. Sum types, however, previously required nominal `(type ... (Tagged ...))` or `(error ...)` declarations up front. This RFC adds **structural open polymorphic variants** as the dual of open records: - **Type syntax:** `(Variant (NotFound {:id String}) (Timeout String) & e)` for an open variant row with tail variable `e`, and `(Variant (NotFound {:id String}) (Timeout String))` for a closed structural variant. Nullary cases omit the payload type: `(Variant Ok (Err String) & e)`. - **Value syntax:** `(variant :NotFound {:id id})` or `(variant :Ok)` constructs a structural variant directly without any prior `(type ...)` or `(error ...)` declaration. - **Inference:** `(variant :NotFound {:id "1"})` infers the open row-polymorphic type `(Variant (NotFound {:id String}) & r)`, which unifies with any larger variant type that includes `NotFound`. - **Composition:** Two independent functions returning `(Variant (NotFound {:id String}) & e)` and `(Variant (Timeout String) & e)` compose automatically in branches or collections to `(Variant (NotFound {:id String}) (Timeout String) & e)` with zero pre-declared wrapper enum. - **Exhaustive matching:** `match` narrows payload types per arm, enforces exhaustiveness on closed `Variant` types, and requires a wildcard `_` (or residual arm) on open `Variant` types. ## Motivation Nominal `Tagged` unions work well for closed domain models, but they force up-front coordination whenever independent helpers can return distinct failure or event cases: ```lisp ;; No shared enum declaration needed: (define find-user [id] (if (= id "0") (variant :NotFound {:id id}) (variant :Ok {:name "Ada"}))) (define fetch-remote [id] (if (= id "slow") (variant :Timeout "upstream timed out") (find-user id))) ``` In `fetch-remote`, the two branches produce `(Variant (Timeout String) & e)` and `(Variant (NotFound {:id String}) (Ok {:name String}) & e)`. Row unification merges their cases automatically into: ```lisp (Variant (Timeout String) (NotFound {:id String}) (Ok {:name String}) & e) ``` This mirrors OCaml's polymorphic variants and Koka/Row-polymorphic sum types while staying idiomatic to Forma's keyword-tagged Lisp syntax and reusing the HM checker's existing row machinery. ## Surface syntax ### Type expressions ```lisp ;; Open variant row (tail variable `e` represents additional possible cases) (Variant (NotFound {:id String}) (Timeout String) & e) ;; Closed structural variant (no tail variable) (Variant (NotFound {:id String}) (Timeout String)) ;; Nullary cases alongside payload-carrying cases (Variant Ok (Err String) & e) (Variant Pending Running Done) ``` Case labels are capitalized symbols (matching `Tagged` constructor naming). A case with a payload is written `(Tag PayloadType)`; a nullary case is written `Tag`. An optional `& tail` at the end introduces a row tail variable (`RVar`); omitting `& tail` closes the variant row (`REmpty`). ### Value expressions ```lisp ;; Payload-carrying structural variant (variant :NotFound {:id id}) (variant :Timeout "500ms exceeded") ;; Nullary structural variant (variant :Ok) ``` `(variant :Tag payload)` evaluates `payload` and constructs a structural variant tagged with `:Tag`. `(variant :Tag)` constructs a nullary structural variant. No prior `type` or `error` declaration is required. ### Pattern matching `match` inspects structural variants and narrows the payload type in each arm: ```lisp (: describe (-> (Variant (NotFound {:id String}) (Timeout String)) String)) (define describe [err] (match err (variant :NotFound {:id id}) (str "missing " id) (variant :Timeout msg) (str "timeout: " msg))) ``` For an open variant type `(Variant (NotFound {:id String}) & e)`, the match must include a fallback `_` arm to handle the open tail: ```lisp (define describe-open [err] (match err (variant :NotFound {:id id}) (str "missing " id) _ "other error")) ``` ## Type system (`TVariant`) Open and closed structural variants are represented in the HM typechecker as `TVariant(row)`, reusing the existing row algebra (`Row` = `RExtend` | `RVar` | `REmpty`): | Surface type | Internal representation | | --- | --- | | `(Variant (NotFound {:id String}) & e)` | `TVariant(RExtend("NotFound", TRecord({id: String}), RVar(e)))` | | `(Variant (NotFound {:id String}) (Timeout String))` | `TVariant(RExtend("NotFound", ..., RExtend("Timeout", String, REmpty)))` | | `(Variant Ok & r)` | `TVariant(RExtend("Ok", TUnit, RVar(r)))` | ### Inference and unification 1. **Injection:** `(variant :Tag expr)` infers `expr : T` and assigns the expression type `TVariant(RExtend(Tag, T, RVar(fresh)))`. Nullary `(variant :Tag)` uses `TUnit` as the payload type. 2. **Row unification:** Unifying `TVariant(r1)` with `TVariant(r2)` delegates to standard Remy-style row unification: - Common labels unify their payload types (`NotFound` with `{:id String}` vs `{:id Int}` is rejected as a payload type mismatch). - Labels present only on one side are pushed into the other side's open tail variable `RVar`. - Unifying a missing label against `REmpty` (a closed variant) reports a compile-time type error. 3. **Exhaustiveness:** - Against a closed `TVariant` (tail `REmpty`), `match` checks that every label in the row is covered; missing cases are compile-time errors. - Against an open `TVariant` (tail `RVar`), `match` requires a wildcard `_` arm (unless row-polymorphic residual elimination is added in a future stage). ## Runtime semantics Both the tree-walking evaluator and the bytecode VM represent structural variants uniformly with their tag and payload (unit for nullary cases), ensuring full evaluator/VM parity for constructing, comparing, and pattern-matching structural variants. ## Relationship to other Forma features - **Open records ([RFC 0005](./0005-row-operations.md), [RFC 0006](./0006-qualified-rows.md)):** Open records (`{:name String & r}`) provide row polymorphism for products; open polymorphic variants (`(Variant (Tag T) & e)`) provide the exact dual for sums. - **Nominal `Tagged` unions and `error` declarations:** Nominal `Tagged` types (including GADTs and existentials) and `error` declarations remain the primary choice for schema-backed domain models and Effect 4 `Schema.TaggedError` generation. Structural `Variant` types complement them for ad-hoc, composable return cases and local error unions. - **Direct-style effects ([RFC 0003](./0003-direct-style-effects.md)):** Structural open variants lay the type-theoretic groundwork for open, composable error rows without requiring upfront global error enums. ## Planned follow-ups (not yet implemented) - **Effect 4 TypeScript / Schema lowering:** Emitting structural `Variant` types as discriminated TypeScript unions and `Schema.Union` codecs in the Effect codegen backend. - **Row-polymorphic residual matching:** Narrowing an open variant in a `match` arm by binding the unmatched cases with a smaller row tail (eliminating a handled case from `e` without a catch-all `_`). - **Disjointness / lacks constraints:** Sharing row-constraint machinery with [RFC 0006](./0006-qualified-rows.md) for higher-order variant combinators.