Skip to content

Coerce class types automatically at arguments - #9433

Open
jfrolich wants to merge 1 commit into
class-identity-explicitfrom
class-identity-arguments
Open

jfrolich wants to merge 1 commit into
class-identity-explicitfrom
class-identity-arguments

Conversation

@jfrolich

@jfrolich jfrolich commented Nov 26, 2026 •

Copy link
Copy Markdown
Collaborator

When a function expects one package's declaration of a JavaScript class, a value using another declaration currently needs an explicit :> even though its JavaScript representation is unchanged. This adds automatic class coercion at function arguments, record construction (including JSX props), and constructor payloads.

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

let focus = (el: ReactDOM.element) => WebAPI.focus(el)

This is the automatic-coercion part of #9413, stacked on the explicit class-coercion PR #9432. The fallback runs only after ordinary unification fails. At the outermost type it accepts the same class or a declared subclass; inside another type it accepts only declarations of the same class. Branch results, mutable-field assignments, and nested subclass coercions still require :>. Failed checks restore the type state and retain the original diagnostic.

Includes the automatic-coercion docs, completion text, runtime and diagnostic tests, and a separate changelog fragment. Function arguments include labelled, optional, and piped arguments.

Known limitation: a parameter's expected type can come from an earlier argument through a type variable. For let same: ('a, 'a) => bool, same(element, input) can compile while same(input, element) does not.

Validation: built the compiler from this branch; all five class-identity runtime tests and the full super_errors suite pass; generated regression JavaScript matches the fixtures; changelog and commit-record checks pass. The combined compiler implementation, docs, and tests match #9413. 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.

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>
@jfrolich
jfrolich added this pull request to stack #9434 November 26, 2026 08:32
@github-actions

Copy link
Copy Markdown

Changelog

🚀 New Feature

  • Accept another declaration of a JavaScript class, or a subclass, without
    :> at function arguments, record fields (including JSX props), and
    constructor payloads. Within another type, automatic coercion accepts only
    different declarations of the same class; nested subclass coercions still
    require :>.

Semantic Diff

1 commit · Full page

Accept another declaration of a class at an argument without :>

181b0bb · 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.

@github-actions

Copy link
Copy Markdown

✅ Compiler benchmarks

Allocated words

In total: 638,997,763 → 639,550,485 (+0.09%).

Generated projects: 629,067,834 → 629,168,749 (+0.02%).

Benchmark Base Head Change
stress/NestedClosures.res 10,273,654 10,314,846 +0.40%
stress/ListLiteral.res 3,400,591 3,412,593 +0.35%
stress/LetRec.res 31,619,789 31,715,785 +0.30%
packages/@rescript/belt/src/Belt_Array.res 2,154,305 2,158,211 +0.18%
packages/@rescript/belt/src/Belt_SortArrayInt.res 1,342,434 1,344,836 +0.18%
packages/@rescript/belt/src/Belt_SortArrayString.res 1,344,236 1,346,623 +0.18%
packages/@rescript/belt/src/Belt_SortArray.res 1,447,593 1,450,002 +0.17%
packages/@rescript/runtime/Primitive_hash.res 964,625 966,053 +0.15%
packages/@rescript/runtime/Primitive_object.res 1,154,877 1,156,547 +0.14%
stress/InlineChain.res 3,511,214 3,516,022 +0.14%
22 more changes
Benchmark Base Head Change
build/leaf-edit 13,047,663 13,065,231 +0.13%
build/shared-edit 73,423,892 73,521,081 +0.13%
build/no-op 9,233,662 9,245,870 +0.13%
packages/@rescript/belt/src/Belt_internalAVLset.res 2,876,045 2,879,808 +0.13%
packages/@rescript/belt/src/Belt_internalAVLtree.res 3,506,414 3,510,728 +0.12%
packages/@rescript/runtime/Primitive_array.res 191,995 192,219 +0.12%
packages/@rescript/runtime/Stdlib_List.res 2,686,433 2,689,524 +0.12%
packages/@rescript/belt/src/Belt_MutableSet.res 1,902,486 1,904,674 +0.12%
packages/@rescript/belt/src/Belt_MutableSetString.res 1,665,812 1,667,684 +0.11%
packages/@rescript/belt/src/Belt_MutableQueue.res 791,345 792,225 +0.11%
packages/@rescript/belt/src/Belt_MutableSetInt.res 1,664,566 1,666,414 +0.11%
packages/@rescript/runtime/Primitive_option.res 297,422 297,748 +0.11%
packages/@rescript/belt/src/Belt_internalBuckets.res 966,635 967,689 +0.11%
packages/@rescript/belt/src/Belt_HashSetInt.res 850,531 851,434 +0.11%
packages/@rescript/belt/src/Belt_List.res 3,175,370 3,178,734 +0.11%
packages/@rescript/belt/src/Belt_HashSetString.res 850,848 851,749 +0.11%
packages/@rescript/belt/src/Belt_HashMapInt.res 1,060,718 1,061,834 +0.11%
packages/@rescript/runtime/Stdlib_Array.res 1,281,112 1,282,458 +0.11%
packages/@rescript/belt/src/Belt_HashMapString.res 1,061,430 1,062,544 +0.10%
packages/@rescript/belt/src/Belt_HashMap.res 1,200,060 1,201,314 +0.10%
packages/@rescript/belt/src/Belt_HashSet.res 978,219 979,235 +0.10%
stress/RefsInLoop.res 16,462,416 16,479,218 +0.10%

Instructions

In total: 9,222,162,488 → 9,226,038,556 (+0.04%).

Benchmark Base Head Change
packages/@rescript/runtime/Stdlib_Math.resi 21,331,193 21,408,029 +0.36%
stress/ListLiteral.res 131,179,457 131,635,041 +0.35%
packages/@rescript/runtime/Stdlib_Temporal_PlainDate.res 24,119,293 24,196,840 +0.32%
packages/@rescript/runtime/Stdlib_List.resi 24,558,657 24,634,881 +0.31%
packages/@rescript/runtime/Stdlib_Temporal_PlainDateTime.res 25,561,851 25,637,446 +0.30%
parse/RedBlackTreeNoComments.res 14,507,856 14,547,785 +0.28%
packages/@rescript/runtime/Stdlib_String.resi 29,481,886 29,559,694 +0.26%
parse/RedBlackTree.res 14,932,505 14,970,201 +0.25%
packages/@rescript/belt/src/Belt_Array.resi 33,742,789 33,819,324 +0.23%
packages/@rescript/runtime/Stdlib_Date.resi 34,318,132 34,394,531 +0.22%
8 more changes
Benchmark Base Head Change
packages/@rescript/runtime/Stdlib_Temporal_ZonedDateTime.res 31,235,838 31,304,747 +0.22%
packages/@rescript/belt/src/Belt_List.resi 39,001,542 39,078,131 +0.20%
packages/@rescript/runtime/Stdlib_Array.resi 40,140,446 40,216,760 +0.19%
packages/@rescript/runtime/Stdlib_TypedArray.res 41,359,812 41,436,378 +0.19%
format/RedBlackTreeNoComments.res 24,091,255 24,129,574 +0.16%
format/RedBlackTree.res 24,436,213 24,474,532 +0.16%
packages/@rescript/belt/src/Belt_List.res 118,164,712 118,310,312 +0.12%
packages/@rescript/belt/src/Belt_internalAVLtree.res 136,450,656 136,589,076 +0.10%

Output size

In total: 26,089,181 → 26,090,118 (±0.00%).

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

Pull request 181b0bb compared with base 7964eea 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@9433

@rescript/belt

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

@rescript/darwin-arm64

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

@rescript/linux-arm64

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

@rescript/linux-x64

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

@rescript/runtime

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

@rescript/win32-x64

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

commit: 181b0bb

@codecov

codecov Bot commented Nov 26, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 94.28571% with 4 lines in your changes missing coverage. Please review.
✅ Project coverage is 82.22%. Comparing base (7964eea) to head (181b0bb).

Files with missing lines Patch % Lines
compiler/typing/ctype.ml 91.11% 4 Missing ⚠️
Additional details and impacted files
@@                   Coverage Diff                    @@
##           class-identity-explicit    #9433   +/-   ##
========================================================
  Coverage                    82.21%   82.22%           
========================================================
  Files                          462      462           
  Lines                        65628    65666   +38     
========================================================
+ Hits                         53957    53992   +35     
- Misses                       11671    11674    +3     
Files with missing lines Coverage Δ
compiler/typing/typecore.ml 89.17% <100.00%> (+0.05%) ⬆️
compiler/typing/ctype.ml 70.79% <91.11%> (+0.26%) ⬆️

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

@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:43:24.047756Z 181b0bb 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: 181b0bbbda

ℹ️ 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 +4398 to +4400
type_expect ~context ~class_coercion ?recarg env sarg ty_expected'
in
if class_coercion then unify_exp_at_argument ~context env texp ty_expected

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 Apply the class fallback to inline callback arguments

When a callback literal annotates its parameter with another declaration of the expected class, type_expect raises before reaching the fallback below. For example, using the added test modules, View.handle((_: Class_identity_dom.event) => (), Class_identity_dom.makeEvent()) is rejected, although binding that same callback to listener and passing listener succeeds. The Pexp_fun path calls type_function with the expected arrow type, so its parameter-pattern check requires ordinary unification and never uses class_coercion. Handle this early checking failure as well so the advertised coercion for function-valued arguments works for inline event handlers, not just previously bound functions.

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.

2 participants