Repository navigation
Description
Capturing a comment thread here
Let's say there's a class Foo that's not annotated at all, ie., T's effective specifier is "unknown nullness":
public class Foo<T> {
private T value;
T getOrThrow() { return checkNotNull(value); }
T getOrNull() { return value; }
set(T value); { this.value = checkNotNull(value); }
}
Now in some other Java file you do:
@DefaultNotNull
public class Bar {
String baz(Foo<String> x) {
return x.getOrNull();
}
}
Meaning x has the fully explicit type @NotNull Foo<@NotNull String>. So when considering method calls on x, should we (unsoundly) assume that getOrNull() will return a @NotNull String? That set's parameter is a @NotNull String?
@cpovirk points out:
I commented on this somewhere else, saying that it was pretty scary: Even if
Foois@DefaultNullnessUnknown, then sure, Bar'sFoo<String>can meanFoo<@NotNull String>. But I hope that doesn't mean that x.getOrNull() is considered to return@NotNull String. I'm hoping that@NotNullgets trumped by the effectively@NullnessUnknown Treturn type ofgetOrNull(), per:"If the bound’s effective specifier is
@NotNullor@NullnessUnknownthen that is the type variable usage’s effective specifier."
I wrote the sentence quoted above but I don't think I anticipated this application of it. We could possibly do it that way but I think we'll want to be sure either way.
In general I believe the mental model I've been working with is that when a type parameter gets instantiated, the instantiation gets "pasted" everywhere the corresponding type variable is used. So T getOrNull() becomes @NotNull String getOrNull(). I think that's what you want to do if T is declared as <T extends @Nullable Object> But if T is bounded by @NullnessUnknown, as in the above example, then we could indeed just consider occurrences of T to have unknown nullness no matter how T is instantiated. And while the language quoted above just discusses type variables, and we've been trying not to specify implementation checking and what happens on method calls, it does seem like we want to formalize what Foo<@NotNull String> means in terms of methods declared in Foo.
Playing with IntelliJ's code completion popups, it seems that Kotlin, given x: Foo<String> indeed types x.getOrNull() : String!, i.e., with unknown nullness as @cpovirk would like. Given y: Foo<String?>, it types y.getOrNull() : String?, i.e., as @Nullable (which also seems sensible but i'm not sure how to specify that).
I'll note that the inverse situation also creates headaches. What I mean is, if Foo was instead declared class Foo<T extends @NotNull Object>, and given a variable Foo<@NullnessUnknown String> z, then should we expect z.getOrNull() to return a @NotNull String or a @NullnessUnknown String? Should we expect z.set(expr) to expect a @NotNull String argument or @NullnessUnknown String? I think the answer here is that it's sensible to use @NotNull String for both method result and method parameter type, though it is weird to get any @NotNull even though we had Foo<@NullnessUnknown String> z. Especially considering that if Foo was declared class Foo<T extends @Nullable Object> then we presumably would expect the same z.getOrNull() to return @NullnessUnknown String.
Maybe the asymmetry pointed out in the last example is ok. I've been trying to avoid that very asymmetry with wildcards, but if we consider it ok here then I think we may need to revisit it there for consistency.
Activity
stephan-herrmann commentedon Aug 2, 2019
In this example Eclipse warns at the field
Foo.value:IOW, a type parameter with no nullness constraints must be used with special care. Eclipse also has a separate option to tune the severity of such "pessimistic analysis for free type variables".
kevin1e100 commentedon Aug 2, 2019
@abreslav I believe mentioned there's a writeup of instantiation rules. Any chance you could share that (or paste them into the proposal doc)?
kevinb9n commentedon Aug 2, 2019
I believe he means this: https://docs.google.com/document/d/1J44paXrplWzpCsXFpOobeBz_yiVH0W_yfgZR4sJsUfU/edit#bookmark=id.kmx5jvwou7pl
abreslav commentedon Aug 2, 2019
Did some analysis in the issue linked above: #57
stephan-herrmann commentedon Aug 11, 2019
I disagree, and that's why I filed #62. I would really want to read
Tas unconstrained in this situation, not unspecified!Otherwise all collection types from the JRE, e.g., could only be instantiated with type arguments of unspecified nullness, which would block a lot of useful analysis.
cpovirk commentedon Aug 12, 2019
I think that, because we're talking about the spec, our discussion have focused to an almost distorted degree on "unknown nullness." In practice, most unannotated types that users see, especially those from
java.*, will come with stubs / external annotations / specifications / something. That allows the checkers to treatArrayList<E>asArrayList<E extends @Nullable Object>butOptional<T>asOptional<T extends @NotNull Object>. I see stubs as the "real" solution to unannotated code (well, besides the solution of actually annotating the code directly when possible :)), with@NullnessUnknownas more of a fallback because our checkers have to do something besides crash or give up completely.Stubs have the advantage that we can catch problems like
Optional<@Nullable String>, which we'd permit (albeit with a warning) if the type parameter ofOptionalhad a bound whose nullness was unknown.All that said, I think I was confused (and thus misleading) in what I said above. I'm going to reread it and see if I can do any better.
cpovirk commentedon Aug 12, 2019
(Sorry, reading what I just wrote below, I'm unsure whether it's much help or not. I'm posting it, anyway, partially so that I have it for my own reference. But feel very free to skip reading it.)
OK, I think that what I said does align with the spec text, but all the credit there goes to the spec, because my mental model wasn't very well defined before I read it.
The way part of me thinks of it is -- again, keeping in mind that the real checkers won't see
Mapthis way because they'll have stubs -- that an unannotatedMapclass would effectively look like this to the checker:In other words, part of me thinks of "undefined nullness" as "pasted" not only onto each type variable bound but also onto each type parameter use. (I mean this in a way contrary to what the spec says, even though the spec says something sort of like this. But I endorse the spec; I am just explaining how I originally thought of this in case that somehow helps someonoe.) That would mean that, even if the spec didn't have its current specific rule that says to make every usage of
KandVhave unknown nullness (on account of their bound), then no matter what typeMapis instantiated with, the return type and parameter types ofputwould have unknown nullness, thanks to the "pasted"@UnknownNullnesson those type-parameter usages.I guess my thinking is as follows: In the extremely implausible event that
Map.javawere annotated as follows......then it seems reasonable for
puton aMap<@NotNull K, @NotNull V>to require@NotNullinputs. After all, the type usages are annotated (by the default annotation); the only uncertainty that we're declaring is over whetherKandVshould be permitted to be@NotNullor@Nullablein the first place. Checkers might well warn about that at the instantiation site, but once they've done that, they've done their job: They don't need to warn about usage sites, too.But, again: I do prefer the rules that the spec currently has. I think they work well in practice because they treat a completely unannotated type as if all its parameter and return types, whether they use type parameters or not, have unknown nullness. And that's what I really want, since it produces suppressible warnings for cases the checker is unsure about. If users want more than that, they should annotate the type directly or in stub files.
kevinb9n commentedon Aug 14, 2019
I think interpreting
Tas unconstrained very likely means that if we were analyzing that (e.g. JRE) class we would probably find violations. Since we're not analyzing that code and those violations aren't being reported, that means the problems they relate to might show up somewhere else.Well, surely parameterizing with a nullness-unspecified type argument should be safe and normal. But parameterizing with anything else seems like it should make you suppress a warning to indicate that you're aware of the risk. Of course, to the degree that's annoying, that's supposed to motivate users to bite the bullet and get/provide the right stub files, and that seems kinda working-as-intended to me at the moment.
kevin1e100 commentedon Aug 17, 2019
I suspect there's some kind of disconnect here, specifically around how a type parameter in a legacy file (i.e., a type parameter of "unknown nullness") is different from a known-parametric type parameter (here often referred to as a type parameter whose upper bound is a nullable type, but the idea is just a type parameter that where it is somehow (typically through some form of annotations) known that it can be instantiated with either a nullable or a non-null type, e.g., the type parameter of
j.u.List<T>).The former will commonly appear in legacy
.javafiles where no-one has take the time to provide any annotations; let's imagine a fictitiousLegacy<T>class for that. The latter will commonly appear in.javafiles that have annotations, for instance, after someone annotatedj.u.List, either externally or directly in the source file, so let's assume someone annotatedListand we use that as an example of an interface with a known-parametric type parameter in the discussion below. Finally, let's assume someone also annotatedj.u.Optional<T>, but (let's assume) its annotations limitTto instantiations to non-null types (which would make sense in this case I believe).Now what's the difference? I believe the desire in both cases is that they can be instantiated with type arguments of any nullability. That is,
L<@NotNull String>,L<@Nullable String>, andL<@NullnessUnknown>should all be possible for bothL=LegacyandL=List. Why? ForListthat's the explicit intent, and forLegacy, well, we don't know any better, so it should probably allowed (though one could consider generating warnings). (Conversely, onlyOptional<@NotNull String>should clearly be allowed, whileOptional<@Nullable String>should probably result in some kind of "illegal type" error, andOptional<@NullnessUnknown String>also feels suspect if not outright wrong.)But on the other hand it feels like something is fishy about just instantiating
Legacy<T>with anything. That's what @cpovirk referred to as "pretty scary" in the doc comment quoted above. The issue is that becauseLegacyhasn't been annotated, we don't know if any of the uses of its type variable are actually parametric with howTwas instantiated. For instance,Legacymay define a methodT getOrNull()that could always return null, even when called on aLegacy<@NotNull String>. It may define a methodsetOrClear(T)that could always accept null. Or it could have methods that never accept or return null in places where the type variableTis used.Because of that it's problematic and afaict not "typesafe" to just "paste" any type argument where
Tappears inLegacy's API. What I mean by that is, it's not safe to assume that a callx.getOrNull()on a variable declaredLegacy<@NotNull String> xwill return a non-null string, for instance. On the other hand, doing that fory.get(0)onList<@NotNull String> yis ok. (Similarly, btw, it's problematic / unsafe to letListjust return null fromget(int), since the type parameter allows non-null types. Conversely, inLegacy's method bodies we again don't really know what's ok and what isn't, though we probably won't run a checker over unannotatedLegacy's implementation.)One way of dealing with this is to consider all uses of
Legacy's type variable inLegacy's API as having "unknown nullness" regardless of howLegacy's type parameter is instantiated, which is what this issue was originally filed about. Doing that allows tools to raise warnings when dereferencing unknown nullness method results coming fromLegacy, and to raise warnings when passing nullable values intoLegacymethod parameters. Conversely, withList, checkers should likely "paste" any type argument's nullness into any type variable use inList's method parameters or results (unless they were further annotated). And withOptional, its type variable uses can just be considered to represent non-null types (again unless further annotated).Nonetheless I want to emphasize that both known-parametric (here often call
@Nullable-bounded) type parameters and type parameters "of unknown nullness" (typically appearing in unannotated legacy types) can be instantiated any which way, but at least for a sound checking tool it'll be important to nonetheless treat those instantiations differently: trust them when the type parameter is known parametric, but use "nullness unknown" everywhere if the type parameter itself is "of unknown nullness".One source of confusion here, and I'm still not sure I'm explaining all this very well, is that the term "unknown nullness" is decidedly ambiguous when used for type parameters since "unknown" could refer to a known-parametric type parameter, where at the declaration site we don't know whether it'll be instantiated with a nullable or non-null type. That is generally not what I have meant when I've talked about type parameters with unknown nullness. Instead I was referring to situations like
Legacyas described above.stephan-herrmann commentedon Aug 20, 2019
Much of what @kevin1e100 writes here, gives a nice motivation for #62 and I concur in many regards.
What sounds strange to me is the proposal to (a) allow instantiating the legacy type parameter with any nullness, but (b) ignoring the instantiation in so far that references to that type variable are still seen as unspec'ed types. As a user who instantiates
Legacy<@Nonnull String>I would feel cheated if that annotation has no positive effect. At least I expect some feedback whether I'm using this instantiated type in a consistent way, e.g., passingnullto a parameter of typeTshould be flagged.I know this is a muddled area, and the question how to distinguish
LegacyfromListis a tough one. In my GenericsEclipsePOV essay I outlined the heuristics employed by Eclipse for deciding whether aTreturn type can be trusted to support the contract of a nonnull instantiation. It's not perfect but for this migration / legacy topic it helps to put the blame where it belongs without causing trouble in the core semantics.cpovirk commentedon Aug 20, 2019
Thanks. I came here after reading your email and essay, but thanks for the points here, as well.
In my original comment, I was concerned about the bad side of trusting
Legacy<@NotNull String>: Checkers would assume that aStringthat comes out of the object is non-null (but more on that later). I had completely overlooked what you point out, which is that we can offer a good side: Checkers would force callers to put in only non-null strings. I can understand feeling cheated if this checking doesn't happen.(From that perspective, there's some sense in allowing even
Legacy<@Nullable String>, which lets users opt in to stricter checking of values coming out of the object (but then also see looser checking of values put in). But as you point out in your email (which I'm still processing, along with your essay), we already have conflicting requirements for the hierarchy of nullnesses. PermittingLegacy<@Nullable String>forLegacy<T extends @UnknownNullness Object>would make things worse.)On the other hand, I still don't love the possibility that
Legacy<@NotNull String>would usually effectively mean "SetTto@NotNull String, and also trust that no occurrences ofTin theLegacyAPI should have had overriding nullness annotations." I think that part of what bothers me is the non-local-ness: A suppression on the declaration effectively affects the use sites. Another part may be that I usually expect a suppression to apply to an expression, not to a type. So I might see@SuppressWarnings("nullness") Legacy<@NotNull String> foo = client.getFoo();and think that the problem is thatclient.getFoo()doesn't declare nullness, when in fact the problem is thatLegacydoesn't declare nullness.I understand that Eclipse has heuristics to catch the problems this would otherwise create. I'm wondering if the way to go for both of us, though, is to embrace unknown nullness by getting in the habit of writing
Legacy<@UnknownNullness String>. That will produce warnings in similar cases(?) to Eclipse. And I might not care too much what instantiations are possible (since we have enough difficultly already with the hierarchy of nullnesses), given that there's one that produces the behavior that I want.I guess my main remaining concern is whether
Legacy<@NotNull String>(typically written as justLegacy<String>) will produce a noisy enough warning for me to notice it. I can imagine running in "lenient" mode (i.e., with most unknown-nullness warnings suppressed) a lot of the time, but the danger of interpretingLegacy<@NotNull String>as discussed a couple paragraphs ago feels somehow worse to me than a typical nullness warning. But does that really justify making it an error? (And would a suppressible error be better or worse?) Or maybe I just need to get over the idea that it's a "worse" kind of warning.[edit: a late remark on non-local-ness: Many suppressions of nullness warnings can create a
NullPointerExceptionlater, so we could call those "non-local," too. (In that way, they're just like unchecked warnings.) I still see this case as sort of different, since it's effectively disabling what would otherwise be nullness warnings elsewhere in the code. But I grant that actual runtime effect is the same.]kevin1e100 commentedon Aug 21, 2019
Just to clarify, my previous comment was mostly to say, in a lot of words, that there seem to be benefits from distinguishing "unknown" (aka unspecified,legacy,whatever) from known-parametric (and known-non-parametric) type parameters.
One benefit of doing that is that it seemingly allows to more precisely define the heuristics that should be used for "unknown" type parameters, and when to use the heuristics. There's a strong desire to leave those heuristics up to individual checkers, but by defining which type usages (including uses of type variables) have "unknown" nullness we identify where those heuristics should (likely) apply. If a particular tool's heuristics include issuing warnings when a nullable string is passed into a Legacy<@NotNull String> method, and not warning when dereferencing method results coming from such a thing, that's fine as far as I'm concerned. (Though I believe it's not always "safe" to go by these particular heuristics, and they may be noisy sometimes, so some tools may not want to use them. kotlinc for instance uses a slightly different approach, as an example.)
With that in mind I think it does make sense to assign "unknown" nullness to usages of type parameters which are themselves "unknown" (rather than known-parametric), though I struggle with this myself (see my initial description of this issue), and there could be other ways of achieving this. But I think the intuition is this: if we don't know anything about the type parameter then we probably also shouldn't blindly assume that usages of that type parameter in method parameter and return types are parametric (certainly doesn't seem safe to do so): any given use may be parametric (like
List.get), but it seems like it can also always be nullable (likeMap.get), or always non-null, and we just have no way of knowing that in a legacy class, unless I'm missing something. Conversely, if someone took the time to mark a type parameter as parametric (or non-parametric) then it seems reasonable to assume that they also went over the usages of that type parameter and annotated any occurrences that need it. In other words, once a type parameter is marked as parametric we can assume any usages to be parametric unless annotated, and it seems safe to do so.cpovirk commentedon Oct 18, 2019
Copying over some discussion from #74, which I've closed, since it's about one specific case of the general rule discussed here. (Specifically, it's about the case that I hadn't thought of in my original comment quoted in the first post here.)
In #74, I wrote:
[*] edit: Originally I used
Referenceas my example throughout, rather than usingSupplierat the beginning and switching toReferencebriefly later, as I now do. The problem with usingReferenceat the beginning: I would probably annotateReferenceasReference<T [extends @NotNull Object>, forbiddingReference<@Nullable Object>. (The class can still support all callers because its constructor would accept a@Nullable T, and itsgetmethod would return a@Nullable T.)cpovirk commentedon Oct 18, 2019
And @kevinb9n replied:
cpovirk commentedon Oct 18, 2019
First of all, again, thanks. @kevin1e100 had already tried to explain this to me in the "pasting" model described above, but I had still been under the impression that there was a special case for
@NullnessUnspecified, and I forgot to circle back here. But now I understand why @kevin1e100 "didn't anticipate" this application of the rule, which previously appeared to me to be exactly the intended application of said rule :)I would like to make the case that the spec is unclear on this:
Boxexample). Possibly I was confused because I thought that discussion had focused on implementation code. But the concern indeed applies APIs, which is why the design proposal mentions parametric nullability where it does.@NullnessUnknownbounds" in Checking and interpreting type instantiations wrt declared bounds #57. (Or maybe he just anticipated that this current thread was going to result in a change to the current design.)I should acknowledge that this behavior is in fact "obvious." But I think it's also obviously dangerous, as discussed in the first post here. Given that, when I saw a phrase in the doc that appeared to be solving the problem, I jumped on it.
(Aside: In the long term, it may be useful for our docs to acknowledge the cases in which we've set rules that we recognize to be unsound.)
We can try to make the doc clearer, but before we rush to do that, I want to make the case for different behavior (and also say another thing or two, to no one's surprise :))
34 remaining items
cpovirk commentedon Nov 8, 2019
An amendment to something I said before:
I recently said that I was down on the idea of different rules for what @kevinb9n is considering calling "in-types" and "out-types".
I still stand by that if I am more precise about it: The thing I'm down on is what we might call different "substitution" (and maybe "defaulting") rules for in-types vs. out-types.
Very broadly speaking, though, I do expect for us to sometimes see "different behavior" for in-types and out-types. This behavior would arise naturally when, for example, we handle parametric nullability: Given a type parameter
<T extends @Nullable Object>, we'd forbid dereferencing a parameter of typeT(it might benull!), but we'd also forbid returningnullfrom a method that returnsT(it might not benull!). This is in some sense asymmetric: "IsT@Nullableor not?"But it's still symmetric in terms of substitution rules. That is, we'd still consider the type to be
Tin both cases: It's just that we're checking conversion rules in "the opposite direction":@Nullableisn't convertible toT, but neither isTconvertible to@NotNull.(Similar logic may apply for unspecified nullness, but I haven't thought it through deeply.)
So even though we see "different behavior" for in-types and out-types, it's not because we have different substitution rules for those types: It's just that, thanks to normal type-checking (and sometimes PECS), we sometimes check whether
Tis convertible to a given nullness, and we sometimes check the reverse. And for "in-between" types like parametric nullness, the two don't have the completely opposite behavior that we'd expect from a simpler system with only@NotNulland@Nullable.I think this is probably all reasonably well understood already, but my earlier comments may have been misleading. Plus, I'm still not 100% sure that I have expressed it right :)
kevin1e100 commentedon Jan 3, 2020
Two follow-ups to my previous comment that was trying to tease apart the concerns seemingly at work in "more nullable" concerns @cpovirk has raised on this thread (and elsewhere):
since we're not pursuing default annotations on methods for the time being (Allow annotating null-markedness at method/constructor level? #43), partially annotated files don't seem to be as important ATM: either a class is defaulted/opted-in, or not, IIUC.
experimenting with Kotlin a bit, Kotlin seems to always honor JSR305's
@Nonnull, even when placed on a type variable usage (e.g.,@Nonnull T foo() { return ... }). I'm not aware of any existing tool that would ignore@No[nt][Nn]ullanywhere, but I haven't explicitly tried other tools in preparation for this post. I still grant that there are (almost) no valid use cases for annotating type variable usages this way, but I do also really struggle to see the point of ignoring explicit@Nonnullannotations in this case, not least since that seems to be at odds with how existing annotations are treated: since, e.g., it would be a breaking change for Kotlin to start ignoring JSR@Nonnull, it seems extremely confusing to ask it to ignore another spelling of that annotation.kevinb9n commentedon Jan 9, 2020
I just attempted to read over the 37 screenfuls of chatter on this issue. It didn't go too well.
I think our new goal should be to get this issue CLOSED, and replaced with a set of specific issues which ask specific answerable questions, and we need to try to keep the chatter on those issues on-topic somehow.
cpovirk commentedon Jan 9, 2020
Yeah, a set of specific issues is the aim of that doc of example code snippets that I have temporarily abandoned. Later, hopefully we can all look at the examples, get an idea of what behavior we'd like for each, and then come up with an overarching principle that makes that happen. Fun to look forward to in Q2 :)
cpovirk commentedon Jan 14, 2020
Thanks, that is valuable information and a good point, much as I have advocated for the opposite behavior :(
Furthermore, as I think I said somewhere or other, I acknowledge that people are likely to expect
@NonNull Tto mean "notnull," even without Kotlin precedent.(This is part of the reason that I wish we could justify leaving
@NonNullout entirely. But I grant that it may be too useful to people who are incrementally annotating a codebase, so I've backed off that somewhat.)My recent thinking has been to reimagine
@NonNullas something like "@DefaultNullness." The "default nullness" for a type in annotated code is always going to be@NonNull-- except, notably, in case of type-variable usages, for which it can be parametric nullness. Ideally, users will apply the defaults to all types in their file by using the "in the club" annotation -- call it@ApplyNullnessDefaults.The name "
@DefaultNullness" has the advantage that users are unlikely to apply it frivolously (as we have seen happen with@NonNull). After all, why would they want to explicitly specify the default?The only case in which users would explicit specify the default is when they haven't told the checker that it's safe to apply the default universally -- that is, code without
@ApplyNullnessDefaults. (Yes, this means that it's not exactly "the default," since users have to opt it. It's "the default for code that is annotated" -- "a default," if you will.)cpovirk commentedon Jan 14, 2020
One other point: We should definitely expect some differences in behavior like this. After all, Kotlin hasn't fully implemented the rules that we're still in the process of defining :)
For example, if we change the following code to use our annotations and our rules, then the Kotlin code (bottom) shouldn't compile against the Java code (top):
But currently it compiles:
We can still seek to minimize such differences, of course. But some are inevitable, barring significant compromises.
cpovirk commentedon Jan 15, 2020
Sorry, another belated reply.
Even without defaulting annotations, it's possible to have a partially annotated file. In particular, it's possible to write my original example, under which the file defaults to unspecified nullness but one particular type is annotated
@NonNull.This is true even if there is no explicit
@DefaultNullnessUnspecifiedannotation, since that's the default for a file without@DefaultNonNull.This is true even if we were to omit projection to
@NonNull. If I'm reading the design proposal right, then I could tweak my example to:...and our proposal would still assume that a
Map<@NonNull String, @NonNull String>returns a@NonNull Stringfromget.kevin1e100 commentedon Jan 15, 2020
No argument that if individual methods can't have a default, it's still possible to "sprinkle"
@Nullable/@NonNullinto a file where the default is (implicitly or explicitly)@DefaultNullnessUnspecified. My intention indeed has been that annotating just a type parameter bound has the effect you mention. The idea behind that was that if someone annotates a bound, that annotation indicates a promise that they went through the type variable's usages and added annotations as needed to them as well, which I feel is consistent with the idea that type variable usages are not affected by the surrounding default.No question this is a weird case, and IMHO very much edge cases: it seems much preferable to also slap
@DefaultNonNullon a class with an annotated type parameter bound, so I'm not particularly tied to a particular behavior here.Indeed Kotlin compatibility could be a consideration here, and I'd be curious to hear @abreslav's and other's perspective on that. But my suspicion is that Kotlin's behavior observed above comes from Kotlin currently completely ignoring type annotations in Java code if it's inside brackets. I'm saying that because it seems to treat
MySupplier<@Nullable String>written in Java different fromMySupplier<String?>written in Kotlin: the@Nullableis ignored while the?is used, AFAICT, since the desired error is flagged when implementingmakeSupplierOfNullablein Kotlin instead of Java. If existing annotations are completely ignored by Kotlin then to me it seems "our" annotations can induce any meaning we want, but again, I'd love to hear the Kotlin maintainers' perspective on that.While we're at it, the inverse case seems very confusing as well:
"More nullable" rules here I believe interpret
m.get's return value to be non-null (?), while the proposal in its current form assigns unspecified nullness I believe. Again the latter goes with the idea that annotating a type parameter bound says something about all unannotated type variable usages. To me this is also a very confusing case, and probably even more of an edge case, so again I'm not tied to a particular answer.Thinking about idea that there's a promise somewhere that type variable usages were inspected and annotated if needed, with "more nullable",
@DefaultNonNulladded to the class seems to serve that purpose not just for type variable usages but all type usages, which seems nice.The one I'm struggling with more is:
Here I do feel it would be nice if we could know that
m.getwill return a non-null String. Again, clearly an edge case, so I'm not sure how much it's worth worrying about.cpovirk commentedon Jan 15, 2020
(Your understanding of Kotlin's behavior matches what I'd been assuming. And I agree that it's tolerable for Kotlin to treat
@codeanalysis.annotations.Nullableand@some.other.package.Nullabledifferently -- not ideal, but the necessary cost of handling nullness better.)[edit: As @kevin1e100 notes below, I misread the example, so I got the following wrong:]
The model I'm advocating for is a combination of "most nullable" and "apply the default to type-variable usages." As a result of that second point, the return typeVgets interpreted as@NullnessUnspecified V. Then we pick the most nullable value from that and the argument@NonNull String, so we get unspecified nullness under my model, too.We don't want that, though, right?
get()can returnnullif the key is not present.Of course your point stands if we use
List.getinstead. I think your model might produce non-null, whereas mine would say: "ThatVreturn type is in the scope of@DefaultNullnessUnspecified. Therefore, we don't know that the owner has annotated it properly. So we don't know if we're dealing with aMap.get-like case or aList.get-like case. Let's assume unspecified nullness."kevin1e100 commentedon Jan 15, 2020
Err, yes, I was thinking of a
List.getlike situation where the method always returns a value. I guess your choice ofMap.getwas deliberate here, sorry for not catching on to that.Really? That surprises me I guess. I hope we're talking about the same example (my mistake for including two in the previous comment). The way I thought you would reason this:
@DefaultNonNull@NonNull String@NullnessUnspecifiedbut I thought that didn't matter)Conversely, when using the bound:
@NonNull String@DefaultNonNullbut that doesn't matter)Again I'm not sure I'm particularly invested one way or the other. I might argue that deriving from the type parameter seems convenient for sprinkling annotations, b/c I can annotate a type parameter bound knowing that this will only affect usages of that type variable. On the other hand it does feel like the default annotation is a better "signal" for indicating "I have thought about this whole file including type variable usages", than to derive that signal from default annotations and annotations on type parameter bounds.
One consequence of "more nullable" is that type variable usages don't seem to have a nullability per se, unlike other type usages. Any thoughts on how that could be handled in the definition of "effective nullability specifiers"?
Maybe we're thinking the same thing, but AFAICT Kotlin does honor
@Nullabledeclaration annotations includingjavax.annotation.Nullable. But it seems to ignoreTYPE_USEannotations, in particular, checkerframework's.kevin1e100 commentedon Jan 16, 2020
To @kevinb9n's point I created issues #89 and #90 to try and peel off some questions. I'm going to go ahead and close this issue (sic), having also created issue #91 for handling of annotations on type variables.
I think it's fine to close this, modulo issue #91, because I believe we have figured out a number of important things:
Unannotated<@NonNull String>/Unannotated<@Nullable String>. Kotlin handles this case in a particular way that we've captured here, and we've found a way ("union type argument with@NullnessUnspecified") to specify that behavior. I feel it's critical we are consistent with Kotlin here, since we would otherwise prescribe something that conflicts with Kotlin's handling of completely unannotated generic classes, seemingly a commonly-enough case to create substantial friction.My point being, while there may be different ways of specifying what we need to happen here, I feel we have established what does need to happen. Even if there's disagreement, let's try to create new issues, ideally with smaller scope, to continue the discussion there.
cpovirk commentedon Jan 25, 2020
To close the loop: As I mentioned offline, I did indeed misread your first example. I agree that
getwould return@NonNull Stringin that example. That brings us back to the questions of what users would expect, how often this comes up, etc. I'm happy to continue discussing those questions on the other issues that you've opened. Thanks for splitting them off.