JetBrains / java-annotations

Annotations for JVM-based languages.
Apache License 2.0
404 stars 47 forks source link

Code generation wrong for arrays annotated with @NotNull on elements #12

Closed reitzig closed 5 years ago

reitzig commented 5 years ago

I'm not sure whether this here is the correct repo to report this.

The nullability checks generated on arrays seem to be wrong. Consider this code:

import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

class Foo {
    static void foo(@NotNull String @Nullable [] query) {
        if ( query == null ) {
            System.out.println("query null");
        } else {
            System.out.println(String.join(", ", query));
        }
    }

    static void bar(@Nullable String @NotNull [] query) {
        if ( query == null ) {
            System.out.println("query null");
        } else {
            System.out.println(String.join(", ", query));
        }
    }

    public static void main(String[] args) {
        Runnable[] tests = new Runnable[] {
                () -> { foo(new String[] {"a", "b", "c"}); },
                () -> { foo(new String[] {"a", null, "c"}); },
                () -> { foo(null); },
                () -> { bar(new String[] {"a", "b", "c"}); },
                () -> { bar(new String[] {"a", null, "c"}); },
                () -> { bar(null); }
        };

        for ( Runnable test : tests ) {
            try {
                test.run();
            } catch ( Exception e ) {
                System.err.println(e);
            }
        }
    }
}

Expected:

a, b, c
java.lang.IllegalArgumentException: <something along the lines of no element can be null>
query null
a, b, c
a, null, c
java.lang.IllegalArgumentException: Argument for @NotNull parameter 'query' of com/digithurst/hacc/sdk/Foo.bar must not be null

This is consistent with IDEA inspections: image image

Actual:

a, b, c
a, null, c
java.lang.IllegalArgumentException: Argument for @NotNull parameter 'query' of com/digithurst/hacc/sdk/Foo.foo must not be null
a, b, c
a, null, c
java.lang.IllegalArgumentException: Argument for @NotNull parameter 'query' of com/digithurst/hacc/sdk/Foo.bar must not be null

Observed with annotations 17.0.0, Java 8.0.181-oracle run from IDEA 2019.1 (directly and via Gradle 5.3.1).

amaembo commented 5 years ago

This repository is for annotations themselves, not for IDE or annotation processors which use them. I copied your report to appropriate issue tracker: https://youtrack.jetbrains.com/issue/IDEA-211172 You may watch there for progress.

trespasserw commented 5 years ago

Mixed-use annotations are confusing and always were discouraged by JSR-308 authors. A proper fix would be restricting @NotNull and @Nullable annotations to type-use-only.

reitzig commented 5 years ago

@amaembo Thanks!

@trespasserw On arrays, I agree. It's much clearer (not to mention very helpful) on generics, and IIRC you can't enable only one but not the other.