Repository navigation
JDK javac plugin: properly handle nested annotations on array parameter types and varargs #1497
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from all commits
eb33482
e040092
ff30681
1aa61da
8a6d1ef
d8cd65a
ca1c83d
69ae57e
82f6a18
f87b13e
32fddf6
82fa32f
2a9fdd7
b0e5445
d7df44f
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -39,6 +39,24 @@ | |
| */ | ||
| public class AstubxGenerator { | ||
|
|
||
| /** Used to strip only top-level nullness annotations from a parameter type signature */ | ||
| private static final Pattern TOP_LEVEL_NULLNESS_ANNOTATION_PATTERN = | ||
| buildTopLevelNullnessAnnotationPattern(); | ||
|
|
||
| /** | ||
| * Matches annotations immediately before the "[]" for array parameters. Does not properly handle | ||
| * explicit {@code @NonNull} annotations; see https://github.com/uber/NullAway/issues/1498 | ||
| */ | ||
| private static final Pattern ARRAY_NULLNESS_ANNOTATION_PATTERN = | ||
| Pattern.compile("@[\\w.]+(?=\\s*\\[])"); | ||
|
|
||
| /** | ||
| * Matches annotations immediately before the "..." for varargs parameters Does not handle | ||
| * explicit {@code @NonNull} annotations; see https://github.com/uber/NullAway/issues/1498 | ||
| */ | ||
| private static final Pattern VARARGS_ARRAY_NULLNESS_ANNOTATION_PATTERN = | ||
| Pattern.compile("@[\\w.]+(?=\\.\\.\\.)"); | ||
|
|
||
| /** | ||
| * Contains all information that will be added to the astubx file. | ||
| * | ||
|
|
@@ -258,25 +276,12 @@ private static void getMethodRecords( | |
| for (int i = 0; i < argumentList.length; i++) { | ||
| // remove generic annotations on arguments | ||
| String typeSignature = removeGenericAnnotations(argumentList[i].trim()); | ||
| // remove annotations | ||
| if (typeSignature.contains("@")) { | ||
| String[] signatureTokens = typeSignature.split(" "); | ||
| typeSignature = ""; | ||
| for (String token : signatureTokens) { | ||
| if (token.contains("@")) { | ||
| if (token.contains("@org.jspecify.annotations.Nullable")) { | ||
| argAnnotation.put(i, ImmutableSet.of("Nullable")); | ||
| } | ||
| typeSignature += token.substring(0, token.indexOf('@')); | ||
| } else { | ||
| typeSignature += token; | ||
| } | ||
| } | ||
| } else { | ||
| // remove any spaces in Array types | ||
| typeSignature = typeSignature.replace(" []", "[]"); | ||
| if (hasTopLevelNullableAnnotation(typeSignature)) { | ||
| argAnnotation.put(i, ImmutableSet.of("Nullable")); | ||
| } | ||
| argumentList[i] = typeSignature; | ||
| // Remove top-level annotations before writing the method signature key, while preserving | ||
| // the varargs ellipsis so the generated key still matches the erased bytecode signature. | ||
| argumentList[i] = stripTopLevelNullnessAnnotations(typeSignature).replace(" []", "[]"); | ||
| } | ||
| ImmutableSetMultimap.Builder<Integer, NestedAnnotationInfo> nestedAnnotations = | ||
| new ImmutableSetMultimap.Builder<>(); | ||
|
|
@@ -373,4 +378,46 @@ private static String removeGenericAnnotations(String typeSignature) { | |
| } | ||
| return typeSignature; | ||
| } | ||
|
|
||
| /** | ||
| * Checks if the given parameter type has a top-level {@code @Nullable} annotation. Assumes there | ||
| * are no annotations on any generic type arguments in the type. We only handle JSpecify | ||
| * {@code @Nullable} annotations for now, as those are the only type present in the JSpecify JDK. | ||
| * | ||
| * @param parameterType the parameter type. | ||
| * @return true if the type has a top-level {@code @Nullable} annotation, false otherwise | ||
| */ | ||
| private static boolean hasTopLevelNullableAnnotation(String parameterType) { | ||
| if (!(parameterType.contains("@org.jspecify.annotations.Nullable") | ||
| || parameterType.contains("@Nullable"))) { | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. How about
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Yes, this is all fragile. We are assuming this all runs only on the JSpecify JDK; no other input is supported. The intended end use of this would be that we run all this code on the JSpecify JDK and then take the generated astubx and package it with NullAway. We don't need to support any other codebase, and I don't think any end user would have any reason to run this code. We probably should robustify it in the future, but for now, I think it's ok to leave it a bit hacky, as we have full control over when we run the code to generate a new astubx and I've got an eye on all the changes going into the JSpecify JDK model so we'll know if some new types of annotations are showing up. |
||
| return false; | ||
| } | ||
| if (!parameterType.contains("...")) { | ||
| if (parameterType.contains("[")) { | ||
| // Arrays need special handling: | ||
| // @Nullable String[] -> nullable elements, not a nullable array parameter | ||
| // String @Nullable [] -> nullable array parameter | ||
| // Only the latter is a top-level annotation | ||
| return ARRAY_NULLNESS_ANNOTATION_PATTERN.matcher(parameterType).find(); | ||
| } | ||
| return true; | ||
| } | ||
| // Varargs need special handling: | ||
| // @Nullable Object... -> nullable elements, not a nullable array parameter | ||
| // Object @Nullable ... -> nullable array parameter | ||
| // Only the latter is a top-level annotation | ||
| return VARARGS_ARRAY_NULLNESS_ANNOTATION_PATTERN.matcher(parameterType).find(); | ||
| } | ||
|
|
||
| private static String stripTopLevelNullnessAnnotations(String typeSignature) { | ||
| return TOP_LEVEL_NULLNESS_ANNOTATION_PATTERN.matcher(typeSignature).replaceAll(""); | ||
| } | ||
|
|
||
| private static Pattern buildTopLevelNullnessAnnotationPattern() { | ||
| String annotationWithSpace = "@[\\w.]+\\s"; | ||
| // top-level varargs array annotations (for the array itself) are rendered directly before the | ||
| // ellipsis. | ||
| String annotationOfVarargsArray = "@[\\w.]+(?=\\.\\.\\.)"; | ||
| return Pattern.compile(annotationWithSpace + "|" + annotationOfVarargsArray); | ||
| } | ||
|
msridhar marked this conversation as resolved.
Resolved
|
||
| } | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,7 @@ | ||
| These integration tests for the javac plugin work as follows. We have two versions of code used as a "library" for | ||
| input, in the sibling `test-annotated` and `test-unannotated` modules. For the `test-annotated` code, we generate an | ||
| astubx using the javac plugin (to generate JSON) and the astubx generator (to generate astubx from the JSON). Then, | ||
| when building the jar for the `test-unannotated` code, we include the generated astubx in the jar file. This module | ||
| depends only on the `test-unannotated` module, so the tests are run against the unannotated code, but with the astubx | ||
| available on the classpath. This allows us to test that the javac plugin is correctly generating the astubx and that | ||
| the astubx is correctly being loaded and used by NullAway. |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -248,6 +248,48 @@ public void nullableArrayTest() { | |
| .doTest(); | ||
| } | ||
|
|
||
| @Test | ||
| public void arrayParametersNullableArrayVsElements() { | ||
| compilationHelper | ||
| .setArgs( | ||
| JSpecifyJavacConfig.withJSpecifyModeArgs( | ||
| Arrays.asList( | ||
| "-d", | ||
| temporaryFolder.getRoot().getAbsolutePath(), | ||
| "-XepOpt:NullAway:AnnotatedPackages=com.uber", | ||
| "-XepOpt:NullAway:JarInferEnabled=true"))) | ||
| .addSourceLines( | ||
| "Test.java", | ||
| "package com.uber;", | ||
| "import org.jspecify.annotations.Nullable;", | ||
| "import com.uber.nullaway.jdkannotations.ParameterAnnotation;", | ||
| "class Test {", | ||
| " String[] nonNullArray = new String[] {\"value\"};", | ||
| " @Nullable String[] nullableElements = new String[] {\"value\", null};", | ||
| " String @Nullable [] nullableArray = null;", | ||
| " @Nullable String @Nullable [] nullableArrayAndElements = new String[] {\"value\", null};", | ||
| " void testCall() {", | ||
| " ParameterAnnotation.takesNullableArray(nonNullArray);", | ||
| " ParameterAnnotation.takesNullableArray(nullableArray);", | ||
| " // BUG: Diagnostic contains: incompatible types", | ||
| " ParameterAnnotation.takesNullableArray(nullableElements);", | ||
| " // BUG: Diagnostic contains: incompatible types", | ||
| " ParameterAnnotation.takesNullableArray(nullableArrayAndElements);", | ||
| " ParameterAnnotation.takesNullableElements(nonNullArray);", | ||
| " ParameterAnnotation.takesNullableElements(nullableElements);", | ||
| " // BUG: Diagnostic contains: passing @Nullable parameter 'nullableArray' where @NonNull is required", | ||
| " ParameterAnnotation.takesNullableElements(nullableArray);", | ||
| " // BUG: Diagnostic contains: passing @Nullable parameter 'nullableArrayAndElements' where @NonNull is required", | ||
| " ParameterAnnotation.takesNullableElements(nullableArrayAndElements);", | ||
| " ParameterAnnotation.takesNullableArrayAndElements(nonNullArray);", | ||
| " ParameterAnnotation.takesNullableArrayAndElements(nullableElements);", | ||
| " ParameterAnnotation.takesNullableArrayAndElements(nullableArray);", | ||
| " ParameterAnnotation.takesNullableArrayAndElements(nullableArrayAndElements);", | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. For symmetry, maybe let's add this
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Good idea, will do |
||
| " }", | ||
| "}") | ||
| .doTest(); | ||
| } | ||
|
|
||
| @Test | ||
| public void nullableGenericArrayTest() { | ||
| compilationHelper | ||
|
|
@@ -330,6 +372,84 @@ public void genericParameterTest() { | |
| .doTest(); | ||
| } | ||
|
|
||
| @Test | ||
| public void varargsNullableArrayOnly() { | ||
| compilationHelper | ||
| .setArgs( | ||
| JSpecifyJavacConfig.withJSpecifyModeArgs( | ||
| Arrays.asList( | ||
| "-d", | ||
| temporaryFolder.getRoot().getAbsolutePath(), | ||
| "-XepOpt:NullAway:AnnotatedPackages=com.uber", | ||
| "-XepOpt:NullAway:JarInferEnabled=true"))) | ||
| .addSourceLines( | ||
| "Test.java", | ||
| "package com.uber;", | ||
| "import com.uber.nullaway.jdkannotations.ParameterAnnotation;", | ||
| "class Test {", | ||
| " static void testPositive() {", | ||
| " // BUG: Diagnostic contains: passing @Nullable parameter '(Object) null' where @NonNull is required", | ||
| " ParameterAnnotation.varargsArrayNullable((Object) null);", | ||
| " }", | ||
| " static void testNegative() {", | ||
| " Object[] args = null;", | ||
| " ParameterAnnotation.varargsArrayNullable(args);", | ||
| " }", | ||
| "}") | ||
| .doTest(); | ||
| } | ||
|
|
||
| @Test | ||
| public void varargsNullableElementsOnly() { | ||
| compilationHelper | ||
| .setArgs( | ||
| JSpecifyJavacConfig.withJSpecifyModeArgs( | ||
| Arrays.asList( | ||
| "-d", | ||
| temporaryFolder.getRoot().getAbsolutePath(), | ||
| "-XepOpt:NullAway:AnnotatedPackages=com.uber", | ||
| "-XepOpt:NullAway:JarInferEnabled=true"))) | ||
| .addSourceLines( | ||
| "Test.java", | ||
| "package com.uber;", | ||
| "import com.uber.nullaway.jdkannotations.ParameterAnnotation;", | ||
| "class Test {", | ||
| " static void testPositive() {", | ||
| " Object[] args = null;", | ||
| " // BUG: Diagnostic contains: passing @Nullable parameter 'args' where @NonNull is required", | ||
| " ParameterAnnotation.varargsElementsNullable(args);", | ||
| " }", | ||
| " static void testNegative() {", | ||
| " ParameterAnnotation.varargsElementsNullable(null, null);", | ||
| " }", | ||
| "}") | ||
| .doTest(); | ||
| } | ||
|
|
||
| @Test | ||
| public void varargsNullableArrayAndElements() { | ||
| compilationHelper | ||
| .setArgs( | ||
| JSpecifyJavacConfig.withJSpecifyModeArgs( | ||
| Arrays.asList( | ||
| "-d", | ||
| temporaryFolder.getRoot().getAbsolutePath(), | ||
| "-XepOpt:NullAway:AnnotatedPackages=com.uber", | ||
| "-XepOpt:NullAway:JarInferEnabled=true"))) | ||
| .addSourceLines( | ||
| "Test.java", | ||
| "package com.uber;", | ||
| "import com.uber.nullaway.jdkannotations.ParameterAnnotation;", | ||
| "class Test {", | ||
| " static void testNegative() {", | ||
| " ParameterAnnotation.varargs(null, null);", | ||
| " Object[] args = null;", | ||
| " ParameterAnnotation.varargs(args);", | ||
| " }", | ||
| "}") | ||
| .doTest(); | ||
| } | ||
|
|
||
| @Test | ||
| public void libraryLoadMethodParserReturn() { | ||
| compilationHelper | ||
|
|
||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Not ultra-familiar with this jdk annotations generation process in general, but I am a bit suspicious of the fact that we are using regexes to parse Java signatures vs any form of Java parser...
For example, doesn't this just grab the last annotation in something like
Object @A @B @C []?There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Yes, you're absolutely right...we're assuming that only one annotation either
@Nullableor@NonNullwill appear for now. Again, given our use case, I'm going to put off doing a deeper cleanup and refactor of this code. If you think it's urgent to fix it or to document it better, please let me know though.