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 @@ -64,6 +64,7 @@
import com.google.errorprone.suppliers.Supplier;
import com.google.errorprone.suppliers.Suppliers;
import com.google.errorprone.util.ASTHelpers;
import com.google.errorprone.util.SourceVersion;
import com.sun.source.tree.ArrayAccessTree;
import com.sun.source.tree.AssignmentTree;
import com.sun.source.tree.BindingPatternTree;
Expand Down Expand Up @@ -247,21 +248,27 @@ public Description matchCompilationUnit(CompilationUnitTree tree, VisitorState s
if (!unusedElements.containsKey(unusedSymbol)) {
isEverUsed.add(unusedSymbol);
}
boolean suggestUnderscore =
suggestUnderscore(state, isEverUsed, unusedSymbol, specs, allUsageSites);
SuggestedFix makeFirstAssignmentDeclaration =
makeAssignmentDeclaration(unusedSymbol, specs, allUsageSites, state);
// Don't complain if this is a public method and we only overwrote it once.
if (onlyCheckForReassignments.contains(unusedSymbol) && specs.size() <= 1) {
if ((onlyCheckForReassignments.contains(unusedSymbol) && specs.size() <= 1)
&& !suggestUnderscore) {
continue;
}
Tree unused = specs.iterator().next().assignmentPath().getLeaf();
VarSymbol symbol = (VarSymbol) unusedSymbol;
ImmutableList<SuggestedFix> fixes;
ImmutableList.Builder<SuggestedFix> fixes = ImmutableList.builder();
if (symbol.getKind() == ElementKind.PARAMETER
&& !onlyCheckForReassignments.contains(unusedSymbol)
&& !isEverUsed.contains(unusedSymbol)) {
fixes = buildUnusedParameterFixes(symbol, allUsageSites, state);
fixes.addAll(buildUnusedParameterFixes(symbol, allUsageSites, state));
} else {
fixes = buildUnusedVarFixes(symbol, allUsageSites, state);
fixes.addAll(buildUnusedVarFixes(symbol, allUsageSites, state));
}
if (suggestUnderscore) {
fixes.add(SuggestedFixes.renameVariable((VariableTree) unused, "_", state));
}
state.reportMatch(
buildDescription(unused)
Expand All @@ -272,14 +279,49 @@ public Description matchCompilationUnit(CompilationUnitTree tree, VisitorState s
describeVariable(symbol),
symbol.name))
.addAllFixes(
fixes.stream()
fixes.build().stream()
.map(f -> SuggestedFix.merge(makeFirstAssignmentDeclaration, f))
.collect(toImmutableList()))
.build());
}
return Description.NO_MATCH;
}

private static boolean suggestUnderscore(
VisitorState state,
Set<Symbol> isEverUsed,
Symbol symbol,
Collection<UnusedSpec> specs,
ImmutableList<TreePath> allUsageSites) {
TreePath unusedPath = specs.iterator().next().assignmentPath();
Tree unused = unusedPath.getLeaf();
if (!(unused instanceof VariableTree variableTree)) {
return false;
}
if (isEverUsed.contains(symbol) || specs.size() != 1 || allUsageSites.size() > 1) {
return false;
}
if (!SourceVersion.supportsUnnamedVariablesAndPatterns(state.context)) {
return false;
}
if (!allowsUnderscore((VarSymbol) symbol, unusedPath)) {
return false;
}
if (symbol.getKind().equals(ElementKind.LOCAL_VARIABLE)
&& variableTree.getInitializer() == null) {
return false;
}
return true;
}

private static boolean allowsUnderscore(VarSymbol symbol, TreePath path) {
return switch (symbol.getKind()) {
case LOCAL_VARIABLE -> true;
case PARAMETER -> path.getParentPath().getLeaf() instanceof LambdaExpressionTree;
default -> false;
};
}

private static SuggestedFix makeAssignmentDeclaration(
Symbol unusedSymbol,
Collection<UnusedSpec> specs,
Expand Down Expand Up @@ -615,11 +657,8 @@ private void handleVariable(VariableTree variableTree) {
VarSymbol symbol = getSymbol(variableTree);
var parent = getCurrentPath().getParentPath().getLeaf();
if (parent instanceof LambdaExpressionTree) {
if (FUNCTIONAL_INTERFACE_TYPES_TO_CHECK.stream()
.anyMatch(t -> isSubtype(getType(parent), state.getTypeFromString(t), state))) {
unusedElements.put(symbol, getCurrentPath());
usageSites.put(symbol, getCurrentPath());
}
unusedElements.put(symbol, getCurrentPath());
usageSites.put(symbol, getCurrentPath());
return;
}
if (symbol.getKind() == ElementKind.FIELD
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,10 @@
package com.google.errorprone.bugpatterns;

import static com.google.common.truth.TruthJUnit.assume;
import static com.google.errorprone.BugCheckerRefactoringTestHelper.TestMode.TEXT_MATCH;

import com.google.common.collect.ImmutableList;
import com.google.common.collect.Iterables;
import com.google.errorprone.BugCheckerRefactoringTestHelper;
import com.google.errorprone.BugCheckerRefactoringTestHelper.FixChoosers;
import com.google.errorprone.BugCheckerRefactoringTestHelper.TestMode;
Expand Down Expand Up @@ -1956,6 +1958,7 @@ void test() {

@Test
public void unusedFunctionalInterfaceParameter() {
assume().that(Runtime.version().feature()).isAtLeast(22);
helper
.addSourceLines(
"Test.java",
Expand Down Expand Up @@ -2010,6 +2013,7 @@ public void test(List<Integer> xs) {

@Test
public void unusedFunctionalInterfaceParameter_noFix() {
assume().that(Runtime.version().feature()).isAtLeast(22);
refactoringHelper
.addInputLines(
"Test.java",
Expand All @@ -2020,7 +2024,7 @@ public void unusedFunctionalInterfaceParameter_noFix() {

class Test {
public void test(List<Integer> xs) {
Collections.sort(xs, (a, b) -> a > a ? 1 : 0);
Collections.sort(xs, (a, unused) -> a > a ? 1 : 0);
Collections.sort(xs, (a, unused) -> a > a ? 1 : 0);
Collections.sort(
xs,
Expand Down Expand Up @@ -2141,4 +2145,50 @@ private boolean eq(Object o) {
.expectUnchanged()
.doTest();
}

@Test
public void suggestUnderscoreVariable() {
assume().that(Runtime.version().feature()).isAtLeast(22);
refactoringHelper
.addInputLines(
"Test.java",
"""
import java.util.function.Function;

class Test {

static void sink(Object... o) {}

public static void main(String[] args) {
int x;
var foo = new Object();
Function<String, Integer> f = s -> 1;
Function<String, Integer> g = (String s) -> 1;
Function<String, Integer> h = (s) -> 1;
sink(f, g, h);
}
}
""")
.addOutputLines(
"Test.java",
"""
import java.util.function.Function;

class Test {

static void sink(Object... o) {}

public static void main(String[] args) {

var _ = new Object();
Function<String, Integer> f = _ -> 1;
Function<String, Integer> g = (String _) -> 1;
Function<String, Integer> h = (_) -> 1;
sink(f, g, h);
}
}
""")
.setFixChooser(Iterables::getLast)
.doTest(TEXT_MATCH);
}
}
Loading