Repository navigation
JDK javac plugin: properly handle nested annotations on array parameter types and varargs - #1497
Conversation
Codecov Report❌ Patch coverage is
Additional details and impacted files@@ Coverage Diff @@
## master #1497 +/- ##
=========================================
Coverage 88.43% 88.44%
- Complexity 2808 2813 +5
=========================================
Files 99 99
Lines 9406 9414 +8
Branches 1890 1890
=========================================
+ Hits 8318 8326 +8
Misses 529 529
Partials 559 559 ☔ View full report in Codecov by Sentry. 🚀 New features to boost your workflow:
|
|
Note Reviews pausedIt looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
WalkthroughThe change updates AstubxGenerator.getMethodRecords to detect and record top-level parameter nullability via regex-based detection/stripping of top-level Possibly related PRs
Suggested reviewers
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Actionable comments posted: 1
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In
`@jdk-annotations/astubx-generator/src/main/java/com/uber/nullaway/jdkannotations/AstubxGenerator.java`:
- Around line 264-267: The current logic uses
containsNullableAnnotation(typeSignature) to set argAnnotation for parameter
nullability, which incorrectly treats element-only nullability (for
arrays/varargs) as outer/parameter nullability; change to detect only
top-level/outer nullability by introducing or using a
containsTopLevelNullableAnnotation(typeSignature) predicate and use that to
populate argAnnotation (keeping method.nestedAnnotationsList() responsible for
ARRAY_ELEMENT paths), and ensure stripTopLevelNullnessAnnotations still removes
only top-level annotations; update the same pattern in the other occurrences
around the blocks referenced by containsNullableAnnotation and
stripTopLevelNullnessAnnotations so array-element-only cases do not mark the
whole parameter Nullable.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: ASSERTIVE
Plan: Pro
Run ID: e3eebe09-d51d-429f-8c2a-ea17c31bf198
📒 Files selected for processing (6)
jdk-annotations/astubx-generator/src/main/java/com/uber/nullaway/jdkannotations/AstubxGenerator.javajdk-annotations/astubx-generator/src/test/java/com/uber/nullaway/jdkannotations/AstubxTest.javajdk-annotations/jdk-integration-test/src/test/java/com/uber/nullaway/jdkannotations/JDKIntegrationTest.javajdk-annotations/test-annotated/src/main/java/com/uber/nullaway/jdkannotations/ParameterAnnotation.javajdk-annotations/test-unannotated/src/main/java/com/uber/nullaway/jdkannotations/ParameterAnnotation.javajdk-javac-plugin/src/test/java/com/uber/nullaway/javacplugin/NullnessAnnotationSerializerTest.java
There was a problem hiding this comment.
♻️ Duplicate comments (1)
jdk-annotations/astubx-generator/src/main/java/com/uber/nullaway/jdkannotations/AstubxGenerator.java (1)
269-277:⚠️ Potential issue | 🟠 MajorDon’t mark element-nullable arrays as nullable parameters.
The varargs split is good, but non-varargs arrays still follow the old “any
@Nullablemeans nullable parameter” rule. For@Nullable String[],containsNullableAnnotation()still returnstrue, so Line 273 records the whole parameter as nullable even though that shape should only be represented via nestedARRAY_ELEMENTmetadata. That broadens the generated stub and will incorrectly acceptnullarrays for element-nullable signatures.Suggested direction
- if (containsNullableAnnotation(typeSignature)) { + if (containsTopLevelNullableAnnotation(typeSignature)) { argAnnotation.put(i, ImmutableSet.of("Nullable")); }Extend the helper to distinguish ordinary arrays (
@Nullable String[]vsString@nullable[]), not just the two varargs spellings, and add a regression around that shape.#!/bin/bash set -euo pipefail # Reproduce the current helper behavior on representative signatures. # Expected: the two array forms should differ, but the current logic prints True for both. python - <<'PY' import re VARARGS_ARRAY_NULLNESS_ANNOTATION_PATTERN = re.compile(r'@[\w.]+(?=\.\.\.)') def contains_nullable_annotation(type_signature: str) -> bool: if "@org.jspecify.annotations.Nullable" not in type_signature and "@Nullable" not in type_signature: return False if "..." not in type_signature: return True return VARARGS_ARRAY_NULLNESS_ANNOTATION_PATTERN.search(type_signature) is not None cases = [ "@Nullable String[]", # element-nullable array "String `@Nullable` []", # nullable array "@Nullable Object...", # element-nullable varargs "Object `@Nullable`...", # nullable varargs array ] for case in cases: print(f"{case} -> {contains_nullable_annotation(case)}") PYAlso applies to: 375-399
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@jdk-annotations/astubx-generator/src/main/java/com/uber/nullaway/jdkannotations/AstubxGenerator.java` around lines 269 - 277, containsNullableAnnotation currently treats any `@Nullable` in an array type as top-level; change it to only report top-level nullability when the annotation syntactically applies to the array itself (e.g., "String `@Nullable` []" or "Object `@Nullable`..."), not when it applies to the element ("@Nullable String[]" or "@Nullable Object..."). Update containsNullableAnnotation to: if the signature contains "..." use the existing varargs-pattern check (VARARGS_ARRAY_NULLNESS_ANNOTATION_PATTERN); else if the signature contains "[]" only consider it top-level nullable when the `@Nullable` token appears immediately before the "[]" (e.g., match r'@(?:org\.jspecify\.annotations\.)?Nullable(?=\s*\[\])'); otherwise return false. Make the change where containsNullableAnnotation is defined and add/adjust the regression test covering "@Nullable String[]", "String `@Nullable` []", "@Nullable Object...", and "Object `@Nullable`..." so the two array forms differ as expected.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Duplicate comments:
In
`@jdk-annotations/astubx-generator/src/main/java/com/uber/nullaway/jdkannotations/AstubxGenerator.java`:
- Around line 269-277: containsNullableAnnotation currently treats any `@Nullable`
in an array type as top-level; change it to only report top-level nullability
when the annotation syntactically applies to the array itself (e.g., "String
`@Nullable` []" or "Object `@Nullable`..."), not when it applies to the element
("@Nullable String[]" or "@Nullable Object..."). Update
containsNullableAnnotation to: if the signature contains "..." use the existing
varargs-pattern check (VARARGS_ARRAY_NULLNESS_ANNOTATION_PATTERN); else if the
signature contains "[]" only consider it top-level nullable when the `@Nullable`
token appears immediately before the "[]" (e.g., match
r'@(?:org\.jspecify\.annotations\.)?Nullable(?=\s*\[\])'); otherwise return
false. Make the change where containsNullableAnnotation is defined and
add/adjust the regression test covering "@Nullable String[]", "String `@Nullable`
[]", "@Nullable Object...", and "Object `@Nullable`..." so the two array forms
differ as expected.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: ASSERTIVE
Plan: Pro
Run ID: d9dd8130-f259-492b-817d-0290df170ab3
📒 Files selected for processing (6)
jdk-annotations/astubx-generator/src/main/java/com/uber/nullaway/jdkannotations/AstubxGenerator.javajdk-annotations/astubx-generator/src/test/java/com/uber/nullaway/jdkannotations/AstubxTest.javajdk-annotations/jdk-integration-test/src/test/java/com/uber/nullaway/jdkannotations/JDKIntegrationTest.javajdk-annotations/test-annotated/src/main/java/com/uber/nullaway/jdkannotations/ParameterAnnotation.javajdk-annotations/test-unannotated/src/main/java/com/uber/nullaway/jdkannotations/ParameterAnnotation.javajdk-javac-plugin/src/test/java/com/uber/nullaway/javacplugin/NullnessAnnotationSerializerTest.java
There was a problem hiding this comment.
Actionable comments posted: 1
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In
`@jdk-annotations/astubx-generator/src/main/java/com/uber/nullaway/jdkannotations/AstubxGenerator.java`:
- Around line 46-52: The outer-slot regexes currently match any annotation and
should be restricted to only `@Nullable`; change ARRAY_NULLNESS_ANNOTATION_PATTERN
and VARARGS_ARRAY_NULLNESS_ANNOTATION_PATTERN so they match only the Nullable
annotation (e.g., `@Nullable` and fully-qualified variants like
`@javax.annotation.Nullable` if used in the codebase), then update all usages in
containsNullableAnnotation() to reference these updated patterns (and rename
patterns if you add more specific names) so the outer-slot check does not treat
`@NonNull` as nullable; finally add a unit test covering a mixed case like
"@Nullable String `@NonNull` []" (or varargs equivalent) to prevent regression.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: ASSERTIVE
Plan: Pro
Run ID: c5b3d535-c975-4ace-8a21-ebfac9e53dc7
📒 Files selected for processing (6)
jdk-annotations/astubx-generator/src/main/java/com/uber/nullaway/jdkannotations/AstubxGenerator.javajdk-annotations/astubx-generator/src/test/java/com/uber/nullaway/jdkannotations/AstubxTest.javajdk-annotations/jdk-integration-test/src/test/java/com/uber/nullaway/jdkannotations/JDKIntegrationTest.javajdk-annotations/test-annotated/src/main/java/com/uber/nullaway/jdkannotations/ParameterAnnotation.javajdk-annotations/test-unannotated/src/main/java/com/uber/nullaway/jdkannotations/ParameterAnnotation.javajdk-javac-plugin/src/test/java/com/uber/nullaway/javacplugin/NullnessAnnotationSerializerTest.java
There was a problem hiding this comment.
Actionable comments posted: 1
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In
`@jdk-annotations/astubx-generator/src/main/java/com/uber/nullaway/jdkannotations/AstubxGenerator.java`:
- Around line 407-417: Rename and document the methods/pattern to reflect that
they remove all top-level annotations (not just nullness) and that array
element/bracket annotations are excluded (only varargs handled); update
stripTopLevelNullnessAnnotations to a clearer name like
stripTopLevelAnnotations, rename TOP_LEVEL_NULLNESS_ANNOTATION_PATTERN
accordingly (e.g., TOP_LEVEL_ANNOTATION_PATTERN), and rename
buildTopLevelNullnessAnnotationPattern to buildTopLevelAnnotationPattern; also
update the javadoc/comments on stripTopLevelAnnotations,
buildTopLevelAnnotationPattern, and the pattern constant to state they remove
any top-level annotations matching the regex, that annotations before [] are
intentionally not removed (only varargs ... handled via (?=\\.\\.\\.)), and note
the relation/consistency with LibraryModels.ANNOTATION_STRIPPING_PATTERN.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: ASSERTIVE
Plan: Pro
Run ID: 4f8434c4-10bc-4650-9484-c492b341c793
📒 Files selected for processing (1)
jdk-annotations/astubx-generator/src/main/java/com/uber/nullaway/jdkannotations/AstubxGenerator.java
lazaroclapp
left a comment
There was a problem hiding this comment.
So, before this change, we were adding nested @Nullable annotations in var args and arrays both to their corresponding place in the nested annotations list but also on the top level argument annotations? Or is it more than that?
Either way, looks like a clear improvement to me, but a few nits / caveats / and more general worries below (note I am not super familiar with the jdkannotations pipeline here)
| " String[] nonNullArray = new String[] {\"value\"};", | ||
| " @Nullable String[] nullableElements = new String[] {\"value\", null};", | ||
| " String @Nullable [] nullableArray = null;", | ||
| " @Nullable String @Nullable [] nullableArrayAndElements = new String[] {\"value\", null};", |
There was a problem hiding this comment.
Do we expect dataflow, now or in the future, to just refine this type to @Nullable String @Nonnull [] nullableArrayAndElements? It is the top-level nullability of a local, so...
Also, for arrays / generics we are currently requiring explicit type annotations more generally? (I hadn't realized if we did, but I guess outside of array expressions you rarely see the "deep nullability" of a local at the point of definition)
Presumably at least String @Nullable [] nullableArray should work without annotation, though. No? And the identical case for non-null?
There was a problem hiding this comment.
Good catch! All these variables should have been fields, not local variables. For local variables, we still infer top-level nullability for array variables, just not element nullability. I've fixed to make the variables fields and confirmed the test still passes.
| " ParameterAnnotation.takesNullableArrayAndElements(nonNullArray);", | ||
| " ParameterAnnotation.takesNullableArrayAndElements(nullableElements);", | ||
| " ParameterAnnotation.takesNullableArrayAndElements(nullableArray);", | ||
| " ParameterAnnotation.takesNullableArrayAndElements(nullableArrayAndElements);", |
There was a problem hiding this comment.
For symmetry, maybe let's add this nullableArrayAndElements argument case to the tests of the other two methods above?
There was a problem hiding this comment.
Good idea, will do
| @Nullable String[] array, | ||
| @Nullable List<@Nullable Integer>[] mixed) {} | ||
|
|
||
| public static int varargsArrayNullable(Object @Nullable ... args) { |
There was a problem hiding this comment.
Curious, why do these return int as opposed to void like the other consumer methods above?
There was a problem hiding this comment.
Yeah, I think the LLM just randomly decided to use int 🙂 will switch to void
| @@ -19,15 +19,15 @@ public static void printObjectString(Object object) { | |||
| System.out.println(object.toString()); | |||
There was a problem hiding this comment.
Sorry, but I am not sure I remember, what does this test-unannotated copy of the library stubs get used for? (I think the tests in this PR are all working over the annotated version, which makes sense, but then I am not sure I understand where these fit in)
I also see no library models for the added ones.
There was a problem hiding this comment.
Sorry, this should be documented better. What happens is:
- For the
test-annotatedversion, we run the javac plugin and then the astubx generator to generate an astubx file; see here. - The
test-unnatotatedversion get the astubx from 1 copied into its jar; see here. - The
JDKIntegrationTestdepends on thetest-unnanotatedjar.
So, this way, we check that we can correctly analyze calls into the unannotated code where the annotations are introduced via an astubx generated from an annotated version of the code.
I've added documentation of this to a new README file in the integration test module.
|
|
||
| /** | ||
| * 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. |
There was a problem hiding this comment.
Is this risky in the sense that in the future this will read List<@Nullable String> foo, and assume foo is @Nullable?
There was a problem hiding this comment.
So this method is only called in one place (line 279), and the annotations on generic type arguments are stripped out immediately before that, so I think we are fine as long as that annotation-stripping logic keeps working.
Taking a step back, I agree there is some hairy string parsing code in here that is rather scary. Eventually, we may want to refactor things so that the javac plugin emits more structured JSON rather than serializing method signature strings, to avoid this. But, given this is "internal" code not exposed to users, and it's working for now, I'd like to put off that refactoring for the moment.
| */ | ||
| private static boolean hasTopLevelNullableAnnotation(String parameterType) { | ||
| if (!(parameterType.contains("@org.jspecify.annotations.Nullable") | ||
| || parameterType.contains("@Nullable"))) { |
There was a problem hiding this comment.
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?)
There was a problem hiding this comment.
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.
| * explicit {@code @NonNull} annotations; see https://github.com/uber/NullAway/issues/1498 | ||
| */ | ||
| private static final Pattern ARRAY_NULLNESS_ANNOTATION_PATTERN = | ||
| Pattern.compile("@[\\w.]+(?=\\s*\\[])"); |
There was a problem hiding this comment.
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.
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.
Fixes #1480
For array and varargs parameter types, we were not properly distinguishing between
@Nullableannotations on the array elements vs the array itself.The logic changes are in
AstubxGenerator. We add unit tests inNullnessAnnotationSerializerTest(for serializing from source code to JSON),AstubxTest(for going from JSON to astubx), and inJDKIntegrationTestas full integration tests. For review probably the most interesting to read areJDKIntegrationTest.Summary by CodeRabbit
New Features
Tests
Chores