Skip to content

Non-null projection of a type variable usage #86

Closed

Description

@kevinb9n

We've agreed to support the "nullable projection of a type variable"; that is, for a type variable T, the ability to denote the type representing "T union null"? This would presumably be written @Nullable T. (Of course, we get that for free with the way we've conceptualized what "Nullable" means.)

Should we support the "non-null projection of a type variable"; denoting the type "T minus null"? On this we seem to have less agreement, so let's look at use cases.

Activity

  1. added
    nullness
    on Dec 11, 2019
  2. kevinb9n commented on Dec 11, 2019

    @kevinb9n
    CollaboratorAuthor

    I am currently thinking this concept may not apply to wildcards. The way to think about wildcards is perhaps instead #88.

  3. cpovirk commented on Feb 3, 2020

    @cpovirk
    Collaborator

    Trying to summarize where I think we stand, part 1: Projecting to non-null

    We don't think there is much need for this in practice:

    • Existing usages in the Checker Framework JDK appear unlikely to be necessary under our system.
    • We were able to annotate Guava without using it. (OK, I made one compromise on Maps.difference because I didn't want to add a type parameter. It doesn't appear that the compromise affects any existing callers. [edit: And now see some other small examples.])
    • The only existing method we're aware of that it would be necessary for is filterNonNull -- but that's a Kotlin method, not a Java method. And it seems somewhat unlikely for such methods to become common in Java unless nullness becomes a language feature and that feature supports projecting to non-null (which seems somewhat unlikely, even if our project supports it). [edit: I later learned of a JDK method that does use non-null projection: Map.merge, discussed below.]

    But this is all distinct from other questions:

    • We are still likely to include a @NonNull annotation, as it helps users incrementally annotate codebases ([moved to #230] Decide whether to include a @NonNull annotation #4). [edit: The common case will be applying it to type usages that aren't type variables: For example, we'll see @NonNull String.]
    • @NonNull T will still be valid Java. (And even if our checkers forbid it, users may write it in code that is not checked by our checker -- possibly including stub files.) So we will need to settle the behavior of that -- which could still be "project to non-null" if we think that would be least confusing, even if that's not a behavior we need to support (or necessarily even want to support).
  4. cpovirk commented on Feb 3, 2020

    @cpovirk
    Collaborator

    Trying to summarize where I think we stand, part 2: Projecting to unspecified nullness

    This is a bit harder to summarize.

    We suspect that users will want something kind of like this on occasion:

    However, in the second case (and perhaps the first, too, if @NullnessUnspecified is applied to methods like Map.get) users probably don't want full projection. That is, they don't want @NullnessUnspecified T to unconditionally override the nullness of T. Instead, if they instantiate with T as @Nullable String, they'll want @NullnessUnspecified T to turn into @Nullable String.

    However, if they instantiate T as @NonNull String, they may want the type to become @NullnessUnspecified String. That case would be a projection.

    My model for this is that @NullnessUnspecified means "@Nullable or no annotation, but I don't know which." Under that model, it makes sense that @NullnessUnspecified T could "add" nullness (because it might be meant to be @Nullable T) but never "remove" it (because it might be meant to be plain T).

    As in the previous post, though, we might or might not feel that we can give @NullnessUnspecified T the behavior that we ideally might want.

    [*] To produce an effect much like @NullnessUnspecified T (possibly exactly like it? or is it "inconsistent?"), Android could just leave that whole method as @DefaultNullnessUnspecified. That might not be a good solution in general, since the blast radius can be large, but if such cases are rare enough, it might be sufficient.

  5. kevin1e100 commented on Feb 3, 2020

    @kevin1e100
    Collaborator

    (FWIW, findViewById's type parameter seemingly could be bounded by non-null. Similar to Map.get, another way of looking at it could be that a nullable type argument seemingly justifiably "could" result in a proper nullable, since the caller code went through the trouble of using a nullable type argument, and maybe even "should", since that's probably what Kotlin would do today with findViewById<MyView?>(...).)

  6. cpovirk commented on Feb 5, 2020

    @cpovirk
    Collaborator

    I don't have a particularly strong opinion, but FWIW:

    I would see that as covered by the second paragraph of Type Arguments of Parameterized Types, which says to ignore the ? (well, @Nullable) in that case. I suspect that that's how you interpret the current text, too, but you're saying that we could change it? I would guess that the current rule is more useful on net. Do you think it's worth a new issue for this? (If so, I will try to remember to link it from the design proposal.)

  7. kevin1e100 commented on Feb 6, 2020

    @kevin1e100
    Collaborator

    Agreed on the ignoring if the type parameter was bounded by non-null. I meant to say that that's not the only possible way of specifying findViewById, though: it could alternatively seemingly be declared like this:

    <T extends @Nullable View> @NullnessUnspecified T findViewById(int id) {...}
    
  8. cpovirk commented on Feb 6, 2020

    @cpovirk
    Collaborator

    Ah, thanks, now I get it, and I'm not sure what else I could have thought the first sentence of your previous post meant :)

    While I've spoken against "unnecessarily" nullable bounds in the past (like on Class and Optional), I see that this is different:

    • The nullable bound actually affects the result you get from the method (at least assuming we make a particular decision about substitution rules).
    • This is a method, not an object, so there's no danger that some method will require a Foo<@NonNull Object> when a user has a Foo<@Nullable Object>.

    I am maybe somewhat still vaguely against a nullable bound here, simply because I like the idea of encouraging users to always pick the "obvious" signature when annotating their own code (and especially writing stub files, since multiple users might write stubs for the same API, and it would be nice for them to agree). But I'm not that opposed. And it's not like we'd have to add a new feature to allow it.

    (This ends up not being that relevant, but out of curiosity, I looked at what percentage of callers of findViewById in our depot perform a null check on the result. It looks like maybe a little under 2%.)

  9. cpovirk commented on Feb 19, 2020

    @cpovirk
    Collaborator

    I tried to search Google's codebase for cases in which CF users needed Class<T> to be instantiable with a nullable type. (That's relevant to this issue because, if it's possible to instantiate Class<@Nullable Foo>, then we need (or at least might want) to project the return value of methods like newInstance to @NonNull T.)

    I didn't find much, though I was searching for a very specific pattern, as discussed in this post, in which I also report the results. (Most of what my search turned up was various proxying/intercepting use cases, like retrying, rate limiting, and memoizing, in which the input object had to be non-null.)

    If anyone has ideas for patterns of "project to non-null" that I could look for, including other patterns of using Class<T> with a potentially nullable type argument, let me know, and I may see what I can find.

  10. cpovirk commented on Feb 19, 2020

    @cpovirk
    Collaborator

    [@wmdietlGC , since we recently spoke about nullable instantiations of Class<T>]

  11. cpovirk commented on Feb 21, 2020

    @cpovirk
    Collaborator

    RE: needing Class<T> to be instantiable with a nullable type:

    I could also imagine searching for methods that accept a Class<T> and a Foo<T>[*]. I suspect that most of those are either only reading from the Foo or only writing to it, though, in which case they could accept both nullable and non-nullable instantiations by using wildcards like Foo<? extends @Nullable T>. (And wildcards are likely a good idea for non-nullness-related PECS reasons, too.)

    [*] maybe starting with a search like Class<T>.*\w[^s]+<T> lang:java

  12. cpovirk commented on Feb 21, 2020

    @cpovirk
    Collaborator

    (Possibly exception: arrays, for which you can't use wildcards. But arrays are trouble all around.)

  13. kevin1e100 commented on Feb 24, 2020

    @kevin1e100
    Collaborator

    I can believe that examples like class Optional<T> can be annotated to not allow nullable type arguments, and then their methods can refer to plain T, not needing non-null projections. I even feel that ruling out other possible annotation schemes for the same classes that do rely on projections is maybe a good thing: give users one way of doing things but not more than one. But some existing systems seem to allow things like Optional<@Nullable String>, raising questions I think:

    • Are there adoption concerns here? If Optional (as an example) in our system cannot be annotated such that Optional<@Nullable String> is allowable, will that create issues for users trying to adopt our annotations?
    • Are there cases where using something like Optional<@Nullable String> (or Optional<U>, where U is some nullable type parameter in scope) is useful / necessary? If so then that would suggest there is a need to non-null project somewhere, though it could be when specifying Optional's type argument instead of annotating Optional itself.

    @wmdietlGC seems to feel that things like Optional<@Nullable String> and Class<@Nullable String> aren't needed, IIRC, though I'm not sure right now where he said that, so that's encouraging to me.

  14. cpovirk commented on Feb 25, 2020

    @cpovirk
    Collaborator

    You might be looking for this @wmdietlGC post.

    I should note that Guava implementation code did contain one usage of Optional<U> with a nullable U parameter. But that usage turned out to be not just avoidable but obfuscating. You can see that it forces wrapping and unwrapping so that it can distinguish between null (i.e., no Optional) and Optional.absent(), but then it doesn't use that distinction at all. I have it ripped out in my annotated Guava, and I'll be ripping it out in the mainline.

    I will see how I can search for users of Optional who really do want to permit nullable instantiations. I might just change the stub file to forbid nullable instantiations, identify all the breakages, and look at a sample.

  15. 22 remaining items

  16. modified the milestones: 1.0, 0.3 on Dec 2, 2022
  17. cpovirk commented on Jun 9, 2023

    @cpovirk
    Collaborator

    I should admit here that I have since learned of a JDK method that does use non-null projection in the way that people normally think of it (i.e., not just for Class<@NonNull T> or Optional<@NonNull T>: Map.merge, whose value parameter (and whose remappingFunction's parameter types) should be @NonNull V: jspecify/jdk#14, eisop/jdk#41.

  18. kevinb9n commented on Jun 9, 2023

    @kevinb9n
    CollaboratorAuthor

    Hmm. They've continued to prove rare?

    Was there an issue where we were considering whether Optional</*parametric*/T> should automatically conform to bounds? It still feels highly problematic to me, but do you feel like it's worth reconsidering?

  19. cpovirk commented on Jun 9, 2023

    @cpovirk
    Collaborator

    Up until the Map.merge thing, it was used only for the checked* collections (Class<@NonNull E>) and the stream single-element methods (Optional<@NonNull E>):

    $ git grep @NonNull src/java.base/share/classes/java | grep -v ElementType.java
    src/java.base/share/classes/java/util/Collections.java:                                                      Class<@NonNull E> type) {
    src/java.base/share/classes/java/util/Collections.java:    public static <E extends @Nullable Object> Queue<E> checkedQueue(Queue<E> queue, Class<@NonNull E> type) {
    src/java.base/share/classes/java/util/Collections.java:    public static <E extends @Nullable Object> Set<E> checkedSet(Set<E> s, Class<@NonNull E> type) {
    src/java.base/share/classes/java/util/Collections.java:                                                    Class<@NonNull E> type) {
    src/java.base/share/classes/java/util/Collections.java:                                                    Class<@NonNull E> type) {
    src/java.base/share/classes/java/util/Collections.java:    public static <E extends @Nullable Object> List<E> checkedList(List<E> list, Class<@NonNull E> type) {
    src/java.base/share/classes/java/util/Collections.java:                                              Class<@NonNull K> keyType,
    src/java.base/share/classes/java/util/Collections.java:                                              Class<@NonNull V> valueType) {
    src/java.base/share/classes/java/util/Collections.java:                                                        Class<@NonNull K> keyType,
    src/java.base/share/classes/java/util/Collections.java:                                                        Class<@NonNull V> valueType) {
    src/java.base/share/classes/java/util/Collections.java:                                                        Class<@NonNull K> keyType,
    src/java.base/share/classes/java/util/Collections.java:                                                        Class<@NonNull V> valueType) {
    src/java.base/share/classes/java/util/stream/Stream.java:    Optional<@NonNull T> reduce(BinaryOperator<T> accumulator);
    src/java.base/share/classes/java/util/stream/Stream.java:    Optional<@NonNull T> min(Comparator<? super T> comparator);
    src/java.base/share/classes/java/util/stream/Stream.java:    Optional<@NonNull T> max(Comparator<? super T> comparator);
    src/java.base/share/classes/java/util/stream/Stream.java:    Optional<@NonNull T> findFirst();
    src/java.base/share/classes/java/util/stream/Stream.java:    Optional<@NonNull T> findAny();
    

    We may of course still be missing others, but I think we'd be hearing from our Checker Framework users if any of them were of great importance.

  20. cpovirk commented on Jun 9, 2023

    @cpovirk
    Collaborator

    Was there an issue where we were considering whether Optional</*parametric*/T> should automatically conform to bounds? It still feels highly problematic to me, but do you feel like it's worth reconsidering?

    If anything, I'm inclined to view the rarity as more reason not to reconsider: Apparently users won't have to reach for @NonNull T often, so I'm less inclined to save them the trouble. (And I agree that "saving them the trouble" is likely to complicate things.)

    In fairness, I do expect users to hit this more than I'm suggesting here: If you're writing Kotlin, or if you're writing Java using the Checker Framework's "default defaults," then you'll get in trouble if you write a "class Foo<T>" that uses a "Class<T>." Or actually, you won't get in trouble with Class and Optional with the Checker Framework as long as you use its stubs. But you could have similar problems with ImmutableList and similar. And you can definitely see problems with Kotlin, though probably less, given the lesser usage of Class and Optional (and perhaps ImmutableList) there.

    So I do expect users to be confused sometimes. Hopefully we can find ways to manage that, but "automatically conform to bounds" is not at the top of my list.

  21. netdpb commented on Apr 9, 2024

    @netdpb
    Collaborator

    Current decision: Yes, @NonNull T is a valid augmented type usage.

    Argument for changing: It would be simpler not to support nullability projections. However, no strong case was made for changing the decision.

    Timing: This must be decided before version 1.0 of the jar.

    Proposal for 1.0: Finalize the current decision. If you agree, please add a thumbs-up emoji (👍) to this comment. If you disagree, please add a thumbs-down emoji (👎) to this comment and briefly explain your disagreement. Please only add a thumbs-down if you feel you can make a strong case why this decision will be materially worse for users or tool providers than an alternative.

    Results: This proposal received six 👍s and no other votes. It is finalized. I'll edit the title to reflect that.

  22. netdpb commented on May 17, 2024

    @netdpb
    Collaborator

    Decision: @NonNull T is a valid non-null projection.

  23. changed the title [-]Non-null projection of a type variable usage [working decision: yes, support][/-] [+]Non-null projection of a type variable usage[/+] on May 17, 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

    designnullness

    Type

    No type

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions