Skip to content

Match untagged variants with a literal switch and one typeof dispatch - #9015

Merged
cknitt merged 11 commits into
instanceof-typeof-annotationsfrom
untagged-dispatch
Oct 25, 2026
Merged

cknitt merged 11 commits into
instanceof-typeof-annotationsfrom
untagged-dispatch

Conversation

@cknitt

@cknitt cknitt commented Oct 24, 2026 •

Copy link
Copy Markdown
Member

Stacked on #8950. Replaces #8967 with the dispatch structure the architecture review proposed.

An untagged variant now matches in two steps:

  1. Literals are compared with ===, by one switch (x), or by an if per body for at most two literals. Its default is the payload dispatch.
  2. Payloads go through one switch (typeof x) over the primitive kinds, or an if for one kind. Its default is an if chain, in this order: the instance cases (a subclass before its superclasses, otherwise declaration order), the function case and the object case. Since Make @unboxed apply to a whole variant only #9040 a variant is untagged as a whole, so no tagged block appears here.

In a complete match the last arm is never checked, whichever form it is in.

What this removes:

  • the size heuristic Dynamic_checks.is_a_literal_case, and with it the rest of Ast_untagged_variants.Dynamic_checks and Js_exp_make.emit_check: Js_exp_make builds the int-tag test of tagged variants and the instance checks directly, and matching_facts drops has_null, has_undefined and has_other_literal;
  • the null/array/instance guards in front of the typeof switch;
  • the !(x instanceof Sub) negations in superclass checks.

Code generation and constant folding share one table of which literal passes which payload check (Variant_runtime.literal_passes). The two copies disagreed on null and an object case; folding now follows the generated code, where typeof null is "object".

What follows from the new structure:

  • Primitives never reach instanceof. A class missing at run time therefore throws only for objects and functions, and Symbol.hasInstance can't claim strings.
  • A literal handled by the default arm skips the literal switch when no payload check would accept it.
  • A null that only the object check would accept becomes && x !== null on that check. JSON decoders keep their single typeof x === "object" && x !== null && !Array.isArray(x).
  • Checks that lead to the default before the last checked arm are folded into its check, as in typeof x === "object" && !(x instanceof Date). Class checks then run only on objects.

Spec rules 7–10 in compiler/ml/UntaggedVariants.md describe the new structure, and rule 11 names the values constant folding sees. Rule 10 changes one outcome: with PPromise | PFloat, the float case is now checked, so a thenable lands in PPromise.

New tests:

  • untagged_loop_control_test.res: break and continue in literal, primitive, class, object and default arms leave or continue the loop, not the generated switch.
  • untagged_default_arm_test.res:
    • a class whose Symbol.hasInstance accepts everything doesn't take primitives or literals (carried over from Test primitive untagged cases before class checks #8967);
    • an incomplete inner match lets values no arm takes fall through to later arms. This is a regression test for a bug in an earlier draft of this branch;
    • an arm that does nothing keeps the checks before it (found by Codex).
  • untagged_runtime_annotations_test.res: a class missing at run time doesn't affect primitive cases, with every arm present or with a default (partly from Test primitive untagged cases before class checks #8967). Also a default shared by primitive and object cases.
  • ounit_lambda_constant_tests.ml: null without a null case folds into the object case.

🤖 Generated with Claude Code

https://claude.ai/code/session_01CMkrYaktctdKc4M41WF36t

@github-actions

github-actions Bot commented Oct 24, 2026 •

Copy link
Copy Markdown

Changelog

💅 Polish

  • Match an untagged variant with one switch over its literals and one switch (typeof x) over its primitive cases before any class check, so that strings and numbers skip instanceof and a class missing at run time no longer throws for them.

Semantic Diff

11 commits · Full page

Match untagged variants with a literal switch and one typeof dispatch

0ea7333 · cknitt + Claude · Oct 24, 2026, 10:17 UTC

Why

The payload dispatch of an untagged variant ran its instance checks before the typeof checks, so strings and numbers reached instanceof: a class missing at run time threw for them, and a Symbol.hasInstance could claim them. Literals were tested by a size heuristic that chose between two equivalent expressions, the object case by a guard per instance case, and a subclass by negating it in its superclass's check.

The literals come first, compared with === by one switch (x) (an if per body for at most two), whose default is the payload dispatch: one switch (typeof x) over the primitive kinds, whose default is an if chain over the instance cases (a subclass first), the function case, the tagged constructors and the object case. In a complete match the last arm is not checked. A literal without an arm skips the switch when no payload check would accept it, and a null that only the object check would accept adds x !== null to it. Checks leading to the default before the last checked arm fold into its check, so class checks run only on objects. Dynamic_checks.is_a_literal_case and the per-instance guards are gone.

JS modified (primitives before classes)

@unboxed
type t = Missing(missing) | Text(string) | Count(float)
let kind = value =>
  switch value {
  | Missing(_) => "missing"
  | Text(text) => text
  | Count(_) => "count"
  }

js

-if (value instanceof UntaggedMissingClass) {
-  return "missing";
-}
 switch (typeof value) {
   case "string" :
     return value;
   case "number" :
     return "count";
+  default:
+    return "missing";
 }

JS modified (instances without an arm)

@unboxed
type t = D(Date.t) | R(RegExp.t) | O({x: int}) | S(string) | I(int) | F(int => int)
let kind = value =>
  switch value {
  | O(_) => "O"
  | S(_) => "S"
  | _ => "other"
  }

js

-if (value instanceof RegExp || value instanceof Date) {
+if (typeof value === "string") {
+  return "S";
+} else if (typeof value === "object" && !(value instanceof RegExp) && !(value instanceof Date)) {
+  return "O";
+} else {
   return "other";
 }
-switch (typeof value) {
-  case "object" :
-    return "O";
-  case "string" :
-    return "S";
-  default:
-    return "other";
-}

JS modified (a subclass first)

@unboxed
type upload = Blob(Blob.t) | File(File.t)
let kind = upload =>
  switch upload {
  | Blob(_) => "blob"
  | File(_) => "file"
  }

js

-if (upload instanceof Blob && !(upload instanceof File)) {
-  return "blob";
-} else {
+if (upload instanceof File) {
   return "file";
+} else {
+  return "blob";
 }

Review

  • Does break in an arm leave the generated switch instead of the loop? No: every arm placed in a generated switch is compiled in a switch context, where break and continue are labeled; untagged_loop_control_test.res checks arms of every part.
  • What changes for a value outside every case? It lands in the last arm of the chain: with PPromise | PFloat the float case is now checked, so a thenable lands in PPromise (rule 10).
Drop literal arms that a complete payload dispatch runs anyway

f5ed4ce · cknitt + Claude · Oct 24, 2026, 10:25 UTC

A complete payload dispatch with one body runs it unchecked, so a literal arm with the same body needs no case of its own.

JS modified (literal arm equal to the payload arm)

@unboxed
type rec t = | @as(null) Null | @as(undefined) Undefined | WhyNotAnotherOne | Point({x: int, y: int})
let plus = (x, y) =>
  switch y {
  | Null | Undefined => x
  | WhyNotAnotherOne => WhyNotAnotherOne
  | Point(_) => WhyNotAnotherOne
  }

js

-switch (y) {
-  case null :
-  case undefined :
-    return x;
-  case "WhyNotAnotherOne" :
-    return "WhyNotAnotherOne";
-  default:
-    return "WhyNotAnotherOne";
+if (y == null) {
+  return x;
+} else {
+  return "WhyNotAnotherOne";
 }
Update the gentype example for the untagged dispatch

9d8cae0 · cknitt + Claude · Oct 24, 2026, 10:37 UTC

The gentype example matches an untagged variant too; its output follows the new dispatch.

Say precisely when literals use an if and what folds

f7fceb2 · cknitt + Claude · Oct 24, 2026, 16:18 UTC

Rule 7 counts the literals that get a case, as the code does, and rule 11 names the values constant folding sees: literals and blocks of constants.

Emit untagged checks directly instead of through Dynamic_checks

61dd7e5 · cknitt + Claude · Oct 24, 2026, 16:21 UTC

The check AST in Ast_untagged_variants only encoded the int-tag test of tagged variants and the instance checks. Js_exp_make now builds both directly (is_int_tag from the literal list, is_instance_of), and matching_facts no longer carries has_null, has_undefined and has_other_literal, which that test derived. A class is never a switch key, so block_type_name no longer pretends to emit one. No output changes.

Share which literal passes which payload check

e8f4c02 · cknitt + Claude · Oct 24, 2026, 16:23 UTC

Code generation and constant folding each had a table of the literals a payload case accepts, and they disagreed on null and an object case. Variant_runtime.literal_passes is now the one table; folding follows the generated code, where typeof null is "object", so null without a null case folds into the object case as it is matched at run time.

Keep the checks an empty arm or a tagged block needs

e5a2af7 · cknitt + Claude · Oct 25, 2026, 05:59 UTC

Why

The payload dispatch decided that a match had no arm besides its primitive ones from the compiled chain of the others, which is empty when their bodies do nothing, and then ran the last primitive arm unchecked. A literal arm sharing the body of the payload dispatch was dropped, although two tagged blocks are told apart by reading their tag, which a literal such as null does not have.

Whether there are other arms comes from the dispatch entries. A literal arm joins the payload dispatch only when at most one tagged block is matched, and the last tag of a complete match is not checked, as the last arm of every other complete match.

JS modified (an arm that does nothing)

@unboxed type t = S(string) | O({x: int})
let f = v => {
  switch v {
  | S(_) => Console.log("s")
  | O(_) => ()
  }
  Console.log("after")
}

js

-switch (typeof v) {
-  default:
-    console.log("s");
+if (typeof v === "string") {
+  console.log("s");
 }
 console.log("after");

JS modified (a literal sharing the body of tagged blocks)

type t = | @unboxed MS(string) | MB({x: int}) | MC(int) | @as(null) MNull | @as(1) MOne
let f = v =>
  switch v {
  | MB(_) => "other"
  | MC(_) => "other"
  | MOne => "one"
  | MNull | MS(_) => "other"
  }

js

+if (v === null) {
+  return "other";
+}
 if (v === 1) {
   return "one";
 }
 if (typeof v === "string") {
   return "other";
 }
 switch (v.TAG) {
   case "MB" :
-  case "MC" :
+  default:
     return "other";
 }
Drop the tagged blocks of mixed variants from the dispatch

5558fab · cknitt + Claude · Oct 25, 2026, 13:09 UTC

Since #9040 a variant is untagged as a whole or not at all, so the payload dispatch of an untagged variant never meets a tagged block. The switch on the tag inside its if chain, the merging of tagged clauses, the count of tagged blocks before dropping literal arms and the tag-name parameter are gone, and rule 8 no longer lists tagged constructors.

Give a literal a case where skipping would add a check

1230264 · cknitt + Claude · Oct 25, 2026, 14:56 UTC

Why

A literal without an arm skipped the literal switch whenever the payload dispatch led it to the default, even where that made a complete dispatch check its last arm or added x !== null, although the switch existed for other literals anyway.

When other literals get a case, a literal whose skipping would add such a check gets a case too. Literals that reach the default without a new check still skip. The fallback for tagged blocks is gone: an untagged variant has none since #9040. Rule 10 now says where a value outside every case lands when the match shares a default.

Generated code changed (a bool literal beside string literals):

@unboxed
type t = | @as("a") A | @as("b") B | @as(true) T | S(string) | O({x: int})
let f = (x: t) => switch x { | S(_) => 1 | O(_) => 2 | _ => 3 }

Before (JS):

switch (x) {
  case "a" :
  case "b" :
    return 3;
  default:
    if (typeof x === "string") {
      return 1;
    } else if (typeof x === "object") {
      return 2;
    } else {
      return 3;
    }
}

After (JS):

switch (x) {
  case "a" :
  case "b" :
  case true :
    return 3;
  default:
    if (typeof x === "string") {
      return 1;
    } else {
      return 2;
    }
}
Let literals skip the switch whatever other literals do

c7e3f70 · cknitt + Claude · Oct 25, 2026, 15:13 UTC

Why

Giving a literal a case where skipping would add a check saves one typeof or null check in a narrow situation, at the price of two more predicates in the most intricate part of the dispatch.

This undoes that rule, keeping the removal of the tagged-block fallback and the rule 10 clause from the same commit.

Generated code changed (a bool literal beside string literals):

@unboxed
type t = | @as("a") A | @as("b") B | @as(true) T | S(string) | O({x: int})
let f = (x: t) => switch x { | S(_) => 1 | O(_) => 2 | _ => 3 }

Before (JS):

switch (x) {
  case "a" :
  case "b" :
  case true :
    return 3;
  default:
    if (typeof x === "string") {
      return 1;
    } else {
      return 2;
    }
}

After (JS):

switch (x) {
  case "a" :
  case "b" :
    return 3;
  default:
    if (typeof x === "string") {
      return 1;
    } else if (typeof x === "object") {
      return 2;
    } else {
      return 3;
    }
}
Regenerate the callable-instance test for the typeof dispatch

141e433 · cknitt + Claude · Oct 25, 2026, 16:27 UTC

Why

The test added to the bottom of the stack is compiled by this pull request's dispatch, which checks the function arm against the classes.

@cknitt
cknitt added this pull request to stack #9016 October 24, 2026 10:19
@cknitt
cknitt marked this pull request as ready for review October 24, 2026 10:22
@cknitt

cknitt commented Oct 24, 2026

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 24, 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-25T16:47:06.867687Z c54bc94 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. Chef's kiss.

Reviewed commit: 43963921be

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

@codecov

codecov Bot commented Oct 24, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 88.88889% with 25 lines in your changes missing coverage. Please review.
✅ Project coverage is 81.32%. Comparing base (743b80b) to head (141e433).
⚠️ Report is 28 commits behind head on instanceof-typeof-annotations.

Files with missing lines Patch % Lines
compiler/core/lam_compile.ml 91.48% 16 Missing ⚠️
compiler/core/js_exp_make.ml 68.42% 6 Missing ⚠️
compiler/ml/variant_runtime.ml 83.33% 2 Missing ⚠️
compiler/ml/lambda.ml 50.00% 1 Missing ⚠️
Additional details and impacted files
@@                      Coverage Diff                       @@
##           instanceof-typeof-annotations    #9015   +/-   ##
==============================================================
  Coverage                          81.31%   81.32%           
==============================================================
  Files                                456      456           
  Lines                              64145    64181   +36     
==============================================================
+ Hits                               52161    52193   +32     
- Misses                             11984    11988    +4     
Files with missing lines Coverage Δ
compiler/ml/ast_untagged_variants.ml 88.23% <ø> (+1.77%) ⬆️
tests/ounit_tests/ounit_lambda_constant_tests.ml 94.59% <100.00%> (+0.15%) ⬆️
tests/ounit_tests/ounit_string_literal_tests.ml 90.51% <ø> (-0.05%) ⬇️
compiler/ml/lambda.ml 68.83% <50.00%> (+0.68%) ⬆️
compiler/ml/variant_runtime.ml 91.42% <83.33%> (-2.12%) ⬇️
compiler/core/js_exp_make.ml 65.19% <68.42%> (-3.05%) ⬇️
compiler/core/lam_compile.ml 91.23% <91.48%> (+0.91%) ⬆️

... and 23 files 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.

@pkg-pr-new

pkg-pr-new Bot commented Oct 24, 2026 •

Copy link
Copy Markdown

Open in StackBlitz

rescript

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

@rescript/belt

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

@rescript/darwin-arm64

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

@rescript/linux-arm64

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

@rescript/linux-x64

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

@rescript/runtime

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

@rescript/win32-x64

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

commit: 141e433

@cknitt
cknitt force-pushed the untagged-dispatch branch from 85c7fd6 to 77e7004 Compare October 24, 2026 20:20
@cknitt

cknitt commented Oct 25, 2026

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

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

Reviewed commit: 77e70041bb

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

Copy link
Copy Markdown
Member Author

@codex review

@cknitt
cknitt removed this pull request from stack #9016 October 25, 2026 05:37
@cknitt
cknitt added this pull request to stack #9033 October 25, 2026 05:37

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 66880b8db8

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

Comment thread compiler/core/lam_compile.ml Outdated
@cknitt
cknitt force-pushed the untagged-dispatch branch from 66880b8 to caf4899 Compare October 25, 2026 13:18
@cknitt

cknitt commented Oct 25, 2026

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. 👍

Reviewed commit: caf48992d0

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

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Keep it up!

Reviewed commit: 94bc549e3e

ℹ️ 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 force-pushed the untagged-dispatch branch from 94bc549 to c54bc94 Compare October 25, 2026 16:30
@cknitt

cknitt commented Oct 25, 2026

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Nice work!

Reviewed commit: c54bc94890

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

Why:
    The payload dispatch of an untagged variant ran its instance checks
    before the `typeof` checks, so strings and numbers reached `instanceof`:
    a class missing at run time threw for them, and a `Symbol.hasInstance`
    could claim them. Literals were tested by a size heuristic that chose
    between two equivalent expressions, the object case by a guard per
    instance case, and a subclass by negating it in its superclass's check.

The literals come first, compared with `===` by one `switch (x)` (an `if`
per body for at most two), whose default is the payload dispatch: one
`switch (typeof x)` over the primitive kinds, whose default is an `if` chain
over the instance cases (a subclass first), the function case, the tagged
constructors and the object case. In a complete match the last arm is not
checked. A literal without an arm skips the `switch` when no payload check
would accept it, and a `null` that only the object check would accept adds
`x !== null` to it. Checks leading to the default before the last checked
arm fold into its check, so class checks run only on objects.
`Dynamic_checks.is_a_literal_case` and the per-instance guards are gone.

JS modified (primitives before classes):
Example:
    @unboxed
    type t = Missing(missing) | Text(string) | Count(float)
    let kind = value =>
      switch value {
      | Missing(_) => "missing"
      | Text(text) => text
      | Count(_) => "count"
      }
Before (js):
    if (value instanceof UntaggedMissingClass) {
      return "missing";
    }
    switch (typeof value) {
      case "string" :
        return value;
      case "number" :
        return "count";
    }
After (js):
    switch (typeof value) {
      case "string" :
        return value;
      case "number" :
        return "count";
      default:
        return "missing";
    }

JS modified (instances without an arm):
Example:
    @unboxed
    type t = D(Date.t) | R(RegExp.t) | O({x: int}) | S(string) | I(int) | F(int => int)
    let kind = value =>
      switch value {
      | O(_) => "O"
      | S(_) => "S"
      | _ => "other"
      }
Before (js):
    if (value instanceof RegExp || value instanceof Date) {
      return "other";
    }
    switch (typeof value) {
      case "object" :
        return "O";
      case "string" :
        return "S";
      default:
        return "other";
    }
After (js):
    if (typeof value === "string") {
      return "S";
    } else if (typeof value === "object" && !(value instanceof RegExp) && !(value instanceof Date)) {
      return "O";
    } else {
      return "other";
    }

JS modified (a subclass first):
Example:
    @unboxed
    type upload = Blob(Blob.t) | File(File.t)
    let kind = upload =>
      switch upload {
      | Blob(_) => "blob"
      | File(_) => "file"
      }
Before (js):
    if (upload instanceof Blob && !(upload instanceof File)) {
      return "blob";
    } else {
      return "file";
    }
After (js):
    if (upload instanceof File) {
      return "file";
    } else {
      return "blob";
    }

Review: Does `break` in an arm leave the generated `switch` instead of the
loop? No: every arm placed in a generated `switch` is compiled in a switch
context, where `break` and `continue` are labeled;
`untagged_loop_control_test.res` checks arms of every part.

Review: What changes for a value outside every case? It lands in the last
arm of the chain: with `PPromise | PFloat` the float case is now checked, so
a thenable lands in `PPromise` (rule 10).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01CMkrYaktctdKc4M41WF36t
Signed-off-by: Christoph Knittel <[email protected]>
cknitt and others added 10 commits October 25, 2026 16:58
A complete payload dispatch with one body runs it unchecked, so a literal arm
with the same body needs no case of its own.

JS modified (literal arm equal to the payload arm):
Example:
    @unboxed
    type rec t = | @as(null) Null | @as(undefined) Undefined | WhyNotAnotherOne | Point({x: int, y: int})
    let plus = (x, y) =>
      switch y {
      | Null | Undefined => x
      | WhyNotAnotherOne => WhyNotAnotherOne
      | Point(_) => WhyNotAnotherOne
      }
Before (js):
    switch (y) {
      case null :
      case undefined :
        return x;
      case "WhyNotAnotherOne" :
        return "WhyNotAnotherOne";
      default:
        return "WhyNotAnotherOne";
    }
After (js):
    if (y == null) {
      return x;
    } else {
      return "WhyNotAnotherOne";
    }

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01CMkrYaktctdKc4M41WF36t
Signed-off-by: Christoph Knittel <[email protected]>
The gentype example matches an untagged variant too; its output follows the
new dispatch.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01CMkrYaktctdKc4M41WF36t
Signed-off-by: Christoph Knittel <[email protected]>
Rule 7 counts the literals that get a case, as the code does, and rule 11
names the values constant folding sees: literals and blocks of constants.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01CMkrYaktctdKc4M41WF36t
Signed-off-by: Christoph Knittel <[email protected]>
The check AST in Ast_untagged_variants only encoded the int-tag test of
tagged variants and the instance checks. Js_exp_make now builds both
directly (is_int_tag from the literal list, is_instance_of), and
matching_facts no longer carries has_null, has_undefined and
has_other_literal, which that test derived. A class is never a switch key,
so block_type_name no longer pretends to emit one. No output changes.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01CMkrYaktctdKc4M41WF36t
Signed-off-by: Christoph Knittel <[email protected]>
Code generation and constant folding each had a table of the literals a
payload case accepts, and they disagreed on null and an object case.
Variant_runtime.literal_passes is now the one table; folding follows the
generated code, where `typeof null` is "object", so null without a null
case folds into the object case as it is matched at run time.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01CMkrYaktctdKc4M41WF36t
Signed-off-by: Christoph Knittel <[email protected]>
Why:
    The payload dispatch decided that a match had no arm besides its
    primitive ones from the compiled chain of the others, which is empty when
    their bodies do nothing, and then ran the last primitive arm unchecked.
    A literal arm sharing the body of the payload dispatch was dropped,
    although two tagged blocks are told apart by reading their tag, which a
    literal such as `null` does not have.

Whether there are other arms comes from the dispatch entries. A literal arm
joins the payload dispatch only when at most one tagged block is matched, and
the last tag of a complete match is not checked, as the last arm of every
other complete match.

JS modified (an arm that does nothing):
Example:
    @unboxed type t = S(string) | O({x: int})
    let f = v => {
      switch v {
      | S(_) => Console.log("s")
      | O(_) => ()
      }
      Console.log("after")
    }
Before (js):
    switch (typeof v) {
      default:
        console.log("s");
    }
    console.log("after");
After (js):
    if (typeof v === "string") {
      console.log("s");
    }
    console.log("after");

JS modified (a literal sharing the body of tagged blocks):
Example:
    type t = | @unboxed MS(string) | MB({x: int}) | MC(int) | @as(null) MNull | @as(1) MOne
    let f = v =>
      switch v {
      | MB(_) => "other"
      | MC(_) => "other"
      | MOne => "one"
      | MNull | MS(_) => "other"
      }
Before (js):
    if (v === 1) {
      return "one";
    }
    if (typeof v === "string") {
      return "other";
    }
    switch (v.TAG) {
      case "MB" :
      case "MC" :
        return "other";
    }
After (js):
    if (v === null) {
      return "other";
    }
    if (v === 1) {
      return "one";
    }
    if (typeof v === "string") {
      return "other";
    }
    switch (v.TAG) {
      case "MB" :
      default:
        return "other";
    }

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01CMkrYaktctdKc4M41WF36t
Signed-off-by: Christoph Knittel <[email protected]>
Since #9040 a variant is untagged as a whole or not at all, so the payload
dispatch of an untagged variant never meets a tagged block. The `switch` on
the tag inside its `if` chain, the merging of tagged clauses, the count of
tagged blocks before dropping literal arms and the tag-name parameter are
gone, and rule 8 no longer lists tagged constructors.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01CMkrYaktctdKc4M41WF36t
Signed-off-by: Christoph Knittel <[email protected]>
Why:
    A literal without an arm skipped the literal switch whenever the payload
    dispatch led it to the default, even where that made a complete
    dispatch check its last arm or added `x !== null`, although the switch
    existed for other literals anyway.

When other literals get a case, a literal whose skipping would add such a
check gets a case too. Literals that reach the default without a new check
still skip. The fallback for tagged blocks is gone: an untagged variant has
none since #9040. Rule 10 now says where a value outside every case lands
when the match shares a default.

Generated code changed (a bool literal beside string literals):
Example:
    @unboxed
    type t = | @as("a") A | @as("b") B | @as(true) T | S(string) | O({x: int})
    let f = (x: t) => switch x { | S(_) => 1 | O(_) => 2 | _ => 3 }
Before (JS):
    switch (x) {
      case "a" :
      case "b" :
        return 3;
      default:
        if (typeof x === "string") {
          return 1;
        } else if (typeof x === "object") {
          return 2;
        } else {
          return 3;
        }
    }
After (JS):
    switch (x) {
      case "a" :
      case "b" :
      case true :
        return 3;
      default:
        if (typeof x === "string") {
          return 1;
        } else {
          return 2;
        }
    }

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01CMkrYaktctdKc4M41WF36t
Signed-off-by: Christoph Knittel <[email protected]>
Why:
    Giving a literal a case where skipping would add a check saves one
    typeof or null check in a narrow situation, at the price of two more
    predicates in the most intricate part of the dispatch.

This undoes that rule, keeping the removal of the tagged-block fallback and
the rule 10 clause from the same commit.

Generated code changed (a bool literal beside string literals):
Example:
    @unboxed
    type t = | @as("a") A | @as("b") B | @as(true) T | S(string) | O({x: int})
    let f = (x: t) => switch x { | S(_) => 1 | O(_) => 2 | _ => 3 }
Before (JS):
    switch (x) {
      case "a" :
      case "b" :
      case true :
        return 3;
      default:
        if (typeof x === "string") {
          return 1;
        } else {
          return 2;
        }
    }
After (JS):
    switch (x) {
      case "a" :
      case "b" :
        return 3;
      default:
        if (typeof x === "string") {
          return 1;
        } else if (typeof x === "object") {
          return 2;
        } else {
          return 3;
        }
    }

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01CMkrYaktctdKc4M41WF36t
Signed-off-by: Christoph Knittel <[email protected]>
Why:
    The test added to the bottom of the stack is compiled by this pull
    request's dispatch, which checks the function arm against the classes.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01CMkrYaktctdKc4M41WF36t
Signed-off-by: Christoph Knittel <[email protected]>
@cknitt
cknitt force-pushed the untagged-dispatch branch from c54bc94 to 141e433 Compare October 25, 2026 17:05
@cknitt
cknitt merged commit ea15824 into master Oct 25, 2026
27 of 42 checks passed
@cknitt
cknitt deleted the untagged-dispatch branch October 25, 2026 19:26
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