Skip to content

Unwrap Some of a variant with an undefined case before matching it - #9206

Merged
cknitt merged 2 commits into
masterfrom
drift-9184-untagged-undefined-some
Nov 5, 2026
Merged

cknitt merged 2 commits into
masterfrom
drift-9184-untagged-undefined-some

Conversation

@cknitt

@cknitt cknitt commented Nov 3, 2026 •

Copy link
Copy Markdown
Member

A switch on option<t>, where t is a variant with an @as(undefined) case, took the wrong arm for Some of that case:

@unboxed type t = @as(undefined) U | S(string) | I(int)

let g = (x: option<t>) =>
  switch x {
  | None => "None"
  | Some(S(_)) => "SS"
  | Some(I(_)) => "SI"
  | Some(_) => "SU"
  }

g(Some(U)) // "SI", expected "SU"

Some(U) is represented by an object (Primitive_option.some), which the match has to unwrap before testing the payload. Since #8842 the match compiler skipped the unwrap whenever every payload pattern was a wildcard, a literal case other than undefined, or an untagged case with a primitive type test, on the assumption that each of them rejects the object with its own test. That assumption doesn't hold: the switch on the payload gets a case for every constructor, taken from the match's default rows for the constructors the patterns don't name (mk_failaction_pos), and the dispatch of a complete switch takes its last case without a test. So the object lands in whatever arm comes last. The same happens with a literal-only variant (@as(undefined) | @as(null) | @as("a")), where the complete switch has no default: and the function returns undefined, with a top-level _ default instead of Some(_), with an or-pattern, with a single payload case, and with an optional record field of such a type.

Fix

The pattern-based shortcut (rejects_nested_some / skip_nested_some_check) is removed. The payload is read without unwrapping only when its type rules out undefined (Typeopt.type_cannot_contain_undefined), as in the released versions (12.3.1, 13.0.0-alpha.6), which predate #8842; otherwise it goes through valFromOption. Whether the object would reach the right arm can only be decided from the finished switch, not from the patterns, and the shortcut only fired for payload types with an @as(undefined) case (or an unknown representation), so it isn't worth that machinery.

Changes to generated code of correct matches

Three existing functions now unwrap the payload, and their result is unchanged. In each one the dispatch happened to send the object to the right arm:

  • decodeGroup and decodeNull in tests/tests/src/pattern_match_json.mjs: dict{"id": String(id), ...} and dict{"field": Null} on a JSON-like type with an Undefined case. Every arm except String (or Null) ran the default action.
  • stringOrOther in tests/tests/src/pm_opt_fields_mixed_test.mjs: {u: String(s)}, {u: Null}, _ on an optional field of a type with an Undefined case. The Object case had no arm, so the object went to the default.

Each now gets a presence test plus a valFromOption call. No other output in tests/tests, tests/belt_tests, tests/commonjs_tests or the runtime changes.

Tests

  • New tests/tests/src/option_untagged_undefined_test.res: Some of the @as(undefined) case, both as a constant Some(U) and built at run time through an @inline(never) function, against catch-all Some(_) arms in both payload orders, an explicit Some(U) arm, an or-pattern, a single named case, a top-level default, a literal-only variant, a variant with literal and payload cases (complete and incomplete), an object payload, a single payload case, and an optional record field. Seven of its eight tests fail on master.

Changelog

No fragment (changelog:skip): the bug came with #8842, which no release contains, and the released versions take the right arm.

Fixes #9184

🤖 Generated with Claude Code

https://claude.ai/code/session_01Kbf3gGhHjzBTXqSo8Dckpb

@github-actions

github-actions Bot commented Nov 3, 2026 •

Copy link
Copy Markdown

Changelog

No changelog entry.

Semantic Diff

2 commits · Full page

Unwrap Some of a variant with an undefined case before matching it

6ddec83 · cknitt + Claude · Nov 03, 2026, 18:34 UTC

Why

A switch on option<t>, where t has an @as(undefined) case, read the payload without unwrapping the object that represents Some of that case whenever the payload patterns were wildcards, literal cases or untagged cases, assuming each would reject the object with its own test. But the switch on the payload gets a case for every constructor, from the match's default rows for those the patterns don't name, and takes its last case without a test, so Some(U) reached the arm of another case or no arm at all. The payload is now unwrapped unless its type rules out undefined.

JS modified (switch on an option of an untagged variant)

@unboxed type t = @as(undefined) U | S(string) | I(int)

let g = (x: option<t>) =>
  switch x {
  | None => "None"
  | Some(S(_)) => "SS"
  | Some(I(_)) => "SI"
  | Some(_) => "SU"
  }

js · Before: g(Some(U)) returns "SI" · After: g(Some(U)) returns "SU"

 function g(x) {
-  if (x !== undefined) {
-    if (x === undefined) {
-      return "SU";
-    } else if (typeof x === "string") {
-      return "SS";
-    } else {
-      return "SI";
-    }
-  } else {
+  if (x === undefined) {
     return "None";
   }
+  let tmp = Primitive_option.valFromOption(x);
+  if (tmp === undefined) {
+    return "SU";
+  } else if (typeof tmp === "string") {
+    return "SS";
+  } else {
+    return "SI";
+  }
 }

Fixes #9184

Review

  • Which correct matches get the extra unwrap? Those whose dispatch happened to send the object to the right arm, such as decodeGroup and decodeNull in pattern_match_json and stringOrOther in pm_opt_fields_mixed_test. Telling them apart needs the finished switch, so the patterns no longer decide; only payload types that can't hold undefined skip the unwrap, as before.
Drop the changelog fragment for a regression no release has

2960354 · cknitt + Claude · Nov 05, 2026, 05:55 UTC

The shortcut this branch removes came with #8842, which no release contains: 12.3.1 and 13.0.0-alpha.6 unwrap the payload whenever its type can contain undefined, so they take the right arm.

@codecov

codecov Bot commented Nov 3, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 81.74%. Comparing base (8585311) to head (2960354).

Additional details and impacted files
@@           Coverage Diff           @@
##           master    #9206   +/-   ##
=======================================
  Coverage   81.74%   81.74%           
=======================================
  Files         457      457           
  Lines       65564    65543   -21     
=======================================
- Hits        53595    53579   -16     
+ Misses      11969    11964    -5     
Files with missing lines Coverage Δ
compiler/ml/matching.ml 77.92% <ø> (-0.05%) ⬇️

... and 1 file with indirect coverage changes

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@cknitt

cknitt commented Nov 3, 2026

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 3, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-03T18:52:45.467613Z d1adb21 Manual request
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Keep them coming!

Reviewed commit: d1adb216d6

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@pkg-pr-new

pkg-pr-new Bot commented Nov 3, 2026 •

Copy link
Copy Markdown

Open in StackBlitz

rescript

npm i https://pkg.pr.new/rescript@9206

@rescript/belt

npm i https://pkg.pr.new/@rescript/belt@9206

@rescript/darwin-arm64

npm i https://pkg.pr.new/@rescript/darwin-arm64@9206

@rescript/linux-arm64

npm i https://pkg.pr.new/@rescript/linux-arm64@9206

@rescript/linux-x64

npm i https://pkg.pr.new/@rescript/linux-x64@9206

@rescript/runtime

npm i https://pkg.pr.new/@rescript/runtime@9206

@rescript/win32-x64

npm i https://pkg.pr.new/@rescript/win32-x64@9206

commit: 2960354

@github-actions

github-actions Bot commented Nov 3, 2026

Copy link
Copy Markdown

cknitt and others added 2 commits November 5, 2026 13:59
Why:
    A switch on `option<t>`, where `t` has an `@as(undefined)` case, read
    the payload without unwrapping the object that represents `Some` of
    that case whenever the payload patterns were wildcards, literal cases
    or untagged cases, assuming each would reject the object with its own
    test. But the switch on the payload gets a case for every constructor,
    from the match's default rows for those the patterns don't name, and
    takes its last case without a test, so `Some(U)` reached the arm of
    another case or no arm at all. The payload is now unwrapped unless its
    type rules out undefined.

JS modified (switch on an option of an untagged variant):
Example:
    @unboxed type t = @as(undefined) U | S(string) | I(int)

    let g = (x: option<t>) =>
      switch x {
      | None => "None"
      | Some(S(_)) => "SS"
      | Some(I(_)) => "SI"
      | Some(_) => "SU"
      }
Before (js): g(Some(U)) returns "SI"
    function g(x) {
      if (x !== undefined) {
        if (x === undefined) {
          return "SU";
        } else if (typeof x === "string") {
          return "SS";
        } else {
          return "SI";
        }
      } else {
        return "None";
      }
    }
After (js): g(Some(U)) returns "SU"
    function g(x) {
      if (x === undefined) {
        return "None";
      }
      let tmp = Primitive_option.valFromOption(x);
      if (tmp === undefined) {
        return "SU";
      } else if (typeof tmp === "string") {
        return "SS";
      } else {
        return "SI";
      }
    }

Review: Which correct matches get the extra unwrap? Those whose
dispatch happened to send the object to the right arm, such as
`decodeGroup` and `decodeNull` in pattern_match_json and
`stringOrOther` in pm_opt_fields_mixed_test. Telling them apart needs
the finished switch, so the patterns no longer decide; only payload
types that can't hold undefined skip the unwrap, as before.

Fixes #9184

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Kbf3gGhHjzBTXqSo8Dckpb
Signed-off-by: Christoph Knittel <ck@cca.io>
The shortcut this branch removes came with #8842, which no release
contains: 12.3.1 and 13.0.0-alpha.6 unwrap the payload whenever its type
can contain undefined, so they take the right arm.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Kbf3gJqm3GXKoAsUquKKWf
Signed-off-by: Christoph Knittel <ck@cca.io>
@cknitt
cknitt force-pushed the drift-9184-untagged-undefined-some branch from 41261f2 to 2960354 Compare November 5, 2026 14:02
@cknitt
cknitt requested a review from cristianoc November 5, 2026 14:16
@cknitt
cknitt disabled auto-merge November 5, 2026 14:40
@cknitt
cknitt merged commit 1a11269 into master Nov 5, 2026
26 checks passed
@cknitt
cknitt deleted the drift-9184-untagged-undefined-some branch November 5, 2026 14:40
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

changelog:skip No release notes needed

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Switch on an option of an untagged variant with an @as(undefined) case takes the wrong arm for Some of that case

2 participants