Skip to content

[12.x] Fix constant folding of a switch on an @as(int) constructor - #9318

Open
illusionalsagacity wants to merge 3 commits into
rescript-lang:maintenance/12.xfrom
illusionalsagacity:fix-variant-compilation-issue
Open

illusionalsagacity wants to merge 3 commits into
rescript-lang:maintenance/12.xfrom
illusionalsagacity:fix-variant-compilation-issue

Conversation

@illusionalsagacity

@illusionalsagacity illusionalsagacity commented Nov 17, 2026 •

Copy link
Copy Markdown
Contributor

Fixes #9317.

Problem

Since 12.0.0-alpha.4, the optimizer picks the wrong case when it folds a switch over a constant constructor that has @as(int):

type t = | @as(1) A | @as(0) B

let name = x =>
  switch x {
  | A => "A"
  | B => "B"
  }

let a = name(A)

Before (every 12.x release, 12.3.1 included):

function name(x) {
  if (x === 1) {
    return "A";
  } else {
    return "B";
  }
}

let a = "B";

After:

function name(x) {
  if (x === 1) {
    return "A";
  } else {
    return "B";
  }
}

let a = "A";

The emitted name doesn't change. Only the folded call does.

Root cause

#7058 ("Fix variant coercion with as attribute", 1437815) changed Lam_constant_convert so that a constant constructor with @as(int) becomes Const_int {i = <runtime value>} instead of Const_int {i = <constructor position>}. That fixed folding of (A :> int).

Lam.switch was not updated. It still folds a constant scrutinee by looking up i in sw_consts, and sw_consts is keyed by constructor position. So the fold picks the case whose position equals the constructor's runtime value. If no position matches, the call is not folded at all. This explains the five-constructor example: @as(3)..@as(7) folds Weekly to Quarterly's case and Monthly to Annual's, and leaves BiWeekly, Quarterly and Annual as calls. A direct switch A { ... } goes through the same function and had the same bug.

git bisect between v12.0.0-alpha.3 and v12.0.0-alpha.4 names 1437815 as the first bad commit.

Fix

Lam.switch now finds the case for a constant constructor by its tag (name and @as value) in sw_names.consts, which lists the constant constructors in position order, instead of using i (switch_const_key). Constant blocks are looked up the same way, by constructor name in sw_names.blocks (switch_block_key). If the constructor isn't in that list, the switch is left unfolded, which is always correct. A switch without sw_names, such as an int switch on (A :> int), folds on i as before.

Looking up by tag also fixes an older bug, present before #7058, where coercing between variants with different constructor order folded to the wrong case. The same lookup by name is applied to constant blocks (Const_block), so constructors with a payload, including inline records, fold to the right case after such a coercion too:

type reversed = Second2 | First2
type ordered = First2 | Second2
let orderedName = (x: ordered) => switch x { | First2 => "First2" | Second2 => "Second2" }
orderedName((First2: reversed :> ordered)) // folded to "Second2" before, "First2" now

On master this was fixed as part of #8579 ("Make variant runtime representation canonical across compiler IRs", commit 108aa8f "Replace constructor ordinals with semantic identity and representation"). That change removes constructor ordinals from every compiler IR and touches 73 files, so it isn't a candidate for a backport. This PR is a targeted fix for 12.x.

Tests

The new file tests/tests/src/variant_as_int_fold_test.res follows the pattern of unboxed_variant_fold_test (#8631). Each function is called with a constant argument, which folds, and through an @inline(never) id, which runs the real dispatch. Both results are checked against the expected value. The committed .mjs shows that the constant calls fold to the right literals and that the emitted functions are unchanged. It covers:

  • two constructors with swapped values;
  • five constructors with @as(3)..@as(7), every constructor (both the ones that used to fold wrongly and the ones past the last position);
  • @as(int) mixed with a constructor that has no @as, plus a negative value and @as(0);
  • a switch with a default arm;
  • switch directly on a constant, with no call in between;
  • an int switch on a coerced constructor, switch (A :> int), which must still fold;
  • a coercion between variants with different constructor order;
  • the same coercion for constructors with a payload, including an inline record.

Without the compiler change, the 7 folding tests fail. With it all 8 pass, and none of the other 663 modules in tests/tests change their output.

Tested against a production codebase

With the binaries-darwin-arm64 and lib-ocaml artifacts from this PR's CI run (head 220ef98) installed over rescript@12.3.1:

  • A standalone project with the repro above, the five-constructor case, @as(int) mixed with a constructor that has no @as, a default arm, and a coercion between variant types: 8 of its 15 folded values are wrong on 12.3.1. All 15 are correct with this PR, and all are folded to constants.

  • A production codebase with about 2,900 ReScript modules that use @as(int) variants heavily. Compiled with stock 12.3.1 and with this PR, only one of the 2,935 emitted .res.mjs files differs, and the change is this bug being fixed (frequencyToValue(Weekly), where Weekly is @as(3)):

    - (saved.frequencyTypeId === 6 || saved.frequencyTypeId === frequencyToValue(5))
    + (saved.frequencyTypeId === 3 || saved.frequencyTypeId === 5)

    Its test suite (10,008 tests) passes on this build, including a test that fails on 12.3.1 because of this bug.

Lam.switch folded a constant scrutinee by looking its integer up in
sw_consts, which is keyed by constructor position. Since rescript-lang#7058,
Lam_constant_convert stores the runtime value of an @as(int) constructor
in that integer, so the fold took the case whose position equals the
constructor's runtime value: with `type t = | @as(1) A | @as(0) B`,
`name(A)` folded to B's case.

Look a constant constructor up by its tag in sw_names.consts instead,
and a constant block by its constructor name in sw_names.blocks, leaving
the switch unfolded when it is not found. This also fixes folding after
a coercion to a variant with another constructor order, which picked
the case at the constructor's position in the source type.

Fixes rescript-lang#9317.

Signed-off-by: Rob <illusionalsagacity@users.noreply.github.com>
Signed-off-by: Rob <illusionalsagacity@users.noreply.github.com>
@illusionalsagacity
illusionalsagacity marked this pull request as ready for review November 17, 2026 21:50
@pkg-pr-new

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

Copy link
Copy Markdown

Open in StackBlitz

rescript

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

@rescript/darwin-arm64

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

@rescript/darwin-x64

npm i https://pkg.pr.new/@rescript/darwin-x64@9318

@rescript/linux-arm64

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

@rescript/linux-x64

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

@rescript/runtime

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

@rescript/win32-x64

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

commit: d762b24

@cknitt

cknitt commented Nov 18, 2026

Copy link
Copy Markdown
Member

@codex review

@chatgpt-codex-connector

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

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

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

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-18T18:48:15.454227Z 220ef98 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: 220ef98d83

ℹ️ 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".

@cknitt cknitt left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

This review was done by Claude (Claude Code) on my behalf. I've read it and agree.

Thanks for the careful investigation and the thorough tests!

I built bsc from this PR and from its base (5ee4c56) on linux-arm64 and ran 27 extra cases through both. Each case calls the function with a constant, which the compiler folds, and again through an @inline(never) identity, which runs the real code. The cases covered:

  • @as(int) with a default arm, and mixed with payload constructors
  • coercion from a smaller to a bigger variant, and between @as(int) types
  • @as(string) and @as(bool)
  • @unboxed with null, undefined or int literals
  • @tag with inline records
  • option, list and polymorphic variants
  • an int switch on (A :> int)
  • a call across modules

Results:

  • Wrong folded results: 9 on base, none with this PR.
  • Folding: the PR folds every call base folded, and a few more.
  • Emitted functions: unchanged.

Matching constants by their full tag (name plus @as value) and blocks by name gives the same result as the fix on master. When the constructor isn't found, the switch stays unfolded, which is always safe.

One request: please drop the issue link from the CHANGELOG entry. All other 12.3.x entries link only the PR. The entry could also be shorter, for example:

  • Fix constant folding of a switch picking the wrong case for @as(int) constructors and for coerced variants. #9318

The failing Semantic Diff check isn't caused by this PR. For fork PRs, that workflow runs from master but takes its script from the base branch, and maintenance/12.x doesn't have that script. #9320 skips the job for fork PRs into maintenance branches.

Approving once the changelog entry is updated.

🤖 Generated with Claude Code

Signed-off-by: Rob <illusionalsagacity@users.noreply.github.com>
cknitt added a commit that referenced this pull request Nov 18, 2026
A fork PR runs the workflow from master but checks out its base commit for
the renderer. Maintenance branches don't have the renderer script, so the
job failed there (seen on #9318 into maintenance/12.x).


Claude-Session: https://claude.ai/code/session_01Kbf3gGHHcoxuVopoQtEcJ7

Signed-off-by: Christoph Knittel <ck@cca.io>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
@illusionalsagacity

Copy link
Copy Markdown
Contributor Author

Thanks @cknitt, I made that change to the CHANGELOG

This branch has not been deployed

No deployments
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.

2 participants