FTR: LW2 array covariance

David Simms david.simms at oracle.com
Fri Apr 12 10:57:14 UTC 2019


Just dropping a note array covariance and reference conversions rules as 
we currently understand them for LW2 prototype (coming soon...-ish).

Firstly, a small reminder of null-free references. The current prototype 
is still using "Foo.val" and "Foo.box" syntax, but this will change to:

  * "Foo" for "null-free value type" (the best kind)
      o LW2 JVMS draft uses "QFoo;" (Q-type descriptors)
  * "Foo?" value type reference allowing (for compatibility with
    existing object references)
      o LW2 JVMS draft uses "LFoo;" (L-type descriptors)

So using this notation, on to arrays. LW2 is looking to using covariance 
to allow existing code like "Arrays.sort([LObject;)" to "just work", 
even with null-free arrays:

"[QFoo;" <: "[LFoo;” <: “[LObject;” <: “Object;"

We can freely allow widening conversion, but not narrowing. The VM will 
support passing value type arrays into old code, but new code users 
can’t “cast” an array of null-allowable value types into an array of 
null-free value types.

Some checkcast requirements for reference conversions:

  * Q->L : "widening reference conversion" (i.e. JLS 5.1.5)
  * L->Q : "narrowing reference conversion", requires checkcast (cast in
    source)

And for arrays...

  * [Q->[L : widening
  * [L->[Q : narrowing, we can't. checkcast (cast in source) will fail
    if not [Q

Some source code...

   Foo?[] la = la();

   Foo[] qa = qa();

   qa = (Foo[]) la;  // should fail to compile if type known

   qa = (Foo[]) makeErasedReturnType(); // needs checkcast, will pass only if return reference is Foo[]

   la = qa; // Is fine (no checkcast required for Q-to-L conversions)

   Foo?[] la2 = qa;

   Foo[] qa2 = (Foo[]) la2; // checkcast, which will pass

So existing code that accepts and returns array instances, may indeed 
accept null-free arrays without knowing anything about null-free 
qualities. This may result in an exception if an attempt to store null 
is made. So it is up to new code using null-free arrays together with 
existing L-type signatures to actually test or check if null-store are a 
risk.

New code using existing code that returns traditional null-allowed 
arrays, cannot simply cast to a null-free array, but must make a copy.

/David Simms






More information about the valhalla-dev mailing list