Skip to content
Merged
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 @@ -29,6 +29,7 @@
import com.google.errorprone.fixes.SuggestedFixes;
import com.google.errorprone.matchers.Description;
import com.google.errorprone.util.SourceVersion;
import com.sun.source.tree.AssignmentTree;
import com.sun.source.tree.BlockTree;
import com.sun.source.tree.CompilationUnitTree;
import com.sun.source.tree.EnhancedForLoopTree;
Expand Down Expand Up @@ -78,7 +79,7 @@ public Description matchCompilationUnit(CompilationUnitTree tree, VisitorState s

private static SuggestedFix buildFix(
VariableTree tree, Symbol symbol, TreePath path, VisitorState state) {
if (symbol.getKind() == ElementKind.PARAMETER) {
if (symbol.getKind() == ElementKind.PARAMETER && isLambdaInAssignmentOrInitializer(path)) {
// TODO(kak): we should also drop unnecessary parens. E.g.,
// before: `(String unused) -> 1`
// after: `(_) -> 1`
Expand All @@ -94,6 +95,21 @@ private static SuggestedFix buildFix(
return fix;
}

/**
* Returns true if the lambda expression containing the variable at the given {@link TreePath} is
* used as an initializer in a {@link VariableTree} or as the expression in an {@link
* AssignmentTree}.
*/
private static boolean isLambdaInAssignmentOrInitializer(TreePath path) {
TreePath parentPath = path.getParentPath();
return parentPath.getLeaf() instanceof LambdaExpressionTree lambda
&& switch (parentPath.getParentPath().getLeaf()) {
case VariableTree varTree -> varTree.getInitializer() == lambda;
case AssignmentTree assignmentTree -> assignmentTree.getExpression() == lambda;
default -> false;
};
}

/**
* Returns true if the given variable can be declared using {@code var}. This is true if the
* variable is:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,7 @@ public static void main(String[] args) {

public void foo(List<String> list) {
list.forEach(_ -> System.out.println());
list.forEach((_) -> System.out.println());
list.forEach((String _) -> System.out.println());
}
}
""")
Expand Down
Loading