Skip to content

Should we support a definitely-nullable type parameter (or wildcard)? #85

Closed

Description

@kevinb9n

I'm splitting this from #60 as a single focused requirements question.

Should we support declaring a type parameter which can only be given nullable types as type arguments?

What are the compelling use cases? We think Guava's ArrayTable might be one and should examine it in a future comment here.

Its Equivalence is almost an example, because its public APIs guarantee to accept null and to return null in cases. But, it has a protected API as well, which makes clear that we actually need <T extends @NotNull Object> and it is only the appearances of T in the public methods that should be projected to nullable. (Not the other way around, since it's senseless to admit different parameterizations of that type; all Equivalences are mandated to handle null in exactly the same way.)

The case has been raised in #60 of a method which reads values from a list but nulls them out as it goes.

Activity

  1. cpovirk commented on Dec 5, 2019

    @cpovirk
    Collaborator

    We can look for motivation for this in 2 places:

    1. What additional functionality would this provide?
    2. For use cases that are already possible to express, when does this allow users to better expression their intention?

    For (1):

    • We have one implementation detail in Equivalence.Wrapper that benefits from a definitely-nullable type parameter or (or, alternatively, from projecting to @NotNull).
    • For nulling out values in a list as we read them, I think I much belatedly found a solution that doesn't require definitely-nullable type parameters: <T extends Foo> void foo(List<@Nullable T> c). Note, though, that that requires introducing a type parameter that looks unnecessary.

    For (2), let's look at ArrayTable (as proposed) and also Equivalence:

    Seen through one lens, ArrayTable and Equivalence are the same: Without support for definitely-nullable parameters, they have to be defined as:

    class Sub<T> extends Super<@Nullable T>

    It's a little weird that Sub is a subtype of Super and yet Sub<T> isn't a subtype of Super<T>. I don't think it causes any kind of behavioral problem, but I suspect it's the kind of thing that Stephan had in mind when saying that definitely-nullable parameters offer a better way to express his intention.

    As for the type parameter of Equivalence specifically: If we were to make it definitely-nullable, we'd need to project the types it uses in its protected methods to @NotNull. This seems as legitimate as any other case for definitely-nullable and projecting to @NotNull. If there's a difference between it and ArrayTable, it might be this:

    • ArrayTable<Foo, Bar, Baz> looks like it ought to have non-null values: First, we know that a plain Table<K, C, V> contains values of type V (similar to with other collection types). Second, it's particularly unfortunate that the bare Foo and Bar do force non-null keys, yet the bare Baz does not do the same for values.

    • Equivalence<Foo>, by contrast, doesn't immediately call to mind its supertype of BiPredicate. Nor does it take a second type argument that affects nullness in a different way. Thus, it's more likely that people will see Equivalence<Foo> and understand that it can accept null than see ArrayTable<Foo, Bar, Baz> and understand the same.

  2. cpovirk commented on Dec 5, 2019

    @cpovirk
    Collaborator

    Pulling in a couple points from other threads:

    1. All else being equal, I like the idea of having only one way to annotate a class for nullness, rather than multiple ways. So, given that it's possible for us to write interface Equivalence<T extends @NonNull Object>, I'd (all else being equal) prefer not to also support interface Equivalence<@MustBeNullable T>. This way, similar classes are likely to be annotated in similar ways, and users will learn what to expect without having to read each type individually. This also helps during incremental adoption: If Equivalence hasn't been annotated yet, users know the one way that it can be annotated, so they can write their usage code in a way that will pass checks when it's later annotated. (And if multiple people independently write stub files for Equivalence to help with the adoption process, those stubs will match.)

    2. Another point related to unannotated code: If we rule out definitely-nullable parameters, then we may be able to always let users write Foo<@NonNull Bar> without a warning, even if Foo has not be annotated for nullness. (Many usages of the resulting object may still trigger warnings, but hopefully not all will, and even if they do, we can reduce the scope of the warnings.)

  3. cpovirk commented on Dec 5, 2019

    @cpovirk
    Collaborator

    (In the same boat as Equivalence: Converter.)

  4. cpovirk commented on Dec 6, 2019

    @cpovirk
    Collaborator

    I looked through the Checker Framework's JDK stubs, and I found one example: The Checker Framework forces ThreadLocal to be instantiated with a nullable type.

    That's an interesting case: I view ThreadLocal like Equivalence and friends, only without the "Equivalence<T> is not a BiPredicate<T, T>" baggage. That is, I would declare its type parameter to require a non-null type T, and I'd declare its methods to operate on @Nullable T:

    class ThreadLocal<T extends @NonNull Object> {
      public @Nullable T get() { ... }
      ...
    }

    In contrast, the Checker Framework has:

    class ThreadLocal<@Nullable T> {
      public T get() { ... }
      ...
    }

    These two are equivalent from the perspective of a user, except that my approach would have the user write ThreadLocal<Foo>, while the Checker Framework's would have the user write ThreadLocal<@Nullable Foo>.

    One advantage of my approach is that it makes for marginally shorter code :) But the real reason I like it is that it's the approach that lets us avoid definitely-nullable type parameters entirely, as discussed above.

    One factor that could go either way: Reasonable people could disagree about which approach better expresses intent.

    The advantage of the Checker Framework's approach is: It's possible to instantiate the class with a non-null type (if you suppress a warning). This can make sense if you override initialValue, thereby ensuring that get always returns a non-null value. Since get returns T, the Checker Framework knows that ThreadLocal<Foo>.get() will return a non-null value.

    However, this is a bit scary: Once you have a ThreadLocal whose type parameter doesn't "fit" into the normal bound for the class, you start getting errors when passing it to methods that accept a ThreadLocal<?>:

    UseThreadLocal.java:5: error: [argument.type.incompatible] incompatible types in argument.
        doSomething(new MyThreadLocal());
                    ^
      found   : @Initialized @NonNull MyThreadLocal
      required: @Initialized @NonNull ThreadLocal<? extends @Initialized @Nullable Object>
    1 error
    

    (Of course, there's yet another option here (well, in addition to "add special support"): We could let users instantiate ThreadLocal with any bound, and we could document that they should use a non-null bound only when overriding initialValue. This would be unsound, but that's not a disqualifier for us. (My guess is that that won't turn out to be the best tradeoff, but I haven't done any research into usages.))

    [edit: We ended up going a different direction with ThreadLocal (and the similar case of AtomicReference).]

  5. cpovirk commented on Dec 9, 2019

    @cpovirk
    Collaborator

    (Cross-link: Use cases for this might also been seen as use cases for #78 and vice versa.)

  6. abreslav commented on Dec 9, 2019

    @abreslav

    What existing systems allow expressing definitely-nullable type parameters? I think most systems I know don't allow this

  7. cpovirk commented on Dec 9, 2019

    @cpovirk
    Collaborator

    Eclipse and CF both do:

    For exact specification a null annotation may be attached to the type parameter declaration itself, which is interpreted as defining both an upper and a lower bound.

    To specify an exact bound, place the same annotation on both bounds.

  8. kevinb9n commented on Dec 11, 2019

    @kevinb9n
    CollaboratorAuthor

    A separate question is, assuming a type parameter that isn't of this "definitely-nullable" kind (and whether we even support that kind or not), should we support a definitely-nullable wildcard? For now I'm okay treating that as part of this issue as well.

  9. changed the title [-]Should we support a definitely-nullable type parameter?[/-] [+]Should we support a definitely-nullable type parameter (or wildcard)?[/+] on Dec 11, 2019
  10. cpovirk commented on Dec 11, 2019

    @cpovirk
    Collaborator

    We are sure to support one kind definitely nullable wildcard, the kind you get with ? super @Nullable Foo. I suspect that you're thinking mostly in terms of a special @Nullable ? that can match any nullable type (and of course, only nullable types). If so, I think this takes us back to the replaceEmptiesWithNulls example in #60.

  11. added
    nullness
    on Dec 12, 2019
  12. cpovirk commented on Dec 13, 2019

    @cpovirk
    Collaborator

    I was thinking a little about another way to emulate this without adding the feature. I don't really like what I came up with, but here it is:

    public class Foo<T extends @Nullable Object> {
      private Foo(...) { ... }
    
      public static <T extends @NonNull Object> Foo<@Nullable T> create(...) { ... }
    }

    This makes it impossible to create a Foo<@NonNull Something>. However, it's still possible to declare variables, etc. of that type. It's also possible to write a type parameter <T extends @Nullable Object> and then refer to a Foo<T>, and Java won't know that T must be @Nullable in that case. To ensure that Java knows that the type is always nullable, you have to stick with the original trick of consistently referring to Foo<@Nullable T>. (And if you want Foo<@Nullable ?>, you might need to declare an "unnecessary" type parameter so that you can write Foo<@Nullable T>.)

    [edit: And methods in Foo that return a T won't be able to return null, either (without suppressing an error, anyway).]

  13. cpovirk commented on Dec 19, 2019

    @cpovirk
    Collaborator

    IIUC, the Checker Framework takes Foo<@Nullable ?> to mean definitely-nullable.

    It annotates ExecutorService with:

    Future<@Nullable ?> submit(Runnable task);

    For the read-only Future type, this doesn't offer a ton more than plain:

    Future<?> submit(Runnable task)

    Also, I see this in Comparator:

    <T> Comparator<@Nullable T> nullsLast(Comparator<@Nullable ? super T> comparator)

    (and similarly for nullsFirst. Here's the commit.)

    I'm not sure I understand this. Surely it would be OK for the input Comparator to reject null?

    These are the only occurrences I saw in the CF JDK stubs.

  14. kevinb9n commented on Jan 13, 2020

    @kevinb9n
    CollaboratorAuthor

    So trying to sum this up -- what are the best use cases for the "definitely nullable type parameter" that can't be satisfactorily addressed by just projecting all the usages of the type variable to nullable? Are there any?

  15. cpovirk commented on Jan 13, 2020

    @cpovirk
    Collaborator

    I don't personally know of anything very compelling, but I'd be interested to hear examples.

    I forget if I've said this before, but: I've wondered if part of the reason that the Checker Framework supports this is that it's a more general feature that might be more valuable for analyses other than nullness. Maybe a "definitely <top> type parameter" makes more sense in some of those analyses than with nullness? But I keep confusing myself trying to find an example.

    (Hmm, I suppose I could say the same thing about @PolyNull. Granted, we already definitely see some use cases for @PolyNull, but I wonder if it ends up being critical for cases like, say, the tainting checker?)

  16. kevinb9n commented on Jan 15, 2020

    @kevinb9n
    CollaboratorAuthor

    Unless/until new information arises I think we're justified in declining this feature.

  17. cpovirk commented on Oct 12, 2020

    @cpovirk
    Collaborator

    This is already closed, but I wanted to add another concern for us to consider if we reopen it someday.

    Above, I talked about the Checker Framework's handling of ThreadLocal. I noted that it enables a new pattern -- namely, instantiating the type with an out-of-bounds type argument when it's known to be safe.

    It just occurred to me that this pattern is spiritually incompatible with a rule we've proposed for JSpecify -- namely, the rule that out-of-bounds type arguments are "clamped" into the bounds. (That rule is split between here and here.) The idea is that, if you have a BlockingQueue<E> type that does not permit nullable type arguments, then methods like blockingQueue.add should not permit null values -- even if your queue is declared as a BlockingQueue<@NullnessUnspecified Foo> (as it would implicitly be in non-null-aware code).

    (This is a problem for JSpecify in particular precisely because of "unspecified nullness": Unspecified nullness causes these out-of-bounds type arguments to occur far more easily.)

    If we were to apply a similar rule to a hypothetical definitely nullable type parameter, that would mean that a ThreadLocal<@NonNull String> would still behave like a ThreadLocal<@Nullable String>.

  18. added
    design
    and removed on Nov 30, 2022
  19. added this to the 0.3 milestone on Mar 27, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    designnullness

    Type

    No type

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions