Skip to content

Coerce class types explicitly across declarations - #9432

Open
jfrolich wants to merge 1 commit into
masterfrom
class-identity-explicit
Open

jfrolich wants to merge 1 commit into
masterfrom
class-identity-explicit

Conversation

@jfrolich

@jfrolich jfrolich commented Nov 26, 2026 •

Copy link
Copy Markdown
Collaborator

Two packages can bind the same JavaScript class with separate @instanceOf types, but currently need shared type declarations or Obj.magic to exchange their values. This change lets :> coerce between declarations of the same class and to declared superclasses, including across compiled module boundaries.

module WebAPI = {
  @instanceOf("Element") type element
  @instanceOf("HTMLInputElement") type input = private element
}
module ReactDOM = {
  @instanceOf("Element") type element
}

let asElement = (input: WebAPI.input) => (input :> ReactDOM.element)

The target must declare its own @instanceOf: an unannotated private refinement remains protected. In invariant positions such as arrays, refs, and mutable fields, only declarations of the same class coerce to one another. Class identity includes its module, so global and imported classes stay distinct. Refused class coercions now name the classes and their declared ancestry.

This is the explicit-coercion part of #9413, recreated on a branch in this repository so benchmark results can be posted. Automatic coercion at arguments is split into #9433, stacked on this one. Includes the explicit-coercion documentation, completion text, and its own changelog fragment.

Validation: built the compiler from this branch; both runtime regression tests and the full super_errors suite pass; generated regression JavaScript matches the fixtures; changelog and commit-record checks pass. The local environment lacks dependencies for the complete toolchain build, so full CI remains required. Local runtime dependencies were prepared with the original PR's CI-built tooling; the changed fixtures and diagnostic suite were compiled with this branch's compiler.

…asses

Why:
    Two packages that bind the same JavaScript class each declare their
    own type for it, `@instanceOf("Element") type element` in one and in
    the other, and `:>` did not get from one to the other: it only follows
    the abbreviations a type is declared with. So every binding package
    depends on the one package that owns the DOM types, or its users
    convert with `Obj.magic`. The class an `@instanceOf` type names is
    what its values are at run time; it now decides what they coerce to.

Typing modified (`:>` between class types, `Ctype.subtype_rec`):
Before (rule):
    p1 = p2
    ──────────────────── (Same path)
    `p1` <: `p2`
After (rule):
    class(p2) ∈ classes(p1)
    ──────────────────── (Class)
    `p1` <: `p2`

    class(p): the class that the declaration of p itself states with @instanceof, with its @module
    classes(p): class(p), or the class p abbreviates, with its declared superclasses

Diagnostic removed (coercions between declarations of one class):
Example:
    module WebAPI = {
      @instanceof("Node") type node
      @instanceof("Element") type element = private node
      @instanceof("HTMLInputElement") type input = private element
    }
    module ReactDOM = {
      @instanceof("Node") type node
      @instanceof("Element") type element = private node
    }
    let a = (el: ReactDOM.element) => (el :> WebAPI.element)
    let b = (input: WebAPI.input) => (input :> ReactDOM.node)
    let c = (els: array<ReactDOM.element>) => (els :> array<WebAPI.element>)
Before (diagnostic): each line compiled alone
    Type ReactDOM.element is not a subtype of WebAPI.element
    Type WebAPI.input is not a subtype of ReactDOM.node
    Type array<ReactDOM.element> is not a subtype of array<WebAPI.element>
    Type ReactDOM.element is not compatible with type WebAPI.element
After (diagnostic): none
After (js):
    function a(el) {
      return el;
    }

Diagnostic modified (a class that is not a superclass):
Example:
    let d = (el: ReactDOM.element) => (el :> WebAPI.input)
Before (diagnostic):
    Type ReactDOM.element is not a subtype of WebAPI.input
After (diagnostic):
    Type ReactDOM.element is not a subtype of WebAPI.input
    ReactDOM.element is the class Element, a subclass of Node. WebAPI.input is the class HTMLInputElement. A class type coerces to its own class and to the superclasses it declares.

The fields or contents of the two declarations are not compared: each
says what its module knows about the class. A class is its path and its
module, so a global `Mesh` and the `Mesh` that `"three"` exports stay
unrelated. Where a coercion needs equal types, an invariant parameter as
in `array<_>` or a mutable field, it is checked both ways as before, which
two declarations of one class pass and a subclass does not.

Review: Can `:>` now reach a type it could not before, other than a class type? No: the arm only matches two nullary type constructors whose target states a class with its own `@instanceOf`, so `type mine = private element`, a refinement without an annotation, still accepts no coercion into it.
Review: Do programs that compiled before change? No: the arm only adds coercions, and `:>` produces the value unchanged.

Co-authored-by: Jaap Frolich <jfrolich@gmail.com>
Session: https://os.submodule.nl/session/bks-6674cba8-4481-7b1d-882a-9a317373d7c1
Signed-off-by: Jaap Frolich <jfrolich@gmail.com>
@jfrolich
jfrolich added this pull request to stack #9434 November 26, 2026 08:32
@github-actions

Copy link
Copy Markdown

Changelog

🚀 New Feature

  • A class type (@instanceOf) coerces with :> to every declaration of its
    class and of its superclasses, in any module or package. Packages can each
    declare the part of a class such as the DOM's Element that they use, and
    explicitly coerce values to each other's declarations.

Semantic Diff

1 commit · Full page

Coerce a class type to every declaration of its class and its superclasses

7964eea · jfrolich + Jaap Frolich · Nov 16, 2026, 20:23 UTC

Why

Two packages that bind the same JavaScript class each declare their own type for it, @instanceOf("Element") type element in one and in the other, and :> did not get from one to the other: it only follows the abbreviations a type is declared with. So every binding package depends on the one package that owns the DOM types, or its users convert with Obj.magic. The class an @instanceOf type names is what its values are at run time; it now decides what they coerce to.

Typing modified (:> between class types, Ctype.subtype_rec)

rule

BeforeAfter
$$\dfrac{\color{red}{p1=p2}}{\begin{array}{c}\texttt{p1}<:\texttt{p2}\end{array}} \quad \color{red}{(\textsf{Same path})}$$ $$\begin{array}{l}\dfrac{\color{green}{\mathrm{class}(p2)∈\mathrm{classes}(p1)}}{\begin{array}{c}\texttt{p1}<:\texttt{p2}\end{array}} \quad \color{green}{(\textsf{Class})} \\[1em] \begin{array}{l}\color{green}{\mathrm{class}(p):\mathrm{the}\ \mathrm{class}\ \mathrm{that}\ \mathrm{the}\ \mathrm{declaration}\ \mathrm{of}\ p\ \mathrm{itself}\ \mathrm{states}\ \mathrm{with}@\mathrm{instanceOf},\mathrm{with}\ \mathrm{its}@\mathrm{module}} \\ \color{green}{\mathrm{classes}(p):\mathrm{class}(p),\mathrm{or}\ \mathrm{the}\ \mathrm{class}\ p\ \mathrm{abbreviates},\mathrm{with}\ \mathrm{its}\ \mathrm{declared}\ \mathrm{superclasses}}\end{array}\end{array}$$

Diagnostic removed (coercions between declarations of one class)

module WebAPI = {
  @instanceOf("Node") type node
  @instanceOf("Element") type element = private node
  @instanceOf("HTMLInputElement") type input = private element
}
module ReactDOM = {
  @instanceOf("Node") type node
  @instanceOf("Element") type element = private node
}
let a = (el: ReactDOM.element) => (el :> WebAPI.element)
let b = (input: WebAPI.input) => (input :> ReactDOM.node)
let c = (els: array<ReactDOM.element>) => (els :> array<WebAPI.element>)

diagnostic · Before: each line compiled alone

-Type ReactDOM.element is not a subtype of WebAPI.element
-Type WebAPI.input is not a subtype of ReactDOM.node
-Type array<ReactDOM.element> is not a subtype of array<WebAPI.element>
-Type ReactDOM.element is not compatible with type WebAPI.element
+none

js · After

function a(el) {
  return el;
}

Diagnostic modified (a class that is not a superclass)

let d = (el: ReactDOM.element) => (el :> WebAPI.input)

diagnostic

 Type ReactDOM.element is not a subtype of WebAPI.input
+ReactDOM.element is the class Element, a subclass of Node. WebAPI.input is the class HTMLInputElement. A class type coerces to its own class and to the superclasses it declares.

The fields or contents of the two declarations are not compared: each says what its module knows about the class. A class is its path and its module, so a global Mesh and the Mesh that "three" exports stay unrelated. Where a coercion needs equal types, an invariant parameter as in array<_> or a mutable field, it is checked both ways as before, which two declarations of one class pass and a subclass does not.

Review

  • Can :> now reach a type it could not before, other than a class type? No: the arm only matches two nullary type constructors whose target states a class with its own @instanceOf, so type mine = private element, a refinement without an annotation, still accepts no coercion into it.
  • Do programs that compiled before change? No: the arm only adds coercions, and :> produces the value unchanged.

@codecov

codecov Bot commented Nov 26, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 73.91304% with 12 lines in your changes missing coverage. Please review.
✅ Project coverage is 82.21%. Comparing base (17874c0) to head (7964eea).

Files with missing lines Patch % Lines
compiler/typing/ctype.ml 80.00% 7 Missing ⚠️
compiler/typing/printtyp.ml 54.54% 5 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##           master    #9432      +/-   ##
==========================================
- Coverage   82.22%   82.21%   -0.01%     
==========================================
  Files         462      462              
  Lines       65582    65628      +46     
==========================================
+ Hits        53923    53957      +34     
- Misses      11659    11671      +12     
Files with missing lines Coverage Δ
compiler/typing/printtyp.ml 73.05% <54.54%> (-0.21%) ⬇️
compiler/typing/ctype.ml 70.52% <80.00%> (+0.10%) ⬆️

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

@github-actions

Copy link
Copy Markdown

✅ Compiler benchmarks

Allocated words

In total: 638,385,473 → 638,386,871 (±0.00%).

Generated projects: 629,067,681 → 629,067,670 (±0.00%).

None of the 265 benchmarks changed by 0.1% or more.

Instructions

In total: 9,221,423,617 → 9,222,162,913 (+0.01%).

Benchmark Base Head Change
packages/@rescript/runtime/Stdlib_Math.resi 21,298,470 21,331,201 +0.15%
packages/@rescript/runtime/Stdlib_List.resi 24,525,847 24,558,665 +0.13%
packages/@rescript/runtime/Stdlib_Temporal_PlainDate.res 24,087,324 24,119,301 +0.13%
packages/@rescript/runtime/Stdlib_Temporal_PlainDateTime.res 25,530,161 25,561,859 +0.12%
parse/RedBlackTreeNoComments.res 14,490,929 14,507,896 +0.12%
packages/@rescript/runtime/Stdlib_String.resi 29,450,605 29,481,894 +0.11%
packages/@rescript/runtime/Stdlib_Temporal_ZonedDateTime.res 31,204,074 31,235,846 +0.10%
parse/RedBlackTree.res 14,917,599 14,932,545 +0.10%

Output size

In total: 26,070,038 → 26,072,193 (+0.01%).

Benchmark Base Head Change
output/playground/compiler.js 1,889,271 1,891,426 +0.11%

Pull request 7964eea compared with base 17874c0 in this run.

@pkg-pr-new

pkg-pr-new Bot commented Nov 26, 2026

Copy link
Copy Markdown

Open in StackBlitz

rescript

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

@rescript/belt

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

@rescript/darwin-arm64

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

@rescript/linux-arm64

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

@rescript/linux-x64

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

@rescript/runtime

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

@rescript/win32-x64

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

commit: 7964eea

@github-actions

Copy link
Copy Markdown

@cknitt

cknitt commented Nov 26, 2026

Copy link
Copy Markdown
Member

@codex review

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 26, 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-26T16:42:53.011127Z 7964eea 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 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: 7964eeafec

ℹ️ 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/typing/ctype.ml
Comment on lines +3730 to +3731
match Env.find_type path env with
| {type_shape = Recognized_as (InstanceType (Class {name}))} -> Some name

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Check the target's own annotation before granting class identity

For a private refinement annotated only with @notUndefined, Variant_layout.declaration_shape copies the abbreviated type's recognized class into type_shape. Consequently, with @instanceOf("Element") type element and @notUndefined type validated = private element, this branch treats validated as another declaration of Element and accepts (el :> validated) outside its defining module. This bypasses the private refinement even though the target never declares @instanceOf, contrary to the protection described in this change. Check the declaration's actual annotation rather than relying solely on its resolved shape.

Useful? React with 👍 / 👎.

@cknitt

cknitt commented Nov 26, 2026

Copy link
Copy Markdown
Member

Thanks, this is a small, contained change, and it already gives us what we need for the WebAPI work: JSX and ReactDOM can declare their own Element, and values cross between packages with :>. I'd like to land this one first and take #9433 separately.

1. A class declaration with a record behind it lets any value of the class become that record

module W = { @instanceOf("Element") type element }
type shape = {secret: int}
module Mine = { @instanceOf("Element") type el = private shape }

let read = (x: W.element) => ((x :> Mine.el) :> shape).secret

This compiles to x.secret without Obj.magic; master rejects it. class_step accepts W.element :> Mine.el because both name Element, and never looks at what Mine.el is defined as. The same works with an object type behind the class. Could the class step apply only when the target is abstract or a declaration of another class? Then a target with a record or object behind it would go through the normal checks.

2. Please document that declared superclasses are trusted

module W = {
  @instanceOf("Node") type node
  @instanceOf("Element") type element = private node
}
module Mine = {
  @instanceOf("Element") type myEl
  @instanceOf("Node") type fakeNode = private myEl
}

let down = (n: W.node) => ((n :> Mine.fakeNode) :> W.element)

A wrong superclass in one package lets any Node become an Element everywhere. That's expected, since the compiler can't check a JS class hierarchy, but it should be written down. It fits next to the coercion rules in UntaggedVariants.md and in the @instanceOf completion text: a declaration's class and superclasses are trusted like an external's type.

Apart from these, invariant positions (array, ref, mutable fields) behave as described, and the old coercions and their errors are unchanged.

This review was done by Claude.

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