Skip to content

Coerce a class type to every declaration of its class - #9413

Closed
jfrolich wants to merge 3 commits into
rescript-lang:masterfrom
jfrolich:class-identity
Closed

jfrolich wants to merge 3 commits into
rescript-lang:masterfrom
jfrolich:class-identity

Conversation

@jfrolich

@jfrolich jfrolich commented Nov 25, 2026 •

Copy link
Copy Markdown
Collaborator

Superseded by #9432 (explicit class coercions) and #9433 (automatic argument coercions), recreated on branches in rescript-lang/rescript and linked as stack #9434.


Builds on #9309, which made a class its path and its @module.

Two packages that bind the same JavaScript class each declare their own type for it, and today those types are unrelated: :> only follows the abbreviations a type is declared with. A package that binds DOM APIs therefore has to depend on the one package that owns the DOM types, or its users convert with Obj.magic. With this PR the class that @instanceOf names decides what a class type coerces to, so every package can declare the part of a class it uses.

module WebAPI = {
  @instanceOf("Node") type node
  @instanceOf("Element") type element = private node
  @instanceOf("HTMLInputElement") type input = private element
  @send external focus: element => unit = "focus"
}
module ReactDOM = {
  @instanceOf("Element") type element
  type props = {container: element}
}

let f = (el: ReactDOM.element, input: WebAPI.input) => {
  WebAPI.focus(el) // accepted without :>
  let props: ReactDOM.props = {container: input} // a subclass too
  (el :> WebAPI.element) // explicit
}
  • :>. A class type coerces to any type whose own declaration states its class or one of its declared superclasses, in any module or package. Where a coercion needs equal types (array<_>, ref<_>, a mutable field), two declarations of one class are equal and a subclass is not. A private abbreviation without its own @instanceOf (type mine = private element) is a refinement, and nothing coerces into it. A global Mesh and the Mesh that "three" exports stay unrelated.
  • No :> at an argument. At a site that declares the type it expects (a function parameter, including labelled, optional and piped arguments; a field of a record being built, which includes JSX props in both the prop=x and prop={x} forms; a constructor payload), an argument of another declaration of the class, or of a subclass, is accepted and gets the expected type. Inside another type only the same class is accepted that way (option<input> for option<element> still needs :>). It is not applied where the expected type comes from a neighbouring expression, such as the other branch of an if or switch, because the result would then depend on the order of the branches. Assignments to a mutable field also keep :>.
  • Error. A refused coercion between class types now names both classes: 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.
  • Compatibility. Programs that compiled before keep their types and JavaScript. The implicit rule is only tried where unification already failed, and a failed check restores the type state, so other errors print as before. All existing super_errors expectations and generated test outputs are unchanged.

Implementation: a class arm in Ctype.subtype_rec (class_step), a Same_class mode of it for the implicit rule (Ctype.coerces_between_class_declarations), applied by Typecore.unify_exp_at_argument. No .cmi change: classes come from type_shape.

Docs and tests:

  • Docs: rule 5 of compiler/typing/UntaggedVariants.md, the @instanceOf completion doc.
  • tests/tests/src/class_identity_test.res (with class_identity_dom.res as the other package, read from its .cmi) runs explicit coercions, invariant positions, arguments, record fields, constructor payloads and a listener of one declaration passed for another.
  • super_errors fixtures class_identity_not_an_ancestor, class_identity_branches, class_identity_nested_subclass and class_identity_set_field cover the new message and the places where :> stays written.

Known limitation: the expected type of an argument can itself come from an earlier argument through a type variable. For let same: ('a, 'a) => bool, same(element, input) compiles because input is accepted as an element, while same(input, element) does not.

Checklist

  • Added a changelog fragment (see changes/README.md), or no release notes are needed and a maintainer should apply changelog:skip.
  • Added tests for the fix or feature.
  • Gave every commit a description below its subject, saying why it is made (see "Commit messages" in CONTRIBUTING.md).
  • Signed off every commit for the DCO (git commit -s).

Started by Jaap Frolich in this Assistant session

…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>
Why:
    With the previous commit `WebAPI.focus((el :> WebAPI.element))` compiles
    for an `el: ReactDOM.element`, but each call into another package's
    bindings still needs the written coercion, also for every JSX prop.
    Where the compiler knows the type a site expects, it can make the
    coercion itself: the two types name one class, and the value is the
    same.

Typing modified (an argument at a site that declares its type, `Typecore.unify_exp_at_argument`):
Before (rule):
    Γ ⊢ e : τ   τ = τ'
    ──────────────────── (Argument)
    Γ ⊢ e : τ' at a parameter, record field or constructor payload of type τ'
After (rule):
    Γ ⊢ e : τ   τ = τ'
    ──────────────────── (Argument)
    Γ ⊢ e : τ' at a parameter, record field or constructor payload of type τ'

    Γ ⊢ e : τ   τ ≠ τ'   τ ≤class τ'
    ──────────────────── (Class argument)
    Γ ⊢ e : τ' at a parameter, record field or constructor payload of type τ'

    τ ≤class τ': τ is a class type of the class of τ' or of a subclass, or τ and τ' are equal up to two declarations of one class inside them

Diagnostic removed (another declaration of the parameter's class):
Example:
    module WebAPI = {
      @instanceof("Element") type element
      @instanceof("HTMLInputElement") type input = private element
      @send external focus: element => unit = "focus"
    }
    module ReactDOM = {
      @instanceof("Element") type element
      type props = {container: element}
    }
    let a = (el: ReactDOM.element) => WebAPI.focus(el)
    let b = (input: WebAPI.input): ReactDOM.props => {container: input}
Before (diagnostic): each line compiled alone
    This has type: ReactDOM.element
    But this function argument is expecting: WebAPI.element

    This has type: WebAPI.input
    But the record field container is expected to have type: ReactDOM.element
After (diagnostic): none
After (js):
    function a(el) {
      el.focus();
    }
    function b(input) {
      return {
        container: input
      };
    }

Diagnostic modified (where `:>` stays written):
Example:
    let c = (first, a: ReactDOM.element, b: WebAPI.element) => first ? a : b
    let take = (_: option<ReactDOM.element>) => ()
    let d = (input: option<WebAPI.input>) => take(input)
Before (diagnostic): each compiled alone, the second with the parent commit's compiler
    This has type: WebAPI.element
    But this ternary is expected to return: ReactDOM.element

    This has type: option<WebAPI.input>
    But this function argument is expecting: option<ReactDOM.element>
    The incompatible parts:
      WebAPI.input vs ReactDOM.element
    Possible solutions:
    - These types are compatible at runtime. You can use the coercion operator to convert to the expected type: (input :> option<ReactDOM.element>)
After (diagnostic): unchanged

The sites are the parameters of a function (labelled, optional and piped
arguments too), the fields of a record being built, which includes JSX
props, and constructor payloads: their expected type is declared. In
`first ? a : b` the expected type of `b` is the type of `a`, so accepting
it would make the type of the result, and with a subclass whether it
compiles, depend on the order of the branches; an assignment to a mutable
field keeps `:>` too. Inside another type only the same class is accepted
(`Same_class` steps of `subtype_rec`): `option<input>` for
`option<element>` is a subclass coercion that `:>` states. The argument
gets the expected type, as `(e :> t)` would give it.

Review: Does a program that compiled before get other types? No: the rule is only tried where the argument's type failed to unify with the expected one, which was an error.
Review: Are other errors printed differently? No: when the class check fails, it restores the type state it changed and the original clash is raised. The super_errors expectations are 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>
The rules for `@instanceOf` types in `UntaggedVariants.md` and the
`@instanceOf` completion doc now say what a class type coerces to and where
no `:>` is needed, with the errors and their fixtures. The changelog
fragment describes the feature of the two commits before.

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>
@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, and is accepted
    without :> as a function argument, a record field (so a JSX prop) or a
    constructor payload where another declaration of its class is expected.
    Packages can then each declare the part of a class such as the DOM's
    Element that they use, and pass values to each other.

Semantic Diff

3 commits · Full page

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

bfce750 · 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.
Accept another declaration of a class at an argument without :>

6231f0b · jfrolich + Jaap Frolich · Nov 16, 2026, 20:24 UTC

Why

With the previous commit WebAPI.focus((el :> WebAPI.element)) compiles for an el: ReactDOM.element, but each call into another package's bindings still needs the written coercion, also for every JSX prop. Where the compiler knows the type a site expects, it can make the coercion itself: the two types name one class, and the value is the same.

Typing modified (an argument at a site that declares its type, Typecore.unify_exp_at_argument)

rule

BeforeAfter
$$\dfrac{Γ⊢e:τ \qquad τ=τ'}{\begin{array}{c}Γ⊢e:τ'\ \mathrm{at}\ a\ \mathrm{parameter},\mathrm{record}\ \mathrm{field}\ \mathrm{or}\ \mathrm{constructor}\ \mathrm{payload}\ \mathrm{of}\ \mathrm{type}\ τ'\end{array}} \quad (\textsf{Argument})$$ $$\begin{array}{l}\dfrac{Γ⊢e:τ \qquad τ=τ'}{\begin{array}{c}Γ⊢e:τ'\ \mathrm{at}\ a\ \mathrm{parameter},\mathrm{record}\ \mathrm{field}\ \mathrm{or}\ \mathrm{constructor}\ \mathrm{payload}\ \mathrm{of}\ \mathrm{type}\ τ'\end{array}} \quad (\textsf{Argument}) \\[1em] \dfrac{\color{green}{Γ⊢e:τ} \qquad \color{green}{τ≠τ'} \qquad \color{green}{τ≤\mathrm{class}\ τ'}}{\begin{array}{c}\color{green}{Γ⊢e:τ'\ \mathrm{at}\ a\ \mathrm{parameter},\mathrm{record}\ \mathrm{field}\ \mathrm{or}\ \mathrm{constructor}\ \mathrm{payload}\ \mathrm{of}\ \mathrm{type}\ τ'}\end{array}} \quad \color{green}{(\textsf{Class argument})} \\[1em] \begin{array}{l}\color{green}{τ≤\mathrm{class}\ τ':τ\ \mathrm{is}\ a\ \mathrm{class}\ \mathrm{type}\ \mathrm{of}\ \mathrm{the}\ \mathrm{class}\ \mathrm{of}\ τ'\ \mathrm{or}\ \mathrm{of}\ a\ \mathrm{subclass},\mathrm{or}\ τ\ \mathrm{and}\ τ'\ \mathrm{are}\ \mathrm{equal}\ \mathrm{up}\ \mathrm{to}\ \mathrm{two}\ \mathrm{declarations}\ \mathrm{of}\ \mathrm{one}\ \mathrm{class}\ \mathrm{inside}\ \mathrm{them}}\end{array}\end{array}$$

Diagnostic removed (another declaration of the parameter's class)

module WebAPI = {
  @instanceOf("Element") type element
  @instanceOf("HTMLInputElement") type input = private element
  @send external focus: element => unit = "focus"
}
module ReactDOM = {
  @instanceOf("Element") type element
  type props = {container: element}
}
let a = (el: ReactDOM.element) => WebAPI.focus(el)
let b = (input: WebAPI.input): ReactDOM.props => {container: input}

diagnostic · Before: each line compiled alone

-This has type: ReactDOM.element
-But this function argument is expecting: WebAPI.element
-
-This has type: WebAPI.input
-But the record field container is expected to have type: ReactDOM.element
+none

js · After

function a(el) {
  el.focus();
}
function b(input) {
  return {
    container: input
  };
}

Diagnostic modified (where :> stays written)

let c = (first, a: ReactDOM.element, b: WebAPI.element) => first ? a : b
let take = (_: option<ReactDOM.element>) => ()
let d = (input: option<WebAPI.input>) => take(input)

diagnostic · Before: each compiled alone, the second with the parent commit's compiler

-This has type: WebAPI.element
-But this ternary is expected to return: ReactDOM.element
-
-This has type: option<WebAPI.input>
-But this function argument is expecting: option<ReactDOM.element>
-The incompatible parts:
-  WebAPI.input vs ReactDOM.element
-Possible solutions:
-- These types are compatible at runtime. You can use the coercion operator to convert to the expected type: (input :> option<ReactDOM.element>)
+unchanged

The sites are the parameters of a function (labelled, optional and piped arguments too), the fields of a record being built, which includes JSX props, and constructor payloads: their expected type is declared. In first ? a : b the expected type of b is the type of a, so accepting it would make the type of the result, and with a subclass whether it compiles, depend on the order of the branches; an assignment to a mutable field keeps :> too. Inside another type only the same class is accepted (Same_class steps of subtype_rec): option<input> for option<element> is a subclass coercion that :> states. The argument gets the expected type, as (e :> t) would give it.

Review

  • Does a program that compiled before get other types? No: the rule is only tried where the argument's type failed to unify with the expected one, which was an error.
  • Are other errors printed differently? No: when the class check fails, it restores the type state it changed and the original clash is raised. The super_errors expectations are unchanged.
Document that class types coerce by their class

db3017f · jfrolich + Jaap Frolich · Nov 16, 2026, 20:24 UTC

The rules for @instanceOf types in UntaggedVariants.md and the @instanceOf completion doc now say what a class type coerces to and where no :> is needed, with the errors and their fixtures. The changelog fragment describes the feature of the two commits before.

@codecov

codecov Bot commented Nov 25, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 86.08696% with 16 lines in your changes missing coverage. Please review.
✅ Project coverage is 82.22%. Comparing base (0bd4be2) to head (db3017f).

Files with missing lines Patch % Lines
compiler/typing/ctype.ml 86.07% 11 Missing ⚠️
compiler/typing/printtyp.ml 54.54% 5 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##           master    #9413      +/-   ##
==========================================
- Coverage   82.22%   82.22%   -0.01%     
==========================================
  Files         462      462              
  Lines       65578    65662      +84     
==========================================
+ Hits        53921    53990      +69     
- Misses      11657    11672      +15     
Files with missing lines Coverage Δ
compiler/typing/typecore.ml 89.17% <100.00%> (+0.05%) ⬆️
compiler/typing/printtyp.ml 73.05% <54.54%> (-0.21%) ⬇️
compiler/typing/ctype.ml 70.79% <86.07%> (+0.36%) ⬆️

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

@pkg-pr-new

pkg-pr-new Bot commented Nov 25, 2026

Copy link
Copy Markdown

Open in StackBlitz

rescript

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

@rescript/belt

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

@rescript/darwin-arm64

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

@rescript/linux-arm64

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

@rescript/linux-x64

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

@rescript/runtime

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

@rescript/win32-x64

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

commit: db3017f

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