Class CollectionToArrayHeuristics

  extended by checkers.nullness.CollectionToArrayHeuristics

public class CollectionToArrayHeuristics
extends Object

Handles calls to Collection.toArray() and determines the appropriate nullness type of the returned value.

Collection.toArray() and Collection.toArray(T[]) method semantics cannot be captured by the regular type system. Namely, the nullness of the returned array component depends on the receiver type argument. So

     Collection<@NonNull String> c1 = ...
     c1.toArray();    // --> returns @NonNull Object []

     Collection<@Nullable String> c2 = ...
     c2.toArray();    // --> returns @Nullable Object []
In the case of Collection.toArray(T[]), the type of the returned array depends on the passed parameter as well and its size. In particular, the returned array component would of type @NonNull if the following conditions hold:
  1. The receiver collection type argument is NonNull
  2. The passed array size is less than the collection size
While checking for the second condition, requires a runtime check, we provide heuristics to handle the most common cases of Collection.toArray(T[]), namely if the passed array is
  1. an empty array initializer, e.g. c.toArray(new String[] { }),
  2. array creation tree of size 0, e.g. c.toArray(new String[0]), or
  3. array creation tree of the collection size method invocation c.toArray(new String[c.size()])
Note: The nullness of the returned array doesn't depend on the passed array nullness.

Constructor Summary
Constructor and Description
CollectionToArrayHeuristics(ProcessingEnvironment env, NullnessAnnotatedTypeFactory factory)
Method Summary
Modifier and Type Method and Description
 void handle(MethodInvocationTree tree, AnnotatedTypeMirror.AnnotatedExecutableType method)
          Apply the heuristics to the given method invocation and corresponding Collection.toArray() type.
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail


public CollectionToArrayHeuristics(ProcessingEnvironment env,
                                   NullnessAnnotatedTypeFactory factory)
Method Detail


public void handle(MethodInvocationTree tree,
                   AnnotatedTypeMirror.AnnotatedExecutableType method)
Apply the heuristics to the given method invocation and corresponding Collection.toArray() type. If the method invocation is a call to toArray, then it manipulates the returned type of method arg to contain the appropriate nullness. Otherwise, it does nothing.

tree - method invocation tree
method - invoked method type