Skip to content

case: decoded-data and qualified type patterns - #285

Merged
vito merged 10 commits into
shared-displayfrom
case-on-decoded
Nov 9, 2026
Merged

vito merged 10 commits into
shared-displayfrom
case-on-decoded

Conversation

@vito

@vito vito commented Nov 9, 2026 •

Copy link
Copy Markdown
Owner

case can branch on what decoded data holds. Each arm names a type; an arm matches when the data has that type's shape, and the first matching arm wins. Only the matching arm's data is then converted, exactly like a cast. Patterns can now also be list and map types ([Decoded!], Map[Decoded!]), but only on decoded data.

case (d) {
  n: Int => `the number ${n}`
  items: [Decoded!] => `${items.length} items`
  fields: Map[Decoded!] => `fields ${fields.keys.join(", ")}`
  else => "something else"
}

What changes

  • Grammar.
    • A case clause accepts binding: [T] => and binding: Map[T] =>, with an optional trailing ! that changes nothing.
    • The parser and the tree-sitter grammar are regenerated, and the formatter prints the new patterns.
    • Rescue clauses keep plain named patterns.
    • Code that read a pattern's name (fragment hints, catch modernization) now uses PatternName, so it can't dereference a missing name.
  • Type checking. On a Decoded operand:
    • Each arm's type is resolved and checked as a decode target. Type variables, interfaces and unions are rejected, because data never materializes as them, including an interface every match would need inside the type (a non-null field without a default: ..., which Holder.inner holds).
    • else is required when there is a type arm, unless an x: Decoded arm takes the rest (on a nullable operand, together with a null => arm). Value-only cases (null => ...) need no else.
    • Duplicate arms, arms after a Decoded arm, and arms an earlier arm covers are unreachable-clause errors:
      • Int after Float;
      • a String, scalar or enum arm after a String or custom-scalar arm, either of which takes every string;
      • anything after a hookless schema scalar, which takes any data;
      • an object or map arm after Map[Decoded];
      • a list or map arm after one whose elements cover its elements, e.g. [Int!] after [Decoded].
    • A list or map pattern on any other operand is an error.
  • Evaluation (shape matching, new decoded_match.go). Arms are tried in order. An arm matches when the data has its type's shape: the right kind (number, string, boolean, list, map or object), and for lists, maps and objects the same recursively. An object must hold every key the type requires (non-null, no default), under the decode's own field names (@FORMAT.field, @FORMAT.ignore) and strictness (a strict decode's unknown keys fail the match). A custom-scalar arm matches any string. The check runs no user code: no scalar new(), constructors or validators.
    • The first matching arm's data is then materialized like a cast. Its errors are the case's errors, not a fall-through: a constructor's raise, or a scalar hook rejecting the string.
    • On a nullable Decoded operand, null data takes only a null arm or else, however the null arrived. On Decoded!, it goes to a Decoded arm or else.
  • Decoding fix (also affects casts): an explicit null for a non-null field with a default now takes the default. Before, the non-null field held null. A Decoded! field is the exception: it holds null data as it is, so its value round-trips.
  • Qualified named patterns. A case or rescue clause accepts binding: Lib.Type =>.
    • Grammar: new CaseClause/RescueClause alternatives with Id . qualifiers (as in inline fragments), stored as CaseClause.PatternBase. The parser and tree-sitter grammar are regenerated, with a tree-sitter corpus case.
    • Resolution: a qualified pattern resolves like the same qualified type anywhere else. On a named union it is found among the members by identity, so it can name an imported type that a local one shadows.
    • Readers of the pattern's name use the qualified spelling: unreachable-clause and rescue messages, mutation fragment hints, the formatter, and try/catch migration. LSP rename does not treat a qualified pattern's last segment as a bare reference.
    • NamedTypeNode.Infer no longer panics on a qualifier that has no member types (Decoded.A, also let x: Decoded.Foo).
  • Docs: json-yaml.md ("Keeping data undecoded" and the defaults paragraph), the language guide's type patterns section, and the skill references. The documented caveats:
    • 1 matches both Int and Float, so order matters;
    • a type reads only the fields it declares (extra keys pass unless the decode was strict);
    • a constructor or scalar hook that rejects the matching data is an error of the case;
    • null data matches no type arm but Decoded.

Maintainer decisions

  • Q-39 A: type patterns on a Decoded operand: the first matching arm wins, else is required, and patterns gain list and map types.

  • Q-43 A (arm nullability): every arm binds a non-null value. Null data goes to else, to a Decoded arm (on Decoded!), or to a null => value arm (on a nullable Decoded operand).

  • Q-44 D (how an arm matches): a side-effect-free shape check that runs no user code. Only the matching arm materializes, like a cast, and its errors propagate. A custom-scalar arm matches any string; a hook rejecting it is an error, not a fall-through.

  • Q-45 A: a case whose operand is a union holding decoded data (e.g. JSON.decode(t) rescue 0, typed Decoded | Int!) is a compile error asking to separate the decoded data first. Its arms would otherwise match the Int! by type and the data by shape.

  • Qualified named patterns (maintainer request): g: Lib.Greeter => works in case and rescue, on union, interface and decoded operands. This lifts a limitation that predates this PR.

  • Release note (behavior change, also for plain casts and typed decodes): when decoding into a type, an explicit null for a non-null field that has a default now takes the default. Before, the field held null despite its non-null type. Decoded! fields still keep null data. Code that relied on seeing null there should make the field nullable.

Pending Q-46 (not in this PR)

  • A trailing ! is accepted on list and map patterns but not on named ones (n: Int! => is a syntax error), as before this PR. The maintainer is considering requiring ! on every type pattern, migrated through the legacy grammar; that would be its own PR.

Testing

dang fmt, goldens reviewed, and every check (**) passes, including tree-sitter.

  • test_case_decoded covers:
    • shape matching;
    • constructor and scalar-hook errors propagating;
    • ignored fields;
    • null for defaulted fields;
    • value-only cases;
    • nullable-operand coverage;
    • null consistency;
    • optional interface fields.
  • Error tests:
    • case_decoded_needs_else
    • case_list_pattern_needs_decoded
    • case_decoded_type_variable
    • case_decoded_interface_pattern
    • case_decoded_nested_interface
    • case_decoded_duplicate_arm
    • case_decoded_covered_arm
    • case_decoded_int_after_float
    • case_decoded_nullable_catch_all
    • case_decoded_string_after_scalar
    • case_decoded_list_after_any_list
    • case_decoded_union_operand
    • qualified_type_pattern_not_member
    • qualified_type_pattern_unknown
  • New test_qualified_type_pattern (union, interface, inline union, decoded and rescue operands, with a shadowing local type; the Lib fixture gains an error type), and TestRenameSkipsQualifiedTypePatterns in pkg/lsp.
  • Reviewed with the multi-agent reviewer over five rounds, the last at 25535e7. Its findings are addressed, except the Q-46 item above.

vito added 2 commits November 9, 2026 16:25
A `case` on Decoded data matches type patterns by materializing: an arm
matches when the data materializes at its type, the first match wins, and
`else` is required, since data may match none. Patterns may also be list
and map types (`items: [Decoded!]`, `obj: Map[Decoded!]`), for decoded
data only; the grammar, regenerated parser and tree-sitter grammar, and the
formatter accept them. Arms bind non-null values, so null data goes to a
`null` arm or `else` (pending Q-43).

Rescue clauses keep plain named patterns; code that read a pattern's name
(fragment hints, catch modernization) uses PatternName, so a list or map
pattern never dereferences a missing name.

Signed-off-by: Alex Suraci <[email protected]>
Review of case on Decoded:

- A pattern type with a type variable (`[a!]`) or an interface/union, which
  data can never materialize as, is a compile error rather than a silently
  dead arm or raw data at an arbitrary type.
- Duplicate arms, and arms after an `x: Decoded` arm, are unreachable-clause
  errors; a Decoded arm takes the rest, so it stands in for else.
- List/map patterns accept a trailing `!` (`[Decoded!]!`), which changes
  nothing; pattern errors point at the pattern.
- Docs: null data inside a `Decoded!` goes to else or a Decoded arm (a
  `null` arm only on a nullable operand); a type whose constructor raises
  doesn't match; the language guide's type patterns mention decoded data.

Signed-off-by: Alex Suraci <[email protected]>
@vito
vito added this pull request to stack #282 November 9, 2026 16:32
@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: 72148a8
Status: ✅  Deploy successful!
Preview URL: https://861b8e7c.dang-3kk.pages.dev
Branch Preview URL: https://case-on-decoded.dang-3kk.pages.dev

View logs

vito added 3 commits November 9, 2026 17:40
Q-44 D: an arm on decoded data matches by a side-effect-free check of the
data's shape (its kind, list/map/object structure, and every required key
present, recursively, under the decode's field names and strictness). The
check runs no scalar hooks, constructors or validators. Only the matching
arm's data is then materialized, exactly like a cast, so user code runs at
most once and its errors propagate: a constructor's raise or a scalar hook
rejecting the data is the case's error, not a fall-through. A custom-scalar
arm matches any string. Null data still matches no type arm (Q-43 A).

Signed-off-by: Alex Suraci <[email protected]>
Fixes from review of shape matching:

- An @JSON.ignore'd (ignored) field reads no key, so a type needing it
  (non-null, no default) no longer matches only to fail converting.
- Decoding an explicit null into a non-null field with a default now takes
  the default instead of leaving null in a non-null field; the shape check
  agrees.
- `else` is required only when the case has a type arm: value-only cases on
  decoded data (`null => ...`) compile as before.
- On a nullable Decoded operand, a `Decoded` arm plus a `null` arm covers
  every value, as on Decoded!.
- A pattern type holding an interface or union in its fields is rejected
  statically (`..., which Holder.inner holds`), since such an arm could only
  fail.

Signed-off-by: Alex Suraci <[email protected]>
Second review round on shape matching:

- On a nullable Decoded operand, null data takes only a `null` arm or else,
  however it arrived (straight from decode, through a parameter, out of a
  map); before, a `Decoded` arm ahead of `null =>` took a let-bound null but
  not a passed one. On Decoded!, null data still goes to a Decoded arm.
- A nullable operand with a Decoded arm but no `null` arm now says it needs a
  `null` arm or an else.
- The nested-interface check only rejects interfaces every match needs
  (reached through non-null fields without defaults): a type with an
  optional interface field matches when the field is absent.
- Arms an earlier arm covers are unreachable-clause errors: Int after Float,
  object/map arms after Map[Decoded!], list arms after [Decoded!].
- Docs: decoded data is a case operand in the type-pattern section; the
  ignored-field caveat names the decoding format, not every codec.

Signed-off-by: Alex Suraci <[email protected]>
vito added 4 commits November 9, 2026 18:11
Final review round on case-on-decoded:

- An explicit null for a defaulted Decoded! field is kept, not replaced by the
  default: Decoded! holds null data, so a value whose field is null encoded
  as null and must decode back the same.
- Covered arms are unreachable-clause errors in more cases, matching what the
  shape check does: a String or custom-scalar arm takes every string, so it
  covers later String, scalar and enum arms; a hookless schema scalar takes
  any data; list and map arms cover those whose elements their elements
  cover (`[Decoded]` covers `[Int!]`), with element nullability.

Signed-off-by: Alex Suraci <[email protected]>
Q-45 A: a `case` whose operand is an inline union with a Decoded option, such
as `JSON.decode(t) rescue 0` (Decoded | Int!), is a compile error asking to
separate the decoded data first. Its arms would match the other options by
type and the decoded data by shape, and before this the decoded part quietly
fell through to else.

Signed-off-by: Alex Suraci <[email protected]>
`g: Lib.Greeter =>` now parses in `case` and `rescue` clauses, on union,
interface and decoded operands alike. A qualified pattern resolves like the
same qualified type written anywhere else, so it can name an imported type
that a local one shadows. On a named union it is found among the members by
identity; unqualified patterns resolve as before.

Readers of a pattern's name (unreachable-clause and rescue messages, mutation
fragment hints, the formatter, try/catch migration) use the qualified
spelling. Parser and tree-sitter grammar regenerated. The `!` on named
patterns is untouched (Q-46).

Signed-off-by: Alex Suraci <[email protected]>
- A qualified pattern's name isn't walked as a bare symbol, so renaming a
  local type that shadows the import (the case qualified patterns exist
  for) no longer rewrites `Lib.Dog` patterns.
- A qualifier that names no type scope (`Decoded.A`) is an error instead of
  a panic in NamedTypeNode.Infer; this also fixes `let x: Decoded.Foo`.
- Each qualifier keeps its own source location, and a bad qualified pattern
  on decoded data reports `unknown type X in type pattern` like on any
  other operand.

Signed-off-by: Alex Suraci <[email protected]>
@vito
vito marked this pull request as ready for review November 9, 2026 18:42
@vito vito changed the title case: type patterns on decoded data case: decoded-data and qualified type patterns Nov 9, 2026
The guide said only an interface pattern can make a later type pattern
dead, but on decoded data any covering arm does (Int after Float). And a
schema's scalar without a body holds data of any shape, so its arm on
decoded data matches any data, not only strings; the guide and skill
said nothing about it.

Signed-off-by: Alex Suraci <[email protected]>
@vito
vito merged commit 7fdc20b into main Nov 9, 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