Skip to content
Merged
Original file line number Diff line number Diff line change
Expand Up @@ -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*\\[])");

Copy link
Copy Markdown
Contributor

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 []?

Copy link
Copy Markdown
Contributor Author

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 @Nullable or @NonNull will 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.


/**
* 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.
*
Expand Down Expand Up @@ -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<>();
Expand Down Expand Up @@ -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"))) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

How about @javax.annotation.Nullable or any other @a.b.c.Nullable? Am I missing where the input for this generator comes from and how much we know about it's shape? I also think these regexes might break if the code has a bunch of unrelated annotations, no? (Not sure of it, but it feels fragile. And even future JSpecify jdk models will have a bunch of extra new JSpecify annotations, in theory, no?)

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The 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);
}
Comment thread
msridhar marked this conversation as resolved.
Resolved
}
Original file line number Diff line number Diff line change
Expand Up @@ -259,6 +259,51 @@ public void nullableArrayTypeParameter() {
runTest(expectedMethodRecords, ImmutableMap.of(), ImmutableSet.of("NullableParameters"));
}

@Test
public void arrayParametersNullableArrayVsElements() {
compilationHelper
.addSourceLines(
"ArrayParameters.java",
"import org.jspecify.annotations.NullMarked;",
"import org.jspecify.annotations.Nullable;",
"@NullMarked",
"public class ArrayParameters {",
" public static void arrayNullable(String @Nullable [] arr) {}",
" public static void elementsNullable(@Nullable String[] arr) {}",
" public static void bothNullable(@Nullable String @Nullable [] arr) {}",
"}")
.doTest();
ImmutableMap<String, MethodAnnotationsRecord> expectedMethodRecords =
ImmutableMap.of(
"ArrayParameters:void arrayNullable(java.lang.String[])",
MethodAnnotationsRecord.create(
ImmutableSet.of(),
ImmutableSet.of(),
ImmutableMap.of(0, ImmutableSet.of("Nullable")),
ImmutableSetMultimap.of()),
"ArrayParameters:void elementsNullable(java.lang.String[])",
MethodAnnotationsRecord.create(
ImmutableSet.of(),
ImmutableSet.of(),
ImmutableMap.of(),
ImmutableSetMultimap.of(
0,
new NestedAnnotationInfo(
Annotation.NULLABLE,
ImmutableList.of(new TypePathEntry(Kind.ARRAY_ELEMENT, -1))))),
"ArrayParameters:void bothNullable(java.lang.String[])",
MethodAnnotationsRecord.create(
ImmutableSet.of(),
ImmutableSet.of(),
ImmutableMap.of(0, ImmutableSet.of("Nullable")),
ImmutableSetMultimap.of(
0,
new NestedAnnotationInfo(
Annotation.NULLABLE,
ImmutableList.of(new TypePathEntry(Kind.ARRAY_ELEMENT, -1))))));
runTest(expectedMethodRecords, ImmutableMap.of(), ImmutableSet.of("ArrayParameters"));
}

@Test
public void genericParameter() {
compilationHelper
Expand Down Expand Up @@ -425,6 +470,80 @@ public void methodTypeParameter() {
runTest(expectedMethodRecords, ImmutableMap.of(), ImmutableSet.of("Test"));
}

@Test
public void varargsNullableArrayOnly() {
compilationHelper
.addSourceLines(
"Test.java",
"import org.jspecify.annotations.*;",
"@NullMarked",
"public class Test {",
" public static int varargs(Object @Nullable ... args) { return 0; }",
"}")
.doTest();
ImmutableMap<String, MethodAnnotationsRecord> expectedMethodRecords =
ImmutableMap.of(
"Test:int varargs(java.lang.Object...)",
MethodAnnotationsRecord.create(
ImmutableSet.of(),
ImmutableSet.of(),
ImmutableMap.of(0, ImmutableSet.of("Nullable")),
ImmutableSetMultimap.of()));
runTest(expectedMethodRecords, ImmutableMap.of(), ImmutableSet.of("Test"));
}

@Test
public void varargsNullableElementsOnly() {
compilationHelper
.addSourceLines(
"Test.java",
"import org.jspecify.annotations.*;",
"@NullMarked",
"public class Test {",
" public static int varargs(@Nullable Object... args) { return 0; }",
"}")
.doTest();
ImmutableMap<String, MethodAnnotationsRecord> expectedMethodRecords =
ImmutableMap.of(
"Test:int varargs(java.lang.Object...)",
MethodAnnotationsRecord.create(
ImmutableSet.of(),
ImmutableSet.of(),
ImmutableMap.of(),
ImmutableSetMultimap.of(
0,
new NestedAnnotationInfo(
Annotation.NULLABLE,
ImmutableList.of(new TypePathEntry(Kind.ARRAY_ELEMENT, -1))))));
runTest(expectedMethodRecords, ImmutableMap.of(), ImmutableSet.of("Test"));
}

@Test
public void varargsNullableArrayAndElements() {
compilationHelper
.addSourceLines(
"Test.java",
"import org.jspecify.annotations.*;",
"@NullMarked",
"public class Test {",
" public static int varargs(@Nullable Object @Nullable ... args) { return 0; }",
"}")
.doTest();
ImmutableMap<String, MethodAnnotationsRecord> expectedMethodRecords =
ImmutableMap.of(
"Test:int varargs(java.lang.Object...)",
MethodAnnotationsRecord.create(
ImmutableSet.of(),
ImmutableSet.of(),
ImmutableMap.of(0, ImmutableSet.of("Nullable")),
ImmutableSetMultimap.of(
0,
new NestedAnnotationInfo(
Annotation.NULLABLE,
ImmutableList.of(new TypePathEntry(Kind.ARRAY_ELEMENT, -1))))));
runTest(expectedMethodRecords, ImmutableMap.of(), ImmutableSet.of("Test"));
}

private void runTest(
ImmutableMap<String, MethodAnnotationsRecord> expectedMethodRecords,
ImmutableMap<String, Set<Integer>> expectedNullableUpperBounds,
Expand Down
7 changes: 7 additions & 0 deletions jdk-annotations/jdk-integration-test/README.md
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
Expand Up @@ -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);",

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

For symmetry, maybe let's add this nullableArrayAndElements argument case to the tests of the other two methods above?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good idea, will do

" }",
"}")
.doTest();
}

@Test
public void nullableGenericArrayTest() {
compilationHelper
Expand Down Expand Up @@ -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
Expand Down
Loading
Loading