On this page

0022. Closed enums and flat exhaustive match

Context

Records need a sum-type counterpart for explicit alternatives. Exhaustive matching must teach missing cases and stay simple enough for both backends. The M4 implementation plan fixes syntax, diagnostics and representation.

Decision

Declare enum Shape { Circle(i64), Rect(i64, i64), Empty }. Payloads are positional types; use a record for named fields. Constructors are qualified: Shape.Circle(3) and Shape.Empty. Locals take precedence over type names. Enums are nominal values with structural equality: tag first, then payload in declaration order, strings by bytes. Reject by-value cycles (E0410).

match s { Circle(r) => r * r, Rect(w, h) => w * h, Empty => 0 } is an expression over unions only. Arms end at newline, comma or closing brace. Each body is one statement or a braced block. Reaching arms agree in type when a value is used; divergent arms contribute no value. Discarded tails still run for effects. Evaluate the scrutinee exactly once.

Patterns are flat variant names, optionally qualified, with names or _ for payload slots. A(x, y) | B(y, x) binds the same names and types, even at different positions. A newline may follow |, never precede it. Binders obey ADR-0013; sibling arms may reuse names. No wildcard arm on a closed union. Linear coverage checking lists every missing variant in declaration order (E0502); wildcard help likewise lists every variant (E0503).

Use variant A from the orchestrator's layout decision: uint32_t tag and a C union of per-variant payload structs. Omit empty payload structs and omit the union member entirely for all-nullary enums. Compound literals initialize values. Equality never reads padding. Interpreter values use Union { tag, fields: Rc<[Value]> }. See ADR-0023 for Switch and Payload.

Alternatives considered

Consequences

Enums and matches share layouts and exhaustive Switch IR on both backends. No new runtime trap kinds or dependencies. ADR-0028 defines canonical arms; new cases require explicit source edits rather than falling into a wildcard.