Repository navigation
Description
Informally, and approximately: a method or constructor with any occurrences of @PolyNull in its signature is treated as if it is two distinct overloads: one having all occurrences of @PolyNull replaced with @Nullable, the other having all replaced with @NotNull (under the fantasy that nullness information can actually be used for overload resolution.)
All the cases I'm aware of this being useful involve applying @PolyNull to at least one in-type (e.g parameter type) and at least one out-type (e.g. return type).
The alternative (if this annotation is not available) is that these parameters must be marked @Nullable; it will be like the previous situation but with the @NotNull overload missing. Consumers passing in a not-null expression (which should generally be common) will get a non-nullable result that the compiler will not know is non-nullable.
A bit of early discussion was in #3.
cpovirk edit: various cases / design questions to consider if we end up including @PolyNull:
- (probably not receiver parameters)
- usage in invalid locations (e.g., on fields or classes): typetools/checker-framework#4480 / typetools/checker-framework#1376
- whether it means "
UNION_NULLorMINUS_NULL" or rather "UNION_NULLorNO_CHANGE" - whether a
@PolyNullmethod likeClass.castmapsUNSPECIFIEDtoUNSPECIFIEDand, if so, how we'd specify that, including when the annotation is applied to a type variable that would otherwise have unspecified nullness- Also, do we need to do anything special when the type parameter has an unspecified bound?
- whether users would write
@PolyNull @Nullable, just@PolyNull,@Nullable(onlyJointly = true), a contract, or what (plus related naming questions)- A contract would likely limit us to supporting relationships between a parameter's root type and the method's return type's root type, for better (avoids the field/class mixup noted above, simpler to specify and implement) or for worse (cuts off some use cases).
- how it interacts with overrides, including with contravariant parameters, and maybe subtyping more generally
- example:
ImmutableMap.getOrDefaultcould use@PolyNull, but plainMap.getOrDefaultmight or might not be able to, depending on how we resolve theMINUS_NULL/NO_CHANGEquestion above
- example:
Activity
amaembo commentedon Nov 1, 2019
I already said it somewhere, but cannot find it now.
@Polynullis a very limited thing. E.g. you cannot express "if and only if any of the two arguments is null the result is null" or "if and only if both arguments are null the result is null". Also, you cannot express other useful contracts like "if an argument is null the result is false". So I would prefer a contract language which allows expressing all of these. Otherwise, we will need to create dozens of annotations to support real-world cases.mernst commentedon Nov 1, 2019
I don't agree that
@PolyNullis "very limited". Hundreds of uses are needed in the JDK, Daikon, and utilities, as just a few examples.I agree that there exist properties that
@PolyNulldoes not express, but that is not an argument against@PolyNull. In my experience, the examples you gave are needed much less often than@PolyNull, and@PolyNullcarries its weight: it provides valuable documentation of programmer intent, and it eliminates large numbers of false positive warnings.kevinb9n commentedon Nov 1, 2019
@amaembo Your earlier comments are at the top of the issue I linked to, #3.
If we were to become convinced that
@PolyNullis necessary, and that others were necessary, and could find no reasonable basis for where to draw the line, then I understand why we would be compelled to consider a more general contract language. And to me, that would be a pretty drastic outcome and I would end up feeling sad that we ever took the first steps on that journey at all.I'm not sure whether
@PolyNullis the thing that inexorably slips us onto that slope.cpovirk commentedon Nov 1, 2019
Quick data dump of very quickly grepping through:
annotations.xmlfiles underintellij-community-master/java/jdkAnnotationsfor@Contractannotationschecker-framework/checker/jdk/nullness/srcfor@PolyNullannotations (excludingtoArraybecause it dominates the results)Here are the results.
The first thing that jumps out to me from the IntelliJ annotations is that there's only a single occurrence of its
@PolyNullequivalent,!null -> !null-- forOptional.orElse, one of the cases I'd expect. I don't seeClass.cast. (Maybe it's treated as@NullnessUnspecified, which is more forgiving than straight@Nullable? I discussed using@NullnessUnspecifiedas a naive substitute for@PolyNullin #71.)The first thing that jumps out to me from the Checker Framework annotations is that there aren't as many
@PolyNullannotations as I expected. The full(?) list:Optional.orElseClass.castConcurrentHashMapmethodsCompletableFuture.getNow, and it at one point would have made sense onScopedValue.orElse.]I do know of other cases for
@PolyNull, especially for "conversion" methods:TypeDescriptor.forObject(Spring)Converter.convert(Guava)Optional.fromJavaUtil(Guava)I still don't have a strong opinion here, but this has nudged me slightly from "
@PolyNullfeels somewhat common" to "@PolyNullfeels somewhat less common than I thought." If we're really talking primarily about a handful of methods, it's easier to imagine that users can write wrappers (castNotNull(Class, Object), etc.) when needed.cpovirk commentedon Nov 1, 2019
Also, more anecdotally, among the usages of
@PolyNullin Google's codebase, I see sizable minorities of both:@PolyNullonly once in the signature@PolyNull T(that is, that use it on a type variable)Both are often signs that the API could have used a different feature instead.
Still, the majority of use cases (not a ton, but it comes up) look legitimate at first glance.
kevinb9n commentedon Nov 1, 2019
Re: the previous-previous comment, I'm a little surprised, not that I expected it to be much more popular than this.
I know that other utility libraries that don't have Guava's null-hostile attitude are more fond of null-passthrough, and might have much more use for this.
What will be the consequence of not having this? I am not sure how good the castNotNull() outcome is. Will users complain to their checker vendor about it, and will vendors start to hardcode lists of APIs that have this property? Or, we could share those with each other as data files. In fact, those data files might as well be the same as externally-applied-annotation data files, meaning that a definition for "PolyNull" would have to exist somewhere but just not be part of the artifact you can actually depend on from code.
Maybe that seems like a weird outcome, but I can imagine there being quite a few things that all fall into a bucket like this, and we really wouldn't want to have 29 real annotations.
Random other point: applying
@PolyNullto a type variable usage (as Class.cast() would) highlights a weird issue: that@PolyNullis important when the type argument is nullable, but I'd expect it not to have any effect when the type argument is non-nullable.cpovirk commentedon Nov 1, 2019
Hmm, I think I'm seeing it the opposite way:
@PolyNullon a non-nullableTwould have an effect, but on a nullableT, it's likely not to change much, since the method is likely to already permit, say, both@NotNull Stringand@Nullable String?kevinb9n commentedon Nov 1, 2019
For
Class<@Nullable Foo>,castalready accepts both nullable and not, yes, you just need PolyNull to carry that nullness information through to the return type.Why would it have an effect on a non-nullable
T? There's no other "imaginary overload" to add; null isn't allowed. Oh: maybe you just mean you would expect to interpret@PolyNullas also implying coercion to@Nullable. That doesn't seem justified to me. How would you get it not do that, if that's what it did by default?cpovirk commentedon Nov 1, 2019
We're probably looking at multiple things differently. Here's what I'm picturing:
And what
@PolyNullbuys us is......which effectively provides...
kevinb9n commentedon Nov 1, 2019
Right, I was instead thinking of the case where the type parameter is nullable, and thus intentionally admits both nullable and non-nullable instantiations. And that the cast method doesn't want to override that. It wants to not accept null and not return null when the type argument is non-nullable. And when the type argument nullable, that's the only place we need a refinement: it should accept nullable (or non-nullable), but it should return the same kind of nullness that was passed in.
(This might be a weird thing to do for Class itself, but if we don't then see issue #78...)
kevinb9n commentedon Nov 1, 2019
So I'm saying I would not expect
@PolyNullto imply coercion to@Nullablewhen used on a type variable. However, in the case of@PolyNull Stringit would weird if it did not imply@Nullable. Sigh.cpovirk commentedon Nov 1, 2019
I think I am still missing something on both this and #78. I'd suggest a code example, but I haven't gotten my head around the significance of the one on #78, so maybe that's not what I need. Hmm.
As noted above, I suspect that
@PolyNull Tin practice could usually be written better in another way. (I based that on looking at nearly every example in the Google codebase.) Still, it's spot-on forClass.castandOptional.orElse. Unfortunately, I picture both of those with<T extends @NotNull Object>, so that doesn't help illuminate your nullable case.Maybe we're mostly just agreeing on the weirdness of
@PolyNull TwhenTpermits nullable instantiations?wmdietlGC commentedon Nov 2, 2019
Instead of thinking of
@PolyNullas two overloads of a method, I like thinking of it as a "qualifier parameter", that is, a type parameter that only varies over the nullness information.This makes thinking about
PolyNullsimilar to thinking about@NullnessUnspecified.Let's take
that is conceptually like:
where I use the
<<@T>>syntax to introduce the qualifier parameter. (Which is something we don't actually support, it's just something to write these examples.)All uses of
@PolyNullin a signature correspond to the same qualifier parameter and in the end bind to either@NonNullor@Nullable.In contrast, each use of
@NullnessUnspecifiedconceptually introduces a separate qualifier parameter:corresponds to:
This is similar to how each wildcard is independent of each other and captures some underlying type in a call.
Thinking about
@PolyNulllike this also helps in thinking about it's use on a type parameter use - it caries the nullness information separately from the underlying type and allows linking the nullness information from separate type parameters.Method
convertis nullness-parametric dependent on the instantiations forS, T.In contrast, method
barchanges the nullness fromS, Tand instead links them together.Maybe the correspondence between
@PolyNulland@NullnessUnspecifiedhelps us think through these examples and maybe even unify them.cpovirk commentedon Nov 4, 2019
Thanks. Among other things, that got me thinking more about
@PolyNullon type parameters. Your example is likeConverter.convert, and I'm sure various people have written generic functions that they want to convertnulltonull(like "safe calls").One change that might make
@PolyNullmore widely usable is to define it to mean "@Nullableor no qualifier" rather than "@Nullableor@NotNull." (Yes, I'm back to talking about@NotNull:))This can come in handy in two related cases:
@PolyNull V getOrDefault(Object key, @PolyNull V default)(This turns out not to be very compelling for
Map.getOrDefault, since users who want to passnullcan call plainMap.get. But we could see benefits for other, similar APIs. [edit: Android came to a similar conclusion.] [edit 2: I did come across a large number of calls togetOrDefault(key, null)in Google's depot.])ValueGraph.edgeValueOrDefault.@PolyNullis a good fit there regardless of which of the two definitions we use, asValueGraphforbidsnullvalues.)CompletableFuture.exceptionally+FluentFuture.catchingIf
@PolyNullmeans "@Nullableor no qualifier," then we can apply it to these methods so that users can say both:Futurefails, return aFuturewhose value isnull" (producing aFuture<@Nullable V>)Futurefails, return aFuturewhose value is <someV>" (producing aFuture<V>, whereVretains its original nullness)FluentIterable.appendThis more easily permits combining an
Iterableof not-nullelements with anIterableof nullable elements. I doubt that this comes up a ton, though.One way to look at this definition of
@PolyNullis that it provides a very limited ability to write<T super E>: I have aContainer<E>, and I'd like to combine it with some values of typeT, resulting in something with typelub(E, T). This is easy with a static method because the PECS principle handles it "automatically":But on the occasion that we want it for an instance method, we're out of luck -- except in the specific case of adding nullness, and then only if:
null, or@PolyNullas described above(Call it
@JointlyNullable? Kind of hard to ever imagine it as a full-on language feature, but I wouldn't let that stop us from adding it if we think it's useful.)[edit: I keep getting myself confused here :( I do see that I claimed that
@JointlyNullablewould be useful even for a static method in the case ofIterables.find—though I'm wondering if that is one of the cases that would be doable without@JointlyNullableif only we could add a second type parameter:ResultT extends @Nullable Object, ElementT extends Ror something??? Either way, is it actually the case that classic@PolyNullwould be wrong there? Finally, I may want to think about the private helper methodMutableClassToInstanceMap.cast, though note that I'm working to change its declaration slightly in a pending CL. edit edit: I changed its usages much later so that@PolyNullisn't necessary.]cpovirk commentedon Nov 4, 2019
Another thing that the
@PolyNull-@NullnessUnspecifiedcorrespondence brings to mind: For both annotations, we've often talked about the "2 possibilities" that each permits. That's meant@Nullableand@NotNull-- or now maybe@Nullableand "no qualifier." Another way to look at it is that there are 3 possibilities:@Nullable,@NotNull, and "no qualifier."This of course isn't useful for concrete types like
String, only for type variables. And it seems more likely to matter with@NullnessUnspecifiedthan with@PolyNull. For example:When this class is annotated for nullness, it could have:
U extends @NotNull TU extends @Nullable TU extends TSo maybe we treat
@NullnessUnspecifiedas meaning "one of those 3?"(The idea of having 3 possibilities might(?) fall more naturally out of the
<<@T>>syntax, since we're used to looking at type parameters as being selected from a variety of possible values, rather than just a boolean decision?)42 remaining items
cpovirk commentedon Aug 1, 2023
One thing that we've discussed but seemingly not written about yet here is how Kotlin reduces the need for
@PolyNull, at least if you design APIs with Kotlin in mind.?.letIn Kotlin, developers are less likely to define
@PolyNull-style APIs and more likely to define APIs that accept and return non-nullable types. Then, callers who know that they have a non-nullable type can call the method directly (foo.bar()), and callers who know that they have a nullable type can call the method with?.let(foo?.let { it.bar() }). The compiler ensures that you don't call the method directly on a nullable type (but it does let you call it on a platform type, which can be unfortunate!), yet it ensures that the return type of the?.letapproach is a nullable type.extension functions
In at least the specific case of
Optional.orElse, Kotlin provides (thanks to some people :)) an extension function (getOrDefault) that provides@PolyNull-like behavior. I think the reason that this works forOptional.orElsebut doesn't work forClass.castorConverter.convertis that the input type and output type are the same typeT. (It might also be important thatOptionalhas its type parameter declared as non-nullable under our approach. That's the case forClassandConverter, too, so it's not part of the problem for those classes' methods; it just might be part of the problem for others.)update: new, experimental contracts
Kotlin 2.2.20 adds the experimental
returnsNotNull(), which enables:contract { // Guarantees a non-null return value when the input is non-null (encoded != null) implies (returnsNotNull()) }edit: also overloads
See #79 (comment).
edit: on platform types / unspecified nullness
Kotlin will essentially let you treat platform-typed expressions as non-null. This doesn't always go well, as we saw with some
T.toJavaOptional()andT?.toJavaOptional()extension functions inside Google at one point.other stuff?
I don't know, probably? You could reasonably claim that the various nullness-handling operators (like
?:) would make it somewhat practical for a Kotlin-focusedOptionaltype to choose not to provideorElse/getOrDefaultfunctionality at all: If it instead providedorNull, users could combine that with?:to get the other methods' behavior.cpovirk commentedon Aug 1, 2023
(The point here isn't that JSpecify shouldn't continue to be open to adding
@PolyNull, just that we are seeingOptional.getOrDefaultsave us from some Kotlin ugliness that we would otherwise been stuck with until Kotlin supported something like@PolyNull.)agentgt commentedon Aug 1, 2023
I despise PolyNull. Some probably have seen me on reddit openly rant about it so apologies if you are seeing me again.
One of the reasons why we (my company at least) see way less NPE is because PolyNull APIs are nowhere near as wide spread as they used to be. I understand folks are going to complain about PolyNull and with the exception of
Optional.orElseI see much bigger problems like monotonic andsomeStream.filter(p -> p != null)... eg.. why is the stream still nullable for example.The problem with PolyNull in the context of the JDK is that it seems very easy to assume something is PolyNull when it very well might not be in the future. After all the JDK is not annotated.
For example most assume
Map.getOrDefaultis poly null but until the JDK authors actually go off and annotate precisely whatMap.getOrDefaultis we are still assuming.In fact I think making
@PolyNullalways@Nullablemight actually encourage JDK authors to address or add expression based conditionals (I believe that another reason why it is less of a problem with Kotlin):I admit that Caffeine has a strong argument for PolyNull but JSpecify really needs to be like done now and it needs to be simple for adoption and most importantly easier to annotate existing APIs. Having
PolyNullbegs the question should this ancient method here bePolyNulland naturally people can easily just look and seeif (x == null) return null;... ah I will just annotate this PolyNull. You see the danger?@Nullableis safer. Yes it is inconvenient but is safer and that brings me to my next point:Without the JDK
correctlysafely annotated by JSpecify OOB I fear JSpecify will have the same adoption as Eclipse null analysis. Its pretty sad how few know about JDT null analysis. It's equally sad how freaking painful it is to setup because of lack of OOB annotations on the bare minimum: the JDK. (checker is also not exactly any easier to be honest).I don't know what the plan is for external annotation but I feel adding more annotations is going to make this harder, longer and possibly error prone...
agentgt commentedon Aug 1, 2023
BTW speaking of Caffeine
It is funny you mention that because this confused me when going to see if we were using Caffeines getOrDefault.
If I don't have that
requireNonNullEclipse will complain with:And it does not because Eclipse still cannot read Checkers default annotation placement:
But originally I did not read that error or it indeed changed on version upgrade as Ben alluded to from
@Nullableto Eclipses unspecified. I just assumed cache.get was always nullable.The reality is I just haven't gone and externally annotated (EEA) Caffeines type parameters yet.
Anyway I thought that might be just another example of how much the pain of going around annotating existing libraries is and how potentially error prone it can be.
ben-manes commentedon Aug 1, 2023
@agentgt fyi ben-manes/caffeine#594 in v3.0.5. It seemed reasonable to follow Guava's lead which adopted CheckerFramework's annotations as a replacement to jsr305's, where I had no strong opinion and prefered having those who want to discuss it to come to the like minded Guava/JSpecify folks than to me. 🙂
agentgt commentedon Aug 1, 2023
@ben-manes Yes I agree. I didn't mean to make it out as bad choice because I think the first time around when I did it I was annoyed probably similar to the kotlin devs about
LoadingCache.getbeing nullable.It was a safe choice and did not break anything on our end. My jaded tone was more for the libraries that either do not provide any sort of annotations or incorrectly annotated... (well that and Eclipse but Eclipse kind did ok here).
cpovirk commentedon Aug 22, 2023
Sorry, I'm ignoring the posts above for the moment. I haven't caught up yet, but I wanted to dump an unrelated thought.
I'd forgotten another way that Kotlin can get
@PolyNull-like behavior [edit: beyond what I'd mentioned above]: Kotlin lets users declare overloads of a function that differ only in nullness. So you can havefun cast(o: Object): Tandfun cast(o: Object?): T?, at least when you're writing Kotlin.I should look more at what happens if you write a Java API with one set of nullness annotations in a superclass (and/or interface?) and then a Java override with the other set.... I had thought that Kotlin responded by interpreting the API as having platform types, but I thought I might have seen otherwise in some cases. I'd need to look. (Might it matter whether the return type matches?) And even if it does "work," I would be hesitant to rely on what might be a bug, given that the platform-type behavior seemed to be the intended one.
cpovirk commentedon Dec 8, 2023
I also want to dump a link to a Guava discussion in which
@PolyNullcould have been part of the answer but in which I concluded that@NonNullwould suffice (though tools' type inference might be confused either way): google/guava#6824 (comment)cpovirk commentedon Apr 18, 2024
Apparently C# took the approach that you can apply their equivalent of
@PolyNullonly to a pair of types that are (a) the return type and (b) one parameter type: https://devblogs.microsoft.com/dotnet/try-out-nullable-reference-types/#nullness-dependence-between-inputs-and-outputs-notnullifnotnullstringThat's a nice simplification if you can get away with it. (I do wonder if they could have let you annotate the parameter, instead, so that you wouldn't have to refer to the parameter name with a string?) It definitely does solve the common case of null passthrough, but I was surprised at first glance at how many of the
@PolyNullusages I looked at were more involved than that. (Compare my comment about supporting only root types with@Contract.) It remains an option, one that certainly covers lots of calls even if it covers a smaller number of declarations. (For example, coveringClass.castwould get us a lot of mileage.)(Also, more generally: C# had to do a lot of stuff to support its
refand perhapsoutparameters, plus more for its representation of nullable primitives withNullable<int>, etc. It is convenient for us that Java has avoided those particular things.)[edit: random unrelated thing from much later that didn't seem to justify its own post: I just learned recently that
@PolyNull, unlike most cases of "normal type inference," can't be directly "helped" by specifying an explicit type argument, since there's nowhere to put that type argument. Or probably often it can but by putting the type argument on some earlier call.]kevinb9n commentedon Jun 7, 2024
For starters I think PolyNull only makes sense if you mark at least one in-type and at least one out-type (see our wonderful glossary doc). So the questions are
Treat `@PolyNull` like `@Nullable`.
cpovirk commentedon Nov 12, 2024
I recently noted in #705 that
@PolyNullwould need to be covered by rules for type inference. [edit: See eisop/checker-framework#2030 for an example of complexity there.]Today, I'm seeing an example of how it would need to be covered by rules for subtyping... or maybe some higher-level rule? I'm not sure it's as simple as "
@PolyNullis a subtype of x and a supertype of y." It seems more like we'd actually need to check the two conceptual versions of an annotated method separately, both when checking whether a method is a valid override and when checking whether its implementation is valid (including checking any calls to the supermethod, I guess, and I'm not clear on whether we'd treat the supermethod "as@PolyNull" or "as the@Nullable/@NonNullversion that we're currently looking at"). My assumption is that the Checker Framework does things along those lines, since it has a concept of "qualifier polymorphism" that seems to go beyond subtyping. I'm sure we could learn from it as needed.Avoid giving the result of loads a non-null type.
cpovirk commentedon Sep 15, 2026
One subtlety that's come up in some recent contracts discussions is another small difference between
@PolyNulland@Contract("null -> null, !null -> !null): That particular@Contractin theory lets you refine the parameter type based on the check of the return type, but@PolyNulldoes not. However, as best we can tell, no one implements or particularly wants that kind of refinement.The basic idea is something like:
That's safe under the stated contract because
lengthOrNullis null if and only ifmaybeNullis.@PolyNull, by contrast, does not make that guarantee. Here's an example of why not:There,
withBackupcould return non-null even whenbackupis null, since it might be returned a non-null value ofprimary.Not, incidentally, that you should write that signature when when you could instead write:
But the main point here is that users of
@PolyNull-like contracts end up leveraging only the!null -> !nullpart of the contract, not thenull -> nullpart.Add `@Nullable` to more parameters. (#176)