[patterns] primitive widening

John Rose john.r.rose at oracle.com
Sat Oct 14 23:02:14 UTC 2017

Interesting question:  Should a "Short" box value
match a "long" primitive?  More generally, should
pattern matching emulate assignment conversions?
Including primitive widening conversions?  

Probably the answer is yes, under the theory that
a pattern match digs through dynamic information to
search for a *possible* assignment, and then (along
that "match succeeded" path, is ready to make the
assignment to a binding variable.

    void test(Short x) {
        long y = x; //OK
        longConsumer(x); //OK
        assert(x matches long);  //OK??
    void longConsumer(long z) { }

Does the prototype work that way?  No, there is just an
open-coded instanceof test of the wrapper type
(makeTypeTest … boxedTypeOrType).

This is tricky to implement dynamically, but MH.invoke
gets these details correct already, since it makes a
dynamic emulation of (many of) Java's static rules for
method argument conversion.

("Many of" means that the dynamic emulation is aware
only of reified types, as if only raw types were present.
Happily, the Core Reflection API also does the same
emulation, although with different exceptions thrown.)

These are the relevant routines from the MH runtime:

One good thing about this messy stuff:  The widening
primitive conversions (and narrowing ones, in the case
of a cast) only come into play when the target type is
really a primitive, not just a reference wrapping one.

So we don't have to match a Short to a Long, just
a Byte, Short, Character, Integer, Float, and Long to
a primitive long (if the source type is a reference
type that can contain any or all of the above).

A factored runtime for pattern matching will be able
to use the MH routines, if we decide that's the correct
behavior.  By "factored runtime" I hope for, of course,
something with a metafactory for each switch and

— John

More information about the amber-dev mailing list