Skip to content

Test a mutable field again after a guard that may have changed it - #9131

Merged
cknitt merged 1 commit into
masterfrom
match-guard-mutation
Oct 30, 2026
Merged

cknitt merged 1 commit into
masterfrom
match-guard-mutation

Conversation

@cknitt

@cknitt cknitt commented Oct 29, 2026

Copy link
Copy Markdown
Member

Fixes #9129.

A guard can change the value being matched. The cases after a failed guard read the mutable field again, but the match compiler still trusted the tests it had made on the old value, so a switch could take a case that no longer matches and bind undefined at type int. This is upstream OCaml's #7241, fixed in OCaml 5.3.

Two changes in compiler/ml/matching.ml:

  • Contexts (as upstream does in bind_match_arg): exits that leave the binding of a mutable field or an array element forget what the tests on it found, so the code they jump to tests the value it reads again.
  • Exhaustiveness: check_partial makes a match Partial when a case has a guard and a case reads a mutable field. Before, both had to be the same case, so {c: None} => 0 | {d: true} if f() => 1 | {c: Some(x)} => x stayed Total and its last case read r.c without testing it. A Partial match has a default exit, so the cases after the guard can fail with Match_failure, as they do upstream.

Upstream tracks instead whether each argument lies below a mutable field, and whether a jump has happened, and marks only those switches Partial. Without lazy patterns, and on one thread, only a guard can change the value during a match, so the coarser rule is enough. Its cost is a failure branch at immutable positions of matches that have both a guard and a mutable field; no committed output in the stdlib, Belt or the tests changes.

Dict patterns are not affected: an entry is read once and the cases after the guard keep using that value.

New test: tests/tests/src/match_mutation_guard_test.res covers the #9129 shape and a guarded case that reads no mutable field. Both now throw Match_failure when the guard mutates the value into no case. It also checks that guards which mutate into a later case, or mutate nothing, still pick the right case.

🤖 Generated with Claude Code

https://claude.ai/code/session_01Kbf3gLpf7RN1MiRcubPgRn

Why:
    A guard can change the value being matched. The cases after it read the
    mutable field again, but the match compiler kept what its tests had found
    on the old value, so a `switch` could take a case that no longer matches
    and bind a value of the wrong type (#9129, upstream ocaml/ocaml#7241).
    Upstream fixed it in OCaml 5.3; this takes over its erasure of contexts
    and replaces its per-position totality with a simpler criterion.

Matching modified (contexts at a mutable read):
Example:
    type t = {a: bool, mutable b: (option<int>, option<int>)}
    let f = r =>
      switch r {
      | {a: true, b: (None, _)} => 1
      | {a: true, b: (Some(_), _)} if swap(r) => 0
      | {a: false} => 3
      | {b: (_, None)} => 4
      | {b: (Some(x), Some(_))} => x
      }
Before (matrix): context of the exit taken when the guard fails, Matching.compile_match
    {a: true, b: (Some(_), _)}
After (matrix): the column of the mutable read is forgotten
    {a: true, b: _}
Before (js):
    let match$1 = r.b;
    if (match$1[1] !== undefined) {
      return match$1[0];
    } else {
      return 4;
    }
After (js):
    let match$1 = r.b;
    let x = match$1[0];
    if (match$1[1] === undefined) {
      return 4;
    }
    if (x !== undefined) {
      return x;
    }
    throw {
      RE_EXN_ID: "Match_failure",
      …
    };

Matching modified (exhaustiveness after a guard):
Example:
    type flagged = {d: bool, mutable c: option<int>}
    let flagged = r =>
      switch r {
      | {c: None} => 0
      | {d: true} if clear(r) => 1
      | {c: Some(x)} => x
      }
Before (text): Matching.check_partial
    Partial when one case both has a guard and reads a mutable field
After (text): Matching.check_partial
    Partial when a case has a guard and a case reads a mutable field
Before (js):
    if (r.d && (r.c = undefined, false)) {
      return 1;
    } else {
      return r.c;
    }
After (js):
    if (r.d && (r.c = undefined, false)) {
      return 1;
    }
    let x = r.c;
    if (x !== undefined) {
      return x;
    }
    throw {
      RE_EXN_ID: "Match_failure",
      …
    };

Review: Why not upstream's per-position totality (a mut flag on each argument and a First/Following tempo)? Without lazy patterns, and on one thread, only a guard can change the value during a match, so marking the whole match Partial when it has a guard and reads a mutable field is enough. It needs no new state in the compiler; the cost is a failure branch at immutable positions of such matches too. No committed output in the stdlib, Belt or tests changes.
Review: Why are array elements not counted in check_partial? A Total match on arrays has a case matching any array, and the cases after a guard fall through to it; the contexts are still erased after an element is read.
Review: Why are dict patterns left alone? A dict entry is read once into a variable and the cases after the guard keep using it, so they see one consistent value.

Fixes: #9129
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Kbf3gLpf7RN1MiRcubPgRn
Signed-off-by: Christoph Knittel <ck@cca.io>
@github-actions

Copy link
Copy Markdown

Changelog

🐛 Bug fix

  • Test a mutable field again after a guard that may have changed it, instead of taking a switch case that no longer matches.

Semantic Diff

1 commit · Full page

Test a mutable field again after a guard that may have changed it

51592af · cknitt + Claude · Oct 29, 2026, 19:47 UTC

Why

A guard can change the value being matched. The cases after it read the mutable field again, but the match compiler kept what its tests had found on the old value, so a switch could take a case that no longer matches and bind a value of the wrong type (#9129, upstream ocaml/ocaml#7241). Upstream fixed it in OCaml 5.3; this takes over its erasure of contexts and replaces its per-position totality with a simpler criterion.

Matching modified (contexts at a mutable read)

type t = {a: bool, mutable b: (option<int>, option<int>)}
let f = r =>
  switch r {
  | {a: true, b: (None, _)} => 1
  | {a: true, b: (Some(_), _)} if swap(r) => 0
  | {a: false} => 3
  | {b: (_, None)} => 4
  | {b: (Some(x), Some(_))} => x
  }

matrix · Before: context of the exit taken when the guard fails, Matching.compile_match · After: the column of the mutable read is forgotten

-{a: true, b: (Some(_), _)}
+{a: true, b: _}

js

 let match$1 = r.b;
-if (match$1[1] !== undefined) {
-  return match$1[0];
-} else {
+let x = match$1[0];
+if (match$1[1] === undefined) {
   return 4;
 }
+if (x !== undefined) {
+  return x;
+}
+throw {
+  RE_EXN_ID: "Match_failure",
+  …
+};

Matching modified (exhaustiveness after a guard)

type flagged = {d: bool, mutable c: option<int>}
let flagged = r =>
  switch r {
  | {c: None} => 0
  | {d: true} if clear(r) => 1
  | {c: Some(x)} => x
  }

text · Matching.check_partial

-Partial when one case both has a guard and reads a mutable field
+Partial when a case has a guard and a case reads a mutable field

js

 if (r.d && (r.c = undefined, false)) {
   return 1;
-} else {
-  return r.c;
 }
+let x = r.c;
+if (x !== undefined) {
+  return x;
+}
+throw {
+  RE_EXN_ID: "Match_failure",
+  …
+};

Review

  • Why not upstream's per-position totality (a mut flag on each argument and a First/Following tempo)? Without lazy patterns, and on one thread, only a guard can change the value during a match, so marking the whole match Partial when it has a guard and reads a mutable field is enough. It needs no new state in the compiler; the cost is a failure branch at immutable positions of such matches too. No committed output in the stdlib, Belt or tests changes.
  • Why are array elements not counted in check_partial? A Total match on arrays has a case matching any array, and the cases after a guard fall through to it; the contexts are still erased after an element is read.
  • Why are dict patterns left alone? A dict entry is read once into a variable and the cases after the guard keep using it, so they see one consistent value.

@codecov

codecov Bot commented Oct 29, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 77.77778% with 2 lines in your changes missing coverage. Please review.
✅ Project coverage is 81.70%. Comparing base (6ea63e5) to head (51592af).

Files with missing lines Patch % Lines
compiler/ml/matching.ml 77.77% 2 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##           master    #9131      +/-   ##
==========================================
- Coverage   81.71%   81.70%   -0.01%     
==========================================
  Files         460      460              
  Lines       64761    64767       +6     
==========================================
+ Hits        52918    52920       +2     
- Misses      11843    11847       +4     
Files with missing lines Coverage Δ
compiler/ml/matching.ml 77.96% <77.77%> (-0.18%) ⬇️
🚀 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 Oct 29, 2026

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 29, 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-10-29T19:57:37.210479Z 51592af 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. 🎉

Reviewed commit: 51592afe31

ℹ️ 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 Oct 29, 2026

Copy link
Copy Markdown

Open in StackBlitz

rescript

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

@rescript/belt

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

@rescript/darwin-arm64

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

@rescript/linux-arm64

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

@rescript/linux-x64

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

@rescript/runtime

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

@rescript/win32-x64

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

commit: 51592af

@github-actions

Copy link
Copy Markdown

@cknitt
cknitt marked this pull request as ready for review October 29, 2026 20:24
@cknitt
cknitt requested a review from cristianoc October 29, 2026 20:24

@cristianoc cristianoc left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looks good to me. Thanks for the fix.

@cknitt
cknitt merged commit 9d25b40 into master Oct 30, 2026
26 checks passed
@cknitt
cknitt deleted the match-guard-mutation branch October 30, 2026 06:09
aspeddro pushed a commit to aspeddro/rescript-compiler that referenced this pull request Oct 31, 2026
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.

switch can take a non-matching case after a guard mutates the scrutinee

2 participants