Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@
import com.sun.source.tree.ParenthesizedTree;
import com.sun.source.tree.Tree;
import com.sun.source.tree.VariableTree;
import com.sun.source.util.TreePath;
import com.sun.tools.javac.code.Symbol.VarSymbol;

/** A BugPattern; see the summary. */
Expand All @@ -45,7 +46,17 @@ public final class AssignmentExpression extends BugChecker implements Assignment

@Override
public Description matchAssignment(AssignmentTree tree, VisitorState state) {
Tree parent = state.getPath().getParentPath().getLeaf();
TreePath parentPath = state.getPath().getParentPath();
// Exempt the C-ism of (foo = getFoo()) != null, etc. before unwrapping parens.
if (parentPath.getLeaf() instanceof ParenthesizedTree
&& parentPath.getParentPath().getLeaf() instanceof BinaryTree) {
return Description.NO_MATCH;
}
// Unwrap ParenthesizedTree for parenthesis-invariant matching.
while (parentPath.getLeaf() instanceof ParenthesizedTree) {
parentPath = parentPath.getParentPath();
}
Tree parent = parentPath.getLeaf();
if (parent instanceof ExpressionStatementTree) {
return Description.NO_MATCH;
}
Expand All @@ -55,11 +66,6 @@ public Description matchAssignment(AssignmentTree tree, VisitorState state) {
if (parent instanceof LambdaExpressionTree) {
return Description.NO_MATCH;
}
// Exempt the C-ism of (foo = getFoo()) != null, etc.
if (parent instanceof ParenthesizedTree
&& state.getPath().getParentPath().getParentPath().getLeaf() instanceof BinaryTree) {
return Description.NO_MATCH;
}
// Detect duplicate assignments: a = a = foo() so that we can generate a fix.
if (isDuplicateAssignment(tree, parent)) {
return describeMatch(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -147,4 +147,22 @@ Object test() {
""")
.doTest();
}

@Test
public void parenthesizedAssignmentInDeclaration() {
helper
.addSourceLines(
"Test.java",
"""
class Test {
void test() {
int a = 0;
int b = 1;
// BUG: Diagnostic contains:
int k = (a = b);
}
}
""")
.doTest();
}
}
Loading