Initial handling of constructor diamond operators#1464
Conversation
Codecov Report❌ Patch coverage is
Additional details and impacted files@@ Coverage Diff @@
## master #1464 +/- ##
============================================
- Coverage 88.47% 88.41% -0.06%
- Complexity 2759 2782 +23
============================================
Files 99 99
Lines 9204 9283 +79
Branches 1848 1872 +24
============================================
+ Hits 8143 8208 +65
- Misses 521 524 +3
- Partials 540 551 +11 ☔ View full report in Codecov by Sentry. 🚀 New features to boost your workflow:
|
WalkthroughAdds path- and context-aware type inference for Java diamond ( Possibly related PRs
Suggested labels
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 |
|
Main Branch: With This PR: |
|
@coderabbitai resume |
✅ Actions performedReviews resumed. |
|
@coderabbitai review |
✅ Actions performedReview triggered.
|
There was a problem hiding this comment.
Actionable comments posted: 2
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@nullaway/src/main/java/com/uber/nullaway/generics/GenericsChecks.java`:
- Around line 573-583: getDiamondTypeFromParentContext currently returns null
for NewClassTree diamonds inside lambdas (expression or block) because the
ReturnTree/LambdaExpressionTree cases only handle enclosing MethodTree; add
TODOs and fix points: in getDiamondTypeFromParentContext and the
ReturnTree/LambdaExpressionTree handling (referencing symbols ReturnTree,
LambdaExpressionTree, NewClassTree, getDiamondTypeFromParentContext, and
NullabilityUtil.findEnclosingMethodOrLambdaOrInitializer) note that if enclosing
context is a lambda rather than a MethodTree we should attempt to derive the
target type from the lambda's target (expression lambda owner or block lambda
enclosing LambdaExpressionTree) and preserve nullability annotations instead of
falling back to javac; add TODO comments where the method currently returns null
indicating to implement extraction of the lambda target type and propagate
nullability, and link to the existing MethodTree branch as the intended
resolution pattern.
- Around line 598-611: The block handling parent instanceof NewClassTree must
null-check the constructor symbol: after obtaining Symbol parentCtorSymbol =
ASTHelpers.getSymbol(parentConstructorCall) guard if (parentCtorSymbol == null)
and return/fallback (e.g., return null) instead of calling
TypeSubstitutionUtils.memberType with a null symbol; specifically add the null
check before invoking TypeSubstitutionUtils.memberType and only call
getFormalParameterTypeForArgument(parentConstructorCall,
parentCtorType.asMethodType(), tree) when parentCtorSymbol is non-null.
---
Duplicate comments:
In `@nullaway/src/main/java/com/uber/nullaway/generics/GenericsChecks.java`:
- Around line 1613-1627: The diamond inference integration in
compareGenericTypeParameterNullabilityForCall (the new handling around
NewClassTree/newClassTree and enclosingType) is correct and requires no code
changes—keep the current logic that checks hasInferredClassTypeArguments, guards
with state.getPath()/ASTHelpers.stripParentheses, calls
getDiamondTypeFromParentContext(newClassTree, state, parentPath) to set
enclosingType, and falls back to getEnclosingTypeForCallExpression(methodSymbol,
tree, null, state, false) when null; proceed to merge as-is.
| if (parent instanceof NewClassTree parentConstructorCall) { | ||
| // get the type returned by the parent constructor call | ||
| Type parentClassType = getTreeType(parentConstructorCall, state.withPath(parentPath)); | ||
| if (parentClassType != null) { | ||
| Symbol parentCtorSymbol = ASTHelpers.getSymbol(parentConstructorCall); | ||
| // get the proper type for the constructor, as a member of the type returned by the | ||
| // constructor | ||
| Type parentCtorType = | ||
| TypeSubstitutionUtils.memberType( | ||
| state.getTypes(), parentClassType, parentCtorSymbol, config); | ||
| return getFormalParameterTypeForArgument( | ||
| parentConstructorCall, parentCtorType.asMethodType(), tree); | ||
| } | ||
| } |
There was a problem hiding this comment.
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
# Search for ASTHelpers.getSymbol usage with NewClassTree in the codebase
rg -n --type=java 'ASTHelpers\.getSymbol\(' nullaway/src/main/java/ | head -50Repository: uber/NullAway
Length of output: 7770
🏁 Script executed:
#!/bin/bash
# Check the specific file and surrounding context for how getSymbol is used with NewClassTree
# Also look for other NewClassTree getSymbol usages
rg -n --type=java -B2 -A2 'NewClassTree' nullaway/src/main/java/com/uber/nullaway/generics/GenericsChecks.java | grep -A5 -B5 'getSymbol'Repository: uber/NullAway
Length of output: 39
🏁 Script executed:
#!/bin/bash
# Look at the exact context in the file at lines 598-611 and check for null checks
sed -n '590,620p' nullaway/src/main/java/com/uber/nullaway/generics/GenericsChecks.javaRepository: uber/NullAway
Length of output: 1324
🏁 Script executed:
#!/bin/bash
# Check TypeSubstitutionUtils.memberType implementation to see if it handles null
rg -n --type=java 'public.*memberType' nullaway/src/main/java/com/uber/nullaway/Repository: uber/NullAway
Length of output: 218
🏁 Script executed:
#!/bin/bash
# Search for TypeSubstitutionUtils.memberType to understand its signature
rg -n --type=java -A10 'static.*memberType' nullaway/src/main/java/com/uber/nullaway/Repository: uber/NullAway
Length of output: 1493
🏁 Script executed:
#!/bin/bash
# Check if there are other places in the codebase where getSymbol(NewClassTree) is used
# and how they handle potential null
rg -n --type=java -B3 -A3 'NewClassTree' nullaway/src/main/java/com/uber/nullaway/generics/GenericsChecks.java | head -100Repository: uber/NullAway
Length of output: 4962
🏁 Script executed:
#!/bin/bash
# Check the implementation details and null handling in TypeSubstitutionUtils.memberType
cat -n nullaway/src/main/java/com/uber/nullaway/generics/TypeSubstitutionUtils.java | sed -n '67,77p'Repository: uber/NullAway
Length of output: 690
🏁 Script executed:
#!/bin/bash
# Look for any defensive null checks after getSymbol(NewClassTree) in the codebase
rg -n --type=java -B2 -A5 'NewClassTree.*=' nullaway/src/main/java/com/uber/nullaway/generics/GenericsChecks.java | grep -A5 'getSymbol'Repository: uber/NullAway
Length of output: 39
🏁 Script executed:
#!/bin/bash
# Check if there are other instances where getSymbol result from NewClassTree is used
# and whether null checks are applied
rg -n --type=java 'instanceof NewClassTree' nullaway/src/main/java/ -A10 | grep -A10 'getSymbol'Repository: uber/NullAway
Length of output: 1358
🏁 Script executed:
#!/bin/bash
# Check Error Prone's ASTHelpers documentation or implementation for getSymbol behavior
# First, let's see if there's any documentation in NullAway about this
rg -n --type=java 'getSymbol.*NewClass' nullaway/src/main/java/ -B5 -A10Repository: uber/NullAway
Length of output: 39
🏁 Script executed:
#!/bin/bash
# Check if there are any null checks or error handling after getSymbol(NewClassTree)
# in the entire codebase
rg -n --type=java 'getSymbol\(' nullaway/src/main/java/com/uber/nullaway/generics/GenericsChecks.java | grep -A2 -B2 '602'Repository: uber/NullAway
Length of output: 436
🏁 Script executed:
#!/bin/bash
# Look at how getSymbol is typically used after being called
# Check patterns of null checking around line 522 where memberSelectSymbol is retrieved
sed -n '515,530p' nullaway/src/main/java/com/uber/nullaway/generics/GenericsChecks.javaRepository: uber/NullAway
Length of output: 925
🏁 Script executed:
#!/bin/bash
# Let's see the context around line 522 more clearly to confirm null checking pattern
sed -n '520,530p' nullaway/src/main/java/com/uber/nullaway/generics/GenericsChecks.javaRepository: uber/NullAway
Length of output: 639
🏁 Script executed:
#!/bin/bash
# Look at how other similar cases handle getSymbol - check line 502 (assignmentTree)
sed -n '500,510p' nullaway/src/main/java/com/uber/nullaway/generics/GenericsChecks.javaRepository: uber/NullAway
Length of output: 542
🏁 Script executed:
#!/bin/bash
# Check if there are Error Prone docs or other references about getSymbol nullability
# Let's look for any Nullable annotations on the method
rg -n --type=java '@Nullable.*getSymbol|getSymbol.*@Nullable' nullaway/src/Repository: uber/NullAway
Length of output: 39
🏁 Script executed:
#!/bin/bash
# Final confirmation: check if there are any explicit null-safety guarantees in Error Prone
# by looking at how other overloads of getSymbol are documented/used in NullAway
rg -n --type=java 'ASTHelpers\.getSymbol\(' nullaway/src/main/java/com/uber/nullaway/generics/GenericsChecks.java | head -20Repository: uber/NullAway
Length of output: 1665
🏁 Script executed:
#!/bin/bash
# Check the broader pattern: do all other Symbol assignments from getSymbol have null checks?
rg -n --type=java 'Symbol.*=.*ASTHelpers\.getSymbol' nullaway/src/main/java/com/uber/nullaway/generics/GenericsChecks.java | wc -lRepository: uber/NullAway
Length of output: 59
🏁 Script executed:
#!/bin/bash
# Count how many of these have immediate null checks following them
# Let's look at a few more examples to establish the pattern
sed -n '645,680p' nullaway/src/main/java/com/uber/nullaway/generics/GenericsChecks.javaRepository: uber/NullAway
Length of output: 1860
Add null guard for parentCtorSymbol to prevent potential NPE.
ASTHelpers.getSymbol(parentConstructorCall) can return null. The codebase pattern shows null checks for getSymbol() results on MemberSelectTree (line 522) and AssignmentTree (line 502). If parentCtorSymbol is null, TypeSubstitutionUtils.memberType() at line 606 will dereference sym.type and throw an NPE.
🛡️ Proposed null guard
if (parent instanceof NewClassTree parentConstructorCall) {
// get the type returned by the parent constructor call
Type parentClassType = getTreeType(parentConstructorCall, state.withPath(parentPath));
if (parentClassType != null) {
Symbol parentCtorSymbol = ASTHelpers.getSymbol(parentConstructorCall);
+ if (parentCtorSymbol == null) {
+ return null;
+ }
// get the proper type for the constructor, as a member of the type returned by the
// constructor
Type parentCtorType =🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@nullaway/src/main/java/com/uber/nullaway/generics/GenericsChecks.java` around
lines 598 - 611, The block handling parent instanceof NewClassTree must
null-check the constructor symbol: after obtaining Symbol parentCtorSymbol =
ASTHelpers.getSymbol(parentConstructorCall) guard if (parentCtorSymbol == null)
and return/fallback (e.g., return null) instead of calling
TypeSubstitutionUtils.memberType with a null symbol; specifically add the null
check before invoking TypeSubstitutionUtils.memberType and only call
getFormalParameterTypeForArgument(parentConstructorCall,
parentCtorType.asMethodType(), tree) when parentCtorSymbol is non-null.
There was a problem hiding this comment.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Duplicate comments:
In `@nullaway/src/main/java/com/uber/nullaway/generics/GenericsChecks.java`:
- Around line 598-611: The code calls
ASTHelpers.getSymbol(parentConstructorCall) which can return null; add a null
guard after obtaining parentCtorSymbol and bail out (e.g., return null or
continue) before calling TypeSubstitutionUtils.memberType to avoid an NPE.
Specifically, in the block handling parent instanceof NewClassTree, check if
parentCtorSymbol is null and handle it (returning null from this method or
skipping the substitution and subsequent getFormalParameterTypeForArgument call)
so TypeSubstitutionUtils.memberType and parentCtorSymbol.type are never
dereferenced when parentCtorSymbol is null.
|
Main Branch: With This PR: |
lazaroclapp
left a comment
There was a problem hiding this comment.
LGTM with one nit / potential follow up consideration.
There was a problem hiding this comment.
Actionable comments posted: 2
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@nullaway/src/main/java/com/uber/nullaway/NullabilityUtil.java`:
- Line 734: Add a Javadoc comment for the public record ExprTreeAndState to
match the style of other public types in the file: describe the purpose of the
record and its components (ExpressionTree expr and VisitorState state), include
a short summary sentence and `@param` tags for expr and state, and place it
immediately above the record declaration `public record
ExprTreeAndState(ExpressionTree expr, VisitorState state) {}` so tooling and
generated docs will include it.
- Around line 736-752: Update the contract on stripParensAndUpdateTreePath:
change the Javadoc to state that the method requires the provided ExpressionTree
to be the leaf of the VisitorState path (i.e., a hard precondition), remove the
commented-out dead code "return new ExprTreeAndState(expr, state)" and replace
the RuntimeException thrown when the precondition is violated with an idiomatic
precondition check (use IllegalArgumentException or Preconditions.checkArgument)
so callers get a clear, appropriate exception type; references: method
stripParensAndUpdateTreePath, return type ExprTreeAndState, parameter
VisitorState.
| /** | ||
| * strip out enclosing parentheses, and update the tree path in the VisitorState to point to the | ||
| * stripped expression if the original expression was the leaf of the path | ||
| * | ||
| * @param expr a potentially parenthesised expression. | ||
| * @param state the VisitorState | ||
| * @return the same expression without parentheses, and the updated VisitorState | ||
| */ | ||
| public static ExprTreeAndState stripParensAndUpdateTreePath( | ||
| ExpressionTree expr, VisitorState state) { | ||
| TreePath path = state.getPath(); | ||
| if (path.getLeaf() != expr) { | ||
| // if the expression is not the leaf of the path, we can't update the path to point to the | ||
| // stripped expression, so we just return the original expression and state | ||
| // return new ExprTreeAndState(expr, state); | ||
| throw new RuntimeException( | ||
| "stripParensAndUpdateTreePath should only be called when the expression is the leaf of the VisitorState's path"); |
There was a problem hiding this comment.
Three issues: misleading Javadoc, dead commented-out code, and overly broad exception type.
-
Javadoc vs. implementation mismatch: The Javadoc says "update the tree path … if the original expression was the leaf of the path", which implies a soft guard (return unchanged on mismatch). The implementation unconditionally throws. Revise the Javadoc to document the hard precondition/contract.
-
Dead code (Line 750): The commented-out
return new ExprTreeAndState(expr, state)is a development artifact and should be removed. -
RuntimeExceptionfor a precondition violation (Lines 751–752):IllegalArgumentException(orPreconditions.checkArgument, which is already imported) is the idiomatic choice for this kind of input-contract enforcement.
🔧 Proposed fix
/**
- * strip out enclosing parentheses, and update the tree path in the VisitorState to point to the
- * stripped expression if the original expression was the leaf of the path
+ * Strips enclosing parentheses from {`@code` expr} and updates the {`@link` TreePath} in the
+ * returned {`@link` VisitorState} to reflect the unparenthesized expression.
+ *
+ * <p>Requires that {`@code` expr} is the leaf of {`@code` state}'s current path.
*
- * `@param` expr a potentially parenthesised expression.
+ * `@param` expr a potentially parenthesized expression; must be the leaf of {`@code` state}'s path
* `@param` state the VisitorState
* `@return` the same expression without parentheses, and the updated VisitorState
+ * `@throws` IllegalArgumentException if {`@code` expr} is not the leaf of {`@code` state}'s path
*/
public static ExprTreeAndState stripParensAndUpdateTreePath(
ExpressionTree expr, VisitorState state) {
TreePath path = state.getPath();
- if (path.getLeaf() != expr) {
- // if the expression is not the leaf of the path, we can't update the path to point to the
- // stripped expression, so we just return the original expression and state
- // return new ExprTreeAndState(expr, state);
- throw new RuntimeException(
- "stripParensAndUpdateTreePath should only be called when the expression is the leaf of the VisitorState's path");
- }
+ Preconditions.checkArgument(
+ path.getLeaf() == expr,
+ "stripParensAndUpdateTreePath: expr must be the leaf of state's path");
ExpressionTree resultExpr = expr;🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@nullaway/src/main/java/com/uber/nullaway/NullabilityUtil.java` around lines
736 - 752, Update the contract on stripParensAndUpdateTreePath: change the
Javadoc to state that the method requires the provided ExpressionTree to be the
leaf of the VisitorState path (i.e., a hard precondition), remove the
commented-out dead code "return new ExprTreeAndState(expr, state)" and replace
the RuntimeException thrown when the precondition is violated with an idiomatic
precondition check (use IllegalArgumentException or Preconditions.checkArgument)
so callers get a clear, appropriate exception type; references: method
stripParensAndUpdateTreePath, return type ExprTreeAndState, parameter
VisitorState.
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 `@nullaway/src/main/java/com/uber/nullaway/NullabilityUtil.java`:
- Around line 739-756: Update the `@return` Javadoc for
stripParensAndUpdateTreePath to accurately describe both outcomes: when
path.getLeaf() == expr it returns the stripped (parentheses-removed) expression
along with an updated VisitorState, and when path.getLeaf() != expr it returns
the original expression and the original VisitorState without modification (the
fallback case that preserves the potentially parenthesized expr). Mention the
returned types (ExprTreeAndState) and reference the behavior tied to the
parameters expr and state so readers can map the doc to the implementation.
---
Duplicate comments:
In `@nullaway/src/main/java/com/uber/nullaway/NullabilityUtil.java`:
- Around line 734-737: The Javadoc for the record ExprTreeAndState (used by
stripParensAndUpdateTreePath) is present and correct, so no code changes are
required; keep the record declaration public record
ExprTreeAndState(ExpressionTree expr, VisitorState state) {} and its Javadoc
as-is.
| /** | ||
| * strip out enclosing parentheses, and update the tree path in the VisitorState to point to the | ||
| * stripped expression if the original expression was the leaf of the path | ||
| * | ||
| * @param expr a potentially parenthesised expression. | ||
| * @param state the VisitorState | ||
| * @return the same expression without parentheses, and the updated VisitorState | ||
| */ | ||
| public static ExprTreeAndState stripParensAndUpdateTreePath( | ||
| ExpressionTree expr, VisitorState state) { | ||
| TreePath path = state.getPath(); | ||
| if (path.getLeaf() != expr) { | ||
| // if the expression is not the leaf of the path, we can't update the path to point to the | ||
| // stripped expression, so we just return the original expression and state | ||
| // TODO fix all cases where this happens and remove this fallback case | ||
| // Tracked in https://github.com/uber/NullAway/issues/1479 | ||
| return new ExprTreeAndState(expr, state); | ||
| } |
There was a problem hiding this comment.
@return Javadoc is inaccurate for the fallback path.
When path.getLeaf() != expr (line 750), the method returns the original, potentially still-parenthesized expression — not "the same expression without parentheses". The @return tag should document both branches.
✏️ Proposed fix
- * `@return` the same expression without parentheses, and the updated VisitorState
+ * `@return` if {`@code` expr} is the leaf of {`@code` state}'s path, the expression with enclosing
+ * parentheses stripped and a correspondingly updated {`@link` VisitorState}; otherwise
+ * {`@code` expr} and {`@code` state} unchanged (see TODO in body, tracked in
+ * <a href="https://github.com/uber/NullAway/issues/1479">issue 1479</a>)🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@nullaway/src/main/java/com/uber/nullaway/NullabilityUtil.java` around lines
739 - 756, Update the `@return` Javadoc for stripParensAndUpdateTreePath to
accurately describe both outcomes: when path.getLeaf() == expr it returns the
stripped (parentheses-removed) expression along with an updated VisitorState,
and when path.getLeaf() != expr it returns the original expression and the
original VisitorState without modification (the fallback case that preserves the
potentially parenthesized expr). Mention the returned types (ExprTreeAndState)
and reference the behavior tied to the parameters expr and state so readers can
map the doc to the implementation.
Fixes #1451
This adds partial support for diamond operators, sufficient to fix #1451. We still need to fully support diamonds in generic method inference.
Summary by CodeRabbit
New Features
Enhancements
Tests
Public API