You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Should we support a definitely-nullable type parameter (or wildcard)? #85
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 ArrayTablemight 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.
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:
classSub<T> extendsSuper<@NullableT>
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 Bardo 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.
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.)
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.)
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:
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<?>:
(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.))
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.
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.
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
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.
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).]
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?
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?)
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>.
Activity
cpovirk commentedon Dec 5, 2019
We can look for motivation for this in 2 places:
For (1):
Equivalence.Wrapperthat benefits from a definitely-nullable type parameter or (or, alternatively, from projecting to@NotNull).<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 alsoEquivalence:Seen through one lens,
ArrayTableandEquivalenceare the same: Without support for definitely-nullable parameters, they have to be defined as:It's a little weird that
Subis a subtype ofSuperand yetSub<T>isn't a subtype ofSuper<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
Equivalencespecifically: If we were to make it definitely-nullable, we'd need to project the types it uses in itsprotectedmethods to@NotNull. This seems as legitimate as any other case for definitely-nullable and projecting to@NotNull. If there's a difference between it andArrayTable, it might be this:ArrayTable<Foo, Bar, Baz>looks like it ought to have non-null values: First, we know that a plainTable<K, C, V>contains values of typeV(similar to with other collection types). Second, it's particularly unfortunate that the bareFooandBardo force non-null keys, yet the bareBazdoes not do the same for values.Equivalence<Foo>, by contrast, doesn't immediately call to mind its supertype ofBiPredicate. Nor does it take a second type argument that affects nullness in a different way. Thus, it's more likely that people will seeEquivalence<Foo>and understand that it can acceptnullthan seeArrayTable<Foo, Bar, Baz>and understand the same.cpovirk commentedon Dec 5, 2019
Pulling in a couple points from other threads:
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 supportinterface 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: IfEquivalencehasn'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 forEquivalenceto help with the adoption process, those stubs will match.)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 ifFoohas 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.)cpovirk commentedon Dec 5, 2019
(In the same boat as
Equivalence:Converter.)cpovirk commentedon Dec 6, 2019
I looked through the Checker Framework's JDK stubs, and I found one example: The Checker Framework forces
ThreadLocalto be instantiated with a nullable type.That's an interesting case: I view
ThreadLocallikeEquivalenceand friends, only without the "Equivalence<T>is not aBiPredicate<T, T>" baggage. That is, I would declare its type parameter to require a non-null typeT, and I'd declare its methods to operate on@Nullable T:In contrast, the Checker Framework has:
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 writeThreadLocal<@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 thatgetalways returns a non-null value. SincegetreturnsT, the Checker Framework knows thatThreadLocal<Foo>.get()will return a non-null value.However, this is a bit scary: Once you have a
ThreadLocalwhose type parameter doesn't "fit" into the normal bound for the class, you start getting errors when passing it to methods that accept aThreadLocal<?>:(Of course, there's yet another option here (well, in addition to "add special support"): We could let users instantiate
ThreadLocalwith any bound, and we could document that they should use a non-null bound only when overridinginitialValue. 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 ofAtomicReference).]cpovirk commentedon Dec 9, 2019
(Cross-link: Use cases for this might also been seen as use cases for #78 and vice versa.)
abreslav commentedon Dec 9, 2019
What existing systems allow expressing definitely-nullable type parameters? I think most systems I know don't allow this
cpovirk commentedon Dec 9, 2019
Eclipse and CF both do:
kevinb9n commentedon Dec 11, 2019
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.
[-]Should we support a definitely-nullable type parameter?[/-][+]Should we support a definitely-nullable type parameter (or wildcard)?[/+]cpovirk commentedon Dec 11, 2019
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 thereplaceEmptiesWithNullsexample in #60.cpovirk commentedon Dec 13, 2019
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:
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 aFoo<T>, and Java won't know thatTmust be@Nullablein that case. To ensure that Java knows that the type is always nullable, you have to stick with the original trick of consistently referring toFoo<@Nullable T>. (And if you wantFoo<@Nullable ?>, you might need to declare an "unnecessary" type parameter so that you can writeFoo<@Nullable T>.)[edit: And methods in
Foothat return aTwon't be able toreturn null, either (without suppressing an error, anyway).]cpovirk commentedon Dec 19, 2019
IIUC, the Checker Framework takes
Foo<@Nullable ?>to mean definitely-nullable.It annotates
ExecutorServicewith:For the read-only
Futuretype, this doesn't offer a ton more than plain:Also, I see this in
Comparator:(and similarly for
nullsFirst. Here's the commit.)I'm not sure I understand this. Surely it would be OK for the input
Comparatorto rejectnull?These are the only occurrences I saw in the CF JDK stubs.
kevinb9n commentedon Jan 13, 2020
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?
cpovirk commentedon Jan 13, 2020
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?)kevinb9n commentedon Jan 15, 2020
Unless/until new information arises I think we're justified in declining this feature.
cpovirk commentedon Oct 12, 2020
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 likeblockingQueue.addshould not permit null values -- even if your queue is declared as aBlockingQueue<@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 aThreadLocal<@Nullable String>.