Skip to content

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

Open
cknitt wants to merge 6 commits into
instanceof-typeof-annotationsfrom
untagged-dispatch
Open

cknitt wants to merge 6 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, the tagged constructors (one switch on the tag) and the object case.

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.
  • 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.
  • Require = private for every subclass declared with @instanceOf, also in phantom type hierarchies, and fold null into an untagged variant's object case as it is matched at run time.

Semantic Diff

8 commits · Full page

✨ Say in rule 6 that variants with some @unboxed constructors are checked

5e9bfb6 · Christoph Knittel + Claude · Oct 24, 2026, 13:27 UTC · new

#9021 checks a variant with some @unboxed constructors like an untagged one: tagged blocks count as one object case, and an untagged case's @as is not a tag. Rule 6 now says so and names its tests.

✨ Require a private abbreviation for every subclass

0ddbc12 · Christoph Knittel + Claude · Oct 24, 2026, 16:18 UTC · new

Why

A public abbreviation could declare a subclass when its arguments were not all type variables, meant for phantom type hierarchies. The test was syntactic, so @instanceOf("Dog") type dog = animal<int> passed, and every animal<int> was then a dog without a coercion.

A subclass is always a private abbreviation, phantom hierarchies included; upcasts use :>.

Diagnostic added (public subclass of an instantiated class)

@instanceOf("Animal") type animal<'a>
@instanceOf("Dog") type dog = animal<int>

diagnostic

-none
+A subclass must be a private abbreviation: write `= private ...` so that instances of Animal cannot be used as instances of Dog without a coercion.
Match untagged variants with a literal switch and one typeof dispatch

80bb28f · 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

11ffe4e · 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

c549460 · 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

5af3b88 · cknitt + Claude · Oct 24, 2026, 16:18 UTC · new

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

9b1fff8 · cknitt + Claude · Oct 24, 2026, 16:21 UTC · new

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

66880b8 · cknitt + Claude · Oct 24, 2026, 16:23 UTC · new

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.

@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-25T05:38:19.846904Z 66880b8 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 87.39496% with 30 lines in your changes missing coverage. Please review.
✅ Project coverage is 81.31%. Comparing base (0ddbc12) to head (66880b8).

Files with missing lines Patch % Lines
compiler/core/lam_compile.ml 90.04% 20 Missing ⚠️
compiler/core/js_exp_make.ml 68.42% 6 Missing ⚠️
compiler/ml/variant_runtime.ml 75.00% 3 Missing ⚠️
compiler/ml/lambda.ml 50.00% 1 Missing ⚠️
Additional details and impacted files
@@                        Coverage Diff                        @@
##           instanceof-typeof-annotations    #9015      +/-   ##
=================================================================
- Coverage                          81.32%   81.31%   -0.02%     
=================================================================
  Files                                456      456              
  Lines                              64180    64193      +13     
=================================================================
+ Hits                               52196    52197       +1     
- Misses                             11984    11996      +12     
Files with missing lines Coverage Δ
compiler/ml/ast_untagged_variants.ml 88.61% <ø> (+1.61%) ⬆️
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.48%) ⬆️
compiler/ml/variant_runtime.ml 90.00% <75.00%> (-3.55%) ⬇️
compiler/core/js_exp_make.ml 64.62% <68.42%> (-3.80%) ⬇️
compiler/core/lam_compile.ml 90.88% <90.04%> (+0.57%) ⬆️

... and 5 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: 66880b8

@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 and others added 6 commits October 25, 2026 05:17
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 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01CMkrYaktctdKc4M41WF36t
Signed-off-by: Christoph Knittel <ck@cca.io>
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 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01CMkrYaktctdKc4M41WF36t
Signed-off-by: Christoph Knittel <ck@cca.io>
The gentype example matches an untagged variant too; its output follows the
new dispatch.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01CMkrYaktctdKc4M41WF36t
Signed-off-by: Christoph Knittel <ck@cca.io>
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 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01CMkrYaktctdKc4M41WF36t
Signed-off-by: Christoph Knittel <ck@cca.io>
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 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01CMkrYaktctdKc4M41WF36t
Signed-off-by: Christoph Knittel <ck@cca.io>
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 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01CMkrYaktctdKc4M41WF36t
Signed-off-by: Christoph Knittel <ck@cca.io>
@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 on lines +1189 to +1193
| _ :: _, [] -> (
(* No other arm: in a complete match the last primitive arm is not
checked *)
match List.rev primitive_clauses with
| (_, {J.switch_body}) :: rest when complete ->

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Preserve empty non-primitive arms when choosing a default

When a complete match is evaluated for effects and its final non-primitive arm does nothing, other is empty even though that arm exists. For example, with @unboxed type t = S(string) | O({x: int}), evaluate switch v { | S(_) => Console.log("s") | O(_) => () } before another statement. The object arm compiles to [], so this branch removes the string check and makes its logging body the unconditional default; passing O({x: 1}) then incorrectly logs "s". Determine whether non-primitive arms exist from the dispatch entries rather than from whether their compiled bodies contain statements.

Useful? React with 👍 / 👎.

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.

1 participant