Skip to content

Kotlin nullness analysis integration #24

Open

Activity

  1. added
    nullness
    on Jan 10, 2019
  2. cpovirk commented on Jan 15, 2020

    @cpovirk
    Collaborator

    One topic that we've discussed occasionally is what happens to Kotlin users of a library like Guava when all of Guava's jsr305 and Checker Framework annotations are replaced with our new annotations.

    One thing that can happen is that they see new compile errors (or warnings, if the new checks in Kotlin are limited to warning-level). Here's an example of how that can happen.

    Another possibility is runtime errors. I'm not sure how well I can explain this, but here goes:

    Consider Guava's Function. It currently has a somewhat bogus @Nullable annotation on its return type. This annotation is from the days before type annotations, so we were using it to mean something different than our new annotations mean (and, to be fair, different than what the Checker Framework @Nullable annotation itself means, even though we're using that annotation currently). Specifically: We are not using it to mean: "This method returns a T, where T might be a nullable type, but even if it's not a nullable type, the method can still return null." (That would be a contract more like Map.get.) Instead, we are using it to mean: "This method returns a T, and T might be a nullable type, so this method might return null." (This is more like List.get.)

    The point is, it contains the method @Nullable T apply(@Nullable F input), and the part of that I'm going to focus on is the return type. We might as well consider the simpler example of an analogous Supplier type, which would contain the method @Nullable T get(). (Guava's Supplier isn't annotated that way, simply because we haven't been consistent about annotating return types.)

    All that is to say that we could have a legacy class like the following (much like the example I linked above, but tweaked somewhat):

    package demo.java;
    
    import javax.annotation.Nullable;
    import javax.annotation.ParametersAreNonnullByDefault;
    
    @ParametersAreNonnullByDefault
    public interface MySupplier<E> {
      static MySupplier<String> makeSupplierOfNullable() {
        return () -> null;
      }
    
      @Nullable E get();
    }

    And it might have a Kotlin caller like the following:

    package demo
    
    import demo.java.MySupplier.makeSupplierOfNullable
    
    fun main(args : Array<String>) { 
      makeSupplierOfNullable().get().toString()
    }

    This compiles and runs fine:

    $ javac -cp jsr305-3.0.2.jar MySupplier.java -d mylistout && ./kotlinc -d listofnullable.jar -cp mylistout:jsr305-3.0.2.jar -Xjsr305=strict -jvm-target 1.8 UseSupplierOfNullable.kt && ./kotlin -cp mylistout:listofnullable.jar demo.UseSupplierOfNullableKt && echo ok
    ok
    

    Then the owner of MySupplier decides to adopt our new annotations. Since they don't exist yet, I'm going to stick to other annotations that do exist. (I think the point still holds, but that will deserve more discussion in a minute.)

    package demo.java;
    
    import javax.annotation.ParametersAreNonnullByDefault;
    import org.checkerframework.checker.nullness.qual.Nullable;
    
    @ParametersAreNonnullByDefault // would be @DefaultNonNull
    public interface MySupplier<E> {
      static MySupplier<@Nullable String> makeSupplierOfNullable() {
        return () -> null;
      }
    
      E get();
    }

    This produces a runtime error:

    $ javac -cp checker-qual-2.8.1.jar:jsr305-3.0.2.jar MySupplier.java -d mylistout && ./kotlinc -d listofnullable.jar -cp mylistout:checker-qual-2.8.1.jar:jsr305-3.0.2.jar -Xjsr305=strict -jvm-target 1.8 UseSupplierOfNullable.kt && ./kotlin -cp mylistout:listofnullable.jar demo.UseSupplierOfNullableKt && echo ok
    Exception in thread "main" java.lang.NullPointerException
      at demo.UseSupplierOfNullableKt.main(UseSupplierOfNullable.kt:6)
      at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
      at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
      at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
      at java.lang.reflect.Method.invoke(Method.java:498)
      at org.jetbrains.kotlin.runner.AbstractRunner.run(runners.kt:64)
      at org.jetbrains.kotlin.runner.Main.run(Main.kt:110)
      at org.jetbrains.kotlin.runner.Main.main(Main.kt:120)
    

    My understanding is that this is because, if Kotlin believes that get() might return null, then get().toString() performs a null check. The problem, then, is that Kotlin no longer believes that get() might return null, so it no longer performs the null check.

    But wait! Kotlin will recognize our new annotations, so it will know that get() can return null. But I have two concerns:

    1. Some users may be using an older version of Kotlin. We can reduce this risk by releasing Kotlin support before Guava and other libraries adopt the new annotations.
    2. I'm not sure exactly how Kotlin plans to handle the new annotations. Will it always consider get() to return String?, or will it operate in some more conservative mode by default, treating it more like a platform type (maybe with warnings)? If the answer is "String?," then I think everything works. The concern then is that, in other cases with other types, users will get full-on compile errors, not just warnings, where they didn't before. That might be the right choice. I just find it interesting that one of our choices leads to compile-time errors and the other leads to runtime errors.

    Will this ever come up in practice? I have no idea. I just stumbled across it as I was experimenting. If it won't come up in real code, then great :)

  3. cpovirk commented on Jan 17, 2020

    @cpovirk
    Collaborator

    Another possibility is runtime errors.
    ...
    Will this ever come up in practice? I have no idea. I just stumbled across it as I was experimenting. If it won't come up in real code, then great :)

    For what it's worth, replacing @Nullable T with T in Guava (in the cases where that would make sense with our new annotations) doesn't appear to cause any runtime problems in Google's Kotlin tests. This gives us more reason to believe that the runtime errors are an edge case.

    Replacing @Nullable T with T in Guava does break a bunch of our Kotlin code at compile time. I saw this very rarely when removing @Nullable from return types (all specifically from removing it from Function.apply[*]). I saw it much more commonly when removing @Nullable from parameter types: I saw a lot of assigning immediateFuture(null) to a Future<SomeNonNullType>, and I saw a lot of implementing FutureCallback<Foo> with onSuccess(result: Foo?) instead of onSuccess(result: Foo). We'll have to think more about the migration story.

    [*] [edit: The breakages looked something like guavaOptional.map { it.someNullableMethod() }. This would fail at runtime if the method actually returned null, so the code should be fixed, anyway -- and can be fixed before Guava changes nullness annotations, thankfully.]

  4. petukhovv commented on Aug 7, 2020

    @petukhovv
    Collaborator

    I see the following way for integration nullness annotations into Kotlin. Keep in mind we should avoid breaking changes between minor versions anyway and major versions without preliminary warnings.

    So the integration plan can be like this:

    1. (as soon as possible) Start reporting warnings in the Kotlin use sites affected by the new jspecify annotations about future possible change of resolution or appearing a red code. We can do efforts to understand where the resolution can really change or applicability can be broken and report the warnings only there.
    2. (as soon as possible, partially done) Check the current implementation of support jspecify annotations by @dzharkov and merge it into master under an internal or public flag.
    3. (as soon as possible, partially done) Fix an issue around support loading type use annotations from Java binaries (the corresponding issue on the IntelliJ side has already been resolved): https://youtrack.jetbrains.com/issue/KT-11454
    4. (anytime up to 1.5) Fix a few corner cases' problems and implement some design decisions, which are related with support of jspecify annotations (see our internal document "Type annotations support in Kotlin").
    5. (in 1.5) Enable jspecify annotations support by default.

    Also taking into account this:

    One topic that we've discussed occasionally is what happens to Kotlin users of a library like Guava when all of Guava's jsr305 and Checker Framework annotations are replaced with our new annotations. One thing that can happen is that they see new compile errors (or warnings, if the new checks in Kotlin are limited to warning-level). Here's an example of how that can happen.

    I think we can at least detect the situation when used version of the Kotlin compiler is less than 1.5 and the new annotations are used in the version of the library known for us. In such case, the resolution can really change and new errors can appear: the library no longer uses the old annotations, and the Kotlin compiler doesn't yet support the new ones by default. For instance, we can report this using some IDE-level warning and suggest turn on the new annotations interpretation through a compiler flag or update the Kotlin compiler/downgrade a library. Otherwise, warnings only on call sites may be missed.

    So it seems there is another plan item:
    6) (at the same time or earlier with the start of the warnings reporting) Implement additional detection and suggestion mechanism for the case above.

    @abreslav What do you think about such plan? Maybe I missed something or wrote something wrong.

    Also @cpovirk, thanks for described cases, do you think this fits into the plan above?

  5. cpovirk commented on Dec 3, 2020

    @cpovirk
    Collaborator

    Since I keep letting this sit: @kevin1e100 , you probably have a better idea of what we need for Kotlin than I do. Would you mind having a look?

  6. kevin1e100 commented on Dec 3, 2020

    @kevin1e100
    Collaborator

    Sounds very reasonable to me.

    we can report this using some IDE-level warning and suggest turn on the new annotations interpretation through a compiler flag or update the Kotlin compiler/downgrade a library.

    This sounds fine to me, but if JSpecify annotations will be errors starting in 1.5 then I suspect there's a good chance we won't have to worry about this case. That's just my intuition but I have no objections to implementing some safeguards around this regardless.

  7. petukhovv commented on Dec 7, 2020

    @petukhovv
    Collaborator

    Some update.

    Unfortunately, in fact, in Kotlin we will not be able to enable error reporting for jspecify annotations by default in 1.5, as this does not comply with our breaking changes policy, because of jspecify annotations was supported only in 1.4.30 (in the warn mode by default), until 1.5 it will take too little time to enable the error level by default. I am also currently finishing work on support for reading type use annotations from class files and some other improvements (for example, correctly reading annotations on arrays: @Anno1 Integer @Anno2 [] @Anno3 []), which is also a breaking change. These commits will only get into 1.5. At the same time, proper support for reading type use annotations is important for jspecify cases, so I assumed it would be nice if these features (improvements plus jspecify annotation support itself) had the same life cycle so that support was complete and consistent at every point in time. So I see the following scenario: in 1.5 it will be supported to read jspecify annotations properly from both sources and binaries in the warn mode by default with the ability to enable the error mode via a compiler flag; and in 1.6 enable the error mode by default.

    It's also possible that the minimum time for adoption (time to enable errors by default) will be expressed not in versions ("from 1.5 to 1.6"), but in time (for example, half a year). I will additionally inform you if something changes here.

  8. cpovirk commented on Dec 10, 2020

    @cpovirk
    Collaborator

    @PetukhovVictor , a question for you (or maybe your IntelliJ colleagues):

    Once your work on the Kotlin compiler is done, will IntelliJ's Kotlin editor support the same JSpecify warnings/errors as the command-line compiler does? Or does that require additional work?

    (I understand the IntelliJ's Java editor would need significant work to catch up to the Kotlin side.)

  9. petukhovv commented on Dec 14, 2020

    @petukhovv
    Collaborator

    Once your work on the Kotlin compiler is done, will IntelliJ's Kotlin editor support the same JSpecify warnings/errors as the command-line compiler does?

    Yes, it will, but not fully in all combinations of IntelliJ's version and Kotlin plugin's version:

    • IJ 20.1/20.2 + Kotlin 1.4.30: it will work only with sources and without some improvements of the type enhancement (like KT-24392, KT-43919, KT-43920 and some more);
    • IJ 20.3 + Kotlin 1.4.30: it will work both with sources and binaries in the editor and only with sources during compilation (in a sense, these two versions are not fully compatible in terms of loading Java annotations), type enhancement improvements aren't available;
    • IJ 20.3 + Kotlin 1.5.0: it will work both with sources and binaries fully, with type enhancement improvements;
    • IJ 20.1/20.2 + Kotlin 1.5.0: it will work both with sources and binaries during compilation, and only with sources in the editor, type enhancement improvements are available (except for support related reading type use annotations from binaries).

    The differences are due to the fact that compilation and the IntelliJ editor use different Java models (note that in these models at different times there was support for reading type use annotations from binaries).

    Additional work on the IntelliJ side to support something around jspecify annotations in the Kotlin's editor aren't needed for now. The main task, important for us, has already been done and is available in IJ 20.3.

  10. cpovirk commented on Dec 14, 2020

    @cpovirk
    Collaborator

    Thanks! I had figured, but I wanted to make sure I wasn't overlooking something.

  11. petukhovv commented on Dec 23, 2020

    @petukhovv
    Collaborator

    As we discussed internally earlier, support for type use annotations and some other improvements will be available in 1.4.30 (the corresponding type mismatch reports will be warnings, the compiler flag -XXLanguage:+ImprovementsAroundTypeEnhancement turns them to errors), so in the post above it's worth replacing 1.5.0 with 1.4.30 and ignoring the points where 1.4.30 was before :)

    BTW, "some other improvements" are:

    • use annotations in the type parameter position to enhance corresponding types: KT-11454
    • proper support of the type enhancement of the annotated java arrays: KT-24392
    • proper support of the type enhancement of the annotated java varargs' elements: KT-18768
    • type enhancement based on annotated bounds of type parameters
    • type enhancement within type arguments of the base classes and interfaces: KT-43919
    • support type enhancement based on type use annotations on java fields
    • preference of a type use annotation to annotation of another type: KT-24392
      • (if @NotNull has TYPE_USE and, for example, METHOD target, then @NotNull Integer [] -> Array<Int>..Array<out Int>? instead of Array<Int>..Array<out Int>)
  12. cpovirk commented on Dec 23, 2020

    @cpovirk
    Collaborator

    Thanks! I had just yesterday built a kotlinc from the 1.4.30 branch and started experimenting with -XXLanguage:+ImprovementsAroundTypeEnhancement -Xjspecify-annotations=strict, based on your earlier instructions.

    Based on my experiments, I had hoped to send a question to you today, but it looks like I might not get to it until the new year.

  13. added this to the Release-independent milestone on Oct 13, 2021
  14. cpovirk commented on Mar 29, 2022

    @cpovirk
    Collaborator

    (no rush on this; I'm just trying to dump some thoughts from a recent conversation before I forget them)

    One question that's come up in recent discussions is whether it's desirable to have Kotlin issue only warnings (i.e., not errors) for a while after we release JSpecify 1.0 and projects begin to adopt it.

    A small reason for this approach is that we'd get further testing of Kotlin's support before it's on "for real."

    But my impression is that the bigger reason is that library users would get a transition period for free: If we don't provide library owners with a @Migrating annotation in the 1.0 release, then by default, either all JSpecify annotations can produce errors, or all JSpecify annotations can produce warnings. Since it can be useful to offer a transition period in which problems are reported only as warnings, Kotlin could choose to provide that for all JSpecify annotations in the early days of 1.0.

    (Yes, users can always switch between errors and warnings by changing compiler flags (or doing whatever the equivalent of that is in their IDE, I assume?). But the default behavior matters a lot.)

    (And yes, we'd still hope to eventually provide features to simplify migration long after the release of 1.0, since that's when most people would adopt. But such features may take time to design, so we may conclude that it's best to release without them, in which case we'd want to consider "only warnings" as a short-term solution for Kotlin users of early-adopter libraries.)

    I see value in this, but I want to note one reason that I don't see it as a slam dunk: Yes, it provides a valuable transition period when someone annotates a previously unannotated library -- or at least adds more nullness information to a library that starts out with partial nullness information. But I see a disadvantage for libraries that are already annotated and are looking to switch to JSpecify annotations: If JSpecify annotations produce only warnings, then a switch to JSpecify is likely to downgrade nullness problems from errors to warnings. Given that, I would expect some libraries not to want to do that.

    That said, libraries can choose to use multiple sets of annotations during a transition period -- and that might be a good idea for other reasons. (Guava will probably do this.) So a library could stick with an older set of annotations (one that produces errors by default) while also adding the JSpecify annotations (even if they produce only warnings) to signal that they're shifting in that direction. Maybe we'll even have @Implies by then so that a single annotation can serve both roles.

  15. added
    tracking
    and removed on Nov 30, 2022
  16. cpovirk commented on Apr 7, 2023

    @cpovirk
    Collaborator

    Some notes from a chat with kevinb9n:

    • As of the recent 1.8.20 release, Kotlin supports org.jspecify.annotations to replace org.jspecify.nullness.
    • Kotlin's JSpecify support has only one bug that worries me much, KT-50008. I remember also encountering KT-55388 along the way, though that's not JSpecify-specific. Finally, it would also be good to eventually deal with KT-53836.
    • Kotlin will still need support for @NonNull (KT-53835) and @NullUnmarked (KT-53834).
    • We'd also like for Kotlin to emit JSpecify annotations (KT-47417), though we may be able to find alternative ways to get that information for at least some of our nullness checking.

    The support continues to work well for us inside Google. We've seen some of the concerns from the list above crop up occasionally, and we'd expect that to increase over time, but so far, so good.

  17. cpovirk commented on Apr 14, 2023

    @cpovirk
    Collaborator

    I jinxed it! :)

    I just filed KT-57996 for a problem with annotations on arrays. As I note in that bug, I suspect that the Kotlin people are already halfway to fixing it.

  18. kevinb9n commented on Apr 19, 2023

    @kevinb9n
    Collaborator

    @mglukhikh Could you give us an overall update on where things stand with Kotlin and JSpecify conformance?

    I'll also note that making our test suite (ready soon) be useful to Kotlin will take some extra time and may need some extra help. We will do our best to separate sample APIs from sample clients so that they can be ported separately and the cross-traffic tested.

  19. cpovirk commented on May 12, 2023

    @cpovirk
    Collaborator

    We should also figure out what the status of -Xtype-enhancement-improvements-strict-mode is and how much that status matters to JSpecify. I just said a little more about that in another thread.

  20. cpovirk commented on Aug 15, 2023

    @cpovirk
    Collaborator

    Here's a bug we just encountered for the first time. It's not specific to JSpecify, but it's coming up for us as part of annotating Java classes with JSpecify annotations: KT-61227.

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

    nullnesstracking

    Type

    No type

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions