RFR: [type-classes] Initial work to enable type-classes mediated operator support

Maurizio Cimadamore mcimadamore at openjdk.org
Fri Jan 23 10:29:06 UTC 2026


On Thu, 22 Jan 2026 17:57:55 GMT, Maurizio Cimadamore <mcimadamore at openjdk.org> wrote:

> This PR adds experimental support for type-class based operator resolution. This means that it is possible to define classes that "witness" some numerical type class, like so:
> 
> 
> record Box(int i) {
>    __witness Integral<Box> INTEGRAL = ...
> }
> 
> 
> Then, we can start using `Box` in e.g. binary operations, like so:
> 
> 
> Box one = new Box(1);
> Box two = new Box(1);
> one + two // three
> 
> 
> In order to support type-class mediated operator resolution, we needed to add a new kind of operator helper in `Operators`. These new operator helpers (one for unary operators, one for binary operators) wrap some method in one of the standard numeric classes -- for instance, type class `+` is realized through `Numerical::add`, and so forth.
> 
> There's a new kind of operator symbol, namely `TypeClassOperatorSymbol` which is used to store the type of the operation as well as the method symbol in charge of performing the operation.
> 
> To resolve an operator, we basically have to prove that a witness for the corresponding class, parameterized by the operand type exists. E.g. in the above, we need to find a witness for `Numerical<Box>`.
> 
> During lowering, we emit such witness, and call the correct operator method on it.
> 
> Note that support for assignment operators is also provided -- `Lower` already has logic to lower some assignment operators into plain binary operations, so we just leverage that support to translate type-class based assignment ops.

src/jdk.compiler/share/classes/com/sun/tools/javac/comp/Operators.java line 794:

> 792:                         .addUnaryOperator(LONG, LONG, nop)
> 793:                         .addUnaryOperator(INT, INT, nop),
> 794:                 new UnaryTypeClassOperator(Tag.POS, numerical, "plus"),

Note: all type class-backed operators are defined by stating:
* the class in which the operator method is defined (here `numerical`)
* the name (a string) of the operator method (here `"plus"`)
We don't need a type, as we assume the type is going to be compatible with the shape of the unary/binary operator.

This should allow us to change the numeric type class hierarchy with ease, and only do minimal changes here to keep the compiler support up and running (at least that was the intention).

-------------

PR Review Comment: https://git.openjdk.org/valhalla/pull/1948#discussion_r2720620378


More information about the valhalla-dev mailing list