Repository navigation
Description
I think the current proposal is likely to produce the results we want in practice. But it feels like a special case to me, and I think that some of the alternative rules under discussion can make that happen.
The design proposal currently has:
If the bound’s effective specifier is
@NotNullor@NullnessUnknown, then that is the type variable usage’s effective specifier.
For @NotNull, I think we all agree that this is desirable.
For @NullnessUnknown, I'm hoping to replace this and other one-off rules (like #45) with my mental model for @NullnessUnspecified -- which it's sounding like is similar to Kolin's flexible/platform types and to existential types, as laid out by @mernst.
To see what that looks like, let's first look at our existing rule for @Nullable. It produces results like this:
@DefaultNotNull
class Manager<T extends @Nullable Object> {
void log(T obj) {
Logger.log(obj.toString()); // ERROR: null might be possible
}
T create() {
return canCreate ? doCreate() : null; // ERROR: null might be forbidden
}
}Now let's look at the current proposal's rule for @NullnessUnspecified. It considers both usages of T to have unspecified nullness. That demotes both errors to warnings:
[@DefaultNullnessUnspecified]
class Manager<T> {
void log(T obj) {
Logger.log(obj.toString()); // WARNING: null might be possible
}
T create() {
return canCreate ? doCreate() : null; // WARNING: null might be forbidden
}
}I think this is clearly right for log. If we apply my mental model of analyzing the code twice, once with unspecified nullness replaced by @NotNull and once with it replaced by @Nullable:
- If
T"should" extend@NotNull, then the implementation is safe. - If
T"should" extend@Nullable, then it's not safe.
Under my mental model, we look at both outcomes and say that the code deserves a warning.
But for create:
- If
T"should" extend@NotNull, then the implementation is not safe. - If
T"should" extend@Nullable, then it's also not safe (because of parametric nullability).
On the surface, this suggests that the more appropriate outcome for create would be an error.
But that seems wrong: Manager is completely unannotated. Maybe create is "intended" to have a signature of @Nullable T create(). So we should permit that method to return null after all -- with a warning, of course.
This whole outcome can fall out of some generalized alternative rules we've been discussing! Specifically:
- if
@DefaultNullnessUnspecified"contributes to" the effective nullness ofcreate's return type - if we combine that unspecified nullness with the nullness
Tis instantiated with -- and do so by picking the "most nullable" value
...then we conclude that create returns either @Nullable or parametric nullness. Returning null is safe in the first case but not the second, so we issue a warning, as desired.
Activity
cpovirk commentedon Nov 4, 2019
Here's another example -- though a fairly artificial one, as it's a partially annotated file that's been partially annotated in an unlikely way:
I think that this should be an error: Neither
<T extends @Nullable Object>nor<T [extends @NotNull Object]>can make this valid code.I believe it ends up being valid under the current proposal but invalid under the alternative rules I've been discussing.
cpovirk commentedon Nov 26, 2019
We may want to consider the possibility that such unlikely combinations could arise during automated migrations. I'm not sure how likely I think that is yet.
kevinb9n commentedon Nov 27, 2019
Sorry, just gonna capture some thoughts here that may or may not help.
Under the assumption of the
nn <= unspec <= nullableare subtypes (NUNAS?) model [#33] (ignore this whole comment if we don't go that way),And given
Foo<T>orFoo<T extends SomeType>in an unannotated/unspecified-nullness context,Then I believe it does not make sense that we interpret unspec-ness as applying specifically to the upper bound of
T. I believe the behavior of unspec with respect to nullable and to not-null should be highly symmetrical. I can't see a reason why instantiatingFoowith a not-null type is any safer than with nullable, except whenFoois a consumer type -- which are, ironically, relatively rare.This may in fact be a deep flaw with the entire NUNAS model (#33). But it might be that the model is fine, as long as we just rethink what an unspec type parameter really is. Roughly, it might make more sense in the case above to:
Tto be unconstrained/nullableFoo, treat every unannotated type variable usage ofTwithinFooas having unspecified nullness (not parametric). Effect: assignable from nullable to it, or from it to not-null, should yield the softer "unchecked"-style warning.T(There may be another issue here somewhere discussing the last point specifically.)
(Note: if we ended up doing something like this, the next question is how a user should write that they want this handling for T even when inside a not-null context; i.e. should we have them write
Foo<@Unspec T>after all, to avoid confusing the issue.)kevinb9n commentedon Dec 3, 2019
As far as I can tell, I think the topic I'm exploring in the last comment strikes at the heart of the whole "is nullness info carried entirely by types, or do type parameters have additional properties" debate (#60). You could view what I'm suggesting as a partial deviation from the former toward the latter.
(Still, apart from this one issue, I'm not really clear on any other compelling flaw with the former or benefit to the latter. But that's not to be debated here.)
kevin1e100 commentedon Dec 5, 2019
Agree that distinguishing "unspecified nullness"-bounded type parameters is highly awkward, and that they seem (almost) indistinguishably close to parametric type parameters. In my mind there are two key things we're trying to capture:
@Nullableparameterizations make sense for unspecified nullness-bounded type parameters@NotNullparameterization, we don't know whether any of the occurrences of type variable can actually be assumed to be@NotNullin the resulting parameterized type. (@cpovirk has convinced me that@Nullableparameterizations don't have this issue, but as said above, the problem with those is that we don't know if they're even intended.)One takeaway from these two bullets is that the two possible parameterizations seemingly have asymmetric problems (!). Nonetheless, nullness-unspecified type parameters have these two challenges, and that's different from a nullness-unspecified
Stringor other base type usage.Anyway, I'll point out that tools have the freedom to warn or error or be silent in the examples given in the leading comment of this issue, no matter what the specification says. Defining type variable usages as "nullness unspecified" from the specification's point of view is just a technical means that helps us define nullness of members of parameterized types; for the generic class itself only implementation code will care, which tools can treat as they like.
kevinb9n commentedon Dec 5, 2019
I'm now thinking that unspecified-nullness type parameters are exactly the "parametric nulllness" case that you get with
extends @Nullable, just a subcategory with some additional properties too.After all, we have no information about nullness, therefore we have no basis for constraining how it can be parameterized.
I'm still not sure that the problems of
@Nullable/@NotNullparameterizations aren't symmetric. I think I somewhat follow Chris's mental model of "consider both possibilities for how T might be bounded with a proper nullness in the future". But one reason I'm not sure that's valid is that it doesn't necessarily have to be the case that either of those is correct. The third possibility is that the only way to correctly annotate the class must involve both setting the right bound forTand tweaking one or more of theTusages to be projected types at the same time.The symmetric way to look at it is more like:
(Assume
class Legacy<T>is in an unspec context, and contains type usages of T as both in-types and out-types.)With
Legacy<@Nullable Blah>, out-types are safe, but it lets you send null as an in-type, which might be a bug (not necessarily resulting in immediate NPE).With
Legacy<@NotNull Blah>, in-types are safe, but it lets you receive a non-nullable out-type, which might actually hold null at runtime, which would be a bug (not necessarily resulting in immediate NPE).(We still have a separate discussion somewhere about whether this project needs to establish whether to treat only that parameterization itself as problematic, or each individual API usage of the kinds above.)
Is that symmetry appropriate/desirable?
kevin1e100 commentedon Dec 7, 2019
In principle this is certainly true, but there are several things that work in our favor:
@Nullable String xmethod parameter: annotating a method parameter@Nullableis kind of a promise that the method will be careful with dereferencingx, but nothing really guarantees that the method implementation adheres to that promise. A method parameter that "becomes"@Nullable Stringbecause of a type parameterization doesn't seem to be fundamentally more or less dangerous.@Nullable Stringmethod parameter, we have a counter-move, which is to optimistically assume something about the callee. That assumption ends up imposing a requirement on the callee's implementation code. Specifically, for aT xmethod parameter (even if it has unspecified nullness) we can simply assume that it won't be just blindly dereferenced. If a tool ever gets to check the callee's implementation it would be expected to flag such blind dereferences not preceded by a null check. This "trick" that all modular analyses use ends up allowing us to "tune" how optimistic we want to be at call sites, by imposing more or fewer requirements on callees. Again, this isn't fundamentally that different from making assumptions about a@Nullable String xmethod parameter.@Nullableparameterization is supported at all by the generic class then it's very likely that occurrences ofTare indeed expected to be@Nullablein@Nullableparameterizations of the generic class. So the practical likelihood of a "bug" is seemingly low in this case, but there does seem a good chance that@Nullableparameterizations may not be valid in the first place.Right. Technically we can apply the same "trick" as mentioned above here, which is to just assume that the callee returning a
@NotNull Blahwill do so, and hope that the callee implementation will be checked accordingly. There are two differences to the case above, though:T foo()method in fact needs an@Nullableannotation to be correctly specified (e.g.,getOrNull-type methods). Meaning, the likelihood of a hidden bug here is seemingly higher than in the previous case.@NotNullis technically always a legal parameterization (possibly justifying not warning about them).Agreed, and as alluded to, the nuances mentioned above (that @cpovirk initially observed) may help give an answer here, but I agree that it's seemingly always sufficient to warn on either parameterization or API usages.
I think it's fine, despite the mentioned "likelihood" nuances, to stick to a symmetric view. I personally do find it somewhat compelling, for usability's sake, to take advantage of the mentioned nuanced differences between in- and out-types, assuming we can convince ourselves that we believe in them sufficiently. Regardless of whether we're going symmetric or asymmetric, it's been helpful for me to keep in mind that we're always playing the mentioned "trick", where we draw a line at which to start making assumptions about callees (wrt both in-types and out-types), and to realize that this "trick" can be used to make asymmetric assumptions just as soundly as symmetric ones. Does that make sense?
kevin1e100 commentedon Jan 3, 2020
For reference, I tried reworking the proposal document to treat usages of type variables declared as
<T extends [@NullnessUnspecified] X>as "assumed parametric nullability" (term not final). I would have preferred not creating a separate category for this, but this ends up being a bit cleaner I feel than labeling these type variable usages
@NullnessUnspecified, which was always a kluge and I believe prompted this issue (see quoted text above).In case you haven't seen it, the proposal now also has explicit text on how to interpret parameterized types. Distinguishing "parametric nullability" and "assumed parametric nullability" type parameters allows giving the latter, effectively, "more nullable" semantics without changing how type parameters work overall. Using this semantics I believe matches how Kotlin handles unannotated classes with type parameters that are parameterized in a Kotlin file (see #45), and it seems desirable for the specification to agree with Kotlin on that point: it's not clear to me how Kotlin and the spec can disagree on how to handle unannotated files (since unannotated files can't give clues as to whether they want to adhere to the spec), and the alternative would be a breaking change to Kotlin, which seems gratuitous for this case.
kevinb9n commentedon Jun 23, 2021
It's been an eventful 18 months since the last comment on this issue. @cpovirk, can you give a fresh description of what's solved and what's not solved here?
cpovirk commentedon Jul 14, 2021
I think that this was solved with the addition of "assumed parametric nullability": If a type like
Listis unannotated, we're able to detect thatList<@Nullable String>has@Nullabletypes for, e.g., the return value ofget.