Repository navigation
Description
This issue is an attempt at breaking out a piece from issue #45. One problem that came up there is how to "partially annotate" generic classes/interfaces, and in particular, what should happen if just the type parameter bounds are annotated and nothing else (i.e., not in scope of an explicit default annotation, or equivalently, the default annotation in scope is @DefaultNullnessUnspecified). This is an instance of a more general use case, which is fully or partially annotating files but avoiding the use of default annotations for whatever reason.
I'll mention, because I think that might be relevant in this context, that this problem also comes up with generic methods in otherwise unannotated files: What does it mean to annotate type parameters defined by a method in that scenario?
Cases to consider here align with what it should mean to place each available non-default annotation on type parameters (or more specifically, their bounds, assuming that's how we annotate type parameters). Since there's only upper bounds as this is written, that really only allows the following cases:
<T extends @NonNull X>(presumed examples:ImmutableList,ImmutableMap)<T extends @Nullable X>(presumed examples:List,Map,Predicate)<T extends @NullnessUnspecified X>
The last one is redundant, so I'll ignore it. Issue #45 discusses in great detail what to do when parameterizing completely unannotated generic classes (which is what that issue was about), so let's keep that question out of this issue if possible
What are the use cases for this? Two come to my mind:
- Someone wants to partially annotate a file. This can be valuable for generic methods, since we for now don't allow placing a default annotation on methods. For generic classes it seems more unusual to do, since presumably the class's declaration will use the type parameter throughout.
- Someone wants to make all annotations explicit, or put another way, they for whatever reason don't want to use default annotations. This is for instance how Android's APIs are currently annotated.
Let's say we can ignore what type variables "mean" since that's apparently not directly relevant: since generic classes aren't types, what will matter is how to parameterized types (and parameterized methods), such as List<@Nullable String> and Predicate<@NonNull String>.
There seems to be agreement that some kind of substitution will take place at least in some cases in order to figure out what the members of such a parameterized type are, and what the effective "signature" of a parameterized generic method is. There's an additional wrinkle though, and that wrinkle is that there might be annotations also directly placed on type variable usages, and we need to somehow take those into account as well (and if it's just by ignoring them).
Issue #45 puts two proposals on the table for how to do this substitution, given a type argument to parameterize the generic class or method with:
- If there's an annotation on a type variable, use it. Otherwise, substitute, effectively, the intersection of type argument and the type parameter's bound (keep in mind that bound is not
@NullnessUnspecifiedin this context), which will always result in@NonNullif that's the annotation on the type parameter's bound. - Substitute the union of the type argument,
@NullnessUnspecified, and any type-use annotation on a given type variable usage (ignoring the type parameter's bound).
I believe the question of how to handle annotations on type variable usages could be seen orthogonal, seemingly giving a third possible option:
- If there's an annotation on a type variable, use it. Otherwise, substitute the union of the type argument and
@NullnessUnspecified(ignoring the type parameter's bound).
What I'd propose to do here is to explore the strengths and weaknesses of each approach to come up with a solution. @cpovirk do you think we can move this part off of issue #45?
Activity
[-]Annotating type parameters without using default annotations[/-][+]Annotating type parameters and type variables without using default annotations[/+]kevin1e100 commentedon Jan 23, 2020
Thinking through the "alternative" approach proposed in issue #45 a bit, ie., unioning the type argument,
@NullnessUnspecified, and any type-use annotations, that seems to mean that it's impossible to declare a generic class whereTis ever substituted to@NonNull. That's because@NonNull Xxxtype arguments become@NullnessUnspecified Xxxafter substitution. In other words, with this approach it's simply not possible to declare generic classes that have true parametric nullnes or even truly non-null only. That is to say, neither of the following can be specified without using@DefaultNonNull:@DefaultNonNull interface List<T extends @Nullable Object>{...}@DefaultNonNull class ImmutableList<T extends @NonNull Object> implements List<T> {...}In other words,
@DefaultNonNullis apparently never redundant and carries meaning of its own.This has a number of in my mind problematic implications:
@DefaultNonNullto fully annotate generic classes and generic methods (where the same issue seems to arise). Users won't be able to get by without using a default annotation.@DefaultNonNullreally means, since it isn't "just" a shorthand for "@NonNulleverywhere (except type variable usages)": even if@NonNullwas placed on every type usage, the meaning still wouldn't be the same.Just the last point arguably disqualifies the "more nullable" approach unless and until we revisit the requirements. Additionally, I find the substantive issues to be extremely problematic:
@NonNullannotation #4, and rules out using "just" type use annotations.@DefaultNonNullhaving "standalone" meaning, seems harder to explain than straight substitution, and effects of individual annotations seem harder to predict, since multiple annotations "work together" to determine nullability of a given type usage.While some of these could be mitigated by allowing defaulting annotations on methods and fields, I feel that the first two issues still substantially hold, just on in a smaller scale. Additionally, with default annotations allowed on methods, it seems to become even harder to understand and predict what's going on, since different occurrences of the same type variable may have a different meaning depending on whether they're inside a
@DefaultNonNull-annotated method or not. So while that opens up a different "mode" of incrementally annotating a generic class, the intermediate state is extremely complicated.It's taken me a long time to really put my finger on these issues with the "more nullable" approach, but I find them severe. Meanwhile I'm having a hard time seeing what it really buys, TBH.
To be fair, the "substitution" approach is possibly not as uniform:
@NonNull(which is where the "intersection" mentioned in the previous comment comes in). I believe we could eliminate this provision, however, since it only affects cases likeImmutableList<@NullnessUnspecified Xxxx>, which I consider extremely unusual.@DefaultNonNull(see issue Annotating type parameters and type variables in context of@DefaultNonNull#90), which seems to have its own benefits for uniformity. Nonetheless, this part is possibly a bit puzzling, but also hard to avoid if we want to match how Kotlin treats existing Java code.cpovirk commentedon Jan 23, 2020
Thanks, this is helpful. I think we disagree on whether several behaviors are features or bugs. I will try to keep the parts separate as much as I can.
First, an attempt to answer your question (posed elsewhere) about specific concerns I have with the current proposal (since one of those concerns is exactly what you're covering in this issue):
@kevin1e100 and I appear to disagree over what should happen to type-variable usages when code is partially annotated.
Where we disagree, then, is with a partially annotated file:
What does
Map<String, String>.get...()return in this case?@NonNull String.@NullnessUnspecified String.@kevin1e100's reasoning (which hopefully I am representing accurately):
By annotating the type-parameter bound, the user is claiming to have looked at all usages of the type variable and annotated them properly. That is, in this case, the user should also have annotated
getas returning@Nullable V. (Digression: The user need not also annotate it as accepting@Nullable Object[edit: though of course that would be good to do eventually; I just mean that annotating the type-parameter bound doesn't change anything about the parameter]: Tools will still treat the unannotated parameter type as@NullnessUnspecified Object.)My reasoning:
Users won't expect an annotation on the bound to have this kind of effect on the usages. I think that they will look at the bound as "purely a bound": It is merely a type that tells you what kind of types you can instantiate the class with. I see @kevin1e100's proposal as giving the parameter a sort of "orthogonal nullness information." (We've generally tried to avoid that, but my bigger point is that I don't think users will expect it.)
[edit: Users may be especially surprised that putting
@Nullableon one type can make another type non-nullable.]Will this example ever come up? I don't think it will be frequent, but it seems like a natural first step for someone who is incrementally annotating a type like
Map. If we're lucky, that person actually runs a checker againstMap.javaand its implementations, so the checker identifies the problem withreturn nullin some implementation ofget. But sometimes users won't run the checker (including the case in which they're writing stub files, rather than editing the source). In that case, the problem is likely to go undetected.cpovirk commentedon Jan 23, 2020
Agreed. I'd like to split that into 3 cases and drill in more on each:
This case works identically under our proposals:
setaccepts@Nullable Foo,getreturns@Nullable Foo, etc.There are two things you've said about these examples: one that applies to both, and one that replies only to (3):
First: In both cases, if you don't set
@DefaultNonNull, our proposals behave differently:getare@NonNull Foo.getare@NullnessUnspecified Foo.Each of us sees his proposal's behavior as a feature. I've tried to cover that disagreement in the other post I just made, so I'll set it aside for now.
Second: In (3), if we were to implement my proposal to omit
@NonNull(#4), then it would be outright impossible to even set a bound of@NonNull Objectunless you set@DefaultNonNull. This is true, but I would add:@NonNull, while closely related to what we're discussing here, is not an absolute prerequisite [edit: to applying the rest of my model]. My current assumption is that, if we include@NonNullbut otherwise follow my model,@DefaultNullnessUnspecifiedwould not apply to types that are explicitly annotated as@NonNull. This is a bit different than how you described it [edit: at the top of your first post] -- and probably different than how I described it myself when this last came up, sorry :( Today, I would say something like this (I think): "@DefaultNullnessUnspecifiedadds@NullnessUnspecifiedto every type usage that isn't already directly annotated."@NonNullbound will have minimal effect on the substitution rules. So the effect on the substitution rules still seems to be our primary disagreement.ImmutableList's type parameter as having a@NonNullbound unless we put@DefaultNonNullon the class. My approach would be either to annotate it all or else to annotate all its methods as@DefaultNullnessUnspecified. Both of these are additional work, but I would note that your approach, too, requires annotating all usages of the type variable. The difference is only in whether the owner can stop there or must continue to annotate the other types in the file. I think it is actually clearest for users if the owner must annotate them all (or explicitly apply@DefaultNullnessUnspecifiedto methods). For example, I think users will be surprised if they see a method likevoid foo(A a, B b)and find thatAmeansAbutBmeans@NullnessUnspecified B, thanks to an annotation on the bound ofAbut notB.cpovirk commentedon Jan 23, 2020
I think I may have begun addressing this in my previous post: I support the idea that
@DefaultNonNullapplies to all not-explicitly-annotated type usages (modulo some subtleties around type-variable usages). This is possibly contrary to things I have said before. Again, sorry.But I do think it's fair to see an inconsistency here: I do want for
@DefaultNullnessUnspecifiedto apply to type-variable usages, even though@DefaultNonNullarguably sort of doesn't. The reasons for that, again, are the ones around partially annotated classes in my previously previous post.I would like to think the exceptions are still "clearly defined." But I agree that this deserves thought, similar to what we've given to our other exceptions. Additionally, I grant that my "
FoomeansFooandTmeansT" model is best understood as a deeper shift than that, so it is especially deserving of scrutiny. If it feels appropriate to call this a "requirements" issue, then I don't object to addressing it as such.Would it be fair to call this an objection to allowing
@DefaultNonNullon method scope at all, since it applies equally to usages of a type likeObject? (That's still a fair objection to make, but I want to see if I'm understanding it correctly.)I think we are both seeing danger in partially annotated files in general. In my previous post, I gave the example of a single method with different nullness defaults for its parameters; in your post, you gave the example of multiple methods with different nullness defaults for the same type. I am inclined to see it as more important to be consistent within a single method than for a single type across methods, but possibly you hold the opposite view?
Note also that, even without method-scope defaults, it would still be possible for some usages of a type varaible to have different meaning -- specifically, if some are inside a nested class that is annotated
@DefaultNullnessUnspecified(unless we completely omit@DefaultNullnessUnspecified-- I don't remember where we stand with that currently). But at least that is a rarer case.cpovirk commentedon Jan 23, 2020
FWIW, I don't have a strong opinion on this one, either.
I would note that we're also likely to see an even rarer case,
ImmutableList<@Nullable Xxxx>-- or at leastImmutableList<T>, where<T>has parameteric nullness. Notably,FluentIterable.toList()can be called on aFluentIterable<@Nullable Xxxx>(simply because we allowed that before we had nullness checking and now we don't have any way of preventing it).Anyway, for both
@Nullableand@NonNull, I think I like the idea of performing "intersection." While it's arguably an "exception," I can also see it as a way of taking a bogus type and replacing it with something sane. Under that interpretation, we might outright treat anImmutableList<@Nullable Xxxx>as anImmutableList<@NonNull Xxxx>for all purposes, like checking whether it can be assigned to a field of typeImmutableList<@NonNull Xxxx>. This is in contrast to forcing types to@NonNullonly when we're performing substitution to figure out the type of a parameter or return value. (And of course we'd also generate an error, which the user would have to have suppressed to have seen any of the other behavior.) But I haven't thought about this much.[edit: Maybe this already happens? "If the type usage is a type argument then let U be the glb of the effective specifier(s) of the corresponding type parameter’s explicit or implicit bound(s): if U is more specific than the type usage’s defaulting annotation in effect then U is the type argument’s effective nullability specifier." Again, I haven't thought about this a lot.]
Can you give some more detail on why this handling is necessary to match Kotlin's existing treatment of Java code? As I understand it, both our models agree in the case of fully unannotated code, which is the only kind of Java code that exists today.
cpovirk commentedon Jan 23, 2020
This probably comes back to the "deeper shift" I referred to above. Depending on the underlying way that we view types, we could see either model as simpler. I like to see my model as including essentially a single rule[*]:
My proposal:
FoomeansFoo" in "in the club code" [edit: which includes making type-variables take the nullness of their argument] and "Foomeans@NullnessUnspecified Foo" in "other code."Your proposal:
@NonNullin "in the club" code and@NullnessUnspecifiedin "other code."@NullnessUnspecified)if not.[edit: The latter bullet includes an interesting possibly-not-a-special-case rule to consider lub(
<T extends @Nullable Object>,@NullnessUnspecified) to be like an unannotated type-variable usage. I think this is correct, just not necessarily obvious.]Additionally, for explicitly annotated type usages:
My proposal generalizes an existing rule:
Your proposal has a rule that is separate (so more rules☹️ ) but more direct (so more direct 🙂):
So that's how I'd spin mine as "simpler." Probably reasonable people could disagree. But to respond to your specific concerns:
@DefaultNonNulla "standalone" meaning. Does any of the above help change how you feel about that? If not, can you clarify which remaining part feels "standalone?"Map<String, Object>, it's always safe to replaceKwithString, no matter howMapis annotated, and in particular without having to first check whether that usage ofKis annotated.[*] In describing both our models, I'm setting aside wildcards and type arguments. (Hence my rules say "most type usages.") Those already have separate sections in the design proposal, and I wouldn't be surprised if they'd stay that way under both proposals. (Not that I've thought about this much.)
kevin1e100 commentedon Jan 23, 2020
What I meant here is that with "your" proposal, unless I'm missing something, it's simply not possible to specify generic classes or methods equivalently with or without using
@DefaultNonNull. That's because it's necessary to use@DefaultNonNullto specify generic classes or methods in such a way that type arguments are cleanly substituted; without that annotation there's no way to prevent any potential non-null guarantees/requirements for substituted types from being "watered down" to unspecified nullness.To phrase it as a question, how would you specify
ListorImmutableListto your own satisfaction "in your model" but without using@DefaultNonNull? If I understand the model correctly, such a specification isn't possible. Instead, it's necessary to use@DefaultNonNullto fully specify generic classes and methods, and that means that annotation takes on meaning of its own; it isn't just a shorthand as the requirements doc at least by my reading seems to envision. That's what I was referring to with "standalone meaning". Does that make sense?Maybe this helps: in my mind, it should be possible to express everything we want just with type use annotations (even it it's awkward or laborious sometimes). The defaulting annotations should be just shortcuts that we could omit from the set of annotations we provide without losing expressive power (and again, by my reading, that's the role the requirements doc envisions for the defaulting annotations). But the model you're proposing doesn't seem to give this full expressiveness when "just" using the type use anntotations. And I find that to be a "flaw" in the model that's very difficult to get past.
On the other hand, again, it's still very hard for me to see a lot of benefit that this expressiveness gap would buy. We're talking about corner case anyway (type parameters are relatively rare; wanting to partially annotate a class that defines one is even rarer). It's possible that the proposed "watering down" of type variable occurrences until they're surrounded by
@DefaultNonNullwould help some users be "safer" when using annotations, but that seems a matter of perspective (that is to say, reasonable people might disagree on what's "safer" here), and either way is relative: it'll always be possible to mis-annotate things, especially when tools don't aid in the task, up to and including the philosophical question of what makes a "correct" specification for something in the first place. Another way of saying that is, just because@DefaultNonNullis placed somewhere doesn't guarantee that someone added@Nullableeverywhere it's needed; just like annotating a type parameter bound doesn't guarantee that.kevinb9n commentedon Jan 23, 2020
I'm gonna classify this thread "don't attempt to read" :-) until an organized doc or docs are factored out of it.
(To be clear, it's totally fine that it started as a linear conversation; sometimes that will stay manageable and sometimes it will be like this.)
cpovirk commentedon Jan 24, 2020
Thanks. I am encouraged that we appear to be understanding each other, even though we may well not end up with the same preferred approach.
That makes sense. I agree that, under my model, there is no satisfactory way to annotate
ListorImmutableListunless you apply@DefaultNonNull.And thanks, that really zeroes in on it.
Conceptually, this doesn't bother me. I'm sure we will find more people that it does bother -- and hopefully at least a few more that it doesn't :). It will be interesting to see the ratio. It will also be interesting to see if people's existing views can be flipped in one direction or the other.
There are multiple ways that people might argue for your position:
FoomeansFoo" model, as I don't think the latter was under consideration at the time.)Do you think there are other broad categories of arguments that I'm glossing over?
First, thank you for the point that users can always mis-annotate unchecked code. I had thought of this somewhere along the line but had put it out of mind. It's never a good thing to lose sight of.
As for corner cases: While I agree that we're talking about corner cases, I would still expect them to come up at scale -- and eventually be among the first experiences someone has with the nullness annotations -- so I think they're worth worrying about. (Somewhat related: a new issue about stub files, #94.)
It would be nice for users to run the checker when making substantial changes, but I can definitely imagine that someone would skip it for a "trivial, local" change like changing
Map<K, V>toMap<K extends @Nullable Object, V extends @Nullable Object>-- especially if that person was annoyed after spending a bunch of time trying to understand whyMap<String, @Nullable Object>was producing a warning in the first place, discovering along the way that those codeanalysis people made the obviously incorrect decision that bare<T>should mean<T extends @NonNull Object>instead of<T extends @Nullable Object>;) I see this in contrast to putting@DefaultNonNullon the type: Users should pretty clearly expect that to have significant, non-local effects.On top of that, even if the user does run the checker, it won't necessarily catch the problem: If it weren't for the
defaultmethods onMap, the user could annotate the type in any way, and it would pass the checker. It's only when checking an implementation likeHashMap(which users aren't necessarily going to do, both because it's harder and because they don't normally have references of static typeHashMap) that many errors would arise. I grant, though, that we are now talking about a corner case of a corner case.In the less corner-case-y corner case, the user will at least get an error. That's good, but I still worry that the cause of the error will not necessarily be obvious to the user: "I didn't annotate
get, so why is there an error there? And why are there errors for dereferencing parameters in some methods but not others?" The user may end up with something sound, but the experience along the way might not inspire confidence.kevin1e100 commentedon Jan 25, 2020
To the degree that what I wrote sounded like
@DefaultNonNull"must" derive its meaning fully from type-use annotations, I'm not sure I'd go that far. But it's useful to compare expressiveness inside and outside the club, I think, to make sure the same things can be expressed (or to decide that it's ok that there's a gap, and/or describe what those gaps are). Giving equivalent expressive power inside and outside the club I feel is a useful property, regardless of how that's achieved. The point of my earlier post was that "more nullable" rules as presented don't seem to have that property, which I believe this comment confirmed:It happens to be that, by defining
@DefaultNonNull("in the club") in terms of type-use annotations, one automatically gets the same expressive power inside and outside the club. (Besides other implications.) But I can imagine that there are other ways of achieving comparable expressiveness inside and outside the club.cpovirk commentedon Jan 27, 2020
When I think of "annotating for nullness without using defaulting annotations," I think of code like this:
Then I think of going through and replacing every
???with some annotation that expresses the nullness of that type usage.I think we both expect that we're not going to literally make that possible: Doing so would require including a
@ParametricNullnessannotation:Assuming that we don't include that, I see us as already accepting that some type usages can be satisfactorily annotated only by "defaulting." That is, for a usage of
V:@Nullableon the usage itself, the usage changes to nullable.Given that we need "defaulting," I believe it will be simplest to understand if it happens:
The current design, by contrast, gives "defaulting" behavior to type annotations (in the specific case of a type-parameter bound), and it lets an individual method end up partially annotated.
I think that the current design fulfills the letter of the law ("only type-usage annotations are needed") but not what I see as the spirit ("all usages can be annotated individually").
Does "all usages can be annotated individually" sound like a useful property to you? I can see some appeal in it[*]. But assuming that we're not going that far, I would embrace the need for defaulting annotations, rather than making type annotations pull double duty.
That's the theoretical take on it. More practically speaking, here's another example in which I think users would be surprised by the current design's behavior:
I don't think users would expect for
Tto have specified nullness inside the private implementation method.Caveats on that:
@SuppressWarnings("nullness"). Well, it would be a little sad to lose protection from more obvious errors, so maybe the user wants@SuppressWarnings("nullness:lenient")or something. But it's unfortunate for the user to have 3+ choices (@DefaultNullnessUnspecified,@SuppressWarnings("nullness"),@SuppressWarnings("nullness:variousoptions")), only one of which fits very well.@NonNullannotation #4 go), or we may add them later, or at least users may encounter a rarer version of this problem in which@DefaultNullnessUnspecifiedis on an inner class.[*]: And maybe Android would like it [edit: because, as I understand it, they want to explicit annotate all type usages]? But I think their build already translates from their own internal annotations into public ones, so they could have their own internal
@ParametricNullnessif they wanted [edit: and their build would strip it out].kevin1e100 commentedon Jan 28, 2020
Took me a while to realize it, and maybe it was unintentional (?), but the way I read the latest rule proposed in this issue, it seems to achieve the ability to "fully annotate" generic classes with or without a default annotation:
In particular,
Listcould be written:(
ImmutableListvery similar.) If I apply the rule above literally, it seems to do the trick: it seems to makeget's return type parametric, because the return type will be lub(@NonNull, <nullness from type argument>) = <nullness from type argument>.Unintentional or not, I do like this rule quite a bit better. Importantly, it "recovers" the usual meaning of
@NonNullfor on anything but type variables. The only concern I have with this is that it does run counter to how existing tools usually interpret uses of existing annotations on type variables (@NonNull T).Arguably that's the subject of issue #91, and while I have concerns (mostly related to how intuitive this is, and the problem of semantic mismatch with existing spellings of
@NonNull), the good news is that legitimate uses of@NonNull Tare rare, if they exist at all (as discussed at length in issue #4). So even if there's an issue here, it hopefully wouldn't bite users too often in practice.To more directly respond to some parts of the most recent post:
To be clear I do want to make "that" possible, as much as is possible. And indeed I think one option for that is additional type-use annotations. A big part of me favors this, because
@ParametricNullness Tseemingly has less chance of being misinterpreted than@NonNull T. And I do suspect Android would like it, since they already have such an annotation (though indeed they strip it afaik: it's just a marker in the source code).But I feel this has weaknesses:
@NullnessUnspecifiedfor the latter, but that's inconsistent).I've been trying to come up with other ways to avoid that:
NonNullthat works for both regular type usages and type variables, as has been proposed in issue [moved to #230] Decide whether to include a@NonNullannotation #4. I don't like this option for the reasons mentioned there, especially, again, considering how rarely the different name will "matter" to users.@NullnessUnspecified, an annotation that "flips the default", meaning its meaning would be relative to the surrounding default. Doing something "creative" here seems more plausible than with@NonNull, since@NullnessUnspecifieddoesn't have precedence, and its use on type variables will be exceedingly rare. But, a good naming escapes me, and it seems bound to be very confusing.@NonNull(adjustForTypeArgument = true)(which we can then also define for@NullnessUnspecified)I actually like this last option, as ugly as it is, best of the listed alternatives: (1) it allows for both interpretations of
@NonNull T, which I suspect is helpful when migrating from existing annotations to ours. (2) it doesn't perturb the straightforward@NonNull Stringcase. (3) it's pretty explicit on what it does, assuming we can name the attribute reasonably. (4) it doesn't introduce a separate annotation for a "corner case".Yet I admit it's pretty gross, so hopefully we can find something better. But I feel if we can somehow make something like
@NonNull[(adjustForTypeArgument = true)] Tmean@ParametricNullness Tthen the proposed rule can work, and rather nicely. Not least because it's better for issue #90, by allowing@NullnessUnspecified Tto be substituted to@Nullable String, for instance, as well, which the "explicit annotation trumps type argument" rule doesn't allow for. (This is also true for the "previous" alternative proposal mentioned in the first comment in this issue.)cpovirk commentedon Jan 28, 2020
Yes, the
@NonNull T"trick" is the reason that I've hoped to find a different name for the annotation. (Sorry for speaking here under the assumption that@NonNulldoesn't exist but without calling out that assumption.)Neat to hear that Android has an annotation like
@ParametricNullness.I had thought that -- under my model, at least --
@NullnessUnspecified Twas correct for "assumed parametric." See #76, which I should have dug up to cite earlier from #90. Do you see problems with it under my model, or are you thinking about it under the current model?(Hopefully I'll be writing down some more precise rules for my model in the next day or two.)
The idea of a "flips the default" annotation is interesting but probably confusing, as you say. I've also wondered about something like
@NullnessSpecified-- or, I suppose,@NullnessUnspecified(false):) But those names are probably too far from@NonNull....so certainly that's a reason to like
@NonNull(adjustForTypeArgument = ...). I would still love to avoid supporting projecting type variables to@NonNullat all, but maybe this is a viable compromise? I will try to think about names foradjustForTypeArgument. And if people write@NonNull(adjustForTypeArgument = true)on a non-type-variable type, then... no big deal, I guess? Tools could flag it as redundant, but I suppose there's nothing wrong with then saying "OK, we looked for a type variable to adjust it for, and there was none, so we're done adjusting it."cpovirk commentedon Jan 28, 2020
(Apparently the internal Android annotation is called "
@NullFromTypeParam?" [edit: previously])For a parameter to
@NonNull:@NonNull(unlessTypeArgumentPermits = true)?If we hate boolean parameters on principle, it is alternatively possible to do something like:
@NonNull(UNLESS_TYPE_ARGUMENT_PERMITS)(using an enum)@NonNull(UnlessTypeArgumentPermits.class)(using a class)But boolean parameters aren't so bad for annotation parameters. Plus, the alternatives require a separate class.
cpovirk commentedon Jan 28, 2020
While poking around, I saw a report (from Pete) about very occasional usages of
@NullFromTypeParamon non-type-parameter type usages:T @NullFromTypeParam []when they mean@NullFromTypeParam T[]. But this sounds rare.Foo<@NullFromTypeParam ? extends E>. But this is the same problem we have with all our annotations, and it also sounds rare.kevin1e100 commentedon Jan 28, 2020
I find
unlessTypeArgumentPermitspretty good. Note I'd expect@NonNull(unlessTypeArgumentPermits = true) Tto be used a bit at least--since it would be essentially for the use case this issue is about, which is to annotate a generic class without using@DefaultNonNull.On the other hand, as briefly mentioned before, it may just be fine to leave alone. If we're right that "projecting" to non-null isn't really a thing then uses of
@NonNull Ttoday are probably attempts at specifying a generic class with non-null-only type parameter, e.g.,OptionalorImmutableList, where@NonNull(unlessTypeArgumentPermits = true) Tis identical to a straight non-null projection (assumingTis declared as<T extends @NonNull Object>). The main concern is probably just that it would seemingly likely surprise users that@NonNull Tis not necessarily non-null. But if annotating generic classes is a 5% case, and doing so without default annotations but with nullable type parameters is even rarer, then maybe it's ok if the ergonomics aren't completely clean.kevin1e100 commentedon Jan 28, 2020
(and again I realize I should try to have this debate in issue #91)
cpovirk commentedon Jan 29, 2020
In that spirit, I left a reply on #91.
kevinb9n commentedon Feb 2, 2022
@cpovirk or @kevin1e100, would one of you be able to produce a present-day summary of whatever we might need to decide and/or do, here?
cpovirk commentedon Mar 3, 2022
In an ideal world, we would hold this question in our mind simultaneously with the other questions about partially annotated code, which I believe are currently:
@NonNull?@NullnessUnspecified?@NullUnmarked?@NullMarked/@NullUnmarkedat the method level?Piece of cake :)
Anyway, I believe the question is over the rule for when a type usage has unspecified nullness:
Option A
@Nullablehas specified nullness.@NullMarkedhas specified nullness.Option B
Usages that are not type variables are handled as in Option A. For type variables:
Or other hybrids or variants
e.g.,
@NullMarkedannotation or (b) a corresponding type-parameter declaration meeting <whichever of the type-parameter rules above we'd pick>.Going to back strategy for deciding this: One idea that @netdpb(?) had proposed is to draft some sections of the User Guide about partially annotated code, doing so one time for each of the viable combinations we see for our rules and annotations. For example:
If we combine Option A with a method-level
@NullMarked+@NullUnmarked, then the docs would say:If we combine Option B with a method-level
@NullMarked+@NullUnmarked, then the docs would say:If you then throw in
@NullnessUnspecified, then:etc., etc., etc. :)
kevinb9n commentedon Mar 8, 2022
I'm reopening this as #238, as it has become way too long.