Skip to content

Annotating type parameters and type variables without using default annotations #89

Closed as not planned

Description

@kevin1e100

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 @NullnessUnspecified in this context), which will always result in @NonNull if 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

  1. changed the title [-]Annotating type parameters without using default annotations[/-] [+]Annotating type parameters and type variables without using default annotations[/+] on Jan 16, 2020
  2. kevin1e100 commented on Jan 23, 2020

    @kevin1e100
    CollaboratorAuthor

    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 where T is ever substituted to @NonNull. That's because @NonNull Xxx type arguments become @NullnessUnspecified Xxx after 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, @DefaultNonNull is apparently never redundant and carries meaning of its own.

    This has a number of in my mind problematic implications:

    • it forces the use of @DefaultNonNull to 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.
    • it makes it harder to explain what @DefaultNonNull really means, since it isn't "just" a shorthand for "@NonNull everywhere (except type variable usages)": even if @NonNull was placed on every type usage, the meaning still wouldn't be the same.
    • this seems to go against the requirements we laid out for defaulting annotations, which state them

    to be semantically identical to annotating "all" not-explicitly-annotated type usages within that scope, with clearly defined exceptions, with the corresponding type-use annotation

    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:

    • forcing the use of default annotations is an adoption barrier, as mentioned in issue [moved to #230] Decide whether to include a @NonNull annotation #4, and rules out using "just" type use annotations.
    • it's essentially not possible to partially annotate a generic class or generic method: if users want to specify the behavior of a type parameter, they have to specify the entire class, more or less. This puts cognitive burden on users, since they have to think more carefully through all type usages affected by a default annotations, compared to "just" adding a type use annotation somewhere.
    • the "more nullable" model, and specifically @DefaultNonNull having "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:

    • it makes extra allowances for type parameters bounded by @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 like ImmutableList<@NullnessUnspecified Xxxx>, which I consider extremely unusual.
    • It distinguishes "nullness unspecified" type parameters and handles them in a special way as discussed in issue what happens to type variables when @NullnessUnknown (and @NotNull) type parameters are instantiated? #45, while "more nullable" handles those arguably more uniformly with other cases. On the other hand, these type parameters are handled the same with and without @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.
  3. cpovirk commented on Jan 23, 2020

    @cpovirk
    Collaborator

    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.

    Digression / background: We do agree on what happens in the 2 common cases:

    1. a fully annotated file
    @DefaultNonNull
    interface Map<K extends @Nullable Object, V extends @Nullable Object> {
      @Nullable V get(@Nullable Object key);
    }

    Clearly Map<String, String>.get(...) returns a @Nullable String.

    1. a fully unannotated file
    [@DefaultNullnessUnspecified]
    interface Map<K, V> {
      V get(Object key);
    }

    Clearly Map<String, String>.get...() returns a @NullnessUnspecified String.

    Where we disagree, then, is with a partially annotated file:

    [@DefaultNullnessUnspecified]
    interface Map<K extends @Nullable Object, V extends @Nullable Object> {
      V get(Object key);
    }

    What does Map<String, String>.get...() return in this case?

    • @kevin1e100 advocates for @NonNull String.
    • I advocate for @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 get as 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 @Nullable on 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 against Map.java and its implementations, so the checker identifies the problem with return null in some implementation of get. 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.

  4. cpovirk commented on Jan 23, 2020

    @cpovirk
    Collaborator

    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> {...}

    Agreed. I'd like to split that into 3 cases and drill in more on each:

    // 1: instantiation with a @Nullable type
    @DefaultNonNull interface List<T extends @Nullable Object>` {}
    List<@Nullable Foo> list;

    This case works identically under our proposals: set accepts @Nullable Foo, get returns @Nullable Foo, etc.

    // 2: instantiation with a @NonNull type (@Nullable bound)
    @DefaultNonNull interface List<T extends @Nullable Object> {}
    List<[@NonNull] Foo> list;
    
    // 3: instantiation with a @NonNull type (@NonNull bound)
    @DefaultNonNull class ImmutableList<T extends @NonNull Object> implements List<T> {}
    ImmutableList<[@NonNull] Foo> list;

    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:

    • In yours, the types in methods like get are @NonNull Foo.
    • In mine, the types in methods like get are @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 Object unless you set @DefaultNonNull. This is true, but I would add:

    • Omitting @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 @NonNull but otherwise follow my model, @DefaultNullnessUnspecified would 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): "@DefaultNullnessUnspecified adds @NullnessUnspecified to every type usage that isn't already directly annotated."
    • That said, as discussed above, my proposal would mean that the @NonNull bound will have minimal effect on the substitution rules. So the effect on the substitution rules still seems to be our primary disagreement.
    • I do grant that it's somewhat unfortunate that we can't declare ImmutableList's type parameter as having a @NonNull bound unless we put @DefaultNonNull on 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 @DefaultNullnessUnspecified to methods). For example, I think users will be surprised if they see a method like void foo(A a, B b) and find that A means A but B means @NullnessUnspecified B, thanks to an annotation on the bound of A but not B.
  5. cpovirk commented on Jan 23, 2020

    @cpovirk
    Collaborator
    • it makes it harder to explain what @DefaultNonNull really means, since it isn't "just" a shorthand for "@NonNull everywhere (except type variable usages)": even if @NonNull was placed on every type usage, the meaning still wouldn't be the same.
    • this seems to go against the requirements we laid out for defaulting annotations, which state them

    to be semantically identical to annotating "all" not-explicitly-annotated type usages within that scope, with clearly defined exceptions, with the corresponding type-use annotation

    I think I may have begun addressing this in my previous post: I support the idea that @DefaultNonNull applies 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 @DefaultNullnessUnspecified to apply to type-variable usages, even though @DefaultNonNull arguably 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 "Foo means Foo and T means T" 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.

    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.

    Would it be fair to call this an objection to allowing @DefaultNonNull on method scope at all, since it applies equally to usages of a type like Object? (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.

  6. cpovirk commented on Jan 23, 2020

    @cpovirk
    Collaborator

    To be fair, the "substitution" approach is possibly not as uniform:

    • it makes extra allowances for type parameters bounded by @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 like ImmutableList<@NullnessUnspecified Xxxx>, which I consider extremely unusual.

    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 least ImmutableList<T>, where <T> has parameteric nullness. Notably, FluentIterable.toList() can be called on a FluentIterable<@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 @Nullable and @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 an ImmutableList<@Nullable Xxxx> as an ImmutableList<@NonNull Xxxx> for all purposes, like checking whether it can be assigned to a field of type ImmutableList<@NonNull Xxxx>. This is in contrast to forcing types to @NonNull only 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.

  7. cpovirk commented on Jan 23, 2020

    @cpovirk
    Collaborator
    • the "more nullable" model, and specifically @DefaultNonNull having "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.

    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:

    • Most unannotated type usages (including unannotated type-variable usages) are "Foo means Foo" in "in the club code" [edit: which includes making type-variables take the nullness of their argument] and "Foo means @NullnessUnspecified Foo" in "other code."

    Your proposal:

    • Most unannotated type usages are @NonNull in "in the club" code and @NullnessUnspecified in "other code."
    • Unannotated type-variable usages take the nullness of their argument if their bounds are annotated (including implicitly annotated by being declared inside "in the club" code) or lub(<argument>, @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:

    • All type usages have the nullness lub(<explicit or else default annotation from usage>, <nullness from argument if substituting>).

    Your proposal has a rule that is separate (so more rules ☹️) but more direct (so more direct 🙂):

    • Most unannotated type usages are @NonNull in "in the club" code and @NullnessUnspecified in "other code."
    • Unannotated type-variable usages take the nullness of their argument if their bounds are annotated (including implicitly annotated by being declared inside "in the club" code) or lub(<argument>, @NullnessUnspecified) if not.
    • Annotated type usages have the nullness of that annotation.

    So that's how I'd spin mine as "simpler." Probably reasonable people could disagree. But to respond to your specific concerns:

    • I'm not sure my model gives @DefaultNonNull a "standalone" meaning. Does any of the above help change how you feel about that? If not, can you clarify which remaining part feels "standalone?"
    • I see my approach as more like "straight substitution": Inside Map<String, Object>, it's always safe to replace K with String, no matter how Map is annotated, and in particular without having to first check whether that usage of K is annotated.
    • Under either model, users who want to know the effective nullability of a type-variable usage may have to look at both the usage and the argument.

    [*] 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.)

  8. kevin1e100 commented on Jan 23, 2020

    @kevin1e100
    CollaboratorAuthor

    I'm not sure my model gives @DefaultNonNull a "standalone" meaning.

    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 @DefaultNonNull to 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 List or ImmutableList to 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 @DefaultNonNull to 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 @DefaultNonNull would 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 @DefaultNonNull is placed somewhere doesn't guarantee that someone added @Nullable everywhere it's needed; just like annotating a type parameter bound doesn't guarantee that.

  9. kevinb9n commented on Jan 23, 2020

    @kevinb9n
    Collaborator

    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.)

  10. cpovirk commented on Jan 24, 2020

    @cpovirk
    Collaborator

    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.

    To phrase it as a question, how would you specify List or ImmutableList to 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 @DefaultNonNull to 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?

    That makes sense. I agree that, under my model, there is no satisfactory way to annotate List or ImmutableList unless you apply @DefaultNonNull.

    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.

    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:

    • First, there's the concept that our "in the club" annotation "must" be a "defaulting" annotation, as you just described. Your preference for this may come partly from the mere fact that we have text about it in the current requirements doc, but I think it's safe to say that the text is there for deeper reasons, and we should try to get to the bottom of those. (That said, while I wasn't following the nullness discussions closely back then, I don't get the impression that the text was specifically intended to choose between the "defaulting" model and the "Foo means Foo" model, as I don't think the latter was under consideration at the time.)
    • Second, there's the comparison of behavior in specific cases. The two of us disagree in some cases about which behavior is desirable. I think we both see the specific affected cases as corner cases, but more on that below.
    • Third, there's the argument that your model is simpler (or more "understandable," "predictable," "natural," etc.) -- from the perspective of end users and/or from the perspective of the tool developers who have to implement it. The two of us also disagree on which model is simpler.

    Do you think there are other broad categories of arguments that I'm glossing over?

    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'll always be possible to mis-annotate things, especially when tools don't aid in the task.... Another way of saying that is, just because @DefaultNonNull is placed somewhere doesn't guarantee that someone added @Nullable everywhere it's needed; just like annotating a type parameter bound doesn't guarantee that.

    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> to Map<K extends @Nullable Object, V extends @Nullable Object> -- especially if that person was annoyed after spending a bunch of time trying to understand why Map<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 @DefaultNonNull on 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 default methods on Map, the user could annotate the type in any way, and it would pass the checker. It's only when checking an implementation like HashMap (which users aren't necessarily going to do, both because it's harder and because they don't normally have references of static type HashMap) 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.

  11. kevin1e100 commented on Jan 25, 2020

    @kevin1e100
    CollaboratorAuthor

    there's the concept that our "in the club" annotation "must" be a "defaulting" annotation, as you just described.

    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:

    under my model, there is no satisfactory way to annotate List or ImmutableList unless you apply @DefaultNonNull.

    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.

  12. cpovirk commented on Jan 27, 2020

    @cpovirk
    Collaborator

    When I think of "annotating for nullness without using defaulting annotations," I think of code like this:

    interface Map<K extends ??? Object, V extends ??? Object> {
      boolean equals(??? Object obj);
      ??? V put(??? K key, ??? V value);
      ...
    }

    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 @ParametricNullness annotation:

    interface Map<K extends @Nullable Object, V extends @Nullable Object> {
      boolean equals(@Nullable Object obj);
      @ParametricNullness V put(@ParametricNullness K key, @ParametricNullness V value);
      ...
    }

    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:

    • In unannotated code, the usage has assumed parametric nullability.
    • When the user adds an annotation elsewhere, the usage changes to non-null.
    • When the user adds @Nullable on the usage itself, the usage changes to nullable.

    Given that we need "defaulting," I believe it will be simplest to understand if it happens:

    • only as a result of pure defaulting annotations -- to be explicit
    • only following normal scoping rules (i.e., applying to a whole class and perhaps optionally a whole method) -- to be consistent

    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:

    public class Foo<T extends @Nullable Object> {
      public T someMethod() { ... }
    
      public T someOtherMethod() { ... }
    
      @DefaultNullnessUnspecified // TODO: Annotate implementation code.
      private T someComplicatedImplementation() { ... }
    }

    I don't think users would expect for T to have specified nullness inside the private implementation method.

    Caveats on that:

    [*]: 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 @ParametricNullness if they wanted [edit: and their build would strip it out].

  13. kevin1e100 commented on Jan 28, 2020

    @kevin1e100
    CollaboratorAuthor

    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:

    All type usages have the nullness lub(<explicit or else default annotation from usage>, <nullness from argument if substituting>)

    In particular, List could be written:

    interface List<T extends @Nullable Object> {
      @NonNull T get(int intex);
    }
    

    (ImmutableList very similar.) If I apply the rule above literally, it seems to do the trick: it seems to make get'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 @NonNull for 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 T are 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:

    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 @ParametricNullness annotation

    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 T seemingly 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:

    • we'd need 2 variants, for parametric and "assumed parametric" (or use @NullnessUnspecified for the latter, but that's inconsistent).
    • this annotation would only make sense on type variables, but I believe there's no way to make javac enforce that?
    • having extra annotations "just" for type variables seems unfortunate given type variables are comparatively rare.

    I've been trying to come up with other ways to avoid that:

    • A different name for NonNull that works for both regular type usages and type variables, as has been proposed in issue [moved to #230] Decide whether to include a @NonNull annotation #4. I don't like this option for the reasons mentioned there, especially, again, considering how rarely the different name will "matter" to users.
    • Instead of @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 @NullnessUnspecified doesn'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.
    • An attribute, maybe @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 String case. (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)] T mean @ParametricNullness T then the proposed rule can work, and rather nicely. Not least because it's better for issue #90, by allowing @NullnessUnspecified T to 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.)

  14. cpovirk commented on Jan 28, 2020

    @cpovirk
    Collaborator

    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 @NonNull doesn't exist but without calling out that assumption.)


    Neat to hear that Android has an annotation like @ParametricNullness.


    But I feel [@ParametricNullness] has weaknesses:

    • we'd need 2 variants, for parametric and "assumed parametric" (or use @NullnessUnspecified for the latter, but that's inconsistent).

    I had thought that -- under my model, at least -- @NullnessUnspecified T was 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 @NonNull at all, but maybe this is a viable compromise? I will try to think about names for adjustForTypeArgument. 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."

  15. cpovirk commented on Jan 28, 2020

    @cpovirk
    Collaborator

    (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.

  16. cpovirk commented on Jan 28, 2020

    @cpovirk
    Collaborator

    While poking around, I saw a report (from Pete) about very occasional usages of @NullFromTypeParam on non-type-parameter type usages:

    • People occasionally write (IIUC) T @NullFromTypeParam [] when they mean @NullFromTypeParam T[]. But this sounds rare.
    • People occasionally write Foo<@NullFromTypeParam ? extends E>. But this is the same problem we have with all our annotations, and it also sounds rare.
  17. kevin1e100 commented on Jan 28, 2020

    @kevin1e100
    CollaboratorAuthor

    I find unlessTypeArgumentPermits pretty good. Note I'd expect @NonNull(unlessTypeArgumentPermits = true) T to 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 T today are probably attempts at specifying a generic class with non-null-only type parameter, e.g., Optional or ImmutableList, where @NonNull(unlessTypeArgumentPermits = true) T is identical to a straight non-null projection (assuming T is declared as <T extends @NonNull Object>). The main concern is probably just that it would seemingly likely surprise users that @NonNull T is 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.

  18. kevin1e100 commented on Jan 28, 2020

    @kevin1e100
    CollaboratorAuthor

    (and again I realize I should try to have this debate in issue #91)

  19. cpovirk commented on Jan 29, 2020

    @cpovirk
    Collaborator

    In that spirit, I left a reply on #91.

  20. added this to the 1.0 milestone on Oct 13, 2021
  21. kevinb9n commented on Feb 2, 2022

    @kevinb9n
    Collaborator

    @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?

  22. cpovirk commented on Mar 3, 2022

    @cpovirk
    Collaborator

    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:

    • provide @NonNull?
    • provide @NullnessUnspecified?
    • provide @NullUnmarked?
    • support @NullMarked/@NullUnmarked at 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

    • A type usage with @Nullable has specified nullness.
    • A type usage in the scope of @NullMarked has specified nullness.
    • Otherwise, it has unspecified nullness.

    Option B

    Usages that are not type variables are handled as in Option A. For type variables:

    • If at least one bound of the corresponding type parameter has specified nullness, then the usage has specified nullness.
    • Otherwise, it has unspecified nullness.

    Or other hybrids or variants

    e.g.,

    • like Option B but requiring all bounds to have specified nullness
    • A type-variable usage has specified nullness if its type parameter is declared to definitely accept nullable type arguments or to definitely not accept nullable type arguments.
    • Nullness is specified if there is either one of (a) an enclosing @NullMarked annotation 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 you want to annotate a class for nullness but skip a method that you're unsure about, then...

    If we combine Option A with a method-level @NullMarked+@NullUnmarked, then the docs would say:

    ...put @NullMarked on the class and @NullUnmarked on the method you're unsure about. Then, for other types in the class that you want to add null to, annotate them with @Nullable.

    If we combine Option B with a method-level @NullMarked+@NullUnmarked, then the docs would say:

    ...leave the file unmarked, but put @NullMarked on the other methods in the class. Then, for other types in the class that you want to add null to, annotate them with @Nullable, except for any type-parameter bounds that the unmarked method depends on.

    If you then throw in @NullnessUnspecified, then:

    ...put @NullMarked on the class, @NullUnmarked on the method you're unsure about, and @NullnessUnspecified on any usages of class-scope type variables in that method. Then, for other types in the class that you want to add null to, annotate them with @Nullable.

    etc., etc., etc. :)

  23. kevinb9n commented on Mar 8, 2022

    @kevinb9n
    Collaborator

    I'm reopening this as #238, as it has become way too long.

  24. modified the milestones: 1.0, 0.3 on Dec 2, 2022
  25. added
    design
    on Mar 13, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    design

    Type

    No type

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions