Skip to content

case: type switch with T! patterns (Dang 2.4) - #286

Merged
vito merged 12 commits into
mainfrom
case-type-switch
Nov 10, 2026
Merged

vito merged 12 commits into
mainfrom
case-type-switch

Conversation

@vito

@vito vito commented Nov 9, 2026 •

Copy link
Copy Markdown
Owner

case is now a type switch. Every type pattern is written as the non-null type its arm binds (c: Cat! =>), and a pattern can be any type: a named type, a list, a map, or a record.

describe(ints: Boolean!): String! {
  let xs = if (ints) { [1, 2] } else { ["a"] }   # [Int!]! | [String!]!
  case (xs) {
    is: [Int!]! => `ints ${is.length}`           # exhaustive: no else needed
    ss: [String!]! => `strings ${ss.join(",")}`
  }
}

This bumps the language to Dang 2.4 (Version2_4, now CurrentVersion). PRs that change the language and land after this one should reuse 2.4 rather than add another version.

Merge order

Based on main; #291 and #292 stack on top.

What changes

Q-46: ! is required on type patterns

  • Applies to case on unions, interfaces and anything else, to rescue, and to decoded arms.
  • Grammar: one clause form, binding: TypePattern =>.
    • A named pattern is still spelled as a Symbol, optionally qualified, so lowercase type names (common in GraphQL schemas) still match.
    • Any other pattern goes through the Type grammar.
    • The parser and tree-sitter grammar are regenerated, with a tree-sitter corpus case for case.
  • AST: the clause keeps the type without its top-level !, which every pattern has. typePatternClause in version.go builds it and records two flags:
    • BarePattern: no ! was written where one is now required.
    • PatternBang: a ! was written. This field is spelling only; it carries the dang:"spelling" tag, which compareAST now skips.
  • Versions:
    • Before 2.4 (barePatterns()), a bare pattern means the same as the ! form, and the formatter prints each pattern as written.
    • From 2.4, a bare pattern is an inference error with a hint: a type pattern is the non-null type its arm binds: write `c: Cat! =>` .
    • dang migrate and dang fmt -w add the !. A source already written with ! everywhere migrates unchanged.
  • Unchanged: legacy try/catch keeps its bare-name clauses.
  • Fixtures:
    • The tracked fixture projects move to 2.4: tests/, tests/importcalc/, demos/github/ and pkg/lsp/testdata/. tests/importcalc declares its own version, so it was bumped explicitly. Their sources were reformatted with dang fmt under 2.4, which adds the !. I couldn't run dang migrate itself from my environment, but MigrateSource is covered by TestVersionTypePatterns and the new migration fixture.
    • The existing 1.0→2.0 and 2.0→2.1 migration fixtures are untouched. A new tests/testdata/migrations/2.1-to-2.4 fixture covers union, interface, decoded, list and map patterns, rescue clauses, try/catch and patterns already written with !.
  • Keyless projects: version: a dang.toml without a version is current #287 drops DefaultVersion, so a dang.toml without a dang key follows CurrentVersion like source no dang.toml governs. Once both land, keyless projects are 2.4 and need the !; to keep bare patterns they pin dang = "2.1" (or migrate with dang migrate --from 2.1).

Q-47: case is a general type switch

  • When a pattern is accepted: it must overlap the operand's type (typesOverlap). For named types, overlap means one is a subtype of the other, or they share a union member. It is conservative: two unrelated interfaces don't overlap, even if one type implements both.
    • Anything else is an error: pattern P can't match a value of type O.
    • On union or interface operands, the existing not a member of union / does not implement interface errors stay.
    • On a union narrowed by inline fragments, only its members are accepted, since its values hold only the selected fields.
    • A list pattern on a lazy GraphQL object list is an error with a hint to select fields first.
  • How a value matches (valueInhabits, new type_switch.go):
    • Named types match by identity, implementation or membership, as before.
    • Lists and maps match by their recorded element type (Q-48 below).
    • Records match by their field set and field types.
    • Decoded keeps case: decoded-data and qualified type patterns #285's shape matching.
    • Null never matches a type arm.
    • A union operand holding Decoded is still a compile error.
  • Checks:
    • Exhaustiveness (typeCoveredBy) covers inline unions of any pattern kind, so [Int!]! | [String!]! needs no else.
    • Unreachable arms (typeFits) cover the new kinds. That includes [Cat!]! after [Animal!]!, and any arm after one that takes every value of the operand.
    • A nullable operand needs a null arm or else to be exhaustive.
  • IDs: a GraphQL ID is a plain string at runtime. An ID! pattern takes such strings only where the operand's type holds no String, so String! | ID! arms aren't decided by order.

Q-48 option B: static element types

  • Recorded types: list and map literals, selections over lists (including GraphQL results), + and += on lists, map/flatMap, and Map.with/merge now record their static element type as the runtime ElemType. Before, a list recorded its first element's runtime type, and selection lists recorded nothing.
  • Typed boundaries: a boundary of a concrete type (annotation, parameter, return) re-records the target type. A generic [a]! parameter keeps what the list recorded.
  • Fallbacks: where the recorded type has type variables, the elements decide. If an exhaustive case still finds no arm by recorded types, it retries by contents before reporting an internal error.
  • Audit of ElemType readers: on this base they are matching, the stdlib's propagation (filter/sort/take…, which keep subsets) and ListValue.Type(). Display and encoding read elements, not ElemType.

Release note

  • Dang 2.4: type patterns take a !. A case, rescue or decoded-data pattern is written as the non-null type its arm binds: c: Cat! =>, e: Error! =>, items: [Decoded!]! =>, g: Lib.Greeter! =>.
    • Projects declaring dang = "2.1" (or 2.2/2.3) keep working unchanged. Run dang migrate to move to 2.4, which adds the !.
    • dang init now writes dang = "2.4". Source that no dang.toml governs is read as 2.4, so bare patterns there are errors with a hint.
    • A dang.toml without a dang key follows the running Dang (version: a dang.toml without a version is current #287), so it is read as 2.4 too: pin dang = "2.1" to keep it, or move it with dang migrate --from 2.1.
  • case is a type switch.
    • Patterns may be any type: lists, maps and records too, not just decoded data.
    • A pattern must be a type the operand may hold. Patterns that can't match are compile errors; previously, patterns were limited to union and interface operands.
    • Lists and maps match by the element type they were built with, not by their contents. A list typed [Animal!]! doesn't match [Cat!]! even if every element is a Cat.
    • Unreachable arms after a pattern that takes every value of the operand are now errors.
  • Runtime element types changed. Lists and maps now carry their static element type rather than their first element's type.

Testing

  • Checks: all 15 (**) pass at the head after rebasing onto main, including docs, fmt/stale, generate/stale, tree-sitter and editor highlights. On the rebase, empty literals keep dang: empty collections carry their inferred type #278's resolved element type, and non-empty literals, materialized boundaries and map results record their static element type resolved through dang: empty collections carry their inferred type #278's runtime type arguments.
  • New tests:
    • tests/test_case_type_switch.dang: named, supertype and union patterns; nullable operands; list, map and record switches; recorded vs. built element types; the generic fallback and generic boundaries; concatenation; Map.with/merge; lowercase type names; String! | ID!.
    • GraphQL cases in test_graphql_abstract_case.dang:
      • an ID arm;
      • IDs in a generic list;
      • a resolved union handle with an interface pattern;
      • selection lists.
    • Error goldens:
      • case_bare_type_pattern
      • case_type_pattern_disjoint
      • case_list_pattern_disjoint
      • case_nullable_operand_not_exhaustive
      • case_unreachable_list_arm
      • case_unreachable_after_total_arm
      • case_type_pattern_type_variable
      • case_graphql_object_list
      • case_narrowed_union_interface
    • TestVersionTypePatterns:
      • bare patterns parse under 2.1;
      • 2.1 formatting round-trips bare, banged and mixed patterns byte for byte;
      • 2.4 rejects bare patterns with the hint;
      • migration adds only the missing !.
    • versions now includes 2.4. TestKeywordNamesRoundTrip also covers type-pattern bindings.
    • After rebasing onto main, the analysis package's clause-binding test writes its rescue pattern with !.
  • Self-review: three rounds with the multi-agent reviewer. Its IMPORTANT findings are fixed, with these exceptions:
    • A case on a mutation-reached union with an interface pattern every member implements still raises at runtime. That is consistent with the existing design: mutation handles are never resolved, and patterns covering every member already behave the same way.
    • A tree-sitter-only gap from case: decoded-data and qualified type patterns #285 remains: m: Map[Int!]! => parses with an ERROR node, because the lexer reads Map as a word token. Highlighting only.

Open

  • CommonSupertype picks arbitrarily between an interface and a union that both contain two types (e.g. [Cat(), Dog()] with Animal and Pet). Which list arm matches such a literal follows that pre-existing choice.

vito added 3 commits November 9, 2026 20:06
A type pattern is now written as the non-null type its arm binds
(`c: Cat! =>`) and may be any type: named types match by identity as
before, lists and maps by their element types, records by their fields.
A pattern must overlap the operand's type, and unreachable-arm and
exhaustiveness checks cover the new kinds, so `[Int!]! | [String!]!` can
be covered without an else.

Bare patterns parse before Dang 2.4 (new Version2_4, now
CurrentVersion) and migrate by adding the `!`; in 2.4 they are an error
with a hint. The tracked test, demo and LSP fixture projects move to
2.4, migrated with dang fmt.

Lists, maps and selection results now record their static element type
as ElemType, instead of the first element's runtime type, and an arm
matches by that type. Where it still holds type variables the elements
decide, and an exhaustive case falls back to the contents rather than
failing.

Signed-off-by: Alex Suraci <[email protected]>
The guide, error pages and skill references write every type pattern
with its `!`, describe case as a type switch over lists, maps and
records, and explain that a list matches by the element type it was
built with, not by what it holds. Example dang.toml files show 2.4.

Signed-off-by: Alex Suraci <[email protected]>
- Formatting keeps a type pattern's `!` as written where it is optional
  (before 2.4): the pattern records it (PatternBang), a spelling-only
  field that migration's AST comparison ignores. Formatting under 2.1
  used to drop the `!` from `[Decoded!]!`, which kept the meaning but
  not the spelling.
- A list or map passing a generic parameter keeps the element type it
  recorded, instead of recording the type variable; only a concrete
  target re-records it.
- `+` and `+=` on lists record the static type of the result, not a
  join of the operands' recorded types.
- A list pattern on a GraphQL object list, which is a lazy handle until
  its fields are selected, is a compile error with a hint, instead of
  type-checking and never matching.
- An ID pattern matches an ID, which is a string at runtime.

Signed-off-by: Alex Suraci <[email protected]>
@vito
vito added this pull request to stack #282 November 9, 2026 20:48
@cloudflare-workers-and-pages

cloudflare-workers-and-pages Bot commented Nov 9, 2026 •

Copy link
Copy Markdown

Deploying dang with  Cloudflare Pages  Cloudflare Pages

Latest commit: 97a94d6
Status: ✅  Deploy successful!
Preview URL: https://49502beb.dang-3kk.pages.dev
Branch Preview URL: https://case-type-switch.dang-3kk.pages.dev

View logs

An interface pattern on decoded data now points at the types
implementing it; "match its member types" stays for unions, which get
their own error test.

Signed-off-by: Alex Suraci <[email protected]>
Base automatically changed from case-on-decoded to main November 9, 2026 23:00
vito added 7 commits November 9, 2026 18:00
The skill references no longer describe the removed decoded-only rule
for list and map patterns. They say which types a union or a plain
object operand accepts as patterns, and that a generic parameter keeps a
list's recorded element type.

Signed-off-by: Alex Suraci <[email protected]>
- A named type pattern is spelled as a Symbol again, so a type named in
  lowercase (as GraphQL schemas may name them) can be matched; other
  patterns go through the Type grammar.
- A union narrowed by inline fragments takes only its members as
  patterns: an interface or union a member belongs to would bind a
  value holding only the selected fields as a type with others.
- An ID pattern takes a plain string (a GraphQL ID result) only where
  the operand can't be a String, so `String! | ID!` arms aren't decided
  by order; matchesType no longer treats strings as IDs.

Signed-off-by: Alex Suraci <[email protected]>
Say that a pattern must relate to the operand by identity,
implementation or union membership, so two unrelated interfaces don't
overlap even when one type implements both.

Signed-off-by: Alex Suraci <[email protected]>
- Map.with and Map.merge record a value type both sides fit, so a map
  that gains a value of another type no longer matches its old one.
- An ID pattern takes plain strings anywhere in the pattern (a list
  of IDs built in a generic body, say) when the operand's type holds no
  String, through a matchMode passed to valueInhabits.
- A type arm after one that takes every non-null value of the operand
  is an unreachable-clause error.

Signed-off-by: Alex Suraci <[email protected]>
The skill references said the `!` was required "since Dang 2.4" and how
to migrate to it; the dang.toml reference already covers older projects.
The guide called a total pattern "fine", answering the old
union-or-interface rule, and its list of types a pattern may name left
out a union with a qualifying member. A rescue pattern can be any error
type, a union of Error implementers included, and the grammar notes
still sketched a rescue clause as a bare type name.

Signed-off-by: Alex Suraci <[email protected]>
The analysis tests from main analyze source as the current version,
which requires a type pattern's `!`.

Signed-off-by: Alex Suraci <[email protected]>
A rescue arm only binds raised errors, but a union pattern such as
`E1 | Foo` passed the overlap check on Error! through its error member
alone. Every option or member of a rescue pattern (nested unions
included) must now overlap Error, or the clause is a compile error
naming the member that is never raised.

Signed-off-by: Alex Suraci <[email protected]>
@vito
vito force-pushed the case-type-switch branch from 27f4f4c to 53cd9e1 Compare November 9, 2026 23:00
The union-member check is skipped for try/catch blocks, which accept
patterns that can never match as dead code in every version, so legacy
code with such a union pattern keeps compiling. The skill documents the
new rescue error.

Signed-off-by: Alex Suraci <[email protected]>
@vito
vito merged commit e4d33ad into main Nov 10, 2026
9 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant